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