@mailwoman/resolver 7.2.0 → 7.3.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 ADDED
@@ -0,0 +1,1511 @@
1
+ /**
2
+ * @copyright Sister Software
3
+ * @license AGPL-3.0
4
+ * @author Teffen Ellis, et al.
5
+ *
6
+ * `resolveTree` — walk an `AddressTree` top-down and decorate matched nodes with resolver- supplied
7
+ * attribution + coordinates.
8
+ *
9
+ * The walk is parent-constraint-aware: when a parent node resolves to a place id, its children's
10
+ * lookups are scoped to descendants of that parent. This dramatically narrows the search space
11
+ * for ambiguous names — `Springfield` under a resolved `Illinois` parent resolves to the IL one,
12
+ * not the MA one.
13
+ */
14
+
15
+ import { matchCountry, matchSubdivision } from "@mailwoman/codex/country"
16
+ import { isStreetDirectionalToken } from "@mailwoman/codex/us"
17
+ import type { AddressNode, AddressTree, ComponentTag, Interpretation } from "@mailwoman/core/decoder"
18
+ import {
19
+ type AddressPointLookup,
20
+ type CoincidentLocality,
21
+ DEFAULT_PLACETYPE_MAP,
22
+ type InterpolationLookup,
23
+ isPlacetypeFallback,
24
+ type PlacetypeMap,
25
+ type ResolvedPlace,
26
+ type ResolveOpts,
27
+ type Resolver,
28
+ type ResolverBackend,
29
+ type StreetCentroidLookup,
30
+ } from "@mailwoman/core/resolver"
31
+ import { haversineKm } from "@mailwoman/spatial"
32
+
33
+ import { findRescoreCandidate, hasResolvedPlace, postcodeCodeSubset } from "./span-rescore.ts"
34
+
35
+ /**
36
+ * Build a `Resolver` backed by a `ResolverBackend`. The backend can be any concrete impl structurally compatible with
37
+ * `PlaceLookup` — e.g. `new WOFSqlitePlaceLookup({ databasePath }).asResolverBackend()` or a fake for tests.
38
+ */
39
+ export function createWOFResolver(backend: ResolverBackend): Resolver {
40
+ return new WOFResolver(backend)
41
+ }
42
+
43
+ interface ResolutionState {
44
+ lookupsRemaining: number
45
+ placetypeMap: PlacetypeMap
46
+ minWinningScore: number
47
+ candidatesPerLookup: number
48
+ defaultCountry?: string
49
+ parentFallback: boolean
50
+ /**
51
+ * The address's postcode string, extracted once up front, passed to locality lookups so a coordinate-first backend
52
+ * can inject postcode-proximal locality candidates.
53
+ */
54
+ postcode?: string
55
+ /** Proximity-bias points (viewport, user location) — forwarded to every primary lookup. */
56
+ bias?: Array<{ lat: number; lon: number; weight?: number }>
57
+ /** Postcode-anchor country posterior (#369). Undefined = no re-rank (byte-stable default). */
58
+ anchorPosterior?: Record<string, number>
59
+ /** Weight on the posterior in the locality re-rank. Only used when `anchorPosterior` is set. */
60
+ anchorWeight: number
61
+ /**
62
+ * #743/#194 confident-placer country as a HARD filter (empty→unresolved, no global retry). Off = undefined.
63
+ */
64
+ hardCountry?: string
65
+ /** Dual-role hierarchy completion (#405). Off by default → byte-stable. */
66
+ hierarchyCompletion: boolean
67
+ /** Attach ancestor lineage to each resolved node (#404). Off by default → byte-stable. */
68
+ includeAncestors: boolean
69
+ /**
70
+ * Set while resolving when ANY tree node maps to the `locality` placetype (resolved or not) — the completion only
71
+ * fires when the parser emitted no locality at all, never to override one.
72
+ */
73
+ localityNodePresent: boolean
74
+ /** The first region that resolved (its place — for the coincident-roles lookup). */
75
+ resolvedRegion: ResolvedPlace | null
76
+ /**
77
+ * The decorated region NODE that produced {@link resolvedRegion} — completion pushes the locality interpretation onto
78
+ * it in place (no synthesized sibling).
79
+ */
80
+ resolvedRegionNode: AddressNode | null
81
+ }
82
+
83
+ /**
84
+ * Pick the completion locality when an admin maps to several coincident same-name candidates (#405). Population is the
85
+ * PRIMARY signal — the principal city is the populous one, and it can sit FARTHER from the admin centroid than a tiny
86
+ * same-name hamlet (the Niigata case from #403). Nearest centroid breaks a population tie; a genuine tie (same
87
+ * population AND distance) ABSTAINS rather than guess.
88
+ */
89
+ function pickCompletion(candidates: readonly CoincidentLocality[]): CoincidentLocality | null {
90
+ if (candidates.length === 0) return null
91
+
92
+ if (candidates.length === 1) return candidates[0]!
93
+ const ranked = [...candidates].sort((a, b) => b.population - a.population || a.distanceKm - b.distanceKm)
94
+ const [first, second] = ranked
95
+
96
+ if (first!.population === second!.population && first!.distanceKm === second!.distanceKm) return null
97
+
98
+ return first!
99
+ }
100
+
101
+ /**
102
+ * Find the first postcode value anywhere in the tree (a one-shot pre-scan; postcode and locality are siblings, so the
103
+ * top-down walk wouldn't otherwise let the locality lookup see it).
104
+ */
105
+ function firstPostcodeValue(roots: readonly AddressNode[]): string | undefined {
106
+ const stack = [...roots]
107
+
108
+ while (stack.length > 0) {
109
+ const n = stack.pop()!
110
+
111
+ if (n.tag === "postcode" && n.value.trim().length > 0) return n.value.trim()
112
+ stack.push(...n.children)
113
+ }
114
+
115
+ return undefined
116
+ }
117
+
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
+
509
+ for (let i = 0; !hit && i < communes.length; i++) {
510
+ hit = lookup.find({ street, locality: communes[i]! })
511
+ }
512
+
513
+ if (!hit) continue
514
+
515
+ const target =
516
+ streetNode ??
517
+ (() => {
518
+ const injected: AddressNode = {
519
+ tag: "street",
520
+ value: street,
521
+ start: 0,
522
+ end: 0,
523
+ confidence: 0.5,
524
+ children: [],
525
+ }
526
+ roots.push(injected)
527
+
528
+ return injected
529
+ })()
530
+ target.metadata = {
531
+ ...target.metadata,
532
+ street_centroid: { lat: hit.lat, lon: hit.lon, source: hit.source, release: hit.release },
533
+ resolution_tier: "street",
534
+ uncertainty_m: hit.uncertaintyM,
535
+ }
536
+
537
+ return
538
+ }
539
+ }
540
+ }
541
+
542
+ /**
543
+ * Span-rescore tier (#370): opt-in last-resort locality recovery. Runs ONLY when the tree resolved NOTHING (the #685
544
+ * brake — never disturb a working coordinate). Enumerates raw-token spans, exact- matches the same-country gazetteer
545
+ * (longest-wins + postcode-consistency gate; see `span-rescore.ts`), and on a hit INJECTS a resolved `locality` node
546
+ * decorated exactly like a normally-resolved one. Default-ON (#370, promoted 2026-06-25); byte-stable opt-out via
547
+ * `opts.spanRescore: false`. Async (it queries the backend), so it's awaited.
548
+ */
549
+ async function applySpanRescore(
550
+ roots: AddressNode[],
551
+ raw: string,
552
+ backend: ResolverBackend,
553
+ opts: ResolveOpts
554
+ ): Promise<void> {
555
+ if (hasResolvedPlace(roots)) return // already resolved — never second-guess a working coordinate
556
+ // Default-ON since 2026-06-25, so this runs on every unresolved tree — a backend hiccup here must
557
+ // degrade to no-rescore, never crash the resolve (the same fall-through the main walk gives).
558
+ let hit
559
+
560
+ try {
561
+ hit = await findRescoreCandidate(raw, roots, backend, {
562
+ country: opts.defaultCountry,
563
+ postcode: firstPostcodeValue(roots),
564
+ gateKm: opts.spanRescoreGateKm,
565
+ // Default-ON (promoted 2026-07-03); explicit `false` opts out — the spanRescore idiom.
566
+ postalCompoundRecovery: opts.postalCompoundRecovery !== false,
567
+ })
568
+ } catch {
569
+ return
570
+ }
571
+
572
+ // #942 postal-compound recovery, part 2: when NO city span matched, decorate the FAILED postcode
573
+ // node from its code-shaped token subset ("1382 Kožljek" → the bare "1382" row) — a postcode-tier
574
+ // coordinate FLOOR, strictly subordinate to a recovered locality. Only-on-miss matters: a GeoNames
575
+ // medoid postcode centroid is COARSER than the exact village centroid, and consumers that rank
576
+ // postcode above locality (the eval harness does) would otherwise trade a 0.2 km village pin for a
577
+ // 5 km area centroid. Same unresolved tree, so the #685 brake semantics hold.
578
+ if (!hit && opts.postalCompoundRecovery !== false) {
579
+ try {
580
+ await recoverPostcodeNode(roots, backend, opts.defaultCountry)
581
+ } catch {
582
+ // degrade to no-recovery, never crash the resolve
583
+ }
584
+ }
585
+
586
+ if (!hit) return
587
+ const node: AddressNode = {
588
+ tag: "locality",
589
+ value: hit.text,
590
+ start: hit.start,
591
+ end: hit.end,
592
+ // No model confidence for a post-hoc recovery; a mid-tier value marks it as recovered, not asserted.
593
+ confidence: 0.5,
594
+ children: [],
595
+ }
596
+ decorateNode(node, hit.place, [])
597
+ // `rescore_gated` carries the gate's precision signal as an EXPLICIT handle — NOT folded into the
598
+ // calibrated `confidence`, which would break the isotonic guarantee (a true calibrated 0.83 must not
599
+ // be confused with a rescore plug-in estimate; DeepSeek 2026-06-23). true = postcode gate fired
600
+ // (high-precision); false = ungated (no postcode→point coverage for this country, ~83%-precision).
601
+ node.metadata = { ...node.metadata, span_rescore: true, rescore_gated: hit.gated }
602
+ roots.push(node)
603
+ }
604
+
605
+ /**
606
+ * #942: find the first confident-but-UNRESOLVED postcode node whose value is a polluted compound ("1382 Kožljek"),
607
+ * resolve its code-shaped token subset as a `postalcode`, and decorate the node from that hit
608
+ * (`postal_compound_recovered` metadata marks the provenance). No-op when every postcode node resolved, the value has
609
+ * no digit-bearing tokens, or the subset equals the full value (then the walk already tried it).
610
+ */
611
+ async function recoverPostcodeNode(
612
+ roots: AddressNode[],
613
+ backend: ResolverBackend,
614
+ country: string | undefined
615
+ ): Promise<void> {
616
+ const stack: AddressNode[] = [...roots]
617
+
618
+ while (stack.length) {
619
+ const n = stack.pop()!
620
+
621
+ if (n.tag === "postcode" && !n.placeID && n.value.trim()) {
622
+ const code = postcodeCodeSubset(n.value)
623
+
624
+ if (!code || code === n.value.trim()) continue
625
+ const hits = await backend.findPlace({ text: code, placetype: "postalcode", country, limit: 1 })
626
+ const top = hits.find((h) => h.lat !== 0 || h.lon !== 0)
627
+
628
+ if (top) {
629
+ decorateNode(n, top, [])
630
+ n.metadata = { ...n.metadata, postal_compound_recovered: true }
631
+ }
632
+
633
+ return // first postcode node only — one recovery per tree
634
+ }
635
+
636
+ if (n.children?.length) {
637
+ stack.push(...n.children)
638
+ }
639
+ }
640
+ }
641
+
642
+ /** A resolved node carries a real coordinate (placeID set + non-zero lat/lon). */
643
+ function isResolvedWithCoord(n: AddressNode): boolean {
644
+ return !!(n.placeID && typeof n.lat === "number" && typeof n.lon === "number" && (n.lat !== 0 || n.lon !== 0))
645
+ }
646
+
647
+ /**
648
+ * Postcode-disambiguated locality selection (#370 "Lever A"). The single biggest miss on the EU/AU panel is a
649
+ * same-named town resolved to the WRONG instance — "06260 Saint-Pierre" lands 617 km off — while the postcode that
650
+ * would disambiguate it (06260 → Alpes-Maritimes) sits resolved in the same tree, discarded because the
651
+ * coordinate-picker prefers the (wrong) locality node and never cross- checks it. This post-walk pass closes that loop,
652
+ * backend-agnostically and with no extra query:
653
+ *
654
+ * 1. Find the resolved postcode's coordinate (the trustworthy anchor — a postcode is unambiguous within a country in a way
655
+ * a town name is not).
656
+ * 2. For each resolved locality node farther than `gateKm` from it: re-pick the same-named candidate from the node's
657
+ * already-captured `alternatives` that is NEAREST the postcode and within the gate. This keeps locality granularity
658
+ * at the CORRECT instance.
659
+ * 3. If no alternative reconciles, the locality instance is unreliable — fall its coordinate back to the postcode point
660
+ * (right area, the safe answer) and flag `postcode_city_mismatch`.
661
+ *
662
+ * Only fires where the postcode resolved to a point, so it composes with postcode coverage (#193) — add a country's
663
+ * postcodes and this immediately disambiguates its same-named towns. Default-off via `opts.postcodeConsistency`;
664
+ * byte-stable when unset.
665
+ */
666
+ function applyPostcodeConsistency(roots: readonly AddressNode[], gateKm: number): void {
667
+ // The resolved postcode anchor (first one with a real coordinate).
668
+ let anchor: { lat: number; lon: number } | null = null
669
+ const findAnchor: AddressNode[] = [...roots]
670
+
671
+ while (findAnchor.length > 0) {
672
+ const n = findAnchor.pop()!
673
+
674
+ if (n.tag === "postcode" && isResolvedWithCoord(n)) {
675
+ anchor = { lat: n.lat!, lon: n.lon! }
676
+ break
677
+ }
678
+ findAnchor.push(...n.children)
679
+ }
680
+
681
+ if (!anchor) return // no postcode→point — nothing to disambiguate against (gate can't fire)
682
+
683
+ const stack: AddressNode[] = [...roots]
684
+
685
+ while (stack.length > 0) {
686
+ const node = stack.pop()!
687
+ stack.push(...node.children)
688
+
689
+ if ((node.tag !== "locality" && node.tag !== "dependent_locality") || !isResolvedWithCoord(node)) continue
690
+
691
+ if (haversineKm(anchor.lat, anchor.lon, node.lat!, node.lon!) <= gateKm) continue // already consistent
692
+
693
+ // Re-pick: the same-named candidate nearest the postcode, within the gate. `alternatives` is
694
+ // typed `unknown[]` on the node (decoder/types.ts can't import resolver types) — they ARE the
695
+ // `ResolvedPlace` runner-ups decorateNode attached, so the cast is sound.
696
+ const alts = (node.alternatives as ResolvedPlace[] | undefined) ?? []
697
+ const reconciling = alts
698
+ .filter((a) => a.lat !== 0 || a.lon !== 0)
699
+ .map((a) => ({ a, d: haversineKm(anchor!.lat, anchor!.lon, a.lat, a.lon) }))
700
+ .filter((x) => x.d <= gateKm)
701
+ .sort((x, y) => x.d - y.d)[0]
702
+
703
+ if (reconciling) {
704
+ // Swap to the consistent instance; the displaced winner becomes an alternative.
705
+ const displaced: ResolvedPlace = {
706
+ id: 0,
707
+ name: String(node.metadata?.["resolver_name"] ?? node.value),
708
+ placetype: "locality",
709
+ country: reconciling.a.country,
710
+ lat: node.lat!,
711
+ lon: node.lon!,
712
+ score: 0,
713
+ }
714
+ const rest = alts.filter((a) => a !== reconciling.a)
715
+ decorateNode(node, reconciling.a, [displaced, ...rest])
716
+ node.metadata = { ...node.metadata, postcode_repicked: true }
717
+ continue
718
+ }
719
+ // No same-named instance near the postcode → the town is unreliable; trust the postcode's area.
720
+ node.lat = anchor.lat
721
+ node.lon = anchor.lon
722
+ node.metadata = { ...node.metadata, postcode_city_mismatch: true, coordinate_source: "postcode_fallback" }
723
+ }
724
+ }
725
+
726
+ /**
727
+ * Admin descendant-consistency (#263) — the joint-consistency resolve, scoped to the admin assignment. The greedy walk
728
+ * resolves a region on its own (name + population), so "ME" picks Messina (IT) over Maine, then scopes "Portland" to
729
+ * Messina's descendants, finds nothing, and the result falls back to the region centroid (Sicily). The region's
730
+ * same-named runner-ups (Maine, Missouri, …) were already captured as `alternatives`; this pass asks the question the
731
+ * greedy order skipped — _which "ME" has a "Portland" under it?_ — and re-picks the (region, locality) pair where a
732
+ * same-named locality descends from a same-named region candidate. Geography decides; no country prior, no list.
733
+ *
734
+ * Fires ONLY for a resolved region whose child locality fell through (the unresolved-locality signal), so a
735
+ * well-resolved tree ("Springfield, IL" → Illinois, Springfield) is byte-identical. Costs one unscoped locality lookup
736
+ * per triggering pair. Needs {@link ResolverBackend.ancestors}; no-op without it. See `ResolveOpts.adminCoherence`.
737
+ */
738
+ async function applyAdminCoherence(roots: readonly AddressNode[], backend: ResolverBackend): Promise<void> {
739
+ const visit = async (node: AddressNode, regionAncestor: AddressNode | null): Promise<void> => {
740
+ const regionHere = node.tag === "region" && isResolvedWithCoord(node) ? node : regionAncestor
741
+
742
+ if (
743
+ regionHere &&
744
+ (node.tag === "locality" || node.tag === "dependent_locality") &&
745
+ !isResolvedWithCoord(node) &&
746
+ node.value.trim().length > 0
747
+ ) {
748
+ await reconcileAdminPair(regionHere, node, backend)
749
+ }
750
+
751
+ for (const child of node.children) {
752
+ await visit(child, regionHere)
753
+ }
754
+ }
755
+
756
+ for (const root of roots) {
757
+ await visit(root, null)
758
+ }
759
+ }
760
+
761
+ /**
762
+ * Re-pick a (region, locality) pair so the locality descends from the region. `alternatives` on the node are the
763
+ * `ResolvedPlace` runner-ups `decorateNode` attached (typed `unknown[]` in the decoder, which can't import resolver
764
+ * types — the cast is sound). Picks the FIRST same-named locality (already score-ordered) that descends from a
765
+ * same-named region candidate, then swaps both nodes. Leaves both untouched when no consistent pair exists (a genuinely
766
+ * un-gazetteered locality — "Portland, VT" with no Portland in Vermont — stays as the region centroid, not a foreign
767
+ * namesake).
768
+ */
769
+ async function reconcileAdminPair(
770
+ regionNode: AddressNode,
771
+ localityNode: AddressNode,
772
+ backend: ResolverBackend
773
+ ): Promise<void> {
774
+ // EXACT region matches only: the alternatives for a 2-letter token are loose ("ME" also surfaces
775
+ // Missouri/Michigan/Mississippi as fuzzy M-state runner-ups). Restricting to exact name/alias matches
776
+ // (Maine/Messina/Medway for "ME") keeps the join honest. `exactMatch` is stamped by exactMatchTiering.
777
+ const regionCands = ((regionNode.alternatives as ResolvedPlace[] | undefined) ?? []).filter((r) => r.exactMatch)
778
+
779
+ // For each exact region candidate, ask the gazetteer directly: is there a same-named locality UNDER it?
780
+ // The `parentID` scope is the descendant test (over the #832-repaired ancestors table), and it finds the
781
+ // instance regardless of its global population rank — "Springfield, ME" reaches the small Springfield in
782
+ // Maine that an unscoped top-N window would drop. First region with an exact-named descendant wins; the
783
+ // region candidates are score-ordered, so a tie breaks toward the more prominent place.
784
+ for (const region of regionCands) {
785
+ const scoped = await backend.findPlace({
786
+ text: localityNode.value,
787
+ placetype: "locality",
788
+ parentID: region.id,
789
+ limit: 3,
790
+ })
791
+ const lc = scoped.find((l) => l.exactMatch && !(l.lat === 0 && l.lon === 0))
792
+
793
+ if (lc) {
794
+ decorateNode(
795
+ regionNode,
796
+ region,
797
+ regionCands.filter((r) => r !== region)
798
+ )
799
+ regionNode.metadata = { ...regionNode.metadata, admin_coherence_repicked: true }
800
+ decorateNode(
801
+ localityNode,
802
+ lc,
803
+ scoped.filter((l) => l !== lc)
804
+ )
805
+ localityNode.metadata = { ...localityNode.metadata, admin_coherence_repicked: true }
806
+
807
+ return
808
+ }
809
+ }
810
+
811
+ // #267 follow-up: the token may name a COUNTRY whose namesake is a more-populous foreign region — "Tbilisi,
812
+ // Georgia" parses region("Georgia") → the US state, but Tbilisi descends from Georgia the COUNTRY. When no
813
+ // region candidate holds the locality, try same-named country candidates: a foreign capital under its
814
+ // country out-votes the state namesake. Needs the country + the locality's ancestry in the gazetteer (the
815
+ // #267 admin fold). The re-picked region node then carries the country place; the locality coordinate wins.
816
+ const countryCands = (await backend.findPlace({ text: regionNode.value, placetype: "country", limit: 3 })).filter(
817
+ (c) => c.exactMatch
818
+ )
819
+
820
+ for (const country of countryCands) {
821
+ const scoped = await backend.findPlace({
822
+ text: localityNode.value,
823
+ placetype: "locality",
824
+ parentID: country.id,
825
+ limit: 3,
826
+ })
827
+ const lc = scoped.find((l) => l.exactMatch && !(l.lat === 0 && l.lon === 0))
828
+
829
+ if (lc) {
830
+ decorateNode(regionNode, country, regionCands)
831
+ regionNode.metadata = { ...regionNode.metadata, admin_coherence_repicked: true }
832
+ decorateNode(
833
+ localityNode,
834
+ lc,
835
+ scoped.filter((l) => l !== lc)
836
+ )
837
+ localityNode.metadata = { ...localityNode.metadata, admin_coherence_repicked: true }
838
+
839
+ return
840
+ }
841
+ }
842
+
843
+ // #1023: the admin gazetteer may carry NO `country`-placetype node for the token AND the same-named
844
+ // foreign locality may be ORPHANED (parent_id = -1) — the 2026-07-07 rebuild flattened Georgia's admin
845
+ // hierarchy to localities-only, so the country-node lookup above finds nothing and the `parentID`
846
+ // descendant test can never reach Tbilisi. Fall back to matchCountry: normalize the token to an
847
+ // ISO-3166 alpha-2 and scope the locality by the gazetteer's `country` COLUMN (set even on an orphaned
848
+ // row). Same primitive reconcileExplicitCountry (#822) uses, so the region-parsed namesake path
849
+ // ("Tbilisi, Georgia") converges with the country-parsed one ("Vienna, Austria"). matchCountry returns
850
+ // null for a US state name/abbrev ("Illinois" / "ME" / "IL"), so a real US (region, locality) pair
851
+ // never reaches here — this stays inert on the domestic path.
852
+ const mc = matchCountry(regionNode.value)
853
+
854
+ if (mc) {
855
+ const scoped = await backend.findPlace({
856
+ text: localityNode.value,
857
+ placetype: "locality",
858
+ country: mc.iso2,
859
+ limit: 3,
860
+ })
861
+ const lc = scoped.find((l) => l.exactMatch && !(l.lat === 0 && l.lon === 0))
862
+
863
+ if (lc) {
864
+ decorateNode(
865
+ localityNode,
866
+ lc,
867
+ scoped.filter((l) => l !== lc)
868
+ )
869
+ localityNode.metadata = { ...localityNode.metadata, admin_coherence_repicked: true }
870
+ // The token named a foreign country the admin gazetteer has no node for, but the greedy walk had
871
+ // already decorated the region node with the US-state namesake. Revert that stale decoration so the
872
+ // node stops asserting the wrong-country coordinate + `resolver_country` (which would otherwise leak
873
+ // into the result's `countryCode`); the re-picked locality carries the winning coordinate, and the
874
+ // region node falls back to the parsed "Georgia" token, unresolved (the admin DB has nothing truer).
875
+ revertResolverDecoration(regionNode)
876
+ }
877
+ }
878
+ }
879
+
880
+ /**
881
+ * Undo a resolver decoration on a node: restore the classifier attribution {@link decorateNode} displaced into
882
+ * `metadata.classifier_source(_id)` and drop the resolver-supplied coordinate/identity/alternatives. Used by the #1023
883
+ * country fall-through when the region token turns out to name a foreign country the admin gazetteer holds no node for
884
+ * — the greedy walk had bound it to the US-state namesake, and that stale claim must not survive the locality re-pick.
885
+ */
886
+ function revertResolverDecoration(node: AddressNode): void {
887
+ const meta = { ...node.metadata }
888
+ const priorSource = meta["classifier_source"]
889
+ const priorSourceID = meta["classifier_source_id"]
890
+ node.source = typeof priorSource === "string" ? priorSource : undefined
891
+ node.sourceID = typeof priorSourceID === "string" ? priorSourceID : undefined
892
+
893
+ for (const key of [
894
+ "classifier_source",
895
+ "classifier_source_id",
896
+ "resolver_score",
897
+ "resolver_name",
898
+ "resolver_country",
899
+ "resolution_quality",
900
+ "postcode_city_mismatch",
901
+ ]) {
902
+ delete meta[key]
903
+ }
904
+ node.metadata = meta
905
+ node.lat = undefined
906
+ node.lon = undefined
907
+ node.placeID = undefined
908
+ node.alternatives = undefined
909
+ }
910
+
911
+ /**
912
+ * Explicit-country coherence (#822) — the joint-consistency resolve keyed on the query's own EXPLICIT country token.
913
+ * The greedy walk resolves a locality on name + population alone, so "Vienna, Austria" picks the populous US namesake
914
+ * (Vienna WV) and IGNORES the "Austria" the address named. This pass asks the question the greedy order skipped —
915
+ * _which "Vienna" is in the country the address names?_ — and re-picks the locality to the same-named place under that
916
+ * country. The country code comes from the parser's OWN `country` emission via codex's ISO-3166 table (a name→code
917
+ * normalization of a token the model already classified, NOT a routing prior or safelist); the gazetteer's `country`
918
+ * column does the geographic confirmation. No pin, no list; generalizes to every country.
919
+ *
920
+ * Disjoint from {@link applyAdminCoherence} by the region guard: that pass owns the case where a REGION scopes the
921
+ * locality; this one fires only when the explicit country is the locality's nearest admin context (no region between),
922
+ * and then regardless of the locality's resolution state — so it covers both the resolved-but-foreign locality (Sydney
923
+ * → the greedy AU pick was wrong) and the unresolved locality the span-rescore tier would otherwise back-fill with the
924
+ * US namesake (Vienna → Vienna WV). Byte-stable when the locality already resolved in-country (the id guard) or the
925
+ * named country holds no same-named locality (the fail-safe — what also protects "Turkey, TX": no country token ⇒ no
926
+ * trigger; and an in-country lookup that finds nothing keeps the greedy result). Costs one country-scoped locality
927
+ * lookup per triggering pair. See `ResolveOpts.adminCoherence`.
928
+ */
929
+ async function applyExplicitCountryCoherence(roots: readonly AddressNode[], backend: ResolverBackend): Promise<void> {
930
+ const visit = async (node: AddressNode, countryToken: AddressNode | null, regionAbove: boolean): Promise<void> => {
931
+ const countryHere = node.tag === "country" && node.value.trim().length > 0 ? node : countryToken
932
+ const regionHere = regionAbove || node.tag === "region" || node.tag === "subregion"
933
+
934
+ // Fire only when the explicit country is the locality's NEAREST admin context (no region/subregion between).
935
+ // When a region IS present, applyAdminCoherence + the region's `parentID` scope already disambiguate the
936
+ // locality — applying the coarse country filter there would wrongly re-pick "Springfield, IL" to the most
937
+ // populous US "Springfield". Fires regardless of the locality's resolution state, so it PRE-EMPTS the
938
+ // span-rescore tier (which would otherwise back-fill the unresolved locality with the US namesake).
939
+ if (countryHere && !regionHere && (node.tag === "locality" || node.tag === "dependent_locality")) {
940
+ await reconcileExplicitCountry(countryHere, node, backend)
941
+ }
942
+
943
+ for (const child of node.children) {
944
+ await visit(child, countryHere, regionHere)
945
+ }
946
+ }
947
+
948
+ for (const root of roots) {
949
+ await visit(root, null, false)
950
+ }
951
+ }
952
+
953
+ /**
954
+ * Re-pick a resolved locality to its same-named place UNDER the explicitly-named country. `matchCountry` turns the
955
+ * country token into an ISO-3166 alpha-2 (returns null for an unrecognized token → no-op); the backend then surfaces
956
+ * the in-country namesake the population-first unscoped window buried. Leaves the node untouched when the country is
957
+ * unrecognized, the named country has no exact same-named locality (the fail-safe), or the locality already resolved to
958
+ * that place (the id guard → byte-stable). The country node itself stays as the parser emitted it — the named
959
+ * well-covered countries carry no `country`-placetype row in the admin gazetteer, so there is nothing to decorate it
960
+ * with; the locality coordinate is what the re-pick fixes.
961
+ */
962
+ async function reconcileExplicitCountry(
963
+ countryNode: AddressNode,
964
+ localityNode: AddressNode,
965
+ backend: ResolverBackend
966
+ ): Promise<void> {
967
+ const mc = matchCountry(countryNode.value)
968
+
969
+ if (!mc) return
970
+
971
+ const scoped = await backend.findPlace({
972
+ text: localityNode.value,
973
+ placetype: "locality",
974
+ country: mc.iso2,
975
+ limit: 3,
976
+ })
977
+ const lc = scoped.find((l) => l.exactMatch && !(l.lat === 0 && l.lon === 0))
978
+
979
+ if (!lc) return
980
+
981
+ // Already the in-country place? (placeID encodes the WOF id.) Then the greedy walk was right — byte-stable.
982
+ if (localityNode.placeID === `wof:${lc.id}`) return
983
+
984
+ decorateNode(
985
+ localityNode,
986
+ lc,
987
+ scoped.filter((l) => l !== lc)
988
+ )
989
+ localityNode.metadata = { ...localityNode.metadata, explicit_country_repicked: true }
990
+ }
991
+
992
+ /**
993
+ * Region-country coherence — the joint-consistency resolve keyed on a REGION token the locale-inferred default-country
994
+ * filter could not resolve. Companion to {@link applyExplicitCountryCoherence} (which keys on an explicit COUNTRY token)
995
+ * and disjoint from {@link applyAdminCoherence} (which needs a region that DID resolve): this pass owns the mirror case,
996
+ * where the region qualifier is a foreign subdivision the default-country hard filter (`spr.country = ?`) discarded.
997
+ *
998
+ * "Montreal QC" under a US locale: the walk applies `defaultCountry="US"` as a hard candidate filter to every admin
999
+ * lookup, so the region "QC" (a Canadian subdivision) resolves to nothing and is dropped — the one signal that would
1000
+ * redirect the country to CA — and the locality "Montreal" is force-matched to the populous US namesake (Montreal, WI).
1001
+ * The greedy order threw away the evidence that could correct it.
1002
+ *
1003
+ * The fix expands the region token to its country via codex's ISO-3166-2 subdivision table (`matchSubdivision`: "QC" →
1004
+ * `{ name: "Quebec", country: "CA" }`, handling the FTS index's missing "QC" alt-name code-side), then asks the two
1005
+ * questions the greedy walk skipped: does that subdivision genuinely resolve UNDER its own country, and is there a
1006
+ * same-named locality under it? Only when BOTH hold does it swap the region and locality to the in-country pair.
1007
+ * Geography confirms; the subdivision table is a soft name→country prior, not a routing decision.
1008
+ *
1009
+ * Evidence-gated to stay byte-stable on the domestic path. It fires ONLY when (a) a default country is in force, (b)
1010
+ * the region node is UNRESOLVED (the default-country filter came up empty — a US region resolves fine under `US`, so a
1011
+ * well-formed US query never trips this), (c) the token is a subdivision of a DIFFERENT country than the default, and
1012
+ * (d) both the foreign region and a same-named foreign locality resolve. "Springfield, IL" / "Portland, ME": the region
1013
+ * resolves under `US`, so gate (b) fails and the tree is untouched. Costs one region + one locality lookup per
1014
+ * triggering pair. See `ResolveOpts.adminCoherence`.
1015
+ */
1016
+ async function applyRegionCountryCoherence(
1017
+ roots: readonly AddressNode[],
1018
+ backend: ResolverBackend,
1019
+ defaultCountry: string | undefined
1020
+ ): Promise<void> {
1021
+ // No default country → no hard country filter was applied, so no region qualifier was discarded by one. The bug
1022
+ // this pass corrects is specific to the locale-inferred default country; without it, there is nothing to rescue.
1023
+ if (!defaultCountry) return
1024
+
1025
+ const visit = async (node: AddressNode, regionAncestor: AddressNode | null): Promise<void> => {
1026
+ // Track the nearest region ancestor regardless of its resolution state (the trigger is an UNRESOLVED region).
1027
+ const regionHere = node.tag === "region" || node.tag === "subregion" ? node : regionAncestor
1028
+
1029
+ // Fire for an UNRESOLVED region (the default-country filter came up empty) whose companion locality node
1030
+ // exists — regardless of the locality's resolution state, so it covers both the resolved-but-foreign namesake
1031
+ // (Montreal → the greedy US pick, Montreal WI) and the unresolved locality the span-rescore tier would
1032
+ // otherwise back-fill with a US namesake. The in-country lookups below are the evidence gate.
1033
+ if (
1034
+ regionHere &&
1035
+ !isResolvedWithCoord(regionHere) &&
1036
+ (node.tag === "locality" || node.tag === "dependent_locality") &&
1037
+ node.value.trim().length > 0
1038
+ ) {
1039
+ await reconcileRegionCountry(regionHere, node, backend, defaultCountry)
1040
+ }
1041
+
1042
+ for (const child of node.children) {
1043
+ await visit(child, regionHere)
1044
+ }
1045
+ }
1046
+
1047
+ for (const root of roots) {
1048
+ await visit(root, null)
1049
+ }
1050
+ }
1051
+
1052
+ /**
1053
+ * Re-pick an (unresolved region, resolved-but-foreign-namesake locality) pair to the in-country instance the
1054
+ * default-country filter hid. `matchSubdivision` turns the region token into `{ name, country }` (null for anything
1055
+ * that isn't a US state or CA province → no-op); the region's full name then resolves it under that country (expanding
1056
+ * the abbreviation the gazetteer FTS index lacks), and the locality is re-scoped to the same country. Leaves both nodes
1057
+ * untouched unless every gate holds — the subdivision names a different country than the default, the region resolves
1058
+ * under it, and a same-named locality exists there — so the domestic path stays byte-identical.
1059
+ */
1060
+ async function reconcileRegionCountry(
1061
+ regionNode: AddressNode,
1062
+ localityNode: AddressNode,
1063
+ backend: ResolverBackend,
1064
+ defaultCountry: string
1065
+ ): Promise<void> {
1066
+ const sub = matchSubdivision(regionNode.value)
1067
+
1068
+ if (!sub) return
1069
+
1070
+ // The subdivision must belong to a DIFFERENT country than the locale default. A US-state token under a US default
1071
+ // (sub.country === defaultCountry) never reaches the swap — the pass is inert on the domestic path.
1072
+ if (sub.country.toUpperCase() === defaultCountry.toUpperCase()) return
1073
+
1074
+ // The locality already resolved in the subdivision's country? Then the greedy walk was already right — byte-stable.
1075
+ const localityCountry = (localityNode.metadata?.["resolver_country"] as string | undefined)?.toUpperCase()
1076
+
1077
+ if (localityCountry === sub.country.toUpperCase()) return
1078
+
1079
+ // Confirm the subdivision genuinely resolves under its own country, by its full name (expands "QC" → "Quebec", the
1080
+ // form the FTS index carries). No resolvable region → no evidence the token is a real foreign subdivision; abstain.
1081
+ const regionScoped = await backend.findPlace({
1082
+ text: sub.name,
1083
+ placetype: "region",
1084
+ country: sub.country,
1085
+ limit: 3,
1086
+ })
1087
+ const rc = regionScoped.find((r) => r.exactMatch && !(r.lat === 0 && r.lon === 0))
1088
+
1089
+ if (!rc) return
1090
+
1091
+ // Is there a same-named locality under that country? (the descendant test, by country column — the same primitive
1092
+ // reconcileExplicitCountry uses.) No in-country namesake → keep the greedy result (fail-safe).
1093
+ const scoped = await backend.findPlace({
1094
+ text: localityNode.value,
1095
+ placetype: "locality",
1096
+ country: sub.country,
1097
+ limit: 3,
1098
+ })
1099
+ const lc = scoped.find((l) => l.exactMatch && !(l.lat === 0 && l.lon === 0))
1100
+
1101
+ if (!lc) return
1102
+
1103
+ // Adopt the in-country pair: the region gets the foreign subdivision, the locality its same-named foreign instance.
1104
+ decorateNode(
1105
+ regionNode,
1106
+ rc,
1107
+ regionScoped.filter((r) => r !== rc)
1108
+ )
1109
+ regionNode.metadata = { ...regionNode.metadata, region_country_repicked: true }
1110
+ decorateNode(
1111
+ localityNode,
1112
+ lc,
1113
+ scoped.filter((l) => l !== lc)
1114
+ )
1115
+ localityNode.metadata = { ...localityNode.metadata, region_country_repicked: true }
1116
+ }
1117
+
1118
+ class WOFResolver implements Resolver {
1119
+ readonly #backend: ResolverBackend
1120
+
1121
+ constructor(backend: ResolverBackend) {
1122
+ this.#backend = backend
1123
+ }
1124
+
1125
+ async resolveTree(tree: AddressTree, opts: ResolveOpts = {}): Promise<AddressTree> {
1126
+ const state: ResolutionState = {
1127
+ lookupsRemaining: opts.maxLookups ?? 10,
1128
+ // Full replacement when `placetypeMap` is supplied — callers that want to extend rather
1129
+ // than replace should spread DEFAULT_PLACETYPE_MAP themselves.
1130
+ placetypeMap: opts.placetypeMap ?? DEFAULT_PLACETYPE_MAP,
1131
+ minWinningScore: opts.minWinningScore ?? 0,
1132
+ candidatesPerLookup: opts.candidatesPerLookup ?? 5,
1133
+ defaultCountry: opts.defaultCountry,
1134
+ parentFallback: opts.parentFallback ?? true,
1135
+ postcode: firstPostcodeValue(tree.roots),
1136
+ bias: opts.bias,
1137
+ anchorPosterior: opts.anchorPosterior,
1138
+ anchorWeight: opts.anchorWeight ?? 2.0,
1139
+ hardCountry: opts.hardCountry,
1140
+ // Default-ON (#402): completion only fires for a dual-role region whose locality the parser
1141
+ // dropped, and no-ops entirely when the backend has no relation (the browser WASM resolver, or
1142
+ // a gazetteer without `coincident_roles`). Pass `hierarchyCompletion: false` to opt out.
1143
+ // `cityStateFallback` is the #387 alias that #405 generalized — still honored.
1144
+ hierarchyCompletion: opts.hierarchyCompletion ?? opts.cityStateFallback ?? true,
1145
+ includeAncestors: opts.includeAncestors ?? false,
1146
+ localityNodePresent: false,
1147
+ resolvedRegion: null,
1148
+ resolvedRegionNode: null,
1149
+ }
1150
+
1151
+ const newRoots: AddressNode[] = []
1152
+
1153
+ for (const root of tree.roots) {
1154
+ newRoots.push(await this.#walk(root, /* parentResolved */ null, state))
1155
+ }
1156
+
1157
+ // Dual-role hierarchy completion (#405/#415). Only when enabled, a region resolved, and the parser
1158
+ // emitted NO locality — record the dropped locality as a SECONDARY ROLE (an interpretation) on the
1159
+ // resolved region node, from the backend's precomputed coincident-roles relation (#403). One node,
1160
+ // one span, two roles — no synthesized sibling. See ResolveOpts.hierarchyCompletion.
1161
+ if (state.hierarchyCompletion && state.resolvedRegion && state.resolvedRegionNode && !state.localityNodePresent) {
1162
+ this.#completeRegionRole(state.resolvedRegion, state.resolvedRegionNode)
1163
+ }
1164
+
1165
+ // Admin descendant-consistency (#263): default-ON (#895 settled drift D1; `false` opts out). Re-pick a
1166
+ // (region, locality) pair so the locality descends from the region — runs BEFORE postcode-consistency
1167
+ // (it resolves the locality the postcode pass may then refine) and before the street tiers (which key
1168
+ // off the postcode/street, not the admin coordinate this adjusts). Byte-stable when nothing fell
1169
+ // through or the backend lacks `ancestors`.
1170
+ if (opts.adminCoherence !== false) {
1171
+ await applyAdminCoherence(newRoots, this.#backend)
1172
+ // #822 — same joint-consistency family, inverse trigger: an explicit country token whose resolved
1173
+ // locality landed in the wrong country (the populous US namesake). Runs after the region pass so the
1174
+ // two never contend (region-fallthrough vs resolved-but-foreign are disjoint locality states).
1175
+ await applyExplicitCountryCoherence(newRoots, this.#backend)
1176
+ // Region-country coherence: a region qualifier the locale-inferred default-country hard filter could not
1177
+ // resolve (a foreign subdivision — "Montreal QC" under a US locale). The default filter discarded "QC" and
1178
+ // force-matched the locality to the US namesake; this re-resolves the subdivision + its same-named locality
1179
+ // under the subdivision's OWN country. Disjoint from the two passes above (unresolved region + resolved
1180
+ // locality); evidence-gated + byte-stable on the domestic path (a US region resolves under `US`).
1181
+ await applyRegionCountryCoherence(newRoots, this.#backend, state.defaultCountry)
1182
+ }
1183
+
1184
+ // Postcode-consistency (#370 "Lever A"): default-ON (promoted 2026-07-04 — the corrected gate:
1185
+ // FI 231/0, SI 37/6, CZ 47/2, US byte-flat; see the ResolveOpts docstring). After the admin walk
1186
+ // (needs both the locality and the postcode resolved) and before the street tiers (which key off
1187
+ // the postcode/street, not the locality coordinate this adjusts). `false` opts out, byte-stable.
1188
+ if (opts.postcodeConsistency !== false) {
1189
+ applyPostcodeConsistency(newRoots, opts.postcodeConsistencyGateKm ?? 50)
1190
+ }
1191
+
1192
+ // Address-point tier (#476): opt-in street-level exact match. After the admin walk so the
1193
+ // tier can never disturb admin attribution — it only ADDS the precise coordinate. Byte-stable
1194
+ // when opts.addressPoints is absent.
1195
+ if (opts.addressPoints) {
1196
+ applyAddressPoint(newRoots, opts.addressPoints, opts.addressPointBboxFallback)
1197
+ }
1198
+
1199
+ // Interpolation tier (#483): strictly AFTER the exact-point block so an estimate can never
1200
+ // override a real situs point (applyInterpolation also gates on resolution_tier). Opt-in;
1201
+ // byte-stable when opts.interpolation is absent.
1202
+ if (opts.interpolation) {
1203
+ applyInterpolation(newRoots, opts.interpolation, opts.interpolationRadiusCalibration)
1204
+ }
1205
+
1206
+ // Span-rescore tier (#370): default-ON (promoted 2026-06-25 — same-harness EU+AU +1pp @25km,
1207
+ // zero regressions: CZ 90→95, AT 70→73, PL 88→90, IT/PT/FR/AU flat, no-result 4→3%; fires last
1208
+ // so it only runs when every other tier left the tree unresolved, hence inert on the well-resolved
1209
+ // US path). Explicit opt-OUT via `spanRescore: false`; byte-stable then.
1210
+ if (opts.spanRescore !== false) {
1211
+ await applySpanRescore(newRoots, tree.raw, this.#backend, opts)
1212
+ }
1213
+
1214
+ // Street-centroid tier (#1042): LAST, after span-rescore, so it can (a) union the span-rescore-recovered
1215
+ // country into its FR/national country hints (a placer-misrouted street — "Rue Sainte-Catherine" → IT — leaves
1216
+ // admin unresolved, and only span-rescore recovers the FR country signal) and (b) override a coarse recovered
1217
+ // locality with the exact street centroid. Self-gates on no house number + no existing street-level tier, so a
1218
+ // rooftop query is untouched; byte-stable when opts.streetCentroids absent.
1219
+ if (opts.streetCentroids) {
1220
+ applyStreetCentroid(newRoots, tree.raw, opts.streetCentroids, opts.streetCountryHints ?? [])
1221
+ }
1222
+
1223
+ return { raw: tree.raw, roots: newRoots }
1224
+ }
1225
+
1226
+ /**
1227
+ * Record a dropped dual-role locality as a `locality` INTERPRETATION on the resolved region node (#415, generalizes
1228
+ * #405's synthesized node). Consults `coincidentLocalitiesFor(regionID)` (O(1) map lookup — no distance math, no
1229
+ * backend query), picks the principal city ({@link pickCompletion}: population-primary, distance tiebreak, abstain on
1230
+ * a genuine tie), and appends an interpretation to `regionNode.interpretations`. No-op when the backend has no
1231
+ * relation, the region isn't a dual-role place, or it abstains. The region node's primary role stays `region`; the
1232
+ * locality rides alongside.
1233
+ */
1234
+ #completeRegionRole(region: ResolvedPlace, regionNode: AddressNode): void {
1235
+ if (typeof region.id !== "number" || !this.#backend.coincidentLocalitiesFor) return
1236
+ const loc = pickCompletion(this.#backend.coincidentLocalitiesFor(region.id))
1237
+
1238
+ if (!loc) return
1239
+ const interpretation: Interpretation = {
1240
+ tag: "locality",
1241
+ placeID: `wof:${loc.id}`,
1242
+ sourceID: `${loc.placetype}:${loc.id}`,
1243
+ lat: loc.lat,
1244
+ lon: loc.lon,
1245
+ confidence: 0,
1246
+ metadata: { relationship_type: loc.relationshipType, resolver_completed: true, resolver_name: loc.name },
1247
+ }
1248
+ regionNode.interpretations = [...(regionNode.interpretations ?? []), interpretation]
1249
+ }
1250
+
1251
+ async #walk(node: AddressNode, parentResolved: ResolvedPlace | null, state: ResolutionState): Promise<AddressNode> {
1252
+ // Always clone — never mutate input nodes.
1253
+ const decorated: AddressNode = { ...node, children: [] }
1254
+
1255
+ const placetype = state.placetypeMap[node.tag as ComponentTag]
1256
+
1257
+ // Track locality presence for hierarchy completion (#405): completion must NOT fire if the parser
1258
+ // already emitted a locality node (even one that failed to resolve) — it only fills a genuine
1259
+ // gap. Cheap and always-on; only consulted when hierarchyCompletion is set.
1260
+ if (placetype === "locality") {
1261
+ state.localityNodePresent = true
1262
+ }
1263
+ let resolved: ResolvedPlace | null = null
1264
+
1265
+ if (placetype && state.lookupsRemaining > 0 && node.value.trim().length > 0) {
1266
+ const picked = await this.#lookupAndPick(node, placetype, parentResolved, state)
1267
+
1268
+ if (picked) {
1269
+ resolved = picked.top
1270
+ decorateNode(decorated, picked.top, picked.alternatives)
1271
+
1272
+ // Lineage attachment (#404): stamp the resolved place's ancestor chain onto metadata. Opt-in
1273
+ // + only when the backend supplies it, so the default stays byte-identical (no extra query).
1274
+ if (state.includeAncestors && this.#backend.ancestors) {
1275
+ decorated.metadata = { ...decorated.metadata, ancestors: this.#backend.ancestors(picked.top.id) }
1276
+ }
1277
+
1278
+ // Capture the first resolved region (place + node) for hierarchy completion — the locality
1279
+ // interpretation is pushed onto this node in the post-walk pass.
1280
+ if (placetype === "region" && state.resolvedRegion === null) {
1281
+ state.resolvedRegion = picked.top
1282
+ state.resolvedRegionNode = decorated
1283
+ }
1284
+ }
1285
+ }
1286
+
1287
+ const carryParent = resolved ?? parentResolved
1288
+
1289
+ for (const child of node.children) {
1290
+ decorated.children.push(await this.#walk(child, carryParent, state))
1291
+ }
1292
+
1293
+ return decorated
1294
+ }
1295
+
1296
+ async #lookupAndPick(
1297
+ node: AddressNode,
1298
+ placetype: string,
1299
+ parentResolved: ResolvedPlace | null,
1300
+ state: ResolutionState
1301
+ ): Promise<{ top: ResolvedPlace; alternatives: ResolvedPlace[] } | null> {
1302
+ state.lookupsRemaining--
1303
+
1304
+ const query: Parameters<ResolverBackend["findPlace"]>[0] = {
1305
+ text: node.value,
1306
+ placetype,
1307
+ limit: state.candidatesPerLookup,
1308
+ }
1309
+
1310
+ // Proximity bias (viewport center, user location, …) — a SOFT re-rank the backend folds into
1311
+ // its exact-tier prominence; never a filter, so recall is untouched. This is how an ambiguous
1312
+ // bare postcode ("48026") follows the map view instead of a global population coin-flip.
1313
+ if (state.bias && state.bias.length > 0) {
1314
+ query.bias = state.bias
1315
+ }
1316
+
1317
+ // Pass the inherited parent constraint to the backend when available — `parentID` scopes to
1318
+ // the resolved parent's descendants. For `country`: a resolved parent's country wins, else
1319
+ // fall back to the caller's `defaultCountry`. Without this top-level hint a bare "IL" over a
1320
+ // multi-country gazetteer fuzzy-matches a foreign place (e.g. a French region) — see the
1321
+ // Direction-C resolver eval.
1322
+ if (parentResolved && typeof parentResolved.id === "number") {
1323
+ query.parentID = parentResolved.id
1324
+ }
1325
+ // #194: a resolved parent's country wins, then the caller's `defaultCountry`, then the confident
1326
+ // placer `hardCountry`. All three are a HARD candidate filter. The placer's `hardCountry` is gated
1327
+ // upstream on high confidence (so it only fires when the model is sure), and on a miss the node is
1328
+ // left UNRESOLVED rather than re-resolved globally: the off-continent rows are precisely the ones
1329
+ // whose locality isn't in the country's gazetteer slice, so a global retry would just re-admit the
1330
+ // wrong-continent guess the hard filter exists to drop ("in-region or unresolved"). Measured: a
1331
+ // global fallback collapses back to the soft-prior baseline (FI p90 3050, PL p90 1078); pure-hard
1332
+ // collapses the tail (FI 18 km, PL p99 8172→494) at a coverage-bounded recall cost.
1333
+ // #833 forward linkage: a node's own `country_hint` (an address-system recognizer's derived country —
1334
+ // today `recognizeUSRegions` stamping "US" on a recognized closed-set US state) constrains THIS node's
1335
+ // lookup, below a resolved parent's country but above the global defaults. It breaks the two-consistent-
1336
+ // pairs tie ("Augusta, ME" → Maine, not Augusta/Messina) that pure geographic consistency cannot.
1337
+ const countryHint = node.metadata?.["country_hint"]
1338
+ const country =
1339
+ parentResolved?.country ??
1340
+ (typeof countryHint === "string" ? countryHint : undefined) ??
1341
+ state.defaultCountry ??
1342
+ state.hardCountry
1343
+
1344
+ if (country) {
1345
+ query.country = country
1346
+ }
1347
+
1348
+ // Coordinate-first: hand the sibling postcode to locality lookups so the backend can inject
1349
+ // postcode-proximal candidates the name-match would miss. Only for locality (the placetype both
1350
+ // `locality` and `dependent_locality` map to); other placetypes ignore it.
1351
+ if (placetype === "locality" && state.postcode) {
1352
+ query.postcode = state.postcode
1353
+ }
1354
+
1355
+ let candidates: ResolvedPlace[]
1356
+
1357
+ try {
1358
+ candidates = await this.#backend.findPlace(query)
1359
+
1360
+ // Parent soft-gating: `parentID` is a HARD descendant filter in the backend, which wrongly
1361
+ // zeroes the result when the parent resolved wrong OR the gazetteer hierarchy is incomplete
1362
+ // (a real locality whose `ancestors` chain is missing its region). Rather than turn a
1363
+ // resolvable node into an unresolved one, retry once WITHOUT the parent constraint — we
1364
+ // prefer a parent-scoped hit but never sacrifice recall. The country constraint is kept, so
1365
+ // this still can't wander to a foreign place. Same logical resolution → no extra budget.
1366
+ if (candidates.length === 0 && state.parentFallback && query.parentID !== undefined) {
1367
+ delete query.parentID
1368
+ candidates = await this.#backend.findPlace(query)
1369
+ }
1370
+ } catch {
1371
+ // Defensive: a backend failure should not abort the whole tree walk. Leave the node with
1372
+ // its classifier attribution intact.
1373
+ return null
1374
+ }
1375
+
1376
+ if (candidates.length === 0) return null
1377
+ // Postcode-anchor re-rank (#369): when a country posterior is supplied (from the address's
1378
+ // postcode), boost candidates by `anchorWeight * posterior[candidate.country]` and re-sort, so a
1379
+ // postcode that pins the country pulls the right-country place over a higher-BM25 foreign namesake
1380
+ // (the "Berlin DE vs Berlin US" class the #59 harness measured). No-op when `anchorPosterior` is
1381
+ // undefined (the default) → byte-identical resolution.
1382
+ //
1383
+ // Applied to BOTH region and locality — the two placetypes that suffer cross-country namesake/
1384
+ // abbreviation collisions a country posterior can break. The region case is the one #447's window
1385
+ // fix couldn't reach: a bare 2-letter abbreviation is shared across countries ("VT" is
1386
+ // both Vermont and Viterbo; "ME" both Maine and Messina), so with no country signal the score
1387
+ // picks the wrong one — and because resolveTree resolves region FIRST and inherits its country
1388
+ // down, a wrong region poisons the locality too. The postcode posterior breaks the tie at the
1389
+ // region, and the right country then flows to the locality. (Country/macroregion/county are
1390
+ // excluded: they don't exhibit this collision class and carry country via `parentID` when nested.)
1391
+ //
1392
+ // Tier-SAFE ordering: the candidate's exact-match flag is the PRIMARY key, so the country pin
1393
+ // never crosses the exact/partial boundary. WITHIN a tier, `score + anchorWeight * posterior`
1394
+ // applies the (soft) country boost. So a confident US postcode keeps the US EXACT region
1395
+ // ("ME" → Maine) ahead of a more-populous US PARTIAL match (Missouri) AND, within the exact
1396
+ // tier, ahead of a foreign exact match (Messina IT); a soft posterior still blends with score.
1397
+ // (A plain additive re-rank loses the tier — it isn't encoded in `score` — and flips
1398
+ // "ME" → Missouri / "PA" → Alabama. Backends that don't set `exactMatch` degrade to additive.)
1399
+ const anchorEligible = placetype === "region" || placetype === "locality"
1400
+ let ranked = candidates
1401
+
1402
+ if (state.anchorPosterior && anchorEligible && candidates.length > 1) {
1403
+ const post = state.anchorPosterior
1404
+ const w = state.anchorWeight
1405
+ // #928 root cause: this sort's within-tier key was `score + w·posterior` — RAW SCORE order,
1406
+ // the exact metric #910 deprecated inside the exact tier as bm25-length-poisoned (a famous
1407
+ // place's alias-heavy doc reads ~15 pts WORSE than a tiny namesake's clean one; #905
1408
+ // measured it). Before #910 the anchor-off path also sorted by score, so the two paths
1409
+ // agreed; after, anchor-ON silently reverted to the poisoned metric — a CORRECT GB@1.00
1410
+ // pin flipped "London SE15 1DD" to a US namesake because +w·1.0 can't bridge the bm25 gap.
1411
+ // The within-tier key is now the backend's PROMINENCE (population + proximity, #938 units)
1412
+ // with the posterior as the additive country pin; score stays the final tiebreak. Backends
1413
+ // that don't populate `prominence` degrade to the additive score behavior.
1414
+ ranked = [...candidates].sort((a, b) => {
1415
+ const tier = Number(b.exactMatch ?? false) - Number(a.exactMatch ?? false)
1416
+
1417
+ if (tier !== 0) return tier
1418
+ const aKey = (a.prominence ?? a.score) + w * (post[a.country] ?? 0)
1419
+ const bKey = (b.prominence ?? b.score) + w * (post[b.country] ?? 0)
1420
+
1421
+ return bKey - aKey || b.score - a.score
1422
+ })
1423
+ }
1424
+
1425
+ // Exact-type preference (#718): when the placetype-equivalence group let a broader admin tier
1426
+ // (`macroregion`/`macrocounty`) into the candidate pool, prefer a candidate of the EXACT
1427
+ // requested type over the macro fallback — a real `region` (US state, DE Bundesland, ES
1428
+ // provincia) must win over a same-name macroregion namesake, so no real region silently
1429
+ // downgrades to a macro. STABLE partition: exact-type candidates keep their (already-ranked)
1430
+ // relative order ahead of fallbacks, so the score / anchor re-rank survives WITHIN each tier.
1431
+ // No-op for placetypes without a macro fallback (the byte-stable default) and when every
1432
+ // candidate is the same tier.
1433
+ const hasFallbackCandidate = ranked.some((c) => isPlacetypeFallback(placetype, c.placetype))
1434
+
1435
+ if (hasFallbackCandidate && ranked.length > 1) {
1436
+ ranked = [
1437
+ ...ranked.filter((c) => !isPlacetypeFallback(placetype, c.placetype)),
1438
+ ...ranked.filter((c) => isPlacetypeFallback(placetype, c.placetype)),
1439
+ ]
1440
+ }
1441
+
1442
+ const top = ranked[0]!
1443
+
1444
+ if (top.score < state.minWinningScore) return null
1445
+
1446
+ // Fallback-observability (#718): if the winner is a macro-type AND no exact-type candidate
1447
+ // existed for this span, annotate that a broader tier stood in for the true one. Additive —
1448
+ // identity/coordinate are unchanged; only `metadata.resolution_quality` is stamped downstream.
1449
+ if (isPlacetypeFallback(placetype, top.placetype)) {
1450
+ top.resolutionQuality = "fallback"
1451
+ }
1452
+
1453
+ return { top, alternatives: ranked.slice(1) }
1454
+ }
1455
+ }
1456
+
1457
+ /**
1458
+ * Stamp a node with resolver-supplied attribution. Displaces any prior classifier `source` / `sourceID` into
1459
+ * `metadata.classifier_source` / `metadata.classifier_source_id` so debugging tools can still see who made the original
1460
+ * assertion. Surfaces the runner-up candidates on `alternatives` so callers can disambiguate (Springfield-class
1461
+ * failures, [#8 in the failure catalogue]).
1462
+ */
1463
+ function decorateNode(node: AddressNode, resolved: ResolvedPlace, alternatives: ResolvedPlace[]): void {
1464
+ if (node.source !== undefined || node.sourceID !== undefined) {
1465
+ const meta = { ...node.metadata }
1466
+
1467
+ if (node.source !== undefined) {
1468
+ meta["classifier_source"] = node.source
1469
+ }
1470
+
1471
+ if (node.sourceID !== undefined) {
1472
+ meta["classifier_source_id"] = node.sourceID
1473
+ }
1474
+ node.metadata = meta
1475
+ }
1476
+ node.source = "resolver"
1477
+ node.sourceID = `${resolved.placetype}:${resolved.id}`
1478
+ node.lat = resolved.lat
1479
+ node.lon = resolved.lon
1480
+ node.placeID = `wof:${resolved.id}` // v1: only WOF resolvers; the URI scheme stays this simple
1481
+ // Record the resolver's ranking score AND the resolved place's CANONICAL name. The name is the
1482
+ // gazetteer's truth for the place we picked — distinct from `node.value` (the raw input span). It
1483
+ // lets consumers display the canonical name and lets the end-to-end eval check the resolver chose
1484
+ // the right PLACE (gazetteer-name vs ground-truth) rather than merely echoing the parser's text.
1485
+ node.metadata = { ...node.metadata, resolver_score: resolved.score, resolver_name: resolved.name }
1486
+
1487
+ // The resolved place's ISO-3166 alpha-2 country (from the gazetteer/candidate row), when known. #1014: lets a
1488
+ // forward consumer fill country/countrycode without an ancestry walk — the candidate backend carries this even
1489
+ // though it has no `ancestors()` table.
1490
+ if (resolved.country) {
1491
+ node.metadata["resolver_country"] = resolved.country
1492
+ }
1493
+
1494
+ // The postcode/locality conflict flag (the falsehood differentiator): the postcode pointed to a
1495
+ // geographically different place than the parsed city name. Surface it so callers can warn rather
1496
+ // than silently trust the resolved point.
1497
+ if (resolved.mismatch) {
1498
+ node.metadata["postcode_city_mismatch"] = true
1499
+ }
1500
+
1501
+ // Fallback-observability (#718): a broader admin tier (macroregion/macrocounty) stood in for the
1502
+ // true region/county because no exact-type candidate existed. Additive annotation only — the
1503
+ // resolved coordinate/identity above is untouched; this just lets a consumer / QA pass see it.
1504
+ if (resolved.resolutionQuality) {
1505
+ node.metadata["resolution_quality"] = resolved.resolutionQuality
1506
+ }
1507
+
1508
+ if (alternatives.length > 0) {
1509
+ node.alternatives = alternatives
1510
+ }
1511
+ }