@mailwoman/resolver 10.0.0 → 10.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (134) hide show
  1. package/README.md +9 -7
  2. package/lib/admin/coherence-passes.ts +31 -172
  3. package/lib/admin/containment.ts +15 -33
  4. package/lib/admin/jp-municipality.ts +21 -14
  5. package/lib/admin/winner.ts +37 -69
  6. package/lib/backend-capabilities.ts +28 -27
  7. package/lib/bare-toponym-race.ts +69 -37
  8. package/lib/decorate-node.ts +25 -49
  9. package/lib/fold-name.ts +5 -18
  10. package/lib/index.ts +5 -9
  11. package/lib/plausibility.ts +41 -68
  12. package/lib/postcode/country-coherence.ts +92 -296
  13. package/lib/postcode/prefix.ts +24 -86
  14. package/lib/postcode/shape-coherence.ts +26 -116
  15. package/lib/remote-resolver.ts +38 -33
  16. package/lib/rerank.ts +41 -54
  17. package/lib/resolve/passes.ts +188 -177
  18. package/lib/resolve.ts +744 -0
  19. package/lib/span-rescore.ts +219 -175
  20. package/lib/street/evidence.ts +65 -73
  21. package/lib/street/tier.ts +51 -194
  22. package/lib/toponym-prior.ts +54 -180
  23. package/out/admin/coherence-passes.d.ts +18 -69
  24. package/out/admin/coherence-passes.d.ts.map +1 -1
  25. package/out/admin/coherence-passes.js +24 -166
  26. package/out/admin/coherence-passes.js.map +1 -1
  27. package/out/admin/containment.d.ts +13 -31
  28. package/out/admin/containment.d.ts.map +1 -1
  29. package/out/admin/containment.js +13 -31
  30. package/out/admin/containment.js.map +1 -1
  31. package/out/admin/jp-municipality.d.ts +21 -14
  32. package/out/admin/jp-municipality.d.ts.map +1 -1
  33. package/out/admin/jp-municipality.js +18 -12
  34. package/out/admin/jp-municipality.js.map +1 -1
  35. package/out/admin/winner.d.ts +32 -64
  36. package/out/admin/winner.d.ts.map +1 -1
  37. package/out/admin/winner.js +23 -56
  38. package/out/admin/winner.js.map +1 -1
  39. package/out/{admin/index.d.ts → admin.d.ts} +1 -1
  40. package/out/admin.d.ts.map +1 -0
  41. package/out/{admin/index.js → admin.js} +1 -1
  42. package/out/admin.js.map +1 -0
  43. package/out/backend-capabilities.d.ts +19 -20
  44. package/out/backend-capabilities.d.ts.map +1 -1
  45. package/out/backend-capabilities.js +28 -26
  46. package/out/backend-capabilities.js.map +1 -1
  47. package/out/bare-toponym-race.d.ts +54 -27
  48. package/out/bare-toponym-race.d.ts.map +1 -1
  49. package/out/bare-toponym-race.js +69 -37
  50. package/out/bare-toponym-race.js.map +1 -1
  51. package/out/decorate-node.d.ts +6 -8
  52. package/out/decorate-node.d.ts.map +1 -1
  53. package/out/decorate-node.js +25 -49
  54. package/out/decorate-node.js.map +1 -1
  55. package/out/fold-name.d.ts +5 -18
  56. package/out/fold-name.d.ts.map +1 -1
  57. package/out/fold-name.js +5 -18
  58. package/out/fold-name.js.map +1 -1
  59. package/out/index.d.ts +5 -6
  60. package/out/index.d.ts.map +1 -1
  61. package/out/index.js +5 -8
  62. package/out/index.js.map +1 -1
  63. package/out/plausibility.d.ts +30 -60
  64. package/out/plausibility.d.ts.map +1 -1
  65. package/out/plausibility.js +19 -52
  66. package/out/plausibility.js.map +1 -1
  67. package/out/postcode/country-coherence.d.ts +53 -167
  68. package/out/postcode/country-coherence.d.ts.map +1 -1
  69. package/out/postcode/country-coherence.js +42 -259
  70. package/out/postcode/country-coherence.js.map +1 -1
  71. package/out/postcode/prefix.d.ts +18 -69
  72. package/out/postcode/prefix.d.ts.map +1 -1
  73. package/out/postcode/prefix.js +11 -78
  74. package/out/postcode/prefix.js.map +1 -1
  75. package/out/postcode/shape-coherence.d.ts +18 -85
  76. package/out/postcode/shape-coherence.d.ts.map +1 -1
  77. package/out/postcode/shape-coherence.js +11 -107
  78. package/out/postcode/shape-coherence.js.map +1 -1
  79. package/out/{postcode/index.d.ts → postcode.d.ts} +1 -1
  80. package/out/postcode.d.ts.map +1 -0
  81. package/out/{postcode/index.js → postcode.js} +1 -1
  82. package/out/postcode.js.map +1 -0
  83. package/out/remote-resolver.d.ts +32 -31
  84. package/out/remote-resolver.d.ts.map +1 -1
  85. package/out/remote-resolver.js +12 -20
  86. package/out/remote-resolver.js.map +1 -1
  87. package/out/rerank.d.ts +32 -46
  88. package/out/rerank.d.ts.map +1 -1
  89. package/out/rerank.js +16 -41
  90. package/out/rerank.js.map +1 -1
  91. package/out/resolve/passes.d.ts +108 -95
  92. package/out/resolve/passes.d.ts.map +1 -1
  93. package/out/resolve/passes.js +67 -126
  94. package/out/resolve/passes.js.map +1 -1
  95. package/out/resolve.d.ts +15 -0
  96. package/out/resolve.d.ts.map +1 -0
  97. package/out/resolve.js +557 -0
  98. package/out/resolve.js.map +1 -0
  99. package/out/span-rescore.d.ts +56 -65
  100. package/out/span-rescore.d.ts.map +1 -1
  101. package/out/span-rescore.js +134 -132
  102. package/out/span-rescore.js.map +1 -1
  103. package/out/street/evidence.d.ts +56 -61
  104. package/out/street/evidence.d.ts.map +1 -1
  105. package/out/street/evidence.js +22 -46
  106. package/out/street/evidence.js.map +1 -1
  107. package/out/street/tier.d.ts +18 -30
  108. package/out/street/tier.d.ts.map +1 -1
  109. package/out/street/tier.js +43 -191
  110. package/out/street/tier.js.map +1 -1
  111. package/out/{street/index.d.ts → street.d.ts} +1 -1
  112. package/out/street.d.ts.map +1 -0
  113. package/out/{street/index.js → street.js} +1 -1
  114. package/out/street.js.map +1 -0
  115. package/out/toponym-prior.d.ts +22 -110
  116. package/out/toponym-prior.d.ts.map +1 -1
  117. package/out/toponym-prior.js +41 -170
  118. package/out/toponym-prior.js.map +1 -1
  119. package/package.json +44 -147
  120. package/lib/resolve/index.ts +0 -989
  121. package/out/admin/index.d.ts.map +0 -1
  122. package/out/admin/index.js.map +0 -1
  123. package/out/postcode/index.d.ts.map +0 -1
  124. package/out/postcode/index.js.map +0 -1
  125. package/out/resolve/index.d.ts +0 -20
  126. package/out/resolve/index.d.ts.map +0 -1
  127. package/out/resolve/index.js +0 -808
  128. package/out/resolve/index.js.map +0 -1
  129. package/out/street/index.d.ts.map +0 -1
  130. package/out/street/index.js.map +0 -1
  131. package/vitest.config.ts +0 -38
  132. /package/lib/{admin/index.ts → admin.ts} +0 -0
  133. /package/lib/{postcode/index.ts → postcode.ts} +0 -0
  134. /package/lib/{street/index.ts → street.ts} +0 -0
@@ -1,989 +0,0 @@
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 type { ComponentTag } from "@mailwoman/codex/component"
16
- import { matchCountry, matchSubdivision } from "@mailwoman/codex/country"
17
- import { DEFAULT_PLACETYPE_MAP, isPlacetypeFallback } from "@mailwoman/codex/placetype-map"
18
- import { collectNodes, type AddressNode, type AddressTree, type Interpretation } from "@mailwoman/core/decoder"
19
- import {
20
- type BackendCapabilityGap,
21
- type ResolveNodeTrace,
22
- type ResolvedPlace,
23
- type ResolveOpts,
24
- type Resolver,
25
- type ResolverBackend,
26
- countriesFromPostcodeFormat,
27
- } from "@mailwoman/core/resolver"
28
-
29
- import {
30
- applyAdminCoherence,
31
- applyExplicitCountryCoherence,
32
- applyParentFallbackContradiction,
33
- applyRegionCountryCoherence,
34
- } from "#admin/coherence-passes"
35
- import { adminContainmentVerdict, firstRegionQualifier, partitionByContainment } from "#admin/containment"
36
- import { resolveCompoundMunicipality } from "#admin/jp-municipality"
37
- import { describeCapabilityGaps, reportCapabilityGaps } from "#backend-capabilities"
38
- import {
39
- BARE_REGION_DOMINANCE_LOG10,
40
- bareCountryCandidate,
41
- bareRegionCandidate,
42
- logPopulation,
43
- loneBareLocalityNode,
44
- pickLargerAdmin,
45
- } from "#bare-toponym-race"
46
- import { decorateNode } from "#decorate-node"
47
- import {
48
- findPostcodeCountryScope,
49
- type PostcodeCountryScope,
50
- stampPostcodeCountryScope,
51
- } from "#postcode/country-coherence"
52
- import { type CoordinateOptionalPlace, postcodePrefixResolvedPlace, probePostcodePrefix } from "#postcode/prefix"
53
- import { applyPostcodeShapeCoherence, isShapeExcludedPostcode } from "#postcode/shape-coherence"
54
- import {
55
- applyPostcodeConsistency,
56
- applySpanRescore,
57
- createNodeTraceRecorder,
58
- DIAGNOSTIC_BANDS,
59
- firstPostcodeValue,
60
- NOOP_TRACE_RECORDER,
61
- pickCompletion,
62
- type ResolutionState,
63
- } from "#resolve/passes"
64
- import { applyAddressPoint, applyInterpolation, applyStreetCentroid } from "#street/tier"
65
- import {
66
- type CapitalLevelFn,
67
- DEFAULT_COUNTRY_PRIOR_WEIGHT,
68
- promoteCapitals,
69
- rankByCountryPrior,
70
- rankByImportance,
71
- } from "#toponym-prior"
72
-
73
- /**
74
- * Build a `Resolver` backed by a `ResolverBackend`. The backend can be any concrete impl structurally compatible with
75
- * `PlaceLookup` — e.g. `new WOFSQLitePlaceLookup({ databasePath }).asResolverBackend()` or a fake for tests.
76
- */
77
- export function createWOFResolver(backend: ResolverBackend): Resolver {
78
- return new WOFResolver(backend)
79
- }
80
-
81
- /**
82
- * #1735 (second half) — the tree's own country statement, when it is unambiguous.
83
- *
84
- * "SW1A 1AA, UK" under the en-US default parsed correctly and still failed: the walk resolved the country NODE to GB,
85
- * but a sibling's resolution never scopes a sibling — the postcode lookup ran under the locale-inferred `country=US`
86
- * hard filter and missed. An explicit country token is the address's OWN scope declaration, which outranks a locale
87
- * inference the same way the #912 posture ranks explicit over inferred.
88
- *
89
- * Deterministically guarded: exactly ONE country-tagged node, whose value `matchCountry` maps to one ISO country, and
90
- * whose value is NOT also a subdivision name — "Georgia" maps to GE _and_ names a US state, so it never pre-scopes (the
91
- * existing coherence passes keep handling it). Returns the alpha-2 or null.
92
- */
93
- function explicitCountryScope(roots: readonly AddressNode[]): string | null {
94
- const countryNodes = collectNodes(roots, (node) => node.tag === "country" && node.value.trim().length > 0)
95
-
96
- if (countryNodes.length !== 1) return null
97
- const value = countryNodes[0]!.value.trim()
98
- const matched = matchCountry(value)
99
-
100
- if (!matched) return null
101
-
102
- if (matchSubdivision(value)) return null
103
-
104
- return matched.iso2
105
- }
106
-
107
- class WOFResolver implements Resolver {
108
- readonly #backend: ResolverBackend
109
- /**
110
- * The gazetteer artifact's self-declared coverage facts, passed through from the backend so pipeline-level consumers
111
- * read them from the resolver handle they already hold. Absent on artifacts predating the coverage manifest.
112
- */
113
- readonly artifactCoverage: Resolver["artifactCoverage"]
114
- /**
115
- * Optional backend methods this backend omits, each naming the default-ON option it silently disables. Computed once
116
- * here rather than at each guard site so a caller can read the gap before running a query that would quietly skip the
117
- * feature. See `backend-capabilities.ts`.
118
- */
119
- readonly capabilityGaps: readonly BackendCapabilityGap[]
120
-
121
- constructor(backend: ResolverBackend) {
122
- this.#backend = backend
123
- this.artifactCoverage = backend.artifactCoverage
124
- this.capabilityGaps = describeCapabilityGaps(backend)
125
- reportCapabilityGaps(this.capabilityGaps)
126
- }
127
-
128
- /**
129
- * The `Resolver.findPlace` passthrough — one direct gazetteer probe for pipeline-level consumers (#1738's
130
- * dominant-bearer guard). Bound as a method so `this.#backend` stays private.
131
- */
132
- findPlace: Resolver["findPlace"] = (query) => this.#backend.findPlace(query)
133
-
134
- async resolveTree(tree: AddressTree, opts: ResolveOpts = {}): Promise<AddressTree> {
135
- // Postcode-shape coherence (#31, Mechanism 1): the earliest pass in the tree — pure-sync and
136
- // backend-free, run BEFORE `state.postcode` is read so an excluded span can never become the
137
- // address's postcode. Opt-in (`postcodeShapeCoherence: true`), OFF by default (D-rule: demotion
138
- // is the failure mode with teeth). A confirmed span's narrowed systems — the intersection of
139
- // its codex shape with the tree's confident sibling systems — bound the country-scope pass
140
- // below; a pure subset of codex's own candidate list, so it can only narrow, never widen.
141
- // See postcode-shape-coherence.ts.
142
- const shapeVerdict = opts.postcodeShapeCoherence === true ? applyPostcodeShapeCoherence(tree.roots) : null
143
-
144
- const state: ResolutionState = {
145
- lookupsRemaining: opts.maxLookups ?? 10,
146
- // Full replacement when `placetypeMap` is supplied — callers that want to extend rather
147
- // than replace should spread DEFAULT_PLACETYPE_MAP themselves.
148
- placetypeMap: opts.placetypeMap ?? DEFAULT_PLACETYPE_MAP,
149
- minWinningScore: opts.minWinningScore ?? 0,
150
- candidatesPerLookup: opts.candidatesPerLookup ?? 5,
151
- defaultCountry: opts.defaultCountry,
152
- defaultCountryIsInferred: opts.defaultCountryIsInferred === true,
153
- bareLocalityNode: loneBareLocalityNode(tree, opts.placetypeMap ?? DEFAULT_PLACETYPE_MAP),
154
- parentFallback: opts.parentFallback ?? true,
155
- // Requires a sink: with nowhere to record the answer the probes would be pure cost.
156
- ...(opts.diagnoseUnreachable && opts.traceSink ? { diagnoseUnreachable: true } : {}),
157
- postcode: firstPostcodeValue(tree.roots),
158
- // #31 Mechanism 2 — forwarded to locality lookups (see #lookupAndPick). Opt-in, OFF by default.
159
- postcodeContainmentCoherence: opts.postcodeContainmentCoherence === true,
160
- // #31 Mechanism 3 — the prefix prior + its injected index (see #lookupAndPick). Opt-in, OFF by default.
161
- postcodePrefixPrior: opts.postcodePrefixPrior === true,
162
- postcodePrefixIndex: opts.postcodePrefixIndex,
163
- // #1589: derived here when the caller didn't thread it, so the browser cascade and the
164
- // drop-ins get the implied-set probe without per-caller wiring (the staged-repoint e2e
165
- // caught `100 00` resolving in Node and not in the browser over the same artifact).
166
- postcodeFormatCountries:
167
- opts.postcodeFormatCountries ?? countriesFromPostcodeFormat(firstPostcodeValue(tree.roots)),
168
- fuzzyCountryScope: opts.fuzzyCountryScope,
169
- bias: opts.bias,
170
- anchorPosterior: opts.anchorPosterior,
171
- anchorWeight: opts.anchorWeight ?? 2,
172
- localeCountryPrior: opts.localeCountryPrior,
173
- localeCountryPriorWeight: opts.localeCountryPriorWeight ?? DEFAULT_COUNTRY_PRIOR_WEIGHT,
174
- capitalLevel: opts.capitalLevel,
175
- hardCountry: opts.hardCountry,
176
- // Default-ON (#402): completion only fires for a dual-role region whose locality the parser
177
- // dropped, and no-ops entirely when the backend has no relation (the browser WASM resolver, or
178
- // a gazetteer without `coincident_roles`). Pass `hierarchyCompletion: false` to opt out.
179
- //
180
- // Default-ON is nominal on the SHIPPED backend: `WOFCandidateTableLookup` implements no
181
- // `coincidentLocalitiesFor`, so this attaches nothing there. Measured 2026-08-15 on FTS, which
182
- // does implement it, the flag changed 0 of 837 board inputs — see ResolveOpts.hierarchyCompletion.
183
- hierarchyCompletion: opts.hierarchyCompletion ?? true,
184
- includeAncestors: opts.includeAncestors ?? false,
185
- // #1717 stage 2 — default OFF (D-rule); the qualifier is pre-scanned like `postcode` above
186
- // because region and locality are siblings the walk visits independently.
187
- adminContainmentRerank: opts.adminContainmentRerank === true,
188
- regionQualifier: firstRegionQualifier(tree.roots),
189
- ...(opts.traceSink ? { traceSink: opts.traceSink } : {}),
190
- localityNodePresent: false,
191
- resolvedRegion: null,
192
- resolvedRegionNode: null,
193
- }
194
-
195
- // Postcode-country coherence (#42): the one pre-walk LOOKUP pass (the shape verdict above is
196
- // pure-sync, backend-free), and the only mechanism allowed to override `defaultCountry`. Its three
197
- // sibling coherence passes re-pick nodes AFTER the walk; that shape cannot work here, because what
198
- // needs correcting is the walk's country SCOPE — which poisons the postcode node's own resolution,
199
- // the postcode-consistency fallback that then drags the locality onto it, and the hard `country`
200
- // filter on every admin lookup. So the verdict is taken once, up front, and the walk runs under the
201
- // corrected country. Default-ON (operator-promoted 2026-08-05; `false` opts out) — needs a default
202
- // country to correct and both a postcode and a locality to be coherent about; abstains unless
203
- // EXACTLY one country (never the already-coherent default) makes the pair consistent. See
204
- // postcode-country-coherence.ts.
205
- let postcodeScope: PostcodeCountryScope | null = null
206
-
207
- // The pass also runs with NO default in force (#1585/#861 convergence): there is nothing to
208
- // override, but the same exactly-one-country abstention lets the postcode+locality pair
209
- // CONSTRAIN an otherwise population-first walk — `Zabiče 8, 6250 Zabiče` picks the SI row
210
- // coherent with the SI 6250 centroid instead of the more-populous Polish namesake. The
211
- // browser cascade (which sets no default by design) is the consumer this exists for.
212
- // #1735 second half: the address's own country statement scopes the walk BEFORE anything
213
- // resolves — a sibling's resolution never reaches a sibling, so without this the postcode
214
- // lookup in "RM10 8AB, UK" ran under the locale-inferred US filter while the country node
215
- // resolved to GB beside it. Explicit-over-inferred, the #912 precedence, decided from the
216
- // tree's own text; an EXPLICIT caller scope is never overridden.
217
- let explicitScope: string | null = null
218
-
219
- if (!state.defaultCountry || state.defaultCountryIsInferred) {
220
- explicitScope = explicitCountryScope(tree.roots)
221
-
222
- if (explicitScope) {
223
- state.defaultCountry = explicitScope
224
- state.defaultCountryIsInferred = false
225
- }
226
- }
227
-
228
- if (opts.postcodeCountryCoherence !== false && state.postcode) {
229
- postcodeScope = await findPostcodeCountryScope(tree.roots, this.#backend, {
230
- postcode: state.postcode,
231
- defaultCountry: state.defaultCountry,
232
- ...(shapeVerdict?.narrowing !== undefined ? { candidateSystems: shapeVerdict.narrowing } : {}),
233
- ...(opts.postcodeCountryCoherenceThresholdKm !== undefined
234
- ? { thresholdKm: opts.postcodeCountryCoherenceThresholdKm }
235
- : {}),
236
- })
237
-
238
- if (postcodeScope) {
239
- // The override. `hardCountry` is not cleared because it is never consulted while a
240
- // `defaultCountry` is set (`#lookupAndPick`'s precedence chain reaches it only as the last
241
- // fallback), so replacing the default is sufficient to re-scope the entire walk.
242
- state.defaultCountry = postcodeScope.country
243
- }
244
- }
245
-
246
- const newRoots: AddressNode[] = []
247
-
248
- for (const root of tree.roots) {
249
- newRoots.push(await this.#walk(root, /* parentResolved */ null, state))
250
- }
251
-
252
- // Attribution for the override, stamped on the two nodes that bought it. Additive metadata only.
253
- if (postcodeScope) {
254
- stampPostcodeCountryScope(newRoots, postcodeScope)
255
- }
256
-
257
- // The pre-scope's receipt (#1735): consumers that select country-scoped artifacts AFTER the walk
258
- // (geocode-core's rooftop-extract second pass) key on a scope stamp. Without this, an address whose
259
- // country was right FROM THE TREE never writes one — the #42 pass stays silent because the default
260
- // is already coherent — and the FR rooftop extract silently stops loading for "…, France" inputs
261
- // under a non-FR locale (six board venue rows dropped from rooftop to city centroid; the battery
262
- // caught it).
263
- if (explicitScope) {
264
- for (const root of newRoots) {
265
- if (root.tag === "country") {
266
- root.metadata = { ...root.metadata, explicit_country_scope: explicitScope }
267
- }
268
- }
269
- }
270
-
271
- // Dual-role hierarchy completion (#405/#415). Only when enabled, a region resolved, and the parser
272
- // emitted NO locality — record the dropped locality as a SECONDARY ROLE (an interpretation) on the
273
- // resolved region node, from the backend's precomputed coincident-roles relation (#403). One node,
274
- // one span, two roles — no synthesized sibling. See ResolveOpts.hierarchyCompletion.
275
- if (state.hierarchyCompletion && state.resolvedRegion && state.resolvedRegionNode && !state.localityNodePresent) {
276
- this.#completeRegionRole(state.resolvedRegion, state.resolvedRegionNode)
277
- }
278
-
279
- // Admin descendant-consistency (#263): default-ON (#895 settled drift D1; `false` opts out). Re-pick a
280
- // (region, locality) pair so the locality descends from the region — runs BEFORE postcode-consistency
281
- // (it resolves the locality the postcode pass may then refine) and before the street tiers (which key
282
- // off the postcode/street, not the admin coordinate this adjusts). Byte-stable when nothing fell
283
- // through or the backend lacks `ancestors`.
284
- if (opts.adminCoherence !== false) {
285
- // First: a parent-fallback pick whose lineage names another region is un-resolved, so the passes below
286
- // and the admin ladder read it as the fall-through it is, not as a resolved namesake elsewhere.
287
- applyParentFallbackContradiction(newRoots)
288
- await applyAdminCoherence(newRoots, this.#backend)
289
- // #822 — same joint-consistency family, inverse trigger: an explicit country token whose resolved
290
- // locality landed in the wrong country (the populous US namesake). Runs after the region pass so the
291
- // two never contend (region-fallthrough vs resolved-but-foreign are disjoint locality states).
292
- await applyExplicitCountryCoherence(newRoots, this.#backend)
293
- // Region-country coherence: a region qualifier the locale-inferred default-country hard filter could not
294
- // resolve (a foreign subdivision — "Montreal QC" under a US locale). The default filter discarded "QC" and
295
- // force-matched the locality to the US namesake; this re-resolves the subdivision + its same-named locality
296
- // under the subdivision's OWN country. Disjoint from the two passes above (unresolved region + resolved
297
- // locality); evidence-conditional + byte-stable on the domestic path (a US region resolves under `US`).
298
- await applyRegionCountryCoherence(newRoots, this.#backend, state.defaultCountry)
299
- }
300
-
301
- // Postcode-consistency (#370 "Change A"): default-ON (promoted 2026-07-04 — the corrected check:
302
- // FI 231/0, SI 37/6, CZ 47/2, US byte-flat; see the ResolveOpts docstring). After the admin walk
303
- // (needs both the locality and the postcode resolved) and before the street tiers (which key off
304
- // the postcode/street, not the locality coordinate this adjusts). `false` opts out, byte-stable.
305
- if (opts.postcodeConsistency !== false) {
306
- applyPostcodeConsistency(newRoots, opts.postcodeConsistencyThresholdKm ?? 50)
307
- }
308
-
309
- // Address-point tier (#476): opt-in street-level exact match. After the admin walk so the
310
- // tier can never disturb admin attribution — it only ADDS the precise coordinate. Byte-stable
311
- // when opts.addressPoints is absent.
312
- if (opts.addressPoints) {
313
- applyAddressPoint(newRoots, opts.addressPoints, opts.addressPointBboxFallback)
314
- }
315
-
316
- // Interpolation tier (#483): strictly AFTER the exact-point block so an estimate can never
317
- // override a real situs point (applyInterpolation also checks on resolution_tier). Opt-in;
318
- // byte-stable when opts.interpolation is absent.
319
- if (opts.interpolation) {
320
- applyInterpolation(newRoots, opts.interpolation, opts.interpolationRadiusCalibration)
321
- }
322
-
323
- // Span-rescore tier (#370): default-ON (promoted 2026-06-25 — same-harness EU+AU +1pp @25km,
324
- // zero regressions: CZ 90→95, AT 70→73, PL 88→90, IT/PT/FR/AU flat, no-result 4→3%; fires last
325
- // so it only runs when every other tier left the tree unresolved, hence inert on the well-resolved
326
- // US path). Explicit opt-OUT via `spanRescore: false`; byte-stable then.
327
- if (opts.spanRescore !== false) {
328
- await applySpanRescore(newRoots, tree.raw, this.#backend, opts)
329
- }
330
-
331
- // A failed admin walk can leave the exact-point tier without a locality even though span-rescore
332
- // recovers one immediately afterward (for example, a locality the model tagged as `region`). Give
333
- // the exact register one bounded retry with that newly established scope. An existing situs hit is
334
- // returned early by applyAddressPoint, so the normal path performs no duplicate lookup; interpolation
335
- // remains subordinate because an exact point is allowed to replace its estimate.
336
- if (opts.addressPoints) {
337
- applyAddressPoint(newRoots, opts.addressPoints, opts.addressPointBboxFallback)
338
- }
339
-
340
- // Street-centroid tier (#1042): LAST, after span-rescore, so it can (a) union the span-rescore-recovered
341
- // country into its FR/national country hints (a placer-misrouted street — "Rue Sainte-Catherine" → IT — leaves
342
- // admin unresolved, and only span-rescore recovers the FR country signal) and (b) override a coarse recovered
343
- // locality with the exact street centroid. Applies only when there is no house number + no existing street-level tier, so a
344
- // rooftop query is untouched; byte-stable when opts.streetCentroids absent.
345
- if (opts.streetCentroids) {
346
- applyStreetCentroid(newRoots, tree.raw, opts.streetCentroids, opts.streetCountryHints ?? [])
347
- }
348
-
349
- return { raw: tree.raw, roots: newRoots }
350
- }
351
-
352
- /**
353
- * Record a dropped dual-role locality as a `locality` INTERPRETATION on the resolved region node (#415, generalizes
354
- * #405's synthesized node). Consults `coincidentLocalitiesFor(regionID)` (O(1) map lookup — no distance math, no
355
- * backend query), picks the principal city ({@link pickCompletion}: population-primary, distance tiebreak, abstain on
356
- * a genuine tie), and appends an interpretation to `regionNode.interpretations`. No-op when the backend has no
357
- * relation, the region isn't a dual-role place, or it abstains. The region node's primary role stays `region`; the
358
- * locality rides alongside.
359
- */
360
- #completeRegionRole(region: CoordinateOptionalPlace, regionNode: AddressNode): void {
361
- if (typeof region.id !== "number" || !this.#backend.coincidentLocalitiesFor) return
362
- const loc = pickCompletion(this.#backend.coincidentLocalitiesFor(region.id))
363
-
364
- if (!loc) return
365
-
366
- const interpretation: Interpretation = {
367
- tag: "locality",
368
- placeID: `wof:${loc.id}`,
369
- sourceID: `${loc.placetype}:${loc.id}`,
370
- lat: loc.lat,
371
- lon: loc.lon,
372
- confidence: 0,
373
- metadata: { relationship_type: loc.relationshipType, resolver_completed: true, resolver_name: loc.name },
374
- }
375
-
376
- regionNode.interpretations = [...(regionNode.interpretations ?? []), interpretation]
377
- }
378
-
379
- async #walk(
380
- node: AddressNode,
381
- parentResolved: CoordinateOptionalPlace | null,
382
- state: ResolutionState
383
- ): Promise<AddressNode> {
384
- // Always clone — never mutate input nodes.
385
- const decorated: AddressNode = { ...node, children: [] }
386
-
387
- const placetype = state.placetypeMap[node.tag as ComponentTag]
388
-
389
- // Track locality presence for hierarchy completion (#405): completion must NOT fire if the parser
390
- // already emitted a locality node (even one that failed to resolve) — it only fills a genuine
391
- // gap. Cheap and always-on; only consulted when hierarchyCompletion is set.
392
- if (placetype === "locality") {
393
- state.localityNodePresent = true
394
- }
395
-
396
- let resolved: CoordinateOptionalPlace | null = null
397
-
398
- // Shape-excluded postcode spans (letter-bearing ones keep their tag; #31 Mechanism 1) are
399
- // stripped of their resolve contribution — the walk does not look them up. Digit-only excluded
400
- // spans were retagged to `house_number` and flow through their correct sibling placetype.
401
- if (placetype && state.lookupsRemaining > 0 && node.value.trim().length && !isShapeExcludedPostcode(node)) {
402
- let picked = await this.#lookupAndPick(node, placetype, parentResolved, state)
403
-
404
- // A compound JP municipality as a scoped pair: the parent fallback is withheld on the tail probe only.
405
- if (!picked && node.tag === "municipality") {
406
- picked = await resolveCompoundMunicipality(
407
- node.value,
408
- parentResolved,
409
- () => state.lookupsRemaining > 0,
410
- async (value, scope, parentFallback) => {
411
- const prior = state.parentFallback
412
- state.parentFallback = prior && parentFallback
413
-
414
- try {
415
- return await this.#lookupAndPick({ ...node, value }, placetype, scope, state)
416
- } finally {
417
- state.parentFallback = prior
418
- }
419
- }
420
- )
421
- }
422
-
423
- if (picked) {
424
- resolved = picked.top
425
- decorateNode(decorated, picked.top, picked.alternatives)
426
-
427
- if (picked.metadata) {
428
- decorated.metadata = { ...decorated.metadata, ...picked.metadata }
429
- }
430
-
431
- // #1678 thread 2 — the parse half, resolved from the atlas rather than trained in.
432
- //
433
- // The bare-toponym race exists because the model reads a lone country or region name as a
434
- // `locality`; the race finds the right PLACE and the node keeps the wrong TAG. So
435
- // `mw geocode 格鲁吉亚` lands on Georgia the country and reports `{"locality": "格鲁吉亚"}`,
436
- // which is a correct coordinate under a label that will mislead the moment the same toponym
437
- // appears inside a longer address.
438
- //
439
- // The repick metadata already marks exactly these nodes, so the correction is free: retrieval
440
- // established the placetype, and the tag follows it. Only the race's own picks are retagged —
441
- // an ordinary locality that resolved to a locality is untouched.
442
- if (decorated.metadata?.["bare_country_repick"]) {
443
- decorated.tag = "country"
444
- } else if (decorated.metadata?.["bare_region_repick"]) {
445
- decorated.tag = "region"
446
- }
447
-
448
- // Lineage attachment (#404): stamp the resolved place's ancestor chain onto metadata. Opt-in
449
- // + only when the backend supplies it, so the default stays byte-identical (no extra query).
450
- if (state.includeAncestors && this.#backend.ancestors) {
451
- decorated.metadata = { ...decorated.metadata, ancestors: this.#backend.ancestors(picked.top.id) }
452
- }
453
-
454
- // Capture the first resolved region (place + node) for hierarchy completion — the locality
455
- // interpretation is pushed onto this node in the post-walk pass.
456
- if (placetype === "region" && state.resolvedRegion === null) {
457
- state.resolvedRegion = picked.top
458
- state.resolvedRegionNode = decorated
459
- }
460
- }
461
- }
462
-
463
- const carryParent = resolved ?? parentResolved
464
-
465
- for (const child of node.children) {
466
- decorated.children.push(await this.#walk(child, carryParent, state))
467
- }
468
-
469
- return decorated
470
- }
471
-
472
- /**
473
- * Which admin bands hold a value the probed band did not, keeping the country and dropping the parent.
474
- *
475
- * Bands come from `PLACETYPE_SPECIFICITY` rather than a list typed here: that table is already the repo's answer to
476
- * how coarse a placetype is, and a second hand-kept copy would agree right up until a placetype is added. Probed
477
- * coarse-to-fine so the report reads down the admin ladder.
478
- */
479
- async #probeOtherBands(
480
- query: Parameters<ResolverBackend["findPlace"]>[0],
481
- probed: string
482
- ): Promise<NonNullable<ResolveNodeTrace["reachableIn"]>> {
483
- const found: NonNullable<ResolveNodeTrace["reachableIn"]> = []
484
-
485
- for (const band of DIAGNOSTIC_BANDS) {
486
- if (band === probed) continue
487
-
488
- try {
489
- const hits = await this.#backend.findPlace({ ...query, placetype: band, parentID: undefined })
490
-
491
- if (hits.length) {
492
- found.push({ placetype: band, n: hits.length })
493
- }
494
- } catch {
495
- // A band the backend cannot answer for is not evidence that the key is absent from it, so it is
496
- // skipped rather than recorded as an empty result.
497
- continue
498
- }
499
- }
500
-
501
- return found
502
- }
503
-
504
- async #lookupAndPick(
505
- node: AddressNode,
506
- placetype: string,
507
- parentResolved: CoordinateOptionalPlace | null,
508
- state: ResolutionState
509
- ): Promise<{
510
- top: CoordinateOptionalPlace
511
- alternatives: ResolvedPlace[]
512
- metadata?: Record<string, unknown>
513
- } | null> {
514
- state.lookupsRemaining--
515
-
516
- const query: Parameters<ResolverBackend["findPlace"]>[0] = {
517
- text: node.value,
518
- placetype,
519
- limit: state.candidatesPerLookup,
520
- }
521
-
522
- // Proximity bias (viewport center, user location, …) — a SOFT re-rank the backend folds into
523
- // its exact-tier prominence; never a filter, so recall is untouched. This is how an ambiguous
524
- // bare postcode ("48026") follows the map view instead of a global population coin-flip.
525
- if (state.bias && state.bias.length) {
526
- query.bias = state.bias
527
- }
528
-
529
- // Pass the inherited parent constraint to the backend when available — `parentID` scopes to
530
- // the resolved parent's descendants. For `country`: a resolved parent's country wins, else
531
- // fall back to the caller's `defaultCountry`. Without this top-level hint a bare "IL" over a
532
- // multi-country gazetteer fuzzy-matches a foreign place (e.g. a French region) — see the
533
- // Direction-C resolver eval.
534
- if (parentResolved && typeof parentResolved.id === "number") {
535
- query.parentID = parentResolved.id
536
- }
537
-
538
- // #194: a resolved parent's country wins, then the caller's `defaultCountry`, then the confident
539
- // placer `hardCountry`. All three are a HARD candidate filter. The placer's `hardCountry` is conditional
540
- // upstream on high confidence (so it only fires when the model is sure), and on a miss the node is
541
- // left UNRESOLVED rather than re-resolved globally: the off-continent rows are precisely the ones
542
- // whose locality isn't in the country's gazetteer slice, so a global retry would just re-admit the
543
- // wrong-continent guess the hard filter exists to drop ("in-region or unresolved"). Measured: a
544
- // global fallback collapses back to the soft-prior baseline (FI p90 3050, PL p90 1078); pure-hard
545
- // collapses the tail (FI 18 km, PL p99 8172→494) at a coverage-bounded recall cost.
546
- // #833 forward linkage: a node's own `country_hint` (an address-system recognizer's derived country —
547
- // today `recognizeUSRegions` stamping "US" on a recognized closed-set US state) constrains THIS node's
548
- // lookup when the caller supplied no locale/default country. A caller scope outranks this derived hint:
549
- // `WA` is both Washington and Western Australia, so en-AU must reach the AU candidate instead of being
550
- // overwritten by the US-only recognizer. A genuine foreign subdivision under the wrong locale is recovered
551
- // later by region-country coherence after the scoped lookup abstains.
552
- const countryHint = node.metadata?.["country_hint"]
553
-
554
- // A locale-INFERRED default country never filters a `country`-placetype lookup: the span names a
555
- // country outright, and the filter can only admit the scope country itself (bare "Germany" under
556
- // the en-US default filtered out the DE row; the unresolved span then fell to a US locality whose
557
- // historical alias is "Germany, Ohio"). An EXPLICIT caller scope stays supreme, matching the #912
558
- // posture; parent evidence and the confident placer are untouched.
559
- const defaultCountryForLookup =
560
- placetype === "country" && state.defaultCountryIsInferred ? undefined : state.defaultCountry
561
-
562
- const country =
563
- parentResolved?.country ??
564
- defaultCountryForLookup ??
565
- (typeof countryHint === "string" ? countryHint : undefined) ??
566
- state.hardCountry
567
-
568
- if (country) {
569
- query.country = country
570
- }
571
-
572
- // #1585: the locale hint's country rides on every primary lookup as the TYPO-FUZZY tier's scope.
573
- // Deliberately set even when `query.country` is (the backend ignores it there — the hard filter
574
- // is already narrower): the field's contract lives in one place, the backend.
575
- if (state.fuzzyCountryScope) {
576
- query.fuzzyCountry = state.fuzzyCountryScope
577
- }
578
-
579
- // Admin-containment re-rank (#1717 stage 2): thread the tree's region qualifier onto locality
580
- // lookups so a capable backend can vouch for (and surface) the candidates that sit UNDER it.
581
- // Stands down under an EXPLICIT caller country scope (the #912 posture — only a locale-INFERRED
582
- // scope is bypassable by the address's own evidence); the resolved-parent and placer scopes are
583
- // left alone, since a resolved parent usually IS the qualifier and the injection dedupes.
584
- const containmentEligible =
585
- state.adminContainmentRerank &&
586
- placetype === "locality" &&
587
- state.regionQualifier !== undefined &&
588
- (!state.defaultCountry || state.defaultCountryIsInferred)
589
-
590
- if (containmentEligible) {
591
- query.regionQualifier = state.regionQualifier
592
- }
593
-
594
- // Coordinate-first: hand the sibling postcode to locality lookups so the backend can inject
595
- // postcode-proximal candidates the name-match would miss. Only for locality (the placetype both
596
- // `locality` and `dependent_locality` map to); other placetypes ignore it. The containment flag
597
- // (#31, Mechanism 2) asks a coordinate-first backend to re-rank the candidates by proximity to
598
- // the postcode's own centroid — opt-in, OFF by default.
599
- if (placetype === "locality" && state.postcode) {
600
- query.postcode = state.postcode
601
-
602
- if (state.postcodeContainmentCoherence) {
603
- query.postcodeContainmentCoherence = true
604
- }
605
- }
606
-
607
- // #1721 resolver-interior trace. Stage orders hold the SAME candidate objects across re-ranks
608
- // (every stage reorders, never clones), which is what lets emit assemble a per-stage rank
609
- // vector per row. The no-sink walk talks to the frozen no-op recorder — zero per-event branches.
610
- const rec = state.traceSink ? createNodeTraceRecorder(state.traceSink) : NOOP_TRACE_RECORDER
611
-
612
- // The query is SNAPSHOT, not bound live. `emit` reads `ctx.query.parentID` at the END of the walk, and the
613
- // parent-fallback retry `delete`s that key mid-lookup — so binding the object itself lets a later mutation
614
- // rewrite history. That is how 196 lookups which every one of them carried a parent came out of the
615
- // constraint census reading `parentID: absent`.
616
- rec.bind(node, placetype, { ...query }, state.candidatesPerLookup)
617
-
618
- let candidates: ResolvedPlace[]
619
-
620
- // #1589: a `postalcode` whose FORMAT implies specific countries, with no surviving country
621
- // constraint, probes exactly the implied set — most populous hit wins, and an all-miss
622
- // leaves the candidate set EMPTY rather than falling through to the unconstrained fold:
623
- // `100 00` space-strips to `10000`, which answers Troyes FR while the CZ rows sit in the
624
- // artifact under both keyings; a scoped empty must stay empty (the same contract as the
625
- // fuzzy tier's, #1585). The postcode-prefix prior below still gets its turn on the empty
626
- // set — its index is country-scoped by construction, so it is not the fold this branch
627
- // exists to avoid (the B3 tests hold that path).
628
- if (placetype === "postalcode" && !query.country && state.postcodeFormatCountries?.length) {
629
- rec.check("postcode_format_probe")
630
- let best: ResolvedPlace | undefined
631
-
632
- for (const impliedCountry of state.postcodeFormatCountries) {
633
- try {
634
- const hits = await this.#backend.findPlace({ ...query, country: impliedCountry })
635
- const top = hits[0]
636
-
637
- // `score` is the backend's own population-first ranking metric, so comparing the
638
- // per-country winners by it keeps the cross-country pick population-first too.
639
- if (top && (!best || top.score > best.score)) {
640
- best = top
641
- }
642
- } catch {
643
- // A per-country probe failure reads as a miss for that country, never an abort.
644
- }
645
- }
646
-
647
- if (best) {
648
- rec.emit({ id: best.id, name: best.name, source: "postcode_format_probe" })
649
-
650
- return { top: best, alternatives: [] }
651
- }
652
-
653
- candidates = []
654
- } else {
655
- try {
656
- candidates = await this.#backend.findPlace(query)
657
- rec.stage("initial", candidates)
658
-
659
- // #1731: the backend's interior region-scope fallback, surfaced as a check — the resolver
660
- // never sees the scoped probe miss, only the stamp the re-admitted rows carry.
661
- if (candidates[0]?.regionScopeMiss) {
662
- rec.check("region_scope_miss")
663
- }
664
-
665
- // Parent soft-filtering: `parentID` is a HARD descendant filter in the backend, which wrongly
666
- // zeroes the result when the parent resolved wrong OR the gazetteer hierarchy is incomplete
667
- // (a real locality whose `ancestors` chain is missing its region). Rather than turn a
668
- // resolvable node into an unresolved one, retry once WITHOUT the parent constraint — we
669
- // prefer a parent-scoped hit but never sacrifice recall. The country constraint is kept, so
670
- // this still can't wander to a foreign place. Same logical resolution → no extra budget.
671
- if (!candidates.length && state.parentFallback && query.parentID !== undefined) {
672
- delete query.parentID
673
- rec.check("parent_fallback_retry")
674
- candidates = await this.#backend.findPlace(query)
675
- rec.stage("parent_fallback", candidates)
676
- }
677
-
678
- // DIAGNOSTIC ONLY, and after every real attempt: which OTHER bands hold this value. The answer never
679
- // becomes the pick — a band the model did not ask for is not evidence about what the string means —
680
- // but it separates the two facts a `null` cannot: a key we hold under another placetype is a
681
- // reachability failure the tag caused, while a key nowhere is coverage. Off by default; one extra call
682
- // per band per miss.
683
- if (!candidates.length && state.diagnoseUnreachable) {
684
- rec.reachable(await this.#probeOtherBands(query, placetype))
685
- }
686
- } catch (error) {
687
- // Defensive: a backend failure should not abort the whole tree walk. Leave the node with
688
- // its classifier attribution intact.
689
- //
690
- // The reason rides the check name. A bare `backend_error` cannot tell a closed database from a
691
- // finalized statement from a genuine query fault, which is what made three full-board constraint
692
- // runs unreadable — 64 of 591 rows errored and the census could not say why.
693
- rec.check(`backend_error: ${(error as Error).message}`)
694
- rec.emit(null)
695
-
696
- return null
697
- }
698
- }
699
-
700
- // Postcode-prefix prior (#31, Mechanism 3): when a `postalcode` node misses the gazetteer, derive
701
- // the code's prefix and probe the injected PFX1 index (structural — never a model input). A hit
702
- // resolves the node to a synthetic place (id 0), carrying a coordinate ONLY when the index node
703
- // does — the ancestry-only tier stays coordinate-free (B3-3's 0% half, meaning-of-zero). The
704
- // prior's payload is returned as node metadata for #walk to stamp. Opt-in via `postcodePrefixPrior`
705
- // + `postcodePrefixIndex`; OFF by default (D-rule: the PCN1 posture).
706
- if (!candidates.length && placetype === "postalcode" && state.postcodePrefixPrior && state.postcodePrefixIndex) {
707
- const probe = probePostcodePrefix(node.value, state.postcodePrefixIndex, query.country)
708
-
709
- if (probe) {
710
- const metadata: Record<string, unknown> = {
711
- postcode_prefix: probe.prefix,
712
- postcode_prefix_ancestors: probe.node.ancestors,
713
- ...(probe.node.radiusP95Km !== undefined ? { postcode_prefix_radius_p95_km: probe.node.radiusP95Km } : {}),
714
- ...(probe.node.lat !== undefined && probe.node.lon !== undefined
715
- ? { coordinate_source: "postcode_prefix" }
716
- : {}),
717
- }
718
-
719
- rec.check("postcode_prefix_prior")
720
- const prefixPlace = postcodePrefixResolvedPlace(probe.prefix, probe.node, state.postcodePrefixIndex)
721
-
722
- rec.emit({ id: prefixPlace.id, name: prefixPlace.name, source: "postcode_prefix" })
723
-
724
- return {
725
- top: prefixPlace,
726
- alternatives: [],
727
- metadata,
728
- }
729
- }
730
- }
731
-
732
- // The bare-toponym country race (fix B of the bare-country class): a lone locality-tagged span
733
- // also races the `country` placetype, because the parser tags bare country names `locality`
734
- // about half the time ("Japan", "China") and the locality filter makes the country row
735
- // unreachable at any rank. Runs ONLY for the tree's single value-bearing node, so every
736
- // address-shaped input is byte-stable. The locality winner's prominence arbitrates below;
737
- // with no locality candidates at all, a country hit resolves the span outright.
738
- const isBareRace = placetype === "locality" && node === state.bareLocalityNode
739
-
740
- if (isBareRace) {
741
- rec.check("bare_race")
742
- }
743
-
744
- const bareCountry = isBareRace ? await bareCountryCandidate(this.#backend, node.value, query.country) : null
745
- const bareRegion = isBareRace ? await bareRegionCandidate(this.#backend, node.value, query.country) : null
746
-
747
- if (!candidates.length) {
748
- // With no locality candidates at all, the admin namesake with the larger population answers
749
- // outright (the same precedence the dominance rule below applies).
750
- const admin = pickLargerAdmin(bareCountry, bareRegion)
751
-
752
- if (admin) {
753
- rec.check("empty_admin_pick")
754
- rec.emit({ id: admin.id, name: admin.name, source: "empty_admin" })
755
-
756
- return {
757
- top: admin,
758
- alternatives: [],
759
- metadata: admin === bareRegion ? { bare_region_repick: true } : { bare_country_repick: true },
760
- }
761
- }
762
-
763
- rec.emit(null)
764
-
765
- return null
766
- }
767
-
768
- // Postcode-anchor re-rank (#369): when a country posterior is supplied (from the address's
769
- // postcode), boost candidates by `anchorWeight * posterior[candidate.country]` and re-sort, so a
770
- // postcode that pins the country pulls the right-country place over a higher-BM25 foreign namesake
771
- // (the "Berlin DE vs Berlin US" class the #59 harness measured). No-op when `anchorPosterior` is
772
- // undefined (the default) → byte-identical resolution.
773
- //
774
- // Applied to BOTH region and locality — the two placetypes that suffer cross-country namesake/
775
- // abbreviation collisions a country posterior can break. The region case is the one #447's window
776
- // fix couldn't reach: a bare 2-letter abbreviation is shared across countries ("VT" is
777
- // both Vermont and Viterbo; "ME" both Maine and Messina), so with no country signal the score
778
- // picks the wrong one — and because resolveTree resolves region FIRST and inherits its country
779
- // down, a wrong region poisons the locality too. The postcode posterior breaks the tie at the
780
- // region, and the right country then flows to the locality. (Country/macroregion/county are
781
- // excluded: they don't exhibit this collision class and carry country via `parentID` when nested.)
782
- //
783
- // Tier-SAFE ordering: the candidate's exact-match flag is the PRIMARY key, so the country pin
784
- // never crosses the exact/partial boundary. WITHIN a tier, `score + anchorWeight * posterior`
785
- // applies the (soft) country boost. So a confident US postcode keeps the US EXACT region
786
- // ("ME" → Maine) ahead of a more-populous US PARTIAL match (Missouri) AND, within the exact
787
- // tier, ahead of a foreign exact match (Messina IT); a soft posterior still blends with score.
788
- // (A plain additive re-rank loses the tier — it isn't encoded in `score` — and flips
789
- // "ME" → Missouri / "PA" → Alabama. Backends that don't set `exactMatch` degrade to additive.)
790
- const anchorEligible = placetype === "region" || placetype === "locality"
791
- let ranked = candidates
792
-
793
- if (state.anchorPosterior && anchorEligible && candidates.length > 1) {
794
- const post = state.anchorPosterior
795
- const w = state.anchorWeight
796
-
797
- // #928 root cause: this sort's within-tier key was `score + w·posterior` — RAW SCORE order,
798
- // the exact metric #910 deprecated inside the exact tier as bm25-length-poisoned (a famous
799
- // place's alias-heavy doc reads ~15 pts WORSE than a tiny namesake's clean one; #905
800
- // measured it). Before #910 the anchor-off path also sorted by score, so the two paths
801
- // agreed; after, anchor-ON silently reverted to the poisoned metric — a CORRECT GB@1.00
802
- // pin flipped "London SE15 1DD" to a US namesake because +w·1.0 can't bridge the bm25 gap.
803
- // The within-tier key is now the backend's PROMINENCE (population + proximity, #938 units)
804
- // with the posterior as the additive country pin; score stays the final tiebreak. Backends
805
- // that don't populate `prominence` degrade to the additive score behavior.
806
- // oxlint-disable-next-line unicorn/no-array-sort -- sorts a freshly-built array; toSorted would double-allocate on a hot path
807
- ranked = [...candidates].sort((a, b) => {
808
- const tier = Number(b.exactMatch ?? false) - Number(a.exactMatch ?? false)
809
-
810
- if (tier !== 0) return tier
811
- // A candidate with no country gets no posterior mass rather than an index by `undefined`, which reads
812
- // every unknown-country row as the same key.
813
- const aKey = (a.prominence ?? a.score) + w * (a.country === undefined ? 0 : (post[a.country] ?? 0))
814
- const bKey = (b.prominence ?? b.score) + w * (b.country === undefined ? 0 : (post[b.country] ?? 0))
815
-
816
- return bKey - aKey || b.score - a.score
817
- })
818
-
819
- rec.stage("anchor", ranked)
820
- }
821
-
822
- // Locale-country soft prior (#27) — the #912 change's other half, at the tier that decides a bare
823
- // toponym the model tagged `locality`. `--locale en-GB "Whitby"` answers Whitby, Ontario while
824
- // `--default-country GB "Whitby"` answers the gold, because the CLI DROPS the locale-inferred
825
- // country for this shape rather than choosing between "hard filter" and "nothing". This is the
826
- // third option: an additive bonus inside the exact tier, never a filter.
827
- //
828
- // Three stand-downs, in the order they matter. A `defaultCountry` makes the prior a no-op by
829
- // construction (every candidate is already in it), so we skip the work rather than pretend. An
830
- // `anchorPosterior` is derived from the address's OWN postcode — evidence, which outranks a guess
831
- // about where the user is sitting. And an absent prior is the SHIPPED default: `ResolveOpts`
832
- // documents why (the weight that flips the four bare GB rows and the weight that holds the en-US
833
- // board are disjoint intervals), so this is inert unless a caller opts in.
834
- //
835
- // Runs BEFORE the importance key deliberately, matching span-rescore: fame is the stronger signal
836
- // wherever it has been measured, and it leaves an unscored candidate exactly where the prior put it.
837
- if (state.localeCountryPrior && !state.defaultCountry && !state.anchorPosterior && anchorEligible) {
838
- ranked = rankByCountryPrior(ranked, state.localeCountryPrior, state.localeCountryPriorWeight)
839
- rec.stage("locale_prior", ranked)
840
- }
841
-
842
- // Importance-first (#17/#28). Before this key a bare famous name was decided on POPULATION
843
- // alone, which is measurably the wrong prior for the class: `Whitby` answered Whitby, Ontario
844
- // (128,377) over Whitby, North Yorkshire (13,130), 5,508 km from where the person meant. Fame is
845
- // what a bare toponym is asking about, and the candidate build's blended `importance` column
846
- // measures it. Tier-safe and positive-evidence-only (an UNSCORED candidate keeps the rank
847
- // population gave it; only the scored ones permute), so it abstains byte-stably on an artifact
848
- // that predates the column.
849
- //
850
- // Skipped outright when an anchor posterior is in force. Fame is the prior of LAST resort: it answers
851
- // "which one did you probably mean" only when nothing in the query answered it, and a #369 posterior is
852
- // derived from the address's OWN postcode. Evidence outranks a prior. See `toponym-prior.ts`.
853
- if (!state.anchorPosterior) {
854
- ranked = rankByImportance(ranked)
855
- rec.stage("importance", ranked)
856
-
857
- // #1880 — bounded capital promotion, directly above the fame key it corrects and below the
858
- // containment partition (the qualifier is the address's own text; evidence outranks a prior).
859
- // Same stand-down as fame: an anchor posterior is postcode evidence and silences the prior.
860
- if (state.capitalLevel) {
861
- ranked = promoteCapitalsWithReceipt(ranked, state.capitalLevel, node)
862
- rec.stage("capital", ranked)
863
- }
864
- }
865
-
866
- // Admin-containment partition (#1717 stage 2): the LAST soft re-rank, after the anchor/fame keys
867
- // above, because the qualifier is the address's OWN text — evidence, which outranks a prior. The
868
- // backend already put contained rows first; this second partition is required, not belt-and-
869
- // braces: `rankByImportance` just re-ordered the exact tier by fame, and Richmond, Virginia
870
- // outscores Richmond, North Yorkshire on importance — without this the change loses exactly where
871
- // fame disagrees with the qualifier (the shared-function partition, tier-safe + stable, so it can
872
- // never promote a contained partial match over an exact one). No stamps → identity → byte-stable
873
- // on any backend that ignored `regionQualifier`.
874
- if (containmentEligible) {
875
- ranked = partitionByContainment(
876
- ranked,
877
- (c) => c.containedByQualifier === true,
878
- (c) => c.exactMatch === true
879
- )
880
-
881
- rec.stage("containment", ranked)
882
- }
883
-
884
- // Exact-type preference (#718): when the placetype-equivalence group let a broader admin tier
885
- // (`macroregion`/`macrocounty`) into the candidate pool, prefer a candidate of the EXACT
886
- // requested type over the macro fallback — a real `region` (US state, DE Bundesland, ES
887
- // provincia) must win over a same-name macroregion namesake, so no real region silently
888
- // downgrades to a macro. STABLE partition: exact-type candidates keep their (already-ranked)
889
- // relative order ahead of fallbacks, so the score / anchor re-rank survives WITHIN each tier.
890
- // No-op for placetypes without a macro fallback (the byte-stable default) and when every
891
- // candidate is the same tier.
892
- const hasFallbackCandidate = ranked.some((c) => isPlacetypeFallback(placetype, c.placetype))
893
-
894
- if (hasFallbackCandidate && ranked.length > 1) {
895
- ranked = [
896
- ...ranked.filter((c) => !isPlacetypeFallback(placetype, c.placetype)),
897
- ...ranked.filter((c) => isPlacetypeFallback(placetype, c.placetype)),
898
- ]
899
-
900
- rec.stage("exact_type", ranked)
901
- }
902
-
903
- const top = ranked[0]!
904
-
905
- if (top.score < state.minWinningScore) {
906
- rec.check("min_score_reject")
907
- rec.emit(null)
908
-
909
- return null
910
- }
911
-
912
- // The admin side of the bare-toponym race. The COUNTRY row wins on prominence alone —
913
- // Japan-the-country (pop 126M) over Japan, Pennsylvania (pop 0) — while the REGION row must
914
- // DOMINATE the locality winner by {@link BARE_REGION_DOMINANCE_LOG10} in log-population:
915
- // prominence saturates at the backend's populationBoost cap, so the margin is measured on the
916
- // raw populations, and the margin is what keeps bare "New York" on the city (state 19.6M vs
917
- // city 8.8M = 0.35, under the threshold) while bare "Georgia" promotes to the 11M state over the
918
- // Vermont hamlet (margin 3.4). A bare name with no admin namesake never reaches these lines,
919
- // and the displaced locality stays first among the alternatives either way.
920
- if (bareCountry && (bareCountry.prominence ?? bareCountry.score) > (top.prominence ?? top.score)) {
921
- rec.check("bare_country_repick")
922
- rec.emit({ id: bareCountry.id, name: bareCountry.name, source: "bare_country" })
923
-
924
- return { top: bareCountry, alternatives: ranked, metadata: { bare_country_repick: true } }
925
- }
926
-
927
- if (bareRegion && logPopulation(bareRegion) >= logPopulation(top) + BARE_REGION_DOMINANCE_LOG10) {
928
- rec.check("bare_region_repick")
929
- rec.emit({ id: bareRegion.id, name: bareRegion.name, source: "bare_region" })
930
-
931
- return { top: bareRegion, alternatives: ranked, metadata: { bare_region_repick: true } }
932
- }
933
-
934
- // Fallback-observability (#718): if the winner is a macro-type AND no exact-type candidate
935
- // existed for this span, annotate that a broader tier stood in for the true one. Additive —
936
- // identity/coordinate are unchanged; only `metadata.resolution_quality` is stamped downstream.
937
- if (isPlacetypeFallback(placetype, top.placetype)) {
938
- top.resolutionQuality = "fallback"
939
- rec.check("placetype_fallback")
940
- }
941
-
942
- rec.emit({ id: top.id, name: top.name, source: "ranked" })
943
-
944
- // The trace stamps (#1717 stage 2 / #1719's rule): an opted-in mechanism that cannot fire — a
945
- // pre-sidecar artifact, an incapable backend — must say so in the result, not degrade silently.
946
- // The parse-side census cannot see resolver mechanisms, so these stamps are its census surface.
947
- // admin_containment asserts a question was asked; variant_alias_exemption (#1893) asserts the
948
- // winning candidate reached the top BECAUSE the exemption spared it the cross-country penalty —
949
- // the winner-level firing receipt, same posture as capital_promotion.
950
- const pickMetadata = {
951
- ...(containmentEligible ? { admin_containment: adminContainmentVerdict(ranked) } : {}),
952
- ...(top.variantAliasExempted === true ? { variant_alias_exemption: true } : {}),
953
- // The pick was admitted from OUTSIDE the resolved parent's scope, by either widening: the resolver's own retry
954
- // without the parent (the scope was set — a resolved parent with a numeric id — and the retry is the only
955
- // thing that deletes it), or the backend's interior region-scope fallback, which keeps the query intact and
956
- // stamps the rows it re-admitted (#1731). Stamped so `applyParentFallbackContradiction` can tell a namesake
957
- // under another region from the incomplete chain both widenings exist for.
958
- ...((parentResolved && typeof parentResolved.id === "number" && query.parentID === undefined) ||
959
- top.regionScopeMiss === true
960
- ? { parent_fallback: true }
961
- : {}),
962
- }
963
-
964
- return {
965
- top,
966
- alternatives: ranked.slice(1),
967
- ...(Object.keys(pickMetadata).length ? { metadata: pickMetadata } : {}),
968
- }
969
- }
970
- }
971
-
972
- /**
973
- * #1880's promotion plus its firing receipt, in one place: when the promotion changes the race's leading candidate, the
974
- * node is stamped `capital_promotion` with the promoted candidate's country — the same posture as
975
- * `postcode_country_scope`, a mechanism reporting that it SPOKE apart from whether the outcome moved, so an unchanged
976
- * verdict downstream can never mean either "harmless" or "never ran". Metadata-only; nothing reads it to rank.
977
- */
978
- function promoteCapitalsWithReceipt<
979
- T extends Pick<ResolvedPlace, "score" | "name" | "country" | "lat" | "lon"> &
980
- Partial<Pick<ResolvedPlace, "exactMatch" | "importance" | "prominence">>,
981
- >(ranked: readonly T[], level: CapitalLevelFn, node: { metadata?: Record<string, unknown> }): T[] {
982
- const promoted = promoteCapitals(ranked, level)
983
-
984
- if (promoted[0] !== ranked[0]) {
985
- node.metadata = { ...node.metadata, capital_promotion: promoted[0]!.country ?? true }
986
- }
987
-
988
- return promoted
989
- }