@mailwoman/resolver 10.0.0 → 10.1.0

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