@mailwoman/resolver 9.0.0 → 9.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/resolve.ts CHANGED
@@ -18,10 +18,13 @@ import type { AddressNode, AddressTree, ComponentTag, Interpretation } from "@ma
18
18
  import {
19
19
  type AddressPointLookup,
20
20
  type CoincidentLocality,
21
+ compareReferential,
21
22
  DEFAULT_PLACETYPE_MAP,
22
23
  type InterpolationLookup,
23
24
  isPlacetypeFallback,
24
25
  type PlacetypeMap,
26
+ type PostcodePrefixIndexLike,
27
+ referentialFromPopulation,
25
28
  type ResolvedPlace,
26
29
  type ResolveOpts,
27
30
  type Resolver,
@@ -36,8 +39,11 @@ import {
36
39
  type PostcodeCountryScope,
37
40
  stampPostcodeCountryScope,
38
41
  } from "./postcode-country-coherence.ts"
42
+ import { type CoordinateOptionalPlace, postcodePrefixResolvedPlace, probePostcodePrefix } from "./postcode-prefix.ts"
43
+ import { applyPostcodeShapeCoherence, isShapeExcludedPostcode } from "./postcode-shape-coherence.ts"
39
44
  import { findRescoreCandidate, hasResolvedPlace, postcodeCodeSubset } from "./span-rescore.ts"
40
45
  import { applyAddressPoint, applyInterpolation, applyStreetCentroid } from "./street-tier.ts"
46
+ import { DEFAULT_COUNTRY_PRIOR_WEIGHT, rankByCountryPrior, rankByImportance } from "./toponym-prior.ts"
41
47
 
42
48
  /**
43
49
  * Build a `Resolver` backed by a `ResolverBackend`. The backend can be any concrete impl structurally compatible with
@@ -59,6 +65,21 @@ interface ResolutionState {
59
65
  * can inject postcode-proximal locality candidates.
60
66
  */
61
67
  postcode?: string
68
+ /**
69
+ * Postcode-containment coherence (#31, Mechanism 2) — forwarded to locality lookups so a coordinate-first backend can
70
+ * re-rank name candidates by proximity to the postcode's own centroid. Opt-in; OFF by default.
71
+ */
72
+ postcodeContainmentCoherence: boolean
73
+ /**
74
+ * Postcode-prefix prior (#31, Mechanism 3) — on a `postalcode` miss, derive the code's prefix and probe
75
+ * `postcodePrefixIndex`. Opt-in; OFF by default.
76
+ */
77
+ postcodePrefixPrior: boolean
78
+ /**
79
+ * The injected PFX1 index (structural — `PostcodePrefixIndexLike`, core/resolver/types.ts). Absent = the prior cannot
80
+ * fire.
81
+ */
82
+ postcodePrefixIndex?: PostcodePrefixIndexLike
62
83
  /**
63
84
  * Proximity-bias points (viewport, user location) — forwarded to every primary lookup.
64
85
  */
@@ -71,6 +92,15 @@ interface ResolutionState {
71
92
  * Weight on the posterior in the locality re-rank. Only used when `anchorPosterior` is set.
72
93
  */
73
94
  anchorWeight: number
95
+ /**
96
+ * #27 locale-country SOFT prior for the bare-toponym admin walk. Undefined = no prior (the shipped default) →
97
+ * byte-stable. See `ResolveOpts.localeCountryPrior` for the calibration and why it ships opt-in.
98
+ */
99
+ localeCountryPrior?: string
100
+ /**
101
+ * Weight of that prior in log10-population units. Only consulted when `localeCountryPrior` is set.
102
+ */
103
+ localeCountryPriorWeight: number
74
104
  /**
75
105
  * #743/#194 confident-placer country as a HARD filter (empty→unresolved, no global retry). Off = undefined.
76
106
  */
@@ -91,7 +121,7 @@ interface ResolutionState {
91
121
  /**
92
122
  * The first region that resolved (its place — for the coincident-roles lookup).
93
123
  */
94
- resolvedRegion: ResolvedPlace | null
124
+ resolvedRegion: CoordinateOptionalPlace | null
95
125
  /**
96
126
  * The decorated region NODE that produced {@link resolvedRegion} — completion pushes the locality interpretation onto
97
127
  * it in place (no synthesized sibling).
@@ -100,17 +130,27 @@ interface ResolutionState {
100
130
  }
101
131
 
102
132
  /**
103
- * Pick the completion locality when an admin maps to several coincident same-name candidates (#405). Population is the
104
- * PRIMARY signal — the principal city is the populous one, and it can sit FARTHER from the admin centroid than a tiny
105
- * same-name hamlet (the Niigata case from #403). Nearest centroid breaks a population tie; a genuine tie (same
106
- * population AND distance) ABSTAINS rather than guess.
133
+ * Pick the completion locality when an admin maps to several coincident same-name candidates (#405). REFERENTIAL
134
+ * likelihood is the PRIMARY signal — the principal city is the populous one, and it can sit FARTHER from the admin
135
+ * centroid than a tiny same-name hamlet (the Niigata case from #403). Nearest centroid breaks a referential tie; a
136
+ * genuine tie (same population AND distance) ABSTAINS rather than guess.
137
+ *
138
+ * ROAD_TO_V9 §2: `compareReferential` is referential DESC with raw population as its own tiebreak, which is the SAME
139
+ * ORDER as the plain `b.population - a.population` it replaced — referential is strictly increasing in population below
140
+ * saturation and constant above it. The abstention check below still reads raw population, deliberately: two megacities
141
+ * that saturate to the same referential score are not tied, and abstaining there would be a new behavior.
107
142
  */
108
143
  function pickCompletion(candidates: readonly CoincidentLocality[]): CoincidentLocality | null {
109
144
  if (!candidates.length) return null
110
145
 
111
146
  if (candidates.length === 1) return candidates[0]!
112
- // oxlint-disable-next-line unicorn/no-array-sort -- sorts a freshly-built array; toSorted would double-allocate on a hot path
113
- const ranked = [...candidates].sort((a, b) => b.population - a.population || a.distanceKm - b.distanceKm)
147
+
148
+ const ranked = [...candidates]
149
+ .map((c) => ({ c, referential: referentialFromPopulation(c.population), population: c.population }))
150
+ // oxlint-disable-next-line unicorn/no-array-sort -- sorts a freshly-built array; toSorted would double-allocate on a hot path
151
+ .sort((a, b) => compareReferential(a, b) || a.c.distanceKm - b.c.distanceKm)
152
+ .map((x) => x.c)
153
+
114
154
  const [first, second] = ranked
115
155
 
116
156
  if (first!.population === second!.population && first!.distanceKm === second!.distanceKm) return null
@@ -128,7 +168,9 @@ function firstPostcodeValue(roots: readonly AddressNode[]): string | undefined {
128
168
  while (stack.length) {
129
169
  const n = stack.pop()!
130
170
 
131
- if (n.tag === "postcode" && n.value.trim().length) return n.value.trim()
171
+ // #31 Mechanism 1: a shape-excluded span keeps its tag but contributes nothing — its code
172
+ // must never become the address's postcode (it would poison the country-scope pass's anchor).
173
+ if (n.tag === "postcode" && !isShapeExcludedPostcode(n) && n.value.trim().length) return n.value.trim()
132
174
  stack.push(...n.children)
133
175
  }
134
176
 
@@ -191,7 +233,12 @@ async function applySpanRescore(
191
233
  children: [],
192
234
  }
193
235
 
194
- decorateNode(node, hit.place, [])
236
+ // #1537: the same-span namesake runner-ups, not an empty list. A name the model reads as a `street`
237
+ // ("Springfield", "Berlin", "Moscow") never reaches the admin walk, so this tier is the ONLY thing that
238
+ // resolves it — and decorating with `[]` meant the geocode path's `candidates` held one entry and the
239
+ // dominance margin `declared_ambiguity` reads was uncomputable for exactly the famous-homonym class.
240
+ // The winner is unchanged (see findRescoreCandidate); this is additive.
241
+ decorateNode(node, hit.place, hit.alternatives)
195
242
  // `rescore_gated` carries the gate's precision signal as an EXPLICIT handle — NOT folded into the
196
243
  // calibrated `confidence`, which would break the isotonic guarantee (a true calibrated 0.83 must not
197
244
  // be confused with a rescore plug-in estimate; DeepSeek 2026-06-23). true = postcode gate fired
@@ -272,7 +319,8 @@ function applyPostcodeConsistency(roots: readonly AddressNode[], gateKm: number)
272
319
  while (findAnchor.length) {
273
320
  const n = findAnchor.pop()!
274
321
 
275
- if (n.tag === "postcode" && isResolvedWithCoord(n)) {
322
+ // #31 Mechanism 1: a shape-excluded span never anchors the consistency re-pick either.
323
+ if (n.tag === "postcode" && !isShapeExcludedPostcode(n) && isResolvedWithCoord(n)) {
276
324
  anchor = { lat: n.lat!, lon: n.lon! }
277
325
 
278
326
  break
@@ -511,6 +559,7 @@ function revertResolverDecoration(node: AddressNode): void {
511
559
  "classifier_source",
512
560
  "classifier_source_id",
513
561
  "resolver_score",
562
+ "resolver_prominence",
514
563
  "resolver_name",
515
564
  "resolver_country",
516
565
  "resolution_quality",
@@ -755,6 +804,15 @@ class WOFResolver implements Resolver {
755
804
  }
756
805
 
757
806
  async resolveTree(tree: AddressTree, opts: ResolveOpts = {}): Promise<AddressTree> {
807
+ // Postcode-shape coherence (#31, Mechanism 1): the earliest pass in the tree — pure-sync and
808
+ // backend-free, run BEFORE `state.postcode` is read so an excluded span can never become the
809
+ // address's postcode. Opt-in (`postcodeShapeCoherence: true`), OFF by default (D-rule: demotion
810
+ // is the failure mode with teeth). A confirmed span's narrowed systems — the intersection of
811
+ // its codex shape with the tree's confident sibling systems — bound the country-scope pass
812
+ // below; a pure subset of codex's own candidate list, so it can only narrow, never widen.
813
+ // See postcode-shape-coherence.ts.
814
+ const shapeVerdict = opts.postcodeShapeCoherence === true ? applyPostcodeShapeCoherence(tree.roots) : null
815
+
758
816
  const state: ResolutionState = {
759
817
  lookupsRemaining: opts.maxLookups ?? 10,
760
818
  // Full replacement when `placetypeMap` is supplied — callers that want to extend rather
@@ -765,9 +823,16 @@ class WOFResolver implements Resolver {
765
823
  defaultCountry: opts.defaultCountry,
766
824
  parentFallback: opts.parentFallback ?? true,
767
825
  postcode: firstPostcodeValue(tree.roots),
826
+ // #31 Mechanism 2 — forwarded to locality lookups (see #lookupAndPick). Opt-in, OFF by default.
827
+ postcodeContainmentCoherence: opts.postcodeContainmentCoherence === true,
828
+ // #31 Mechanism 3 — the prefix prior + its injected index (see #lookupAndPick). Opt-in, OFF by default.
829
+ postcodePrefixPrior: opts.postcodePrefixPrior === true,
830
+ postcodePrefixIndex: opts.postcodePrefixIndex,
768
831
  bias: opts.bias,
769
832
  anchorPosterior: opts.anchorPosterior,
770
833
  anchorWeight: opts.anchorWeight ?? 2,
834
+ localeCountryPrior: opts.localeCountryPrior,
835
+ localeCountryPriorWeight: opts.localeCountryPriorWeight ?? DEFAULT_COUNTRY_PRIOR_WEIGHT,
771
836
  hardCountry: opts.hardCountry,
772
837
  // Default-ON (#402): completion only fires for a dual-role region whose locality the parser
773
838
  // dropped, and no-ops entirely when the backend has no relation (the browser WASM resolver, or
@@ -779,14 +844,15 @@ class WOFResolver implements Resolver {
779
844
  resolvedRegionNode: null,
780
845
  }
781
846
 
782
- // Postcode-country coherence (#42): the ONE pre-walk pass, and the only mechanism allowed to override
783
- // `defaultCountry`. Its three sibling coherence passes re-pick nodes AFTER the walk; that shape cannot
784
- // work here, because what needs correcting is the walk's country SCOPE — which poisons the postcode
785
- // node's own resolution, the postcode-consistency fallback that then drags the locality onto it, and
786
- // the hard `country` filter on every admin lookup. So the verdict is taken once, up front, and the
787
- // walk runs under the corrected country. Default-ON (operator-promoted 2026-08-05; `false` opts out) —
788
- // needs a default country to correct and both a postcode and a locality to be coherent about; abstains
789
- // unless EXACTLY one country (never the already-coherent default) makes the pair consistent. See
847
+ // Postcode-country coherence (#42): the one pre-walk LOOKUP pass (the shape verdict above is
848
+ // pure-sync, backend-free), and the only mechanism allowed to override `defaultCountry`. Its three
849
+ // sibling coherence passes re-pick nodes AFTER the walk; that shape cannot work here, because what
850
+ // needs correcting is the walk's country SCOPE — which poisons the postcode node's own resolution,
851
+ // the postcode-consistency fallback that then drags the locality onto it, and the hard `country`
852
+ // filter on every admin lookup. So the verdict is taken once, up front, and the walk runs under the
853
+ // corrected country. Default-ON (operator-promoted 2026-08-05; `false` opts out) — needs a default
854
+ // country to correct and both a postcode and a locality to be coherent about; abstains unless
855
+ // EXACTLY one country (never the already-coherent default) makes the pair consistent. See
790
856
  // postcode-country-coherence.ts.
791
857
  let postcodeScope: PostcodeCountryScope | null = null
792
858
 
@@ -794,6 +860,7 @@ class WOFResolver implements Resolver {
794
860
  postcodeScope = await findPostcodeCountryScope(tree.roots, this.#backend, {
795
861
  postcode: state.postcode,
796
862
  defaultCountry: state.defaultCountry,
863
+ ...(shapeVerdict?.narrowing !== undefined ? { candidateSystems: shapeVerdict.narrowing } : {}),
797
864
  ...(opts.postcodeCountryCoherenceGateKm !== undefined ? { gateKm: opts.postcodeCountryCoherenceGateKm } : {}),
798
865
  })
799
866
 
@@ -873,6 +940,15 @@ class WOFResolver implements Resolver {
873
940
  await applySpanRescore(newRoots, tree.raw, this.#backend, opts)
874
941
  }
875
942
 
943
+ // A failed admin walk can leave the exact-point tier without a locality even though span-rescore
944
+ // recovers one immediately afterward (for example, a locality the model tagged as `region`). Give
945
+ // the exact register one bounded retry with that newly established scope. An existing situs hit is
946
+ // returned early by applyAddressPoint, so the normal path performs no duplicate lookup; interpolation
947
+ // remains subordinate because an exact point is allowed to replace its estimate.
948
+ if (opts.addressPoints) {
949
+ applyAddressPoint(newRoots, opts.addressPoints, opts.addressPointBboxFallback)
950
+ }
951
+
876
952
  // Street-centroid tier (#1042): LAST, after span-rescore, so it can (a) union the span-rescore-recovered
877
953
  // country into its FR/national country hints (a placer-misrouted street — "Rue Sainte-Catherine" → IT — leaves
878
954
  // admin unresolved, and only span-rescore recovers the FR country signal) and (b) override a coarse recovered
@@ -893,7 +969,7 @@ class WOFResolver implements Resolver {
893
969
  * relation, the region isn't a dual-role place, or it abstains. The region node's primary role stays `region`; the
894
970
  * locality rides alongside.
895
971
  */
896
- #completeRegionRole(region: ResolvedPlace, regionNode: AddressNode): void {
972
+ #completeRegionRole(region: CoordinateOptionalPlace, regionNode: AddressNode): void {
897
973
  if (typeof region.id !== "number" || !this.#backend.coincidentLocalitiesFor) return
898
974
  const loc = pickCompletion(this.#backend.coincidentLocalitiesFor(region.id))
899
975
 
@@ -912,7 +988,11 @@ class WOFResolver implements Resolver {
912
988
  regionNode.interpretations = [...(regionNode.interpretations ?? []), interpretation]
913
989
  }
914
990
 
915
- async #walk(node: AddressNode, parentResolved: ResolvedPlace | null, state: ResolutionState): Promise<AddressNode> {
991
+ async #walk(
992
+ node: AddressNode,
993
+ parentResolved: CoordinateOptionalPlace | null,
994
+ state: ResolutionState
995
+ ): Promise<AddressNode> {
916
996
  // Always clone — never mutate input nodes.
917
997
  const decorated: AddressNode = { ...node, children: [] }
918
998
 
@@ -925,15 +1005,22 @@ class WOFResolver implements Resolver {
925
1005
  state.localityNodePresent = true
926
1006
  }
927
1007
 
928
- let resolved: ResolvedPlace | null = null
1008
+ let resolved: CoordinateOptionalPlace | null = null
929
1009
 
930
- if (placetype && state.lookupsRemaining > 0 && node.value.trim().length) {
1010
+ // Shape-excluded postcode spans (letter-bearing ones keep their tag; #31 Mechanism 1) are
1011
+ // stripped of their resolve contribution — the walk does not look them up. Digit-only excluded
1012
+ // spans were retagged to `house_number` and flow through their correct sibling placetype.
1013
+ if (placetype && state.lookupsRemaining > 0 && node.value.trim().length && !isShapeExcludedPostcode(node)) {
931
1014
  const picked = await this.#lookupAndPick(node, placetype, parentResolved, state)
932
1015
 
933
1016
  if (picked) {
934
1017
  resolved = picked.top
935
1018
  decorateNode(decorated, picked.top, picked.alternatives)
936
1019
 
1020
+ if (picked.metadata) {
1021
+ decorated.metadata = { ...decorated.metadata, ...picked.metadata }
1022
+ }
1023
+
937
1024
  // Lineage attachment (#404): stamp the resolved place's ancestor chain onto metadata. Opt-in
938
1025
  // + only when the backend supplies it, so the default stays byte-identical (no extra query).
939
1026
  if (state.includeAncestors && this.#backend.ancestors) {
@@ -961,9 +1048,13 @@ class WOFResolver implements Resolver {
961
1048
  async #lookupAndPick(
962
1049
  node: AddressNode,
963
1050
  placetype: string,
964
- parentResolved: ResolvedPlace | null,
1051
+ parentResolved: CoordinateOptionalPlace | null,
965
1052
  state: ResolutionState
966
- ): Promise<{ top: ResolvedPlace; alternatives: ResolvedPlace[] } | null> {
1053
+ ): Promise<{
1054
+ top: CoordinateOptionalPlace
1055
+ alternatives: ResolvedPlace[]
1056
+ metadata?: Record<string, unknown>
1057
+ } | null> {
967
1058
  state.lookupsRemaining--
968
1059
 
969
1060
  const query: Parameters<ResolverBackend["findPlace"]>[0] = {
@@ -998,14 +1089,16 @@ class WOFResolver implements Resolver {
998
1089
  // collapses the tail (FI 18 km, PL p99 8172→494) at a coverage-bounded recall cost.
999
1090
  // #833 forward linkage: a node's own `country_hint` (an address-system recognizer's derived country —
1000
1091
  // today `recognizeUSRegions` stamping "US" on a recognized closed-set US state) constrains THIS node's
1001
- // lookup, below a resolved parent's country but above the global defaults. It breaks the two-consistent-
1002
- // pairs tie ("Augusta, ME" → Maine, not Augusta/Messina) that pure geographic consistency cannot.
1092
+ // lookup when the caller supplied no locale/default country. A caller scope outranks this derived hint:
1093
+ // `WA` is both Washington and Western Australia, so en-AU must reach the AU candidate instead of being
1094
+ // overwritten by the US-only recognizer. A genuine foreign subdivision under the wrong locale is recovered
1095
+ // later by region-country coherence after the scoped lookup abstains.
1003
1096
  const countryHint = node.metadata?.["country_hint"]
1004
1097
 
1005
1098
  const country =
1006
1099
  parentResolved?.country ??
1007
- (typeof countryHint === "string" ? countryHint : undefined) ??
1008
1100
  state.defaultCountry ??
1101
+ (typeof countryHint === "string" ? countryHint : undefined) ??
1009
1102
  state.hardCountry
1010
1103
 
1011
1104
  if (country) {
@@ -1014,9 +1107,15 @@ class WOFResolver implements Resolver {
1014
1107
 
1015
1108
  // Coordinate-first: hand the sibling postcode to locality lookups so the backend can inject
1016
1109
  // postcode-proximal candidates the name-match would miss. Only for locality (the placetype both
1017
- // `locality` and `dependent_locality` map to); other placetypes ignore it.
1110
+ // `locality` and `dependent_locality` map to); other placetypes ignore it. The containment flag
1111
+ // (#31, Mechanism 2) asks a coordinate-first backend to re-rank the candidates by proximity to
1112
+ // the postcode's own centroid — opt-in, OFF by default.
1018
1113
  if (placetype === "locality" && state.postcode) {
1019
1114
  query.postcode = state.postcode
1115
+
1116
+ if (state.postcodeContainmentCoherence) {
1117
+ query.postcodeContainmentCoherence = true
1118
+ }
1020
1119
  }
1021
1120
 
1022
1121
  let candidates: ResolvedPlace[]
@@ -1040,6 +1139,33 @@ class WOFResolver implements Resolver {
1040
1139
  return null
1041
1140
  }
1042
1141
 
1142
+ // Postcode-prefix prior (#31, Mechanism 3): when a `postalcode` node misses the gazetteer, derive
1143
+ // the code's prefix and probe the injected PFX1 index (structural — never a model input). A hit
1144
+ // resolves the node to a synthetic place (id 0), carrying a coordinate ONLY when the index node
1145
+ // does — the ancestry-only tier stays coordinate-free (B3-3's 0% half, meaning-of-zero). The
1146
+ // prior's payload is returned as node metadata for #walk to stamp. Opt-in via `postcodePrefixPrior`
1147
+ // + `postcodePrefixIndex`; OFF by default (D-rule: the PCN1 posture).
1148
+ if (!candidates.length && placetype === "postalcode" && state.postcodePrefixPrior && state.postcodePrefixIndex) {
1149
+ const probe = probePostcodePrefix(node.value, state.postcodePrefixIndex, query.country)
1150
+
1151
+ if (probe) {
1152
+ const metadata: Record<string, unknown> = {
1153
+ postcode_prefix: probe.prefix,
1154
+ postcode_prefix_ancestors: probe.node.ancestors,
1155
+ ...(probe.node.radiusP95Km !== undefined ? { postcode_prefix_radius_p95_km: probe.node.radiusP95Km } : {}),
1156
+ ...(probe.node.lat !== undefined && probe.node.lon !== undefined
1157
+ ? { coordinate_source: "postcode_prefix" }
1158
+ : {}),
1159
+ }
1160
+
1161
+ return {
1162
+ top: postcodePrefixResolvedPlace(probe.prefix, probe.node, state.postcodePrefixIndex),
1163
+ alternatives: [],
1164
+ metadata,
1165
+ }
1166
+ }
1167
+ }
1168
+
1043
1169
  if (!candidates.length) return null
1044
1170
  // Postcode-anchor re-rank (#369): when a country posterior is supplied (from the address's
1045
1171
  // postcode), boost candidates by `anchorWeight * posterior[candidate.country]` and re-sort, so a
@@ -1091,6 +1217,40 @@ class WOFResolver implements Resolver {
1091
1217
  })
1092
1218
  }
1093
1219
 
1220
+ // Locale-country soft prior (#27) — the #912 lever's other half, at the tier that decides a bare
1221
+ // toponym the model tagged `locality`. `--locale en-GB "Whitby"` answers Whitby, Ontario while
1222
+ // `--default-country GB "Whitby"` answers the gold, because the CLI DROPS the locale-inferred
1223
+ // country for this shape rather than choosing between "hard filter" and "nothing". This is the
1224
+ // third option: an additive bonus inside the exact tier, never a filter.
1225
+ //
1226
+ // Three stand-downs, in the order they matter. A `defaultCountry` makes the prior a no-op by
1227
+ // construction (every candidate is already in it), so we skip the work rather than pretend. An
1228
+ // `anchorPosterior` is derived from the address's OWN postcode — evidence, which outranks a guess
1229
+ // about where the user is sitting. And an absent prior is the SHIPPED default: `ResolveOpts`
1230
+ // documents why (the weight that flips the four bare GB rows and the weight that holds the en-US
1231
+ // board are disjoint intervals), so this is inert unless a caller opts in.
1232
+ //
1233
+ // Runs BEFORE the importance key deliberately, matching span-rescore: fame is the stronger signal
1234
+ // wherever it has been measured, and it leaves an unscored candidate exactly where the prior put it.
1235
+ if (state.localeCountryPrior && !state.defaultCountry && !state.anchorPosterior && anchorEligible) {
1236
+ ranked = rankByCountryPrior(ranked, state.localeCountryPrior, state.localeCountryPriorWeight)
1237
+ }
1238
+
1239
+ // Importance-first (#17/#28). Before this key a bare famous name was decided on POPULATION
1240
+ // alone, which is measurably the wrong prior for the class: `Whitby` answered Whitby, Ontario
1241
+ // (128,377) over Whitby, North Yorkshire (13,130), 5,508 km from where the person meant. Fame is
1242
+ // what a bare toponym is asking about, and the candidate build's blended `importance` column
1243
+ // measures it. Tier-safe and positive-evidence-only (an UNSCORED candidate keeps the rank
1244
+ // population gave it; only the scored ones permute), so it abstains byte-stably on an artifact
1245
+ // that predates the column.
1246
+ //
1247
+ // Skipped outright when an anchor posterior is in force. Fame is the prior of LAST resort: it answers
1248
+ // "which one did you probably mean" only when nothing in the query answered it, and a #369 posterior is
1249
+ // derived from the address's OWN postcode. Evidence outranks a prior. See `toponym-prior.ts`.
1250
+ if (!state.anchorPosterior) {
1251
+ ranked = rankByImportance(ranked)
1252
+ }
1253
+
1094
1254
  // Exact-type preference (#718): when the placetype-equivalence group let a broader admin tier
1095
1255
  // (`macroregion`/`macrocounty`) into the candidate pool, prefer a candidate of the EXACT
1096
1256
  // requested type over the macro fallback — a real `region` (US state, DE Bundesland, ES
@@ -1129,7 +1289,7 @@ class WOFResolver implements Resolver {
1129
1289
  * assertion. Surfaces the runner-up candidates on `alternatives` so callers can disambiguate (Springfield-class
1130
1290
  * failures, [#8 in the failure catalogue]).
1131
1291
  */
1132
- function decorateNode(node: AddressNode, resolved: ResolvedPlace, alternatives: ResolvedPlace[]): void {
1292
+ function decorateNode(node: AddressNode, resolved: CoordinateOptionalPlace, alternatives: ResolvedPlace[]): void {
1133
1293
  if (node.source !== undefined || node.sourceID !== undefined) {
1134
1294
  const meta = { ...node.metadata }
1135
1295
 
@@ -1155,6 +1315,15 @@ function decorateNode(node: AddressNode, resolved: ResolvedPlace, alternatives:
1155
1315
  // the right PLACE (gazetteer-name vs ground-truth) rather than merely echoing the parser's text.
1156
1316
  node.metadata = { ...node.metadata, resolver_score: resolved.score, resolver_name: resolved.name }
1157
1317
 
1318
+ // The winner's PROMINENCE, when the backend computed one. `alternatives` below are full `ResolvedPlace`s and
1319
+ // already carry theirs; without this stamp the WINNER's is the one value in the ranked list that gets dropped,
1320
+ // which makes a top-1-vs-top-2 margin uncomputable from the tree — and that margin is what
1321
+ // `mailwoman/query-intent.ts` reads to decide whether a bare-toponym answer was a clear win. Additive metadata
1322
+ // only; nothing in the resolve reads it back.
1323
+ if (resolved.prominence !== undefined) {
1324
+ node.metadata["resolver_prominence"] = resolved.prominence
1325
+ }
1326
+
1158
1327
  // The resolved place's ISO-3166 alpha-2 country (from the gazetteer/candidate row), when known. #1014: lets a
1159
1328
  // forward consumer fill country/countrycode without an ancestry walk — the candidate backend carries this even
1160
1329
  // though it has no `ancestors()` table.
@@ -1162,6 +1331,24 @@ function decorateNode(node: AddressNode, resolved: ResolvedPlace, alternatives:
1162
1331
  node.metadata["resolver_country"] = resolved.country
1163
1332
  }
1164
1333
 
1334
+ // The score-channel carries (ROAD_TO_V9 §2 + #28). Written ONLY when the backend actually has a
1335
+ // value: an absent score means "unmeasured" or "pre-split gazetteer", and a `resolver_*: 0` on the
1336
+ // node would assert a measurement nobody made. Nothing in the resolve path reads these keys back —
1337
+ // they exist for annotation / API surfaces downstream. `resolver_importance` is the blended #28
1338
+ // prior (the value the ranking consulted); `resolver_encyclopedic` is the strict channel, reserved
1339
+ // until a strict-channel source ships.
1340
+ if (resolved.referential !== undefined) {
1341
+ node.metadata["resolver_referential"] = resolved.referential
1342
+ }
1343
+
1344
+ if (resolved.encyclopedic !== undefined) {
1345
+ node.metadata["resolver_encyclopedic"] = resolved.encyclopedic
1346
+ }
1347
+
1348
+ if (resolved.importance !== undefined) {
1349
+ node.metadata["resolver_importance"] = resolved.importance
1350
+ }
1351
+
1165
1352
  // The postcode/locality conflict flag (the falsehood differentiator): the postcode pointed to a
1166
1353
  // geographically different place than the parsed city name. Surface it so callers can warn rather
1167
1354
  // than silently trust the resolved point.
package/span-rescore.ts CHANGED
@@ -29,6 +29,8 @@ import type { AddressNode } from "@mailwoman/core/decoder"
29
29
  import type { ResolvedPlace, ResolverBackend } from "@mailwoman/core/resolver"
30
30
  import { haversineKm } from "@mailwoman/spatial"
31
31
 
32
+ import { DEFAULT_COUNTRY_PRIOR_WEIGHT, rankByCountryPrior, rankByImportance } from "./toponym-prior.ts"
33
+
32
34
  export interface SpanRescoreOptions {
33
35
  /**
34
36
  * ISO-3166 alpha-2 country to constrain the gazetteer match (the parse's detected/ default country).
@@ -60,6 +62,17 @@ export interface SpanRescoreOptions {
60
62
  * France" guard). Default false.
61
63
  */
62
64
  postalCompoundRecovery?: boolean
65
+ /**
66
+ * #17 bare-toponym soft country. When the span covers the WHOLE unqualified input, treat {@link country} as an
67
+ * additive prior instead of a hard gazetteer filter (see the block comment on {@link findRescoreCandidate}'s bare
68
+ * branch). Default true; `false` restores the hard filter byte-for-byte.
69
+ */
70
+ bareToponymSoftCountry?: boolean
71
+ /**
72
+ * Weight of that prior, in log10-population units. Default {@link DEFAULT_COUNTRY_PRIOR_WEIGHT} (2). A large value
73
+ * makes the country effectively hard again without changing the code path; 0 removes the locale's say entirely.
74
+ */
75
+ bareToponymCountryWeight?: number
63
76
  }
64
77
 
65
78
  /**
@@ -88,6 +101,23 @@ export interface RescoreCandidate {
88
101
  * calibrated 0.83 must not be confused with a rescore plug-in estimate).
89
102
  */
90
103
  gated: boolean
104
+ /**
105
+ * The SAME-SPAN namesake runner-ups — the other exact-name matches this recovery's own lookup already returned, in
106
+ * the backend's rank order, minus the winner and minus anything the postcode gate rejected. Empty when the span named
107
+ * exactly one place.
108
+ *
109
+ * #1537: these were being discarded. A name the model reads as a `street` ("Springfield", "Berlin", "Manchester",
110
+ * "Moscow", "Fulda") never reaches the admin walk, so the whole tree comes back unresolved and THIS tier is what
111
+ * recovers it — and it decorated the injected node with no alternatives at all. The result was that the geocode
112
+ * path's `candidates` array held one entry, and the top-1-vs-top-2 dominance margin that `declared_ambiguity` reads
113
+ * was uncomputable, for exactly the famous-homonym class that marker exists for. Measured on the shipped candidate
114
+ * backend, 2026-08-07: those five queries returned 1 candidate each while `Cambridge`/`Athens`/`Paris` — the same
115
+ * class, but parsed as `locality` — returned 4-5.
116
+ *
117
+ * The winner is unchanged by their presence: the pick is still the first gate-passing exact match, and these are the
118
+ * ones that came after it. This costs no extra query — they were in the same `findPlace` response.
119
+ */
120
+ alternatives: ResolvedPlace[]
91
121
  }
92
122
 
93
123
  /**
@@ -135,6 +165,44 @@ export function postcodeCodeSubset(postcode: string): string {
135
165
  .trim()
136
166
  }
137
167
 
168
+ /**
169
+ * Over-fetch for the #17 bare-toponym probe. Without a country filter the top 5 worldwide bearers of a common name are
170
+ * often all in one country, and the candidate the soft prior exists to promote sits below the fold — "Warwick" puts
171
+ * five US rows ahead of Warwick, Warwickshire. The backend orders by the same population key either way, so a wider
172
+ * window only admits more of the same list.
173
+ */
174
+ const BARE_TOPONYM_FETCH = 20
175
+
176
+ /**
177
+ * True when the tree names its OWN admin context — a region, subregion, country, postcode or house number the parser
178
+ * read out of the input. Such a query is not relying on a locale guess, so the #17 soft-country prior stands down and
179
+ * the hard filter keeps its say: this is what holds 'Berlin, Wisconsin' on Berlin, Wisconsin.
180
+ */
181
+ function hasAdminQualifier(roots: readonly AddressNode[]): boolean {
182
+ const stack: AddressNode[] = [...roots]
183
+
184
+ while (stack.length) {
185
+ const n = stack.pop()!
186
+
187
+ if (
188
+ (n.tag === "region" ||
189
+ n.tag === "subregion" ||
190
+ n.tag === "country" ||
191
+ n.tag === "postcode" ||
192
+ n.tag === "house_number") &&
193
+ n.value.trim().length
194
+ ) {
195
+ return true
196
+ }
197
+
198
+ if (n.children?.length) {
199
+ stack.push(...n.children)
200
+ }
201
+ }
202
+
203
+ return false
204
+ }
205
+
138
206
  /**
139
207
  * True if any node in the tree already carries a resolved place id — the #685 brake.
140
208
  */
@@ -279,19 +347,81 @@ export async function findRescoreCandidate(
279
347
 
280
348
  spans.sort((a, b) => b.len - a.len)
281
349
 
350
+ // #17 bare-toponym soft country. The caller's `country` is a LOCALE DEFAULT, not knowledge — the #961
351
+ // block below already says so, and for a bare city name it is the ONLY country signal there is, which
352
+ // makes hard-filtering on it the worst possible use of it. Measured through the compiled CLI on
353
+ // 2026-08-10: `--locale en-US 'Zürich'` returned Zurich, Kansas (population 81) 8,043 km off, and
354
+ // `--locale en-GB 'Zürich'` returned nothing at all, because GB holds no Zurich to filter down to.
355
+ //
356
+ // So for this ONE query shape the filter is demoted to an additive prior: probe the gazetteer
357
+ // unscoped, then rank with `rankByCountryPrior` so an in-country place may be up to 100x smaller and
358
+ // still win. This is the #912 lever ("Paris under en-US must not be hard-scoped to Paris, Texas")
359
+ // applied at the tier that actually decides the class — #912 lives upstream in the CLI and keys on a
360
+ // `locality`-tagged tree, but the model reads a bare famous name as a `street`, so the shape that
361
+ // needs it most is exactly the shape that guard cannot see.
362
+ //
363
+ // The shape gate is deliberately narrow. `qualified` below is the D-rule guard: a postcode, a region,
364
+ // a country or a house number in the tree means the address named its own context and a locale guess
365
+ // is no longer the only evidence — 'Berlin, Wisconsin' keeps resolving to Berlin, Wisconsin. And the
366
+ // span must cover the WHOLE input: a sub-span of a longer query is not a bare toponym, so
367
+ // "Weimar Thüringen" falls back to the country-scoped probe that lands the gold.
368
+ const softCountry = opts.bareToponymSoftCountry !== false
369
+ const countryWeight = opts.bareToponymCountryWeight ?? DEFAULT_COUNTRY_PRIOR_WEIGHT
370
+ const qualified = !!postcode || hasAdminQualifier(roots)
371
+ const wholeInput = toks.length ? { start: toks[0]!.start, end: toks.at(-1)!.end } : null
372
+ // Everything the prior needs EXCEPT the span itself — hoisted so the per-span test is one comparison.
373
+ const softCountryEligible = softCountry && !!country && !qualified && !!wholeInput
374
+
282
375
  for (const sp of spans) {
283
376
  const key = norm(sp.text)
284
377
 
285
378
  if (key.length < 2 || /^\d+$/.test(key)) continue // skip bare numbers / empties
286
- const hits = await backend.findPlace({ text: sp.text, country, postcode, placetype: "locality", limit: 5 })
287
- const exact = hits.filter((h) => h.exactMatch && norm(h.name) === key && (h.lat !== 0 || h.lon !== 0))
379
+ const bare = softCountryEligible && sp.start === wholeInput!.start && sp.end === wholeInput!.end
380
+
381
+ const hits = bare
382
+ ? rankByCountryPrior(
383
+ await backend.findPlace({ text: sp.text, postcode, placetype: "locality", limit: BARE_TOPONYM_FETCH }),
384
+ country,
385
+ countryWeight
386
+ )
387
+ : await backend.findPlace({ text: sp.text, country, postcode, placetype: "locality", limit: 5 })
388
+
389
+ // #1546: NO primary-name re-check here — the backend's `exactMatch` IS the name-OR-alias surface
390
+ // equality (the names table / alt_names bag), so a query matches a place when ANY stored name
391
+ // equals it. Re-comparing only the PRIMARY name folded to [a-z0-9 ] excluded exactly the
392
+ // non-Latin-primary class: Москва folds to "" and could never equal "moscow", so Moscow RU never
393
+ // entered the list and Moscow, Idaho won by default among the Latin-named bearers — population-
394
+ // first ranking starved, not violated. The alias surface is the recall; ranking then does its job.
395
+ // The postcode gate below still applies to every admitted candidate, Moscow RU included.
396
+ //
397
+ // #17: importance-first WITHIN the admitted set. The key is the #28 blended fame prior
398
+ // (`PlaceCandidate.importance`, produced by the candidate build) — the only key that separates
399
+ // the bare GB panel rows; on an artifact predating the column it abstains and changes no pick.
400
+ // See `toponym-prior.ts`. It runs after the country prior deliberately: fame is the stronger
401
+ // signal when it has been measured, and leaves an unscored candidate exactly where population
402
+ // put it.
403
+ const exact = rankByImportance(hits.filter((h) => h.exactMatch && (h.lat !== 0 || h.lon !== 0)))
404
+
405
+ const withinGate = (p: ResolvedPlace): boolean =>
406
+ !anchor || gateKm <= 0 || haversineKm(anchor.lat, anchor.lon, p.lat, p.lon) <= gateKm
288
407
 
289
408
  for (const h of exact) {
290
- if (anchor && gateKm > 0 && haversineKm(anchor.lat, anchor.lon, h.lat, h.lon) > gateKm) continue
409
+ if (!withinGate(h)) continue
291
410
 
292
411
  // gated = the postcode anchor existed AND validated this match (within gateKm). When no anchor
293
412
  // (no postcode→point coverage), the match is ungated — returned, but flagged lower-precision.
294
- return { text: sp.text, start: sp.start, end: sp.end, place: h, gated: anchor !== null }
413
+ //
414
+ // #1537: carry the rest of the SAME lookup's exact matches as the namesake runner-ups. Gate-filtered on the
415
+ // same rule as the winner — a candidate the postcode gate rejected is not a namesake worth offering, it is a
416
+ // place the evidence already excluded. Rank order is the backend's, preserved by `filter`.
417
+ return {
418
+ text: sp.text,
419
+ start: sp.start,
420
+ end: sp.end,
421
+ place: h,
422
+ gated: anchor !== null,
423
+ alternatives: exact.filter((a) => a !== h && withinGate(a)),
424
+ }
295
425
  }
296
426
  }
297
427
 
@@ -312,7 +442,10 @@ export async function findRescoreCandidate(
312
442
 
313
443
  if (key.length < 2 || /^\d+$/.test(key)) continue
314
444
  const hits = await backend.findPlace({ text: sp.text, placetype: "locality", limit: 5 })
315
- const exact = hits.filter((h) => h.exactMatch && norm(h.name) === key && (h.lat !== 0 || h.lon !== 0))
445
+ // #1546: same alias-surface admission as the scoped pass — `exactMatch` is name-OR-alias, so a
446
+ // non-Latin primary (Москва) admitted via its Latin alias stays eligible here too. The
447
+ // per-candidate postcode verification below remains the sole admission bar.
448
+ const exact = hits.filter((h) => h.exactMatch && (h.lat !== 0 || h.lon !== 0))
316
449
 
317
450
  for (const h of exact) {
318
451
  if (!h.country || h.country === country) continue
@@ -328,7 +461,12 @@ export async function findRescoreCandidate(
328
461
  const verified = pcHits.find((p) => p.lat !== 0 || p.lon !== 0)
329
462
 
330
463
  if (verified && haversineKm(verified.lat, verified.lon, h.lat, h.lon) <= gateKm) {
331
- return { text: sp.text, start: sp.start, end: sp.end, place: h, gated: true }
464
+ // No alternatives from this pass, deliberately. Admission here is per-candidate postcode
465
+ // verification — one `findPlace` per runner-up — and the class it serves is the opposite of the
466
+ // namesake one: a postcode is present and has already picked the country, so there is nothing
467
+ // ambiguous left to declare. The bare-toponym queries #1537 is about never reach this branch (it
468
+ // requires a postcode).
469
+ return { text: sp.text, start: sp.start, end: sp.end, place: h, gated: true, alternatives: [] }
332
470
  }
333
471
  }
334
472
  }