@mailwoman/resolver 11.1.0 → 11.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.
Files changed (69) hide show
  1. package/README.md +1 -1
  2. package/lib/admin/coherence-passes.ts +1 -1
  3. package/lib/admin/county-designator.ts +91 -0
  4. package/lib/admin/former-division.ts +116 -0
  5. package/lib/bare-toponym-race.ts +1 -1
  6. package/lib/decorate-node.ts +103 -2
  7. package/lib/postcode/prefix.ts +7 -16
  8. package/lib/postcode/shape-coherence.ts +2 -2
  9. package/lib/remote-resolver.ts +1 -1
  10. package/lib/resolve/parent-place.ts +109 -0
  11. package/lib/resolve/passes.ts +68 -11
  12. package/lib/resolve/sibling-locality.ts +150 -0
  13. package/lib/resolve.ts +407 -78
  14. package/lib/scope-retrieval.ts +91 -0
  15. package/lib/span-rescore.ts +65 -14
  16. package/lib/toponym-prior.ts +57 -6
  17. package/out/admin/coherence-passes.js +1 -1
  18. package/out/admin/coherence-passes.js.map +1 -1
  19. package/out/admin/county-designator.d.ts +33 -0
  20. package/out/admin/county-designator.d.ts.map +1 -0
  21. package/out/admin/county-designator.js +65 -0
  22. package/out/admin/county-designator.js.map +1 -0
  23. package/out/admin/former-division.d.ts +47 -0
  24. package/out/admin/former-division.d.ts.map +1 -0
  25. package/out/admin/former-division.js +74 -0
  26. package/out/admin/former-division.js.map +1 -0
  27. package/out/bare-toponym-race.d.ts +1 -1
  28. package/out/bare-toponym-race.d.ts.map +1 -1
  29. package/out/decorate-node.d.ts +22 -3
  30. package/out/decorate-node.d.ts.map +1 -1
  31. package/out/decorate-node.js +85 -1
  32. package/out/decorate-node.js.map +1 -1
  33. package/out/postcode/prefix.d.ts +4 -2
  34. package/out/postcode/prefix.d.ts.map +1 -1
  35. package/out/postcode/prefix.js +7 -13
  36. package/out/postcode/prefix.js.map +1 -1
  37. package/out/postcode/shape-coherence.js +2 -2
  38. package/out/postcode/shape-coherence.js.map +1 -1
  39. package/out/remote-resolver.d.ts.map +1 -1
  40. package/out/remote-resolver.js +1 -1
  41. package/out/remote-resolver.js.map +1 -1
  42. package/out/resolve/parent-place.d.ts +34 -0
  43. package/out/resolve/parent-place.d.ts.map +1 -0
  44. package/out/resolve/parent-place.js +76 -0
  45. package/out/resolve/parent-place.js.map +1 -0
  46. package/out/resolve/passes.d.ts +44 -8
  47. package/out/resolve/passes.d.ts.map +1 -1
  48. package/out/resolve/passes.js +17 -6
  49. package/out/resolve/passes.js.map +1 -1
  50. package/out/resolve/sibling-locality.d.ts +34 -0
  51. package/out/resolve/sibling-locality.d.ts.map +1 -0
  52. package/out/resolve/sibling-locality.js +95 -0
  53. package/out/resolve/sibling-locality.js.map +1 -0
  54. package/out/resolve.d.ts.map +1 -1
  55. package/out/resolve.js +273 -69
  56. package/out/resolve.js.map +1 -1
  57. package/out/scope-retrieval.d.ts +44 -0
  58. package/out/scope-retrieval.d.ts.map +1 -0
  59. package/out/scope-retrieval.js +52 -0
  60. package/out/scope-retrieval.js.map +1 -0
  61. package/out/span-rescore.d.ts +15 -1
  62. package/out/span-rescore.d.ts.map +1 -1
  63. package/out/span-rescore.js +36 -9
  64. package/out/span-rescore.js.map +1 -1
  65. package/out/toponym-prior.d.ts +15 -0
  66. package/out/toponym-prior.d.ts.map +1 -1
  67. package/out/toponym-prior.js +37 -6
  68. package/out/toponym-prior.js.map +1 -1
  69. package/package.json +9 -9
package/lib/resolve.ts CHANGED
@@ -9,10 +9,12 @@
9
9
 
10
10
  import type { ComponentTag } from "@mailwoman/codex/component"
11
11
  import { matchCountry, matchSubdivision } from "@mailwoman/codex/country"
12
- import { DEFAULT_PLACETYPE_MAP, isPlacetypeFallback } from "@mailwoman/codex/placetype-map"
12
+ import { DEFAULT_PLACETYPE_MAP, isPlacetypeFallback } from "@mailwoman/codex/labels/placetype-map"
13
13
  import { collectNodes, isShapeExcludedPostcode, type AddressNode, type AddressTree } from "@mailwoman/core/decoder"
14
14
  import {
15
15
  type DefaultCountry,
16
+ hardCountryOf,
17
+ ScopeStrength,
16
18
  type ResolveNodeTrace,
17
19
  type ResolvedPlace,
18
20
  type ResolveOpts,
@@ -20,6 +22,7 @@ import {
20
22
  type ResolverBackend,
21
23
  resolveSwitches,
22
24
  } from "@mailwoman/core/resolver"
25
+ import { isPresent } from "@mailwoman/core/values/objects"
23
26
  import { countriesFromPostcodeFormat } from "@mailwoman/postcode/postcode-format"
24
27
 
25
28
  import {
@@ -29,6 +32,8 @@ import {
29
32
  applyRegionCountryCoherence,
30
33
  } from "#admin/coherence-passes"
31
34
  import { adminContainmentVerdict, firstRegionQualifier, partitionByContainment } from "#admin/containment"
35
+ import { COUNTY_DESIGNATOR_FALLBACK, countyFromDesignatedLocality } from "#admin/county-designator"
36
+ import { acceptFormerDivisions, FORMER_DIVISION_TAGS } from "#admin/former-division"
32
37
  import { resolveCompoundMunicipality } from "#admin/jp-municipality"
33
38
  import {
34
39
  BARE_REGION_DOMINANCE_LOG10,
@@ -48,6 +53,12 @@ import { type CoordinateOptionalPlace, postcodePrefixResolvedPlace, probePostcod
48
53
  import { applyPostcodeShapeCoherence } from "#postcode/shape-coherence"
49
54
  import { applyCountryCode, readRegionCodeAsCountry } from "#resolve/country-code"
50
55
  import { applyLandmark } from "#resolve/landmark"
56
+ import {
57
+ agreesWithParent,
58
+ applyCallerParentQualifier,
59
+ applyParentPlaceCountry,
60
+ readParentPlace,
61
+ } from "#resolve/parent-place"
51
62
  import {
52
63
  applyPostcodeConsistency,
53
64
  applyRooftopConsistency,
@@ -56,6 +67,7 @@ import {
56
67
  DIAGNOSTIC_BANDS,
57
68
  firstPostcodeValue,
58
69
  NOOP_TRACE_RECORDER,
70
+ type NodeTraceRecorder,
59
71
  type ResolutionState,
60
72
  type ResolvedOpts,
61
73
  } from "#resolve/passes"
@@ -66,7 +78,14 @@ import {
66
78
  applyStreetAsTown,
67
79
  applyVenueAsTown,
68
80
  } from "#resolve/region-city"
81
+ import { applySiblingLocalityContainment } from "#resolve/sibling-locality"
69
82
  import { applyWholeInputPlace } from "#resolve/whole-input"
83
+ import {
84
+ placesOutsideCountryScope,
85
+ promoteSoftCountry,
86
+ retrieveWithSoftCountry,
87
+ softScopeRetrieves,
88
+ } from "#scope-retrieval"
70
89
  import { applyAddressPoint, applyInterpolation, applyStreetCentroid } from "#street/tier"
71
90
  import {
72
91
  type CapitalLevelFn,
@@ -85,6 +104,15 @@ export function createWOFResolver(backend: ResolverBackend): Resolver {
85
104
  return new WOFResolver(backend)
86
105
  }
87
106
 
107
+ /**
108
+ * One lookup's pick: the place, its runners-up, and the metadata the walk stamps on the node.
109
+ */
110
+ interface LookupPick {
111
+ top: CoordinateOptionalPlace
112
+ alternatives: ResolvedPlace[]
113
+ metadata?: Record<string, unknown>
114
+ }
115
+
88
116
  /**
89
117
  * Return an explicit country scope from the tree when it is unambiguous.
90
118
  *
@@ -157,7 +185,12 @@ class WOFResolver implements Resolver {
157
185
  minWinningScore: opts.minWinningScore ?? 0,
158
186
  minScoreRefusals: 0,
159
187
  candidatesPerLookup: opts.candidatesPerLookup ?? 5,
160
- defaultCountry: opts.defaultCountry ?? null,
188
+ // One scope value: a hard scope filters, and a soft one ranks.
189
+ defaultCountry: hardCountryOf(opts.defaultCountry) ? opts.defaultCountry! : null,
190
+ softCountry: opts.defaultCountry?.strength === ScopeStrength.Soft ? opts.defaultCountry : null,
191
+ softCountryWeight: opts.softCountryWeight ?? DEFAULT_COUNTRY_PRIOR_WEIGHT,
192
+ scopeCountryRetrieval: opts.scopeCountryRetrieval,
193
+ parentPlace: opts.parentPlace ? readParentPlace(this.#backend, opts.parentPlace) : null,
161
194
  bareLocalityNode: loneBareLocalityNode(tree, opts.placetypeMap ?? DEFAULT_PLACETYPE_MAP),
162
195
  parentFallback: opts.parentFallback,
163
196
  // Only enable unreachable diagnostics when a trace sink exists.
@@ -175,18 +208,22 @@ class WOFResolver implements Resolver {
175
208
  bias: opts.bias,
176
209
  anchorPosterior: opts.anchorPosterior,
177
210
  anchorWeight: opts.anchorWeight ?? 2,
178
- localeCountryPrior: opts.localeCountryPrior,
179
- localeCountryPriorWeight: opts.localeCountryPriorWeight ?? DEFAULT_COUNTRY_PRIOR_WEIGHT,
180
211
  capitalLevel: opts.capitalLevel,
181
212
  hardCountry: opts.hardCountry,
182
213
  includeAncestors: opts.includeAncestors,
183
214
  // Optional admin containment rerank uses a pre-scanned region qualifier.
184
215
  adminContainmentRerank: opts.adminContainmentRerank,
185
216
  dependentLocalityContainment: opts.dependentLocalityContainment,
217
+ countyDesignatorFallback: opts.countyDesignatorFallback,
218
+ ...(opts.formerDivisions && opts.formerDivisionLookup
219
+ ? { formerDivisionLookup: opts.formerDivisionLookup, pendingFormerDivisions: new Map() }
220
+ : {}),
186
221
  regionQualifier: firstRegionQualifier(tree.roots),
187
222
  ...(opts.traceSink ? { traceSink: opts.traceSink } : {}),
188
223
  }
189
224
 
225
+ applyParentPlaceCountry(state)
226
+
190
227
  // Optional pre-walk postcode-country coherence pass.
191
228
  // This is the only pass allowed to override `defaultCountry`.
192
229
  let postcodeScope: PostcodeCountryScope | null = null
@@ -229,6 +266,14 @@ class WOFResolver implements Resolver {
229
266
  // A later pass that gives one of these nodes a different place removes the walk's ancestors with the old place.
230
267
  const walkedWithAncestors = collectNodes(newRoots, (n) => n.metadata?.["ancestors"] != null)
231
268
 
269
+ if (opts.siblingLocalityContainment) {
270
+ await applySiblingLocalityContainment(newRoots, this.#backend, {
271
+ placetype: state.placetypeMap.locality ?? "locality",
272
+ limit: state.candidatesPerLookup,
273
+ traceSink: state.traceSink ?? null,
274
+ })
275
+ }
276
+
232
277
  // Stamp metadata for postcode-country override.
233
278
  if (postcodeScope) {
234
279
  stampPostcodeCountryScope(newRoots, postcodeScope)
@@ -302,7 +347,14 @@ class WOFResolver implements Resolver {
302
347
  // Span-rescore fallback tier (default on).
303
348
  // Skip when a min-score refusal already occurred.
304
349
  if (opts.spanRescore && state.minScoreRefusals === 0) {
305
- await applySpanRescore(newRoots, tree.raw, this.#backend, opts)
350
+ await applySpanRescore(
351
+ newRoots,
352
+ tree.raw,
353
+ this.#backend,
354
+ // A hard parent's country filters the probes as a caller's default country does.
355
+ state.parentPlace && state.defaultCountry ? { ...opts, defaultCountry: state.defaultCountry } : opts,
356
+ !state.defaultCountry && softScopeRetrieves(state) ? state.softCountry!.country : null
357
+ )
306
358
  }
307
359
 
308
360
  // OpenStreetMap places answer after span rescore, so a town that holds the whole name keeps it.
@@ -325,6 +377,11 @@ class WOFResolver implements Resolver {
325
377
  applyStreetCentroid(newRoots, tree.raw, opts.streetCentroids, opts.streetCountryHints ?? [])
326
378
  }
327
379
 
380
+ // A value no current division answered is accepted when a former division of that name covered the settlement.
381
+ if (state.pendingFormerDivisions?.size && this.#backend.ancestors) {
382
+ acceptFormerDivisions(newRoots, state.pendingFormerDivisions, this.#backend.ancestors.bind(this.#backend))
383
+ }
384
+
328
385
  // The walk's ancestors are read again for the place that replaced its pick.
329
386
  if (this.#backend.ancestors) {
330
387
  for (const node of walkedWithAncestors) {
@@ -377,7 +434,7 @@ class WOFResolver implements Resolver {
377
434
 
378
435
  if (picked) {
379
436
  resolved = picked.top
380
- decorateNode(decorated, picked.top, picked.alternatives)
437
+ decorateNode(decorated, picked.top, picked.alternatives, picked.considered)
381
438
 
382
439
  if (picked.metadata) {
383
440
  decorated.metadata = { ...decorated.metadata, ...picked.metadata }
@@ -388,12 +445,22 @@ class WOFResolver implements Resolver {
388
445
  decorated.tag = "country"
389
446
  } else if (decorated.metadata?.["bare_region_repick"]) {
390
447
  decorated.tag = "region"
448
+ } else if (decorated.metadata?.[COUNTY_DESIGNATOR_FALLBACK]) {
449
+ decorated.tag = "subregion"
391
450
  }
392
451
 
393
452
  // Optional lineage attachment.
394
453
  if (state.includeAncestors && this.#backend.ancestors) {
395
454
  decorated.metadata = { ...decorated.metadata, ancestors: this.#backend.ancestors(picked.top.id) }
396
455
  }
456
+ } else if (state.formerDivisionLookup && FORMER_DIVISION_TAGS.has(node.tag)) {
457
+ // No current division answered, so the value may name a former one, checked after the walk.
458
+ const country = parentResolved?.country ?? state.defaultCountry?.country ?? null
459
+ const matches = state.formerDivisionLookup.divisionsNamed(node.value, country)
460
+
461
+ if (matches.length) {
462
+ state.pendingFormerDivisions!.set(decorated, matches)
463
+ }
397
464
  }
398
465
  }
399
466
 
@@ -439,6 +506,168 @@ class WOFResolver implements Resolver {
439
506
  return found
440
507
  }
441
508
 
509
+ /**
510
+ * A soft scope's own rows merged into an unscoped lookup's candidates, under scope retrieval.
511
+ *
512
+ * It returns `candidates` unchanged without a soft country, when the lookup already
513
+ * has a country, or when the soft scope ranks only.
514
+ */
515
+ async #withSoftCountryRows(
516
+ query: Parameters<ResolverBackend["findPlace"]>[0],
517
+ candidates: ResolvedPlace[],
518
+ softCountry: string | null,
519
+ state: ResolutionState,
520
+ rec: NodeTraceRecorder
521
+ ): Promise<ResolvedPlace[]> {
522
+ if (!softCountry || query.country || !softScopeRetrieves(state)) return candidates
523
+
524
+ rec.check("soft_country_retrieval")
525
+ const merged = await retrieveWithSoftCountry(this.#backend, query, candidates, softCountry)
526
+
527
+ rec.stage("soft_country", merged)
528
+
529
+ return merged
530
+ }
531
+
532
+ /**
533
+ * A hard caller parent's split of the ranked candidates into those its lineage agrees with
534
+ * and the excluded rest, each marked `outsideScope`.
535
+ *
536
+ * Without a hard parent or an ancestors lookup, every candidate is kept.
537
+ */
538
+ #applyHardParent(
539
+ ranked: ResolvedPlace[],
540
+ qualifierIsParent: boolean,
541
+ state: ResolutionState,
542
+ rec: NodeTraceRecorder
543
+ ): { kept: ResolvedPlace[]; excluded: ResolvedPlace[] } {
544
+ const parent = state.parentPlace
545
+
546
+ if (parent?.scope.strength !== ScopeStrength.Hard || !this.#backend.ancestors) return { kept: ranked, excluded: [] }
547
+
548
+ const ancestors = this.#backend.ancestors.bind(this.#backend)
549
+ const agrees = (c: ResolvedPlace) => agreesWithParent(c, parent, ancestors, qualifierIsParent)
550
+ const kept = ranked.filter(agrees)
551
+
552
+ rec.stage("parent_scope", kept)
553
+
554
+ return {
555
+ kept,
556
+ excluded: ranked.filter((c) => !agrees(c)).map((c) => ({ ...c, outsideScope: true as const })),
557
+ }
558
+ }
559
+
560
+ /**
561
+ * The same-name places outside a hard default country, for the node's
562
+ * `considered` list, under scope retrieval.
563
+ *
564
+ * The probe changes no pick, so a backend error is traced and answers no places.
565
+ */
566
+ async #placesOutsideScope(
567
+ query: Parameters<ResolverBackend["findPlace"]>[0],
568
+ state: ResolutionState,
569
+ rec: NodeTraceRecorder
570
+ ): Promise<ResolvedPlace[]> {
571
+ if (!state.scopeCountryRetrieval || !query.country) return []
572
+
573
+ try {
574
+ const outside = await placesOutsideCountryScope(this.#backend, query, query.country)
575
+
576
+ rec.check(`outside_scope: ${outside.length}`)
577
+
578
+ return outside
579
+ } catch (error) {
580
+ rec.check(`outside_scope_error: ${(error as Error).message}`)
581
+
582
+ return []
583
+ }
584
+ }
585
+
586
+ /**
587
+ * The county of a designated `locality` value's name in its region, when the locality
588
+ * lookup found no locality known to be inside that region.
589
+ *
590
+ * A candidate is known inside when the lookup was scoped by the region and kept it,
591
+ * or when the qualifier containment partition marked it contained.
592
+ * A candidate whose containment neither the region scope nor the partition
593
+ * computed keeps the locality pick.
594
+ *
595
+ * A `locality` lookup is region-scoped exactly when its resolved parent has
596
+ * a numeric id (`applyParentScope`).
597
+ */
598
+ async #countyDesignatorPick(
599
+ node: AddressNode,
600
+ placetype: string,
601
+ country: string | undefined,
602
+ candidates: readonly ResolvedPlace[],
603
+ parentResolved: CoordinateOptionalPlace | null,
604
+ state: ResolutionState,
605
+ rec: NodeTraceRecorder
606
+ ): Promise<LookupPick | null> {
607
+ if (!state.countyDesignatorFallback || placetype !== "locality" || node.tag !== "locality" || !country) return null
608
+
609
+ const regionScoped = typeof parentResolved?.id === "number"
610
+
611
+ const inRegion = candidates.some(
612
+ (c) => c.containedByQualifier === true || (regionScoped && c.regionScopeMiss !== true)
613
+ )
614
+
615
+ const unplaced = candidates.some((c) => c.containedByQualifier == null && !regionScoped)
616
+
617
+ if (inRegion || unplaced) return null
618
+
619
+ const parentIsRegion = parentResolved?.placetype === "region" || parentResolved?.placetype === "macroregion"
620
+
621
+ const county = await countyFromDesignatedLocality(this.#backend, node.value, {
622
+ country,
623
+ regionID: parentIsRegion && typeof parentResolved.id === "number" ? parentResolved.id : null,
624
+ regionQualifier: state.regionQualifier ?? null,
625
+ limit: state.candidatesPerLookup,
626
+ })
627
+
628
+ if (!county) return null
629
+
630
+ rec.check(COUNTY_DESIGNATOR_FALLBACK)
631
+ rec.emit({ id: county.top.id, name: county.top.name, source: COUNTY_DESIGNATOR_FALLBACK })
632
+
633
+ return { ...county, metadata: { [COUNTY_DESIGNATOR_FALLBACK]: true } }
634
+ }
635
+
636
+ /**
637
+ * The postcode-prefix prior's pick for a `postalcode` lookup that missed,
638
+ * when the prior is on and the prefix index holds the code's prefix.
639
+ */
640
+ #postcodePrefixPick(
641
+ node: AddressNode,
642
+ placetype: string,
643
+ country: string | undefined,
644
+ candidates: readonly ResolvedPlace[],
645
+ state: ResolutionState,
646
+ rec: NodeTraceRecorder
647
+ ): LookupPick | null {
648
+ if (candidates.length || placetype !== "postalcode" || !state.postcodePrefixPrior || !state.postcodePrefixIndex) {
649
+ return null
650
+ }
651
+
652
+ const probe = probePostcodePrefix(node.value, state.postcodePrefixIndex, country)
653
+
654
+ if (!probe) return null
655
+
656
+ const metadata: Record<string, unknown> = {
657
+ postcode_prefix: probe.prefix,
658
+ postcode_prefix_ancestors: probe.node.ancestors,
659
+ ...(probe.node.radiusP95Km != null ? { postcode_prefix_radius_p95_km: probe.node.radiusP95Km } : {}),
660
+ ...(probe.node.lat != null && probe.node.lon != null ? { coordinate_source: "postcode_prefix" } : {}),
661
+ }
662
+
663
+ rec.check("postcode_prefix_prior")
664
+ const prefixPlace = postcodePrefixResolvedPlace(probe.prefix, probe.node, state.postcodePrefixIndex)
665
+
666
+ rec.emit({ id: prefixPlace.id, name: prefixPlace.name, source: "postcode_prefix" })
667
+
668
+ return { top: prefixPlace, alternatives: [], metadata }
669
+ }
670
+
442
671
  async #lookupAndPick(
443
672
  node: AddressNode,
444
673
  placetype: string,
@@ -447,6 +676,11 @@ class WOFResolver implements Resolver {
447
676
  ): Promise<{
448
677
  top: CoordinateOptionalPlace
449
678
  alternatives: ResolvedPlace[]
679
+ /**
680
+ * The probe winners the pick passed over.
681
+ * Only the geocode result's candidate list reads them.
682
+ */
683
+ considered?: ResolvedPlace[]
450
684
  metadata?: Record<string, unknown>
451
685
  } | null> {
452
686
  state.lookupsRemaining--
@@ -464,6 +698,8 @@ class WOFResolver implements Resolver {
464
698
 
465
699
  const parentContainment = applyParentScope(query, node, parentResolved, state)
466
700
 
701
+ const callerParentQualifies = applyCallerParentQualifier(query, state)
702
+
467
703
  // Country scope precedence: parent -> default -> node hint -> hard country.
468
704
  const countryHint = node.metadata?.["country_hint"]
469
705
 
@@ -490,7 +726,9 @@ class WOFResolver implements Resolver {
490
726
  state.adminContainmentRerank &&
491
727
  placetype === "locality" &&
492
728
  state.regionQualifier != null &&
493
- !isCallerScope(state.defaultCountry)
729
+ !isCallerScope(state.defaultCountry) &&
730
+ // The backend reads one qualifier, and the caller's parent outranks the parsed region.
731
+ !state.parentPlace
494
732
 
495
733
  if (containmentEligible) {
496
734
  query.regionQualifier = state.regionQualifier!
@@ -513,16 +751,31 @@ class WOFResolver implements Resolver {
513
751
 
514
752
  let candidates: ResolvedPlace[]
515
753
 
754
+ // The anchor posterior and both country scopes act on region and locality lookups only.
755
+ const anchorEligible = placetype === "region" || placetype === "locality"
756
+
757
+ // A soft scope ranks a lookup no hard country, tree parent or anchor posterior already scopes.
758
+ const softCountry =
759
+ anchorEligible && !state.defaultCountry && !state.anchorPosterior ? (state.softCountry?.country ?? null) : null
760
+
761
+ // The places a hard scope excluded, reported on `considered`.
762
+ let outsideScope: ResolvedPlace[] = []
763
+
516
764
  // For unconstrained postalcodes, probe format-implied countries only.
517
765
  if (placetype === "postalcode" && !query.country && state.postcodeFormatCountries?.length) {
518
766
  rec.check("postcode_format_probe")
519
767
  let best: ResolvedPlace | null = null
768
+ const countryWinners: ResolvedPlace[] = []
520
769
 
521
770
  for (const impliedCountry of state.postcodeFormatCountries) {
522
771
  try {
523
772
  const hits = await this.#backend.findPlace({ ...query, country: impliedCountry })
524
773
  const top = hits[0]
525
774
 
775
+ if (top) {
776
+ countryWinners.push(top)
777
+ }
778
+
526
779
  // Keep the best per-country winner by score.
527
780
  if (top && (!best || top.score > best.score)) {
528
781
  best = top
@@ -535,7 +788,7 @@ class WOFResolver implements Resolver {
535
788
  if (best) {
536
789
  rec.emit({ id: best.id, name: best.name, source: "postcode_format_probe" })
537
790
 
538
- return { top: best, alternatives: [] }
791
+ return { top: best, alternatives: [], considered: countryWinners.filter((c) => c !== best) }
539
792
  }
540
793
 
541
794
  candidates = []
@@ -557,6 +810,14 @@ class WOFResolver implements Resolver {
557
810
  rec.stage("parent_fallback", candidates)
558
811
  }
559
812
 
813
+ candidates = await this.#withSoftCountryRows(query, candidates, softCountry, state, rec)
814
+
815
+ // Only a lookup the default country filtered reports the same-name places outside it.
816
+ const filteredByDefault =
817
+ anchorEligible && !parentResolved && query.country != null && query.country === defaultCountryForLookup
818
+
819
+ outsideScope = filteredByDefault ? await this.#placesOutsideScope(query, state, rec) : []
820
+
560
821
  // Optional diagnostics: record other bands that can resolve this value.
561
822
  if (!candidates.length && state.diagnoseUnreachable) {
562
823
  rec.reachable(await this.#probeOtherBands(query, placetype))
@@ -570,30 +831,12 @@ class WOFResolver implements Resolver {
570
831
  }
571
832
  }
572
833
 
573
- // Optional postcode-prefix prior when postcode lookup misses.
574
- if (!candidates.length && placetype === "postalcode" && state.postcodePrefixPrior && state.postcodePrefixIndex) {
575
- const probe = probePostcodePrefix(node.value, state.postcodePrefixIndex, query.country)
834
+ // A designated county span resolves as its region's county, and a missed postcode takes the prefix prior.
835
+ const recovered =
836
+ (await this.#countyDesignatorPick(node, placetype, query.country, candidates, parentResolved, state, rec)) ??
837
+ this.#postcodePrefixPick(node, placetype, query.country, candidates, state, rec)
576
838
 
577
- if (probe) {
578
- const metadata: Record<string, unknown> = {
579
- postcode_prefix: probe.prefix,
580
- postcode_prefix_ancestors: probe.node.ancestors,
581
- ...(probe.node.radiusP95Km != null ? { postcode_prefix_radius_p95_km: probe.node.radiusP95Km } : {}),
582
- ...(probe.node.lat != null && probe.node.lon != null ? { coordinate_source: "postcode_prefix" } : {}),
583
- }
584
-
585
- rec.check("postcode_prefix_prior")
586
- const prefixPlace = postcodePrefixResolvedPlace(probe.prefix, probe.node, state.postcodePrefixIndex)
587
-
588
- rec.emit({ id: prefixPlace.id, name: prefixPlace.name, source: "postcode_prefix" })
589
-
590
- return {
591
- top: prefixPlace,
592
- alternatives: [],
593
- metadata,
594
- }
595
- }
596
- }
839
+ if (recovered) return recovered
597
840
 
598
841
  // Bare-toponym race: locality-tagged single spans also probe country/region.
599
842
  const isBareRace = placetype === "locality" && node === state.bareLocalityNode
@@ -605,6 +848,10 @@ class WOFResolver implements Resolver {
605
848
  const bareCountry = isBareRace ? await bareCountryCandidate(this.#backend, node.value, query.country) : null
606
849
  const bareRegion = isBareRace ? await bareRegionCandidate(this.#backend, node.value, query.country) : null
607
850
 
851
+ // The race probes a pick passes over, kept for the geocode result's candidate list.
852
+ const raceLosers = (picked: ResolvedPlace | null): ResolvedPlace[] =>
853
+ [bareCountry, bareRegion].filter(isPresent).filter((probe) => probe !== picked)
854
+
608
855
  if (!candidates.length) {
609
856
  // With no locality candidates, a bare name takes an admin or sub-locality namesake.
610
857
  const pick = isBareRace
@@ -615,7 +862,12 @@ class WOFResolver implements Resolver {
615
862
  rec.check(pick.check)
616
863
  rec.emit({ id: pick.place.id, name: pick.place.name, source: pick.source })
617
864
 
618
- return { top: pick.place, alternatives: [], metadata: pick.metadata }
865
+ return {
866
+ top: pick.place,
867
+ alternatives: [],
868
+ considered: [...raceLosers(pick.place), ...outsideScope],
869
+ metadata: pick.metadata,
870
+ }
619
871
  }
620
872
 
621
873
  rec.emit(null)
@@ -623,53 +875,12 @@ class WOFResolver implements Resolver {
623
875
  return null
624
876
  }
625
877
 
626
- // Optional anchor-based rerank using postcode country posterior.
627
- // Applied to region/locality and kept tier-safe by exact-match first.
628
- const anchorEligible = placetype === "region" || placetype === "locality"
629
- let ranked = candidates
630
-
631
- if (state.anchorPosterior && anchorEligible && candidates.length > 1) {
632
- const post = state.anchorPosterior
633
- const w = state.anchorWeight
634
-
635
- // Within-tier key uses prominence (fallback score) plus posterior boost.
636
- // oxlint-disable-next-line unicorn/no-array-sort -- sorts a freshly-built array. toSorted would double-allocate on a hot path
637
- ranked = [...candidates].sort((a, b) => {
638
- const tier = Number(b.exactMatch ?? false) - Number(a.exactMatch ?? false)
639
-
640
- if (tier !== 0) return tier
641
- // Unknown-country candidates get zero posterior mass.
642
- const aKey = (a.prominence ?? a.score) + w * (a.country ? (post[a.country] ?? 0) : 0)
643
- const bKey = (b.prominence ?? b.score) + w * (b.country ? (post[b.country] ?? 0) : 0)
644
-
645
- return bKey - aKey || b.score - a.score
646
- })
647
-
648
- rec.stage("anchor", ranked)
649
- }
650
-
651
- // Optional locale-country soft prior adds to candidate scores while retaining every candidate.
652
- // Disabled when default country or anchor posterior is present.
653
- if (state.localeCountryPrior && !state.defaultCountry && !state.anchorPosterior && anchorEligible) {
654
- ranked = rankByCountryPrior(ranked, state.localeCountryPrior, state.localeCountryPriorWeight)
655
- rec.stage("locale_prior", ranked)
656
- }
657
-
658
- // Importance-first rerank (skipped when anchor posterior exists).
659
- if (!state.anchorPosterior) {
660
- ranked = rankByImportance(ranked)
661
- rec.stage("importance", ranked)
662
-
663
- // Optional bounded capital promotion.
664
- if (state.capitalLevel) {
665
- ranked = promoteCapitalsWithReceipt(ranked, state.capitalLevel, node)
666
- rec.stage("capital", ranked)
667
- }
668
- }
878
+ const softPromotion = rankByPriors(candidates, anchorEligible, softCountry, node, state, rec)
879
+ let ranked = softPromotion.ranked
669
880
 
670
881
  // Final containment partition.
671
882
  // It reads the address's own qualifier and preserves the exact-match tier.
672
- const qualifierPartition = containmentEligible || parentContainment
883
+ const qualifierPartition = containmentEligible || parentContainment || callerParentQualifies
673
884
 
674
885
  if (qualifierPartition) {
675
886
  ranked = partitionByContainment(
@@ -693,6 +904,18 @@ class WOFResolver implements Resolver {
693
904
  rec.stage("exact_type", ranked)
694
905
  }
695
906
 
907
+ const parentScoped = this.#applyHardParent(ranked, callerParentQualifies, state, rec)
908
+
909
+ ranked = parentScoped.kept
910
+ outsideScope = [...parentScoped.excluded, ...outsideScope]
911
+
912
+ if (!ranked.length) {
913
+ rec.check("parent_scope_excluded_all")
914
+ rec.emit(null)
915
+
916
+ return null
917
+ }
918
+
696
919
  const top = ranked[0]!
697
920
 
698
921
  if (top.score < state.minWinningScore) {
@@ -708,14 +931,24 @@ class WOFResolver implements Resolver {
708
931
  rec.check("bare_country_repick")
709
932
  rec.emit({ id: bareCountry.id, name: bareCountry.name, source: "bare_country" })
710
933
 
711
- return { top: bareCountry, alternatives: ranked, metadata: { bare_country_repick: true } }
934
+ return {
935
+ top: bareCountry,
936
+ alternatives: ranked,
937
+ considered: [...raceLosers(bareCountry), ...outsideScope],
938
+ metadata: { bare_country_repick: true },
939
+ }
712
940
  }
713
941
 
714
942
  if (bareRegion && logPopulation(bareRegion) >= logPopulation(top) + BARE_REGION_DOMINANCE_LOG10) {
715
943
  rec.check("bare_region_repick")
716
944
  rec.emit({ id: bareRegion.id, name: bareRegion.name, source: "bare_region" })
717
945
 
718
- return { top: bareRegion, alternatives: ranked, metadata: { bare_region_repick: true } }
946
+ return {
947
+ top: bareRegion,
948
+ alternatives: ranked,
949
+ considered: [...raceLosers(bareRegion), ...outsideScope],
950
+ metadata: { bare_region_repick: true },
951
+ }
719
952
  }
720
953
 
721
954
  // Stamp fallback quality when a macro-type winner stands in.
@@ -730,6 +963,8 @@ class WOFResolver implements Resolver {
730
963
  const pickMetadata = {
731
964
  ...containmentStamps(qualifierPartition, parentContainment, ranked, top),
732
965
  ...(top.variantAliasExempted === true ? { variant_alias_exemption: true } : {}),
966
+ // The soft scope's promotion moved this place ahead of a larger namesake.
967
+ ...(top === softPromotion.promoted ? { soft_country_promotion: softCountry } : {}),
733
968
  // Mark picks admitted outside resolved parent scope.
734
969
  ...((parentResolved && typeof parentResolved.id === "number" && query.parentID == null) ||
735
970
  top.regionScopeMiss === true
@@ -740,6 +975,7 @@ class WOFResolver implements Resolver {
740
975
  return {
741
976
  top,
742
977
  alternatives: ranked.slice(1),
978
+ considered: [...raceLosers(null), ...outsideScope],
743
979
  ...(Object.keys(pickMetadata).length ? { metadata: pickMetadata } : {}),
744
980
  }
745
981
  }
@@ -795,6 +1031,99 @@ function containmentStamps(
795
1031
  }
796
1032
  }
797
1033
 
1034
+ /**
1035
+ * Ranks a lookup's candidates by its priors in order: the postcode anchor posterior,
1036
+ * the ranking-only soft scope, importance with capital promotion, then the retrieval soft scope.
1037
+ *
1038
+ * `promoted` is the place the retrieval soft scope moved to the lead, or null.
1039
+ */
1040
+ function rankByPriors(
1041
+ candidates: ResolvedPlace[],
1042
+ anchorEligible: boolean,
1043
+ softCountry: string | null,
1044
+ node: AddressNode,
1045
+ state: ResolutionState,
1046
+ rec: NodeTraceRecorder
1047
+ ): { ranked: ResolvedPlace[]; promoted: ResolvedPlace | null } {
1048
+ let ranked = candidates
1049
+
1050
+ // Optional anchor-based rerank using postcode country posterior, kept tier-safe by exact-match first.
1051
+ if (state.anchorPosterior && anchorEligible && candidates.length > 1) {
1052
+ ranked = rankByAnchorPosterior(candidates, state.anchorPosterior, state.anchorWeight)
1053
+ rec.stage("anchor", ranked)
1054
+ ranked = rankWithinPosteriorCountry(ranked, state.capitalLevel, node)
1055
+ rec.stage("importance", ranked)
1056
+ }
1057
+
1058
+ // Without scope retrieval, the soft scope adds to candidate scores ahead of the importance rerank.
1059
+ if (softCountry && !softScopeRetrieves(state)) {
1060
+ ranked = rankByCountryPrior(ranked, softCountry, state.softCountryWeight)
1061
+ rec.stage("locale_prior", ranked)
1062
+ }
1063
+
1064
+ // Importance-first rerank (the posterior branch above runs its own, within the winning country).
1065
+ if (!state.anchorPosterior) {
1066
+ ranked = rankByImportance(ranked)
1067
+ rec.stage("importance", ranked)
1068
+
1069
+ // Optional bounded capital promotion.
1070
+ if (state.capitalLevel) {
1071
+ ranked = promoteCapitalsWithReceipt(ranked, state.capitalLevel, node)
1072
+ rec.stage("capital", ranked)
1073
+ }
1074
+ }
1075
+
1076
+ return promoteSoftCountry(ranked, softCountry, state, rec)
1077
+ }
1078
+
1079
+ /**
1080
+ * Sorts candidates by the postcode country posterior, exact matches first.
1081
+ *
1082
+ * Within a match tier, the key is a candidate's prominence (its score when it has none)
1083
+ * plus `weight` times its country's posterior mass.
1084
+ * A candidate with no country gets no posterior mass.
1085
+ */
1086
+ function rankByAnchorPosterior<
1087
+ T extends Pick<ResolvedPlace, "score" | "country"> & Partial<Pick<ResolvedPlace, "exactMatch" | "prominence">>,
1088
+ >(candidates: readonly T[], posterior: Readonly<Record<string, number>>, weight: number): T[] {
1089
+ const key = (c: T) => (c.prominence ?? c.score) + weight * (c.country ? (posterior[c.country] ?? 0) : 0)
1090
+
1091
+ // oxlint-disable-next-line unicorn/no-array-sort -- sorts a freshly-built array. toSorted would double-allocate on a hot path
1092
+ return [...candidates].sort(
1093
+ (a, b) => Number(b.exactMatch ?? false) - Number(a.exactMatch ?? false) || key(b) - key(a) || b.score - a.score
1094
+ )
1095
+ }
1096
+
1097
+ /**
1098
+ * Reorders the posterior-ranked leader's peers, the candidates in its country and exact-match
1099
+ * tier, by importance and capital promotion, as the path without a posterior ranks them.
1100
+ *
1101
+ * The posterior decides the country.
1102
+ * Within that country this order makes a venue query (`Clayton Post Office, Clayton, WI`)
1103
+ * pick the same locality as its bare form (`Clayton, WI`).
1104
+ */
1105
+ function rankWithinPosteriorCountry<
1106
+ T extends Pick<ResolvedPlace, "score" | "name" | "country" | "lat" | "lon"> &
1107
+ Partial<Pick<ResolvedPlace, "exactMatch" | "importance" | "prominence">>,
1108
+ >(
1109
+ ranked: readonly T[],
1110
+ capitalLevel: CapitalLevelFn | null | undefined,
1111
+ node: { metadata?: Record<string, unknown> | null }
1112
+ ): T[] {
1113
+ const leader = ranked[0]
1114
+
1115
+ if (!leader?.country) return [...ranked]
1116
+
1117
+ const isPeer = (c: T) => c.country === leader.country && (c.exactMatch === true) === (leader.exactMatch === true)
1118
+ let peers = rankByImportance(ranked.filter(isPeer))
1119
+
1120
+ if (capitalLevel) {
1121
+ peers = promoteCapitalsWithReceipt(peers, capitalLevel, node)
1122
+ }
1123
+
1124
+ return [...peers, ...ranked.filter((c) => !isPeer(c))]
1125
+ }
1126
+
798
1127
  /**
799
1128
  * Promote capitals and stamp `capital_promotion` when the leader changes.
800
1129
  * Metadata only.