@mailwoman/resolver 9.1.0 → 9.3.0

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