@mailwoman/resolver 10.0.0 → 10.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (134) hide show
  1. package/README.md +9 -7
  2. package/lib/admin/coherence-passes.ts +31 -172
  3. package/lib/admin/containment.ts +15 -33
  4. package/lib/admin/jp-municipality.ts +21 -14
  5. package/lib/admin/winner.ts +37 -69
  6. package/lib/backend-capabilities.ts +28 -27
  7. package/lib/bare-toponym-race.ts +69 -37
  8. package/lib/decorate-node.ts +25 -49
  9. package/lib/fold-name.ts +5 -18
  10. package/lib/index.ts +5 -9
  11. package/lib/plausibility.ts +41 -68
  12. package/lib/postcode/country-coherence.ts +92 -296
  13. package/lib/postcode/prefix.ts +24 -86
  14. package/lib/postcode/shape-coherence.ts +26 -116
  15. package/lib/remote-resolver.ts +38 -33
  16. package/lib/rerank.ts +41 -54
  17. package/lib/resolve/passes.ts +188 -177
  18. package/lib/resolve.ts +744 -0
  19. package/lib/span-rescore.ts +219 -175
  20. package/lib/street/evidence.ts +65 -73
  21. package/lib/street/tier.ts +51 -194
  22. package/lib/toponym-prior.ts +54 -180
  23. package/out/admin/coherence-passes.d.ts +18 -69
  24. package/out/admin/coherence-passes.d.ts.map +1 -1
  25. package/out/admin/coherence-passes.js +24 -166
  26. package/out/admin/coherence-passes.js.map +1 -1
  27. package/out/admin/containment.d.ts +13 -31
  28. package/out/admin/containment.d.ts.map +1 -1
  29. package/out/admin/containment.js +13 -31
  30. package/out/admin/containment.js.map +1 -1
  31. package/out/admin/jp-municipality.d.ts +21 -14
  32. package/out/admin/jp-municipality.d.ts.map +1 -1
  33. package/out/admin/jp-municipality.js +18 -12
  34. package/out/admin/jp-municipality.js.map +1 -1
  35. package/out/admin/winner.d.ts +32 -64
  36. package/out/admin/winner.d.ts.map +1 -1
  37. package/out/admin/winner.js +23 -56
  38. package/out/admin/winner.js.map +1 -1
  39. package/out/{admin/index.d.ts → admin.d.ts} +1 -1
  40. package/out/admin.d.ts.map +1 -0
  41. package/out/{admin/index.js → admin.js} +1 -1
  42. package/out/admin.js.map +1 -0
  43. package/out/backend-capabilities.d.ts +19 -20
  44. package/out/backend-capabilities.d.ts.map +1 -1
  45. package/out/backend-capabilities.js +28 -26
  46. package/out/backend-capabilities.js.map +1 -1
  47. package/out/bare-toponym-race.d.ts +54 -27
  48. package/out/bare-toponym-race.d.ts.map +1 -1
  49. package/out/bare-toponym-race.js +69 -37
  50. package/out/bare-toponym-race.js.map +1 -1
  51. package/out/decorate-node.d.ts +6 -8
  52. package/out/decorate-node.d.ts.map +1 -1
  53. package/out/decorate-node.js +25 -49
  54. package/out/decorate-node.js.map +1 -1
  55. package/out/fold-name.d.ts +5 -18
  56. package/out/fold-name.d.ts.map +1 -1
  57. package/out/fold-name.js +5 -18
  58. package/out/fold-name.js.map +1 -1
  59. package/out/index.d.ts +5 -6
  60. package/out/index.d.ts.map +1 -1
  61. package/out/index.js +5 -8
  62. package/out/index.js.map +1 -1
  63. package/out/plausibility.d.ts +30 -60
  64. package/out/plausibility.d.ts.map +1 -1
  65. package/out/plausibility.js +19 -52
  66. package/out/plausibility.js.map +1 -1
  67. package/out/postcode/country-coherence.d.ts +53 -167
  68. package/out/postcode/country-coherence.d.ts.map +1 -1
  69. package/out/postcode/country-coherence.js +42 -259
  70. package/out/postcode/country-coherence.js.map +1 -1
  71. package/out/postcode/prefix.d.ts +18 -69
  72. package/out/postcode/prefix.d.ts.map +1 -1
  73. package/out/postcode/prefix.js +11 -78
  74. package/out/postcode/prefix.js.map +1 -1
  75. package/out/postcode/shape-coherence.d.ts +18 -85
  76. package/out/postcode/shape-coherence.d.ts.map +1 -1
  77. package/out/postcode/shape-coherence.js +11 -107
  78. package/out/postcode/shape-coherence.js.map +1 -1
  79. package/out/{postcode/index.d.ts → postcode.d.ts} +1 -1
  80. package/out/postcode.d.ts.map +1 -0
  81. package/out/{postcode/index.js → postcode.js} +1 -1
  82. package/out/postcode.js.map +1 -0
  83. package/out/remote-resolver.d.ts +32 -31
  84. package/out/remote-resolver.d.ts.map +1 -1
  85. package/out/remote-resolver.js +12 -20
  86. package/out/remote-resolver.js.map +1 -1
  87. package/out/rerank.d.ts +32 -46
  88. package/out/rerank.d.ts.map +1 -1
  89. package/out/rerank.js +16 -41
  90. package/out/rerank.js.map +1 -1
  91. package/out/resolve/passes.d.ts +108 -95
  92. package/out/resolve/passes.d.ts.map +1 -1
  93. package/out/resolve/passes.js +67 -126
  94. package/out/resolve/passes.js.map +1 -1
  95. package/out/resolve.d.ts +15 -0
  96. package/out/resolve.d.ts.map +1 -0
  97. package/out/resolve.js +557 -0
  98. package/out/resolve.js.map +1 -0
  99. package/out/span-rescore.d.ts +56 -65
  100. package/out/span-rescore.d.ts.map +1 -1
  101. package/out/span-rescore.js +134 -132
  102. package/out/span-rescore.js.map +1 -1
  103. package/out/street/evidence.d.ts +56 -61
  104. package/out/street/evidence.d.ts.map +1 -1
  105. package/out/street/evidence.js +22 -46
  106. package/out/street/evidence.js.map +1 -1
  107. package/out/street/tier.d.ts +18 -30
  108. package/out/street/tier.d.ts.map +1 -1
  109. package/out/street/tier.js +43 -191
  110. package/out/street/tier.js.map +1 -1
  111. package/out/{street/index.d.ts → street.d.ts} +1 -1
  112. package/out/street.d.ts.map +1 -0
  113. package/out/{street/index.js → street.js} +1 -1
  114. package/out/street.js.map +1 -0
  115. package/out/toponym-prior.d.ts +22 -110
  116. package/out/toponym-prior.d.ts.map +1 -1
  117. package/out/toponym-prior.js +41 -170
  118. package/out/toponym-prior.js.map +1 -1
  119. package/package.json +44 -147
  120. package/lib/resolve/index.ts +0 -989
  121. package/out/admin/index.d.ts.map +0 -1
  122. package/out/admin/index.js.map +0 -1
  123. package/out/postcode/index.d.ts.map +0 -1
  124. package/out/postcode/index.js.map +0 -1
  125. package/out/resolve/index.d.ts +0 -20
  126. package/out/resolve/index.d.ts.map +0 -1
  127. package/out/resolve/index.js +0 -808
  128. package/out/resolve/index.js.map +0 -1
  129. package/out/street/index.d.ts.map +0 -1
  130. package/out/street/index.js.map +0 -1
  131. package/vitest.config.ts +0 -38
  132. /package/lib/{admin/index.ts → admin.ts} +0 -0
  133. /package/lib/{postcode/index.ts → postcode.ts} +0 -0
  134. /package/lib/{street/index.ts → street.ts} +0 -0
package/lib/resolve.ts ADDED
@@ -0,0 +1,744 @@
1
+ /**
2
+ * @copyright Sister Software
3
+ * @license AGPL-3.0
4
+ * @author Teffen Ellis, et al.
5
+ *
6
+ * `resolveTree` walks an `AddressTree` top-down and decorates matched nodes.
7
+ * Child lookups are scoped by resolved parents to reduce ambiguity.
8
+ */
9
+
10
+ import type { ComponentTag } from "@mailwoman/codex/component"
11
+ import { matchCountry, matchSubdivision } from "@mailwoman/codex/country"
12
+ import { DEFAULT_PLACETYPE_MAP, isPlacetypeFallback } from "@mailwoman/codex/placetype-map"
13
+ import { collectNodes, type AddressNode, type AddressTree, type Interpretation } from "@mailwoman/core/decoder"
14
+ import {
15
+ type BackendCapabilityGap,
16
+ type DefaultCountry,
17
+ type ResolveNodeTrace,
18
+ type ResolvedPlace,
19
+ type ResolveOpts,
20
+ type Resolver,
21
+ type ResolverBackend,
22
+ countriesFromPostcodeFormat,
23
+ resolveSwitches,
24
+ } from "@mailwoman/core/resolver"
25
+
26
+ import {
27
+ applyAdminCoherence,
28
+ applyExplicitCountryCoherence,
29
+ applyParentFallbackContradiction,
30
+ applyRegionCountryCoherence,
31
+ } from "#admin/coherence-passes"
32
+ import { adminContainmentVerdict, firstRegionQualifier, partitionByContainment } from "#admin/containment"
33
+ import { resolveCompoundMunicipality } from "#admin/jp-municipality"
34
+ import { describeCapabilityGaps, reportCapabilityGaps } from "#backend-capabilities"
35
+ import {
36
+ BARE_REGION_DOMINANCE_LOG10,
37
+ bareCountryCandidate,
38
+ bareRegionCandidate,
39
+ logPopulation,
40
+ loneBareLocalityNode,
41
+ pickLargerAdmin,
42
+ } from "#bare-toponym-race"
43
+ import { decorateNode } from "#decorate-node"
44
+ import {
45
+ findPostcodeCountryScope,
46
+ type PostcodeCountryScope,
47
+ stampPostcodeCountryScope,
48
+ } from "#postcode/country-coherence"
49
+ import { type CoordinateOptionalPlace, postcodePrefixResolvedPlace, probePostcodePrefix } from "#postcode/prefix"
50
+ import { applyPostcodeShapeCoherence, isShapeExcludedPostcode } from "#postcode/shape-coherence"
51
+ import {
52
+ applyPostcodeConsistency,
53
+ applySpanRescore,
54
+ createNodeTraceRecorder,
55
+ DIAGNOSTIC_BANDS,
56
+ firstPostcodeValue,
57
+ NOOP_TRACE_RECORDER,
58
+ pickCompletion,
59
+ type ResolutionState,
60
+ type ResolvedOpts,
61
+ } from "#resolve/passes"
62
+ import { applyAddressPoint, applyInterpolation, applyStreetCentroid } from "#street/tier"
63
+ import {
64
+ type CapitalLevelFn,
65
+ DEFAULT_COUNTRY_PRIOR_WEIGHT,
66
+ promoteCapitals,
67
+ rankByCountryPrior,
68
+ rankByImportance,
69
+ } from "#toponym-prior"
70
+
71
+ /**
72
+ * Build a `Resolver` from a `ResolverBackend`.
73
+ */
74
+ export { DEFAULT_POSTCODE_MAX_MOVE_KM } from "#resolve/passes"
75
+
76
+ export function createWOFResolver(backend: ResolverBackend): Resolver {
77
+ return new WOFResolver(backend)
78
+ }
79
+
80
+ /**
81
+ * Return an explicit country scope from the tree when it is unambiguous.
82
+ *
83
+ * The tree must contain one country node.
84
+ * Subdivision-like names are ignored.
85
+ */
86
+ function explicitCountryScope(roots: readonly AddressNode[]): string | null {
87
+ const countryNodes = collectNodes(roots, (node) => node.tag === "country" && node.value.trim())
88
+
89
+ if (countryNodes.length !== 1) return null
90
+
91
+ const value = countryNodes[0]!.value.trim()
92
+ const matched = matchCountry(value)
93
+
94
+ if (!matched) return null
95
+
96
+ if (matchSubdivision(value)) return null
97
+
98
+ return matched.iso2
99
+ }
100
+
101
+ /**
102
+ * The default country a lookup filters by, or undefined when none applies.
103
+ * `country` lookups ignore an inferred scope.
104
+ */
105
+ function scopedCountryFor(placetype: string, scope: DefaultCountry | null): string | undefined {
106
+ if (!scope || (placetype === "country" && scope.source === "inferred")) return undefined
107
+
108
+ return scope.country
109
+ }
110
+
111
+ /**
112
+ * Reports whether the caller chose the default country scope.
113
+ */
114
+ function isCallerScope(scope: DefaultCountry | null): boolean {
115
+ return scope?.source === "caller"
116
+ }
117
+
118
+ class WOFResolver implements Resolver {
119
+ readonly #backend: ResolverBackend
120
+ /**
121
+ * Coverage metadata surfaced from the backend artifact.
122
+ */
123
+ readonly artifactCoverage: Resolver["artifactCoverage"]
124
+ /**
125
+ * Optional backend capabilities that the implementation lacks.
126
+ */
127
+ readonly capabilityGaps: readonly BackendCapabilityGap[]
128
+
129
+ constructor(backend: ResolverBackend) {
130
+ this.#backend = backend
131
+ this.artifactCoverage = backend.artifactCoverage ?? null
132
+ this.capabilityGaps = describeCapabilityGaps(backend)
133
+ reportCapabilityGaps(this.capabilityGaps)
134
+ }
135
+
136
+ /**
137
+ * Direct `findPlace` passthrough.
138
+ */
139
+ findPlace: Resolver["findPlace"] = (query) => this.#backend.findPlace(query)
140
+
141
+ async resolveTree(tree: AddressTree, callerOpts: ResolveOpts = {}): Promise<AddressTree> {
142
+ // Every on/off switch resolves against the one defaults table, so the reads below are plain truthiness.
143
+ const opts: ResolvedOpts = { ...callerOpts, ...resolveSwitches(callerOpts) }
144
+ // Optional early postcode-shape pass.
145
+ // Runs sync and can only narrow candidates.
146
+ const shapeVerdict = opts.postcodeShapeCoherence ? applyPostcodeShapeCoherence(tree.roots) : null
147
+
148
+ const state: ResolutionState = {
149
+ lookupsRemaining: opts.maxLookups ?? 10,
150
+ // If provided, `placetypeMap` fully replaces the default.
151
+ placetypeMap: opts.placetypeMap ?? DEFAULT_PLACETYPE_MAP,
152
+ minWinningScore: opts.minWinningScore ?? 0,
153
+ minScoreRefusals: 0,
154
+ candidatesPerLookup: opts.candidatesPerLookup ?? 5,
155
+ defaultCountry: opts.defaultCountry ?? null,
156
+ bareLocalityNode: loneBareLocalityNode(tree, opts.placetypeMap ?? DEFAULT_PLACETYPE_MAP),
157
+ parentFallback: opts.parentFallback,
158
+ // Only enable unreachable diagnostics when a trace sink exists.
159
+ ...(opts.diagnoseUnreachable && opts.traceSink ? { diagnoseUnreachable: true } : {}),
160
+ postcode: firstPostcodeValue(tree.roots),
161
+ // Optional postcode-containment hint for locality lookups.
162
+ postcodeContainmentCoherence: opts.postcodeContainmentCoherence,
163
+ // Optional postcode-prefix prior and index.
164
+ postcodePrefixPrior: opts.postcodePrefixPrior,
165
+ postcodePrefixIndex: opts.postcodePrefixIndex,
166
+ // Derive format-implied countries when not provided.
167
+ postcodeFormatCountries:
168
+ opts.postcodeFormatCountries ?? countriesFromPostcodeFormat(firstPostcodeValue(tree.roots)),
169
+ fuzzyCountryScope: opts.fuzzyCountryScope,
170
+ bias: opts.bias,
171
+ anchorPosterior: opts.anchorPosterior,
172
+ anchorWeight: opts.anchorWeight ?? 2,
173
+ localeCountryPrior: opts.localeCountryPrior,
174
+ localeCountryPriorWeight: opts.localeCountryPriorWeight ?? DEFAULT_COUNTRY_PRIOR_WEIGHT,
175
+ capitalLevel: opts.capitalLevel,
176
+ hardCountry: opts.hardCountry,
177
+ // Dual-role hierarchy completion (default on, backend-dependent).
178
+ hierarchyCompletion: opts.hierarchyCompletion,
179
+ includeAncestors: opts.includeAncestors,
180
+ // Optional admin containment rerank uses a pre-scanned region qualifier.
181
+ adminContainmentRerank: opts.adminContainmentRerank,
182
+ regionQualifier: firstRegionQualifier(tree.roots),
183
+ ...(opts.traceSink ? { traceSink: opts.traceSink } : {}),
184
+ localityNodePresent: false,
185
+ resolvedRegion: null,
186
+ resolvedRegionNode: null,
187
+ }
188
+
189
+ // Optional pre-walk postcode-country coherence pass.
190
+ // This is the only pass allowed to override `defaultCountry`.
191
+ let postcodeScope: PostcodeCountryScope | null = null
192
+
193
+ // Explicit country text in the tree can pre-scope the walk.
194
+ // Explicit scope outranks inferred default scope.
195
+ let explicitScope: string | null = null
196
+
197
+ if (state.defaultCountry?.source !== "caller") {
198
+ explicitScope = explicitCountryScope(tree.roots)
199
+
200
+ if (explicitScope) {
201
+ state.defaultCountry = { country: explicitScope, source: "caller" }
202
+ }
203
+ }
204
+
205
+ if (opts.postcodeCountryCoherence && state.postcode) {
206
+ postcodeScope = await findPostcodeCountryScope(tree.roots, this.#backend, {
207
+ postcode: state.postcode,
208
+ defaultCountry: state.defaultCountry?.country ?? null,
209
+ ...(shapeVerdict?.narrowing ? { candidateSystems: shapeVerdict.narrowing } : {}),
210
+ ...(opts.postcodeCountryCoherenceThresholdKm != null
211
+ ? { thresholdKm: opts.postcodeCountryCoherenceThresholdKm }
212
+ : {}),
213
+ })
214
+
215
+ if (postcodeScope) {
216
+ // Override default country for the walk.
217
+ // The postcode's country replaces the scope but keeps its source.
218
+ state.defaultCountry = { country: postcodeScope.country, source: state.defaultCountry?.source ?? "caller" }
219
+ }
220
+ }
221
+
222
+ const newRoots: AddressNode[] = []
223
+
224
+ for (const root of tree.roots) {
225
+ newRoots.push(await this.#walk(root, /* parentResolved */ null, state))
226
+ }
227
+
228
+ // Stamp metadata for postcode-country override.
229
+ if (postcodeScope) {
230
+ stampPostcodeCountryScope(newRoots, postcodeScope)
231
+ }
232
+
233
+ // Stamp metadata when explicit country pre-scope was used.
234
+ if (explicitScope) {
235
+ for (const root of newRoots) {
236
+ if (root.tag === "country") {
237
+ root.metadata = { ...root.metadata, explicit_country_scope: explicitScope }
238
+ }
239
+ }
240
+ }
241
+
242
+ // If enabled, add a dropped dual-role locality as a region interpretation.
243
+ if (state.hierarchyCompletion && state.resolvedRegion && state.resolvedRegionNode && !state.localityNodePresent) {
244
+ this.#completeRegionRole(state.resolvedRegion, state.resolvedRegionNode)
245
+ }
246
+
247
+ // Admin coherence passes (default on).
248
+ if (opts.adminCoherence) {
249
+ // Clear contradictory parent-fallback picks before coherence passes.
250
+ applyParentFallbackContradiction(newRoots)
251
+ await applyAdminCoherence(newRoots, this.#backend)
252
+ // Re-resolve locality when explicit country contradicts it.
253
+ await applyExplicitCountryCoherence(newRoots, this.#backend)
254
+ // Re-resolve foreign region/locality pairs blocked by locale scope.
255
+ await applyRegionCountryCoherence(newRoots, this.#backend, state.defaultCountry?.country ?? null)
256
+ }
257
+
258
+ // Postcode/locality consistency pass (default on).
259
+ if (opts.postcodeConsistency) {
260
+ applyPostcodeConsistency(newRoots, opts.postcodeConsistencyThresholdKm ?? 50, opts.postcodeConsistencyMaxMoveKm)
261
+ }
262
+
263
+ // Optional exact address-point tier.
264
+ if (opts.addressPoints) {
265
+ applyAddressPoint(newRoots, opts.addressPoints, opts.addressPointBboxFallback)
266
+ }
267
+
268
+ // Optional interpolation tier after exact points.
269
+ if (opts.interpolation) {
270
+ applyInterpolation(newRoots, opts.interpolation, opts.interpolationRadiusCalibration)
271
+ }
272
+
273
+ // Span-rescore fallback tier (default on).
274
+ // Skip when a min-score refusal already occurred.
275
+ if (opts.spanRescore && state.minScoreRefusals === 0) {
276
+ await applySpanRescore(newRoots, tree.raw, this.#backend, opts)
277
+ }
278
+
279
+ // Retry exact address-point tier once after span-rescore recovery.
280
+ if (opts.addressPoints) {
281
+ applyAddressPoint(newRoots, opts.addressPoints, opts.addressPointBboxFallback)
282
+ }
283
+
284
+ // Optional street-centroid tier runs last.
285
+ if (opts.streetCentroids) {
286
+ applyStreetCentroid(newRoots, tree.raw, opts.streetCentroids, opts.streetCountryHints ?? [])
287
+ }
288
+
289
+ return { raw: tree.raw, roots: newRoots }
290
+ }
291
+
292
+ /**
293
+ * Add a dropped dual-role locality as a `locality` interpretation on a resolved region node.
294
+ */
295
+ #completeRegionRole(region: CoordinateOptionalPlace, regionNode: AddressNode): void {
296
+ if (typeof region.id !== "number" || !this.#backend.coincidentLocalitiesFor) return
297
+ const loc = pickCompletion(this.#backend.coincidentLocalitiesFor(region.id))
298
+
299
+ if (!loc) return
300
+
301
+ const interpretation: Interpretation = {
302
+ tag: "locality",
303
+ placeID: `wof:${loc.id}`,
304
+ sourceID: `${loc.placetype}:${loc.id}`,
305
+ lat: loc.lat,
306
+ lon: loc.lon,
307
+ confidence: 0,
308
+ metadata: { relationship_type: loc.relationshipType, resolver_completed: true, resolver_name: loc.name },
309
+ }
310
+
311
+ regionNode.interpretations = [...(regionNode.interpretations ?? []), interpretation]
312
+ }
313
+
314
+ async #walk(
315
+ node: AddressNode,
316
+ parentResolved: CoordinateOptionalPlace | null,
317
+ state: ResolutionState
318
+ ): Promise<AddressNode> {
319
+ // Clone.
320
+ // The caller's nodes stay as they were passed in.
321
+ const decorated: AddressNode = { ...node, children: [] }
322
+
323
+ const placetype = state.placetypeMap[node.tag as ComponentTag]
324
+
325
+ // Track whether a locality node exists for hierarchy completion.
326
+ if (placetype === "locality") {
327
+ state.localityNodePresent = true
328
+ }
329
+
330
+ let resolved: CoordinateOptionalPlace | null = null
331
+
332
+ // Skip lookup for shape-excluded postcode spans.
333
+ if (placetype && state.lookupsRemaining > 0 && node.value.trim() && !isShapeExcludedPostcode(node)) {
334
+ let picked = await this.#lookupAndPick(node, placetype, parentResolved, state)
335
+
336
+ // Compound JP municipality handling with scoped fallback control.
337
+ if (!picked && node.tag === "municipality") {
338
+ picked = await resolveCompoundMunicipality(
339
+ node.value,
340
+ parentResolved,
341
+ () => state.lookupsRemaining > 0,
342
+ async (value, scope, parentFallback) => {
343
+ const prior = state.parentFallback
344
+ state.parentFallback = prior && parentFallback
345
+
346
+ try {
347
+ return await this.#lookupAndPick({ ...node, value }, placetype, scope, state)
348
+ } finally {
349
+ state.parentFallback = prior
350
+ }
351
+ }
352
+ )
353
+ }
354
+
355
+ if (picked) {
356
+ resolved = picked.top
357
+ decorateNode(decorated, picked.top, picked.alternatives)
358
+
359
+ if (picked.metadata) {
360
+ decorated.metadata = { ...decorated.metadata, ...picked.metadata }
361
+ }
362
+
363
+ // Retag bare-toponym repicks to the resolved admin type.
364
+ if (decorated.metadata?.["bare_country_repick"]) {
365
+ decorated.tag = "country"
366
+ } else if (decorated.metadata?.["bare_region_repick"]) {
367
+ decorated.tag = "region"
368
+ }
369
+
370
+ // Optional lineage attachment.
371
+ if (state.includeAncestors && this.#backend.ancestors) {
372
+ decorated.metadata = { ...decorated.metadata, ancestors: this.#backend.ancestors(picked.top.id) }
373
+ }
374
+
375
+ // Capture first resolved region for hierarchy completion.
376
+ if (placetype === "region" && state.resolvedRegion === null) {
377
+ state.resolvedRegion = picked.top
378
+ state.resolvedRegionNode = decorated
379
+ }
380
+ }
381
+ }
382
+
383
+ const carryParent = resolved ?? parentResolved
384
+
385
+ for (const child of node.children) {
386
+ decorated.children.push(await this.#walk(child, carryParent, state))
387
+ }
388
+
389
+ return decorated
390
+ }
391
+
392
+ /**
393
+ * Find other admin bands that match the same value.
394
+ * Keeps country scope and clears parent scope.
395
+ */
396
+ async #probeOtherBands(
397
+ query: Parameters<ResolverBackend["findPlace"]>[0],
398
+ probed: string
399
+ ): Promise<NonNullable<ResolveNodeTrace["reachableIn"]>> {
400
+ const found: NonNullable<ResolveNodeTrace["reachableIn"]> = []
401
+
402
+ for (const band of DIAGNOSTIC_BANDS) {
403
+ if (band === probed) continue
404
+
405
+ try {
406
+ const hits = await this.#backend.findPlace({ ...query, placetype: band, parentID: undefined })
407
+
408
+ if (hits.length) {
409
+ found.push({ placetype: band, n: hits.length })
410
+ }
411
+ } catch {
412
+ // Skip bands the backend cannot query.
413
+ continue
414
+ }
415
+ }
416
+
417
+ return found
418
+ }
419
+
420
+ async #lookupAndPick(
421
+ node: AddressNode,
422
+ placetype: string,
423
+ parentResolved: CoordinateOptionalPlace | null,
424
+ state: ResolutionState
425
+ ): Promise<{
426
+ top: CoordinateOptionalPlace
427
+ alternatives: ResolvedPlace[]
428
+ metadata?: Record<string, unknown>
429
+ } | null> {
430
+ state.lookupsRemaining--
431
+
432
+ const query: Parameters<ResolverBackend["findPlace"]>[0] = {
433
+ text: node.value,
434
+ placetype,
435
+ limit: state.candidatesPerLookup,
436
+ }
437
+
438
+ // Optional proximity bias reorders candidates without changing the candidate set.
439
+ if (state.bias && state.bias.length) {
440
+ query.bias = state.bias
441
+ }
442
+
443
+ // Apply resolved parent scope when available.
444
+ if (parentResolved && typeof parentResolved.id === "number") {
445
+ query.parentID = parentResolved.id
446
+ }
447
+
448
+ // Country scope precedence: parent -> default -> node hint -> hard country.
449
+ const countryHint = node.metadata?.["country_hint"]
450
+
451
+ // Do not apply inferred default-country filtering to country lookups.
452
+ const defaultCountryForLookup = scopedCountryFor(placetype, state.defaultCountry)
453
+
454
+ const country =
455
+ parentResolved?.country ??
456
+ defaultCountryForLookup ??
457
+ (typeof countryHint === "string" ? countryHint : undefined) ??
458
+ state.hardCountry
459
+
460
+ if (country) {
461
+ query.country = country
462
+ }
463
+
464
+ // Optional fuzzy-country hint for typo-fuzzy backend logic.
465
+ if (state.fuzzyCountryScope) {
466
+ query.fuzzyCountry = state.fuzzyCountryScope
467
+ }
468
+
469
+ // Optional containment rerank for locality using region qualifier.
470
+ const containmentEligible =
471
+ state.adminContainmentRerank &&
472
+ placetype === "locality" &&
473
+ state.regionQualifier != null &&
474
+ !isCallerScope(state.defaultCountry)
475
+
476
+ if (containmentEligible) {
477
+ query.regionQualifier = state.regionQualifier!
478
+ }
479
+
480
+ // Optional locality postcode hint and containment coherence flag.
481
+ if (placetype === "locality" && state.postcode) {
482
+ query.postcode = state.postcode
483
+
484
+ if (state.postcodeContainmentCoherence) {
485
+ query.postcodeContainmentCoherence = true
486
+ }
487
+ }
488
+
489
+ // Trace recorder (no-op when no sink).
490
+ const rec = state.traceSink ? createNodeTraceRecorder(state.traceSink) : NOOP_TRACE_RECORDER
491
+
492
+ // Bind a snapshot so later query mutations do not affect trace history.
493
+ rec.bind(node, placetype, { ...query }, state.candidatesPerLookup)
494
+
495
+ let candidates: ResolvedPlace[]
496
+
497
+ // For unconstrained postalcodes, probe format-implied countries only.
498
+ if (placetype === "postalcode" && !query.country && state.postcodeFormatCountries?.length) {
499
+ rec.check("postcode_format_probe")
500
+ let best: ResolvedPlace | null = null
501
+
502
+ for (const impliedCountry of state.postcodeFormatCountries) {
503
+ try {
504
+ const hits = await this.#backend.findPlace({ ...query, country: impliedCountry })
505
+ const top = hits[0]
506
+
507
+ // Keep the best per-country winner by score.
508
+ if (top && (!best || top.score > best.score)) {
509
+ best = top
510
+ }
511
+ } catch {
512
+ // Treat per-country probe errors as misses.
513
+ }
514
+ }
515
+
516
+ if (best) {
517
+ rec.emit({ id: best.id, name: best.name, source: "postcode_format_probe" })
518
+
519
+ return { top: best, alternatives: [] }
520
+ }
521
+
522
+ candidates = []
523
+ } else {
524
+ try {
525
+ candidates = await this.#backend.findPlace(query)
526
+ rec.stage("initial", candidates)
527
+
528
+ // Surface backend region-scope fallback as a trace check.
529
+ if (candidates[0]?.regionScopeMiss) {
530
+ rec.check("region_scope_miss")
531
+ }
532
+
533
+ // If parent scope misses, retry once without parent scope.
534
+ if (!candidates.length && state.parentFallback && query.parentID != null) {
535
+ delete query.parentID
536
+ rec.check("parent_fallback_retry")
537
+ candidates = await this.#backend.findPlace(query)
538
+ rec.stage("parent_fallback", candidates)
539
+ }
540
+
541
+ // Optional diagnostics: record other bands that can resolve this value.
542
+ if (!candidates.length && state.diagnoseUnreachable) {
543
+ rec.reachable(await this.#probeOtherBands(query, placetype))
544
+ }
545
+ } catch (error) {
546
+ // Defensive: backend errors should not abort the whole tree walk.
547
+ rec.check(`backend_error: ${(error as Error).message}`)
548
+ rec.emit(null)
549
+
550
+ return null
551
+ }
552
+ }
553
+
554
+ // Optional postcode-prefix prior when postcode lookup misses.
555
+ if (!candidates.length && placetype === "postalcode" && state.postcodePrefixPrior && state.postcodePrefixIndex) {
556
+ const probe = probePostcodePrefix(node.value, state.postcodePrefixIndex, query.country)
557
+
558
+ if (probe) {
559
+ const metadata: Record<string, unknown> = {
560
+ postcode_prefix: probe.prefix,
561
+ postcode_prefix_ancestors: probe.node.ancestors,
562
+ ...(probe.node.radiusP95Km != null ? { postcode_prefix_radius_p95_km: probe.node.radiusP95Km } : {}),
563
+ ...(probe.node.lat != null && probe.node.lon != null ? { coordinate_source: "postcode_prefix" } : {}),
564
+ }
565
+
566
+ rec.check("postcode_prefix_prior")
567
+ const prefixPlace = postcodePrefixResolvedPlace(probe.prefix, probe.node, state.postcodePrefixIndex)
568
+
569
+ rec.emit({ id: prefixPlace.id, name: prefixPlace.name, source: "postcode_prefix" })
570
+
571
+ return {
572
+ top: prefixPlace,
573
+ alternatives: [],
574
+ metadata,
575
+ }
576
+ }
577
+ }
578
+
579
+ // Bare-toponym race: locality-tagged single spans also probe country/region.
580
+ const isBareRace = placetype === "locality" && node === state.bareLocalityNode
581
+
582
+ if (isBareRace) {
583
+ rec.check("bare_race")
584
+ }
585
+
586
+ const bareCountry = isBareRace ? await bareCountryCandidate(this.#backend, node.value, query.country) : null
587
+ const bareRegion = isBareRace ? await bareRegionCandidate(this.#backend, node.value, query.country) : null
588
+
589
+ if (!candidates.length) {
590
+ // With no locality candidates, pick the larger admin namesake.
591
+ const admin = pickLargerAdmin(bareCountry, bareRegion)
592
+
593
+ if (admin) {
594
+ rec.check("empty_admin_pick")
595
+ rec.emit({ id: admin.id, name: admin.name, source: "empty_admin" })
596
+
597
+ return {
598
+ top: admin,
599
+ alternatives: [],
600
+ metadata: admin === bareRegion ? { bare_region_repick: true } : { bare_country_repick: true },
601
+ }
602
+ }
603
+
604
+ rec.emit(null)
605
+
606
+ return null
607
+ }
608
+
609
+ // Optional anchor-based rerank using postcode country posterior.
610
+ // Applied to region/locality and kept tier-safe by exact-match first.
611
+ const anchorEligible = placetype === "region" || placetype === "locality"
612
+ let ranked = candidates
613
+
614
+ if (state.anchorPosterior && anchorEligible && candidates.length > 1) {
615
+ const post = state.anchorPosterior
616
+ const w = state.anchorWeight
617
+
618
+ // Within-tier key uses prominence (fallback score) plus posterior boost.
619
+ // oxlint-disable-next-line unicorn/no-array-sort -- sorts a freshly-built array. toSorted would double-allocate on a hot path
620
+ ranked = [...candidates].sort((a, b) => {
621
+ const tier = Number(b.exactMatch ?? false) - Number(a.exactMatch ?? false)
622
+
623
+ if (tier !== 0) return tier
624
+ // Unknown-country candidates get zero posterior mass.
625
+ const aKey = (a.prominence ?? a.score) + w * (a.country ? (post[a.country] ?? 0) : 0)
626
+ const bKey = (b.prominence ?? b.score) + w * (b.country ? (post[b.country] ?? 0) : 0)
627
+
628
+ return bKey - aKey || b.score - a.score
629
+ })
630
+
631
+ rec.stage("anchor", ranked)
632
+ }
633
+
634
+ // Optional locale-country soft prior adds to candidate scores while retaining every candidate.
635
+ // Disabled when default country or anchor posterior is present.
636
+ if (state.localeCountryPrior && !state.defaultCountry && !state.anchorPosterior && anchorEligible) {
637
+ ranked = rankByCountryPrior(ranked, state.localeCountryPrior, state.localeCountryPriorWeight)
638
+ rec.stage("locale_prior", ranked)
639
+ }
640
+
641
+ // Importance-first rerank (skipped when anchor posterior exists).
642
+ if (!state.anchorPosterior) {
643
+ ranked = rankByImportance(ranked)
644
+ rec.stage("importance", ranked)
645
+
646
+ // Optional bounded capital promotion.
647
+ if (state.capitalLevel) {
648
+ ranked = promoteCapitalsWithReceipt(ranked, state.capitalLevel, node)
649
+ rec.stage("capital", ranked)
650
+ }
651
+ }
652
+
653
+ // Final containment partition.
654
+ // It reads the address's own qualifier and preserves the exact-match tier.
655
+ if (containmentEligible) {
656
+ ranked = partitionByContainment(
657
+ ranked,
658
+ (c) => c.containedByQualifier === true,
659
+ (c) => c.exactMatch === true
660
+ )
661
+
662
+ rec.stage("containment", ranked)
663
+ }
664
+
665
+ // Prefer exact requested placetype over macro fallback.
666
+ const hasFallbackCandidate = ranked.some((c) => isPlacetypeFallback(placetype, c.placetype))
667
+
668
+ if (hasFallbackCandidate && ranked.length > 1) {
669
+ ranked = [
670
+ ...ranked.filter((c) => !isPlacetypeFallback(placetype, c.placetype)),
671
+ ...ranked.filter((c) => isPlacetypeFallback(placetype, c.placetype)),
672
+ ]
673
+
674
+ rec.stage("exact_type", ranked)
675
+ }
676
+
677
+ const top = ranked[0]!
678
+
679
+ if (top.score < state.minWinningScore) {
680
+ state.minScoreRefusals++
681
+ rec.check("min_score_reject")
682
+ rec.emit(null)
683
+
684
+ return null
685
+ }
686
+
687
+ // Bare-toponym admin repick rules.
688
+ if (bareCountry && (bareCountry.prominence ?? bareCountry.score) > (top.prominence ?? top.score)) {
689
+ rec.check("bare_country_repick")
690
+ rec.emit({ id: bareCountry.id, name: bareCountry.name, source: "bare_country" })
691
+
692
+ return { top: bareCountry, alternatives: ranked, metadata: { bare_country_repick: true } }
693
+ }
694
+
695
+ if (bareRegion && logPopulation(bareRegion) >= logPopulation(top) + BARE_REGION_DOMINANCE_LOG10) {
696
+ rec.check("bare_region_repick")
697
+ rec.emit({ id: bareRegion.id, name: bareRegion.name, source: "bare_region" })
698
+
699
+ return { top: bareRegion, alternatives: ranked, metadata: { bare_region_repick: true } }
700
+ }
701
+
702
+ // Stamp fallback quality when a macro-type winner stands in.
703
+ if (isPlacetypeFallback(placetype, top.placetype)) {
704
+ top.resolutionQuality = "fallback"
705
+ rec.check("placetype_fallback")
706
+ }
707
+
708
+ rec.emit({ id: top.id, name: top.name, source: "ranked" })
709
+
710
+ // Trace receipts for mechanism-level observability.
711
+ const pickMetadata = {
712
+ ...(containmentEligible ? { admin_containment: adminContainmentVerdict(ranked) } : {}),
713
+ ...(top.variantAliasExempted === true ? { variant_alias_exemption: true } : {}),
714
+ // Mark picks admitted outside resolved parent scope.
715
+ ...((parentResolved && typeof parentResolved.id === "number" && query.parentID == null) ||
716
+ top.regionScopeMiss === true
717
+ ? { parent_fallback: true }
718
+ : {}),
719
+ }
720
+
721
+ return {
722
+ top,
723
+ alternatives: ranked.slice(1),
724
+ ...(Object.keys(pickMetadata).length ? { metadata: pickMetadata } : {}),
725
+ }
726
+ }
727
+ }
728
+
729
+ /**
730
+ * Promote capitals and stamp `capital_promotion` when the leader changes.
731
+ * Metadata only.
732
+ */
733
+ function promoteCapitalsWithReceipt<
734
+ T extends Pick<ResolvedPlace, "score" | "name" | "country" | "lat" | "lon"> &
735
+ Partial<Pick<ResolvedPlace, "exactMatch" | "importance" | "prominence">>,
736
+ >(ranked: readonly T[], level: CapitalLevelFn, node: { metadata?: Record<string, unknown> }): T[] {
737
+ const promoted = promoteCapitals(ranked, level)
738
+
739
+ if (promoted[0] !== ranked[0]) {
740
+ node.metadata = { ...node.metadata, capital_promotion: promoted[0]!.country ?? true }
741
+ }
742
+
743
+ return promoted
744
+ }