@mailwoman/resolver 9.2.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 (143) hide show
  1. package/README.md +5 -5
  2. package/{admin-coherence-passes.ts → lib/admin/coherence-passes.ts} +8 -8
  3. package/{admin-containment.ts → lib/admin/containment.ts} +5 -14
  4. package/lib/admin/index.ts +10 -0
  5. package/lib/admin/jp-municipality.ts +97 -0
  6. package/{admin-winner.ts → lib/admin/winner.ts} +13 -2
  7. package/{backend-capabilities.ts → lib/backend-capabilities.ts} +3 -3
  8. package/{bare-toponym-race.ts → lib/bare-toponym-race.ts} +1 -1
  9. package/{decorate-node.ts → lib/decorate-node.ts} +2 -2
  10. package/{fold-name.ts → lib/fold-name.ts} +2 -2
  11. package/{index.ts → lib/index.ts} +16 -21
  12. package/{plausibility.ts → lib/plausibility.ts} +5 -4
  13. package/{postcode-country-coherence.ts → lib/postcode/country-coherence.ts} +27 -32
  14. package/lib/postcode/index.ts +9 -0
  15. package/{postcode-prefix.ts → lib/postcode/prefix.ts} +4 -4
  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/{resolve.ts → lib/resolve/index.ts} +120 -602
  20. package/lib/resolve/passes.ts +544 -0
  21. package/{span-rescore.ts → lib/span-rescore.ts} +63 -97
  22. package/{street-evidence.ts → lib/street/evidence.ts} +39 -6
  23. package/lib/street/index.ts +8 -0
  24. package/{street-tier.ts → lib/street/tier.ts} +125 -110
  25. package/{toponym-prior.ts → lib/toponym-prior.ts} +8 -8
  26. package/out/{admin-coherence-passes.d.ts → admin/coherence-passes.d.ts} +6 -6
  27. package/out/admin/coherence-passes.d.ts.map +1 -0
  28. package/out/{admin-coherence-passes.js → admin/coherence-passes.js} +9 -9
  29. package/out/admin/coherence-passes.js.map +1 -0
  30. package/out/{admin-containment.d.ts → admin/containment.d.ts} +5 -5
  31. package/out/admin/containment.d.ts.map +1 -0
  32. package/out/{admin-containment.js → admin/containment.js} +6 -12
  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 → admin/winner.d.ts} +8 -3
  43. package/out/admin/winner.d.ts.map +1 -0
  44. package/out/{admin-winner.js → admin/winner.js} +14 -3
  45. package/out/admin/winner.js.map +1 -0
  46. package/out/backend-capabilities.d.ts.map +1 -1
  47. package/out/backend-capabilities.js +3 -3
  48. package/out/backend-capabilities.js.map +1 -1
  49. package/out/bare-toponym-race.d.ts.map +1 -1
  50. package/out/bare-toponym-race.js +1 -1
  51. package/out/bare-toponym-race.js.map +1 -1
  52. package/out/decorate-node.d.ts +1 -1
  53. package/out/decorate-node.d.ts.map +1 -1
  54. package/out/decorate-node.js +1 -1
  55. package/out/decorate-node.js.map +1 -1
  56. package/out/fold-name.d.ts +2 -2
  57. package/out/fold-name.d.ts.map +1 -1
  58. package/out/fold-name.js +2 -2
  59. package/out/fold-name.js.map +1 -1
  60. package/out/index.d.ts +15 -15
  61. package/out/index.d.ts.map +1 -1
  62. package/out/index.js +9 -9
  63. package/out/index.js.map +1 -1
  64. package/out/plausibility.d.ts +5 -4
  65. package/out/plausibility.d.ts.map +1 -1
  66. package/out/plausibility.js +5 -4
  67. package/out/plausibility.js.map +1 -1
  68. package/out/{postcode-country-coherence.d.ts → postcode/country-coherence.d.ts} +16 -16
  69. package/out/postcode/country-coherence.d.ts.map +1 -0
  70. package/out/{postcode-country-coherence.js → postcode/country-coherence.js} +24 -25
  71. package/out/postcode/country-coherence.js.map +1 -0
  72. package/out/postcode/index.d.ts +9 -0
  73. package/out/postcode/index.d.ts.map +1 -0
  74. package/out/postcode/index.js +9 -0
  75. package/out/postcode/index.js.map +1 -0
  76. package/out/{postcode-prefix.d.ts → postcode/prefix.d.ts} +4 -4
  77. package/out/postcode/prefix.d.ts.map +1 -0
  78. package/out/{postcode-prefix.js → postcode/prefix.js} +4 -4
  79. package/out/postcode/prefix.js.map +1 -0
  80. package/out/{postcode-shape-coherence.d.ts → postcode/shape-coherence.d.ts} +3 -3
  81. package/out/postcode/shape-coherence.d.ts.map +1 -0
  82. package/out/{postcode-shape-coherence.js → postcode/shape-coherence.js} +11 -20
  83. package/out/postcode/shape-coherence.js.map +1 -0
  84. package/out/remote-resolver.d.ts +18 -3
  85. package/out/remote-resolver.d.ts.map +1 -1
  86. package/out/remote-resolver.js +2 -2
  87. package/out/remote-resolver.js.map +1 -1
  88. package/out/rerank.d.ts +1 -1
  89. package/out/rerank.d.ts.map +1 -1
  90. package/out/rerank.js +2 -2
  91. package/out/rerank.js.map +1 -1
  92. package/out/{resolve.d.ts → resolve/index.d.ts} +1 -1
  93. package/out/resolve/index.d.ts.map +1 -0
  94. package/out/{resolve.js → resolve/index.js} +88 -387
  95. package/out/resolve/index.js.map +1 -0
  96. package/out/resolve/passes.d.ts +218 -0
  97. package/out/resolve/passes.d.ts.map +1 -0
  98. package/out/resolve/passes.js +333 -0
  99. package/out/resolve/passes.js.map +1 -0
  100. package/out/span-rescore.d.ts +16 -16
  101. package/out/span-rescore.d.ts.map +1 -1
  102. package/out/span-rescore.js +43 -69
  103. package/out/span-rescore.js.map +1 -1
  104. package/out/{street-evidence.d.ts → street/evidence.d.ts} +18 -3
  105. package/out/street/evidence.d.ts.map +1 -0
  106. package/out/{street-evidence.js → street/evidence.js} +22 -6
  107. package/out/street/evidence.js.map +1 -0
  108. package/out/street/index.d.ts +8 -0
  109. package/out/street/index.d.ts.map +1 -0
  110. package/out/street/index.js +8 -0
  111. package/out/street/index.js.map +1 -0
  112. package/out/{street-tier.d.ts → street/tier.d.ts} +14 -3
  113. package/out/street/tier.d.ts.map +1 -0
  114. package/out/{street-tier.js → street/tier.js} +115 -99
  115. package/out/street/tier.js.map +1 -0
  116. package/out/toponym-prior.d.ts +8 -8
  117. package/out/toponym-prior.d.ts.map +1 -1
  118. package/out/toponym-prior.js +8 -8
  119. package/out/toponym-prior.js.map +1 -1
  120. package/package.json +116 -59
  121. package/vitest.config.ts +5 -6
  122. package/out/admin-coherence-passes.d.ts.map +0 -1
  123. package/out/admin-coherence-passes.js.map +0 -1
  124. package/out/admin-containment.d.ts.map +0 -1
  125. package/out/admin-containment.js.map +0 -1
  126. package/out/admin-winner.d.ts.map +0 -1
  127. package/out/admin-winner.js.map +0 -1
  128. package/out/postcode-country-coherence.d.ts.map +0 -1
  129. package/out/postcode-country-coherence.js.map +0 -1
  130. package/out/postcode-prefix.d.ts.map +0 -1
  131. package/out/postcode-prefix.js.map +0 -1
  132. package/out/postcode-shape-coherence.d.ts.map +0 -1
  133. package/out/postcode-shape-coherence.js.map +0 -1
  134. package/out/resolve.d.ts.map +0 -1
  135. package/out/resolve.js.map +0 -1
  136. package/out/street-evidence.d.ts.map +0 -1
  137. package/out/street-evidence.js.map +0 -1
  138. package/out/street-tier.d.ts.map +0 -1
  139. package/out/street-tier.js.map +0 -1
  140. package/out/vitest.config.d.ts +0 -16
  141. package/out/vitest.config.d.ts.map +0 -1
  142. package/out/vitest.config.js +0 -36
  143. package/out/vitest.config.js.map +0 -1
@@ -13,34 +13,33 @@
13
13
  */
14
14
 
15
15
  import { matchCountry, matchSubdivision } from "@mailwoman/codex/country"
16
- import type { AddressNode, AddressTree, ComponentTag, Interpretation } from "@mailwoman/core/decoder"
16
+ import {
17
+ collectNodes,
18
+ type AddressNode,
19
+ type AddressTree,
20
+ type ComponentTag,
21
+ type Interpretation,
22
+ } from "@mailwoman/core/decoder"
17
23
  import {
18
24
  type BackendCapabilityGap,
19
- type CoincidentLocality,
20
- compareReferential,
21
- type ResolveCandidateTrace,
22
25
  type ResolveNodeTrace,
23
26
  DEFAULT_PLACETYPE_MAP,
24
27
  isPlacetypeFallback,
25
- type PlacetypeMap,
26
- type PostcodePrefixIndexLike,
27
- referentialFromPopulation,
28
28
  type ResolvedPlace,
29
29
  type ResolveOpts,
30
30
  type Resolver,
31
31
  type ResolverBackend,
32
32
  countriesFromPostcodeFormat,
33
33
  } from "@mailwoman/core/resolver"
34
- import { PLACETYPE_SPECIFICITY } from "@mailwoman/core/resources/whosonfirst/specificity"
35
- import { haversineKm } from "@mailwoman/spatial"
36
34
 
37
35
  import {
38
36
  applyAdminCoherence,
39
37
  applyExplicitCountryCoherence,
40
38
  applyRegionCountryCoherence,
41
- } from "./admin-coherence-passes.ts"
42
- import { adminContainmentVerdict, firstRegionQualifier, partitionByContainment } from "./admin-containment.ts"
43
- import { describeCapabilityGaps, reportCapabilityGaps } from "./backend-capabilities.ts"
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"
44
43
  import {
45
44
  BARE_REGION_DOMINANCE_LOG10,
46
45
  bareCountryCandidate,
@@ -48,18 +47,33 @@ import {
48
47
  logPopulation,
49
48
  loneBareLocalityNode,
50
49
  pickLargerAdmin,
51
- } from "./bare-toponym-race.ts"
52
- import { decorateNode, isResolvedWithCoord } from "./decorate-node.ts"
50
+ } from "#bare-toponym-race"
51
+ import { decorateNode } from "#decorate-node"
53
52
  import {
54
53
  findPostcodeCountryScope,
55
54
  type PostcodeCountryScope,
56
55
  stampPostcodeCountryScope,
57
- } from "./postcode-country-coherence.ts"
58
- import { type CoordinateOptionalPlace, postcodePrefixResolvedPlace, probePostcodePrefix } from "./postcode-prefix.ts"
59
- import { applyPostcodeShapeCoherence, isShapeExcludedPostcode } from "./postcode-shape-coherence.ts"
60
- import { findRescoreCandidate, hasResolvedPlace, postcodeCodeSubset } from "./span-rescore.ts"
61
- import { applyAddressPoint, applyInterpolation, applyStreetCentroid } from "./street-tier.ts"
62
- import { DEFAULT_COUNTRY_PRIOR_WEIGHT, promoteCapitals, rankByCountryPrior, rankByImportance } from "./toponym-prior.ts"
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"
63
77
 
64
78
  /**
65
79
  * Build a `Resolver` backed by a `ResolverBackend`. The backend can be any concrete impl structurally compatible with
@@ -82,18 +96,7 @@ export function createWOFResolver(backend: ResolverBackend): Resolver {
82
96
  * existing coherence passes keep handling it). Returns the alpha-2 or null.
83
97
  */
84
98
  function explicitCountryScope(roots: readonly AddressNode[]): string | null {
85
- const countryNodes: AddressNode[] = []
86
- const stack = [...roots]
87
-
88
- while (stack.length) {
89
- const node = stack.pop()!
90
-
91
- if (node.tag === "country" && node.value.trim()) {
92
- countryNodes.push(node)
93
- }
94
-
95
- stack.push(...node.children)
96
- }
99
+ const countryNodes = collectNodes(roots, (node) => node.tag === "country" && node.value.trim().length > 0)
97
100
 
98
101
  if (countryNodes.length !== 1) return null
99
102
  const value = countryNodes[0]!.value.trim()
@@ -106,540 +109,6 @@ function explicitCountryScope(roots: readonly AddressNode[]): string | null {
106
109
  return matched.iso2
107
110
  }
108
111
 
109
- /**
110
- * Cap on candidates recorded per {@link ResolveNodeTrace} — the trace is a record, not a dump. The count past the cap is
111
- * reported in `candidatesTruncated`, so absence of a row is never silent.
112
- */
113
- const TRACE_CANDIDATE_CAP = 10
114
-
115
- /**
116
- * The fine end of the probe window: `microhood` and no finer.
117
- *
118
- * Everything above it — `postalcode`, `venue`, `campus`, `building`, `address` — is excluded because a mislabeled ADMIN
119
- * span lands on another admin band, and probing every venue in a country per miss buys a long tail of coincidental name
120
- * matches for a diagnostic that is meant to be read.
121
- */
122
- const FINEST_DIAGNOSTIC_BAND = PLACETYPE_SPECIFICITY["microhood"]!
123
-
124
- /**
125
- * The coarse end of the probe window. `country` and no coarser: a name matching at `continent` or `planet` says nothing
126
- * about a mislabeled admin span, and the walk resolves the country from its own node anyway.
127
- */
128
- const COARSEST_DIAGNOSTIC_BAND = PLACETYPE_SPECIFICITY["country"]!
129
-
130
- /**
131
- * The admin bands `ResolveOpts.diagnoseUnreachable` re-probes, coarse to fine.
132
- *
133
- * Derived from `PLACETYPE_SPECIFICITY` rather than typed out, so a placetype added there is probed here without anyone
134
- * remembering to.
135
- */
136
- const DIAGNOSTIC_BANDS: readonly string[] = Object.entries(PLACETYPE_SPECIFICITY)
137
- .filter(([, rank]) => rank !== undefined && rank <= FINEST_DIAGNOSTIC_BAND && rank >= COARSEST_DIAGNOSTIC_BAND)
138
- .toSorted((a, b) => (a[1] as number) - (b[1] as number))
139
- .map(([placetype]) => placetype)
140
-
141
- /**
142
- * Per-lookup trace bookkeeping (#1721). `#lookupAndPick` talks to ONE of these unconditionally — a real recorder when
143
- * `ResolveOpts.traceSink` is set, the frozen {@link NOOP_TRACE_RECORDER} otherwise — so the hot path carries no
144
- * per-event branches and the no-sink walk costs a handful of empty calls per node.
145
- */
146
- interface NodeTraceRecorder {
147
- bind(
148
- node: AddressNode,
149
- placetype: string,
150
- query: {
151
- country?: string
152
- parentID?: string | number
153
- postcode?: string
154
- regionQualifier?: string
155
- limit?: number
156
- },
157
- defaultLimit: number
158
- ): void
159
- gate(name: string): void
160
- stage(name: string, order: readonly ResolvedPlace[]): void
161
- reachable(bands: NonNullable<ResolveNodeTrace["reachableIn"]>): void
162
- emit(picked: NonNullable<ResolveNodeTrace["picked"]> | null): void
163
- }
164
-
165
- const NOOP_TRACE_RECORDER: NodeTraceRecorder = Object.freeze({
166
- bind() {},
167
- gate() {},
168
- stage() {},
169
- reachable() {},
170
- emit() {},
171
- })
172
-
173
- function createNodeTraceRecorder(sink: (record: ResolveNodeTrace) => void): NodeTraceRecorder {
174
- const gates: string[] = []
175
- const stageOrders: Array<[string, readonly ResolvedPlace[]]> = []
176
-
177
- let reachableIn: ResolveNodeTrace["reachableIn"]
178
-
179
- let ctx: {
180
- node: AddressNode
181
- placetype: string
182
- query: Parameters<NodeTraceRecorder["bind"]>[2]
183
- defaultLimit: number
184
- } | null = null
185
-
186
- return {
187
- bind(node, placetype, query, defaultLimit) {
188
- ctx = { node, placetype, query, defaultLimit }
189
- },
190
- gate(name) {
191
- gates.push(name)
192
- },
193
- stage(name, order) {
194
- stageOrders.push([name, order])
195
- },
196
- reachable(bands) {
197
- reachableIn = bands
198
- },
199
- emit(picked) {
200
- if (!ctx) return
201
-
202
- const rankMap = new Map<ResolvedPlace, Record<string, number>>()
203
-
204
- for (const [stage, order] of stageOrders) {
205
- order.forEach((candidate, index) => {
206
- let ranks = rankMap.get(candidate)
207
-
208
- if (!ranks) {
209
- ranks = {}
210
- rankMap.set(candidate, ranks)
211
- }
212
-
213
- ranks[stage] = index + 1
214
- })
215
- }
216
-
217
- const finalOrder = stageOrders.at(-1)?.[1] ?? []
218
-
219
- const rows: ResolveCandidateTrace[] = finalOrder.slice(0, TRACE_CANDIDATE_CAP).map((c) => ({
220
- id: c.id,
221
- name: c.name,
222
- country: c.country,
223
- placetype: c.placetype,
224
- score: c.score,
225
- ...(c.prominence !== undefined ? { prominence: c.prominence } : {}),
226
- ...(c.importance !== undefined ? { importance: c.importance } : {}),
227
- ...(c.population !== undefined ? { population: c.population } : {}),
228
- ...(c.exactMatch !== undefined ? { exactMatch: c.exactMatch } : {}),
229
- ...(c.containedByQualifier !== undefined ? { containedByQualifier: c.containedByQualifier } : {}),
230
- ranks: rankMap.get(c) ?? {},
231
- }))
232
-
233
- sink({
234
- tag: ctx.node.tag,
235
- value: ctx.node.value,
236
- placetype: ctx.placetype,
237
- query: {
238
- ...(ctx.query.country ? { country: ctx.query.country } : {}),
239
- ...(ctx.query.parentID !== undefined ? { parentID: ctx.query.parentID } : {}),
240
- ...(ctx.query.postcode ? { postcode: ctx.query.postcode } : {}),
241
- ...(ctx.query.regionQualifier ? { regionQualifier: ctx.query.regionQualifier } : {}),
242
- limit: ctx.query.limit ?? ctx.defaultLimit,
243
- },
244
- gates,
245
- ...(reachableIn ? { reachableIn } : {}),
246
- candidates: rows,
247
- candidatesTruncated: Math.max(0, finalOrder.length - TRACE_CANDIDATE_CAP),
248
- picked,
249
- })
250
- },
251
- }
252
- }
253
-
254
- interface ResolutionState {
255
- lookupsRemaining: number
256
- placetypeMap: PlacetypeMap
257
- minWinningScore: number
258
- candidatesPerLookup: number
259
- defaultCountry?: string
260
- /**
261
- * Whether {@link defaultCountry} came from the locale rather than the caller. Consulted only by `country`-placetype
262
- * lookups, which skip an inferred scope — see `ResolveOpts.defaultCountryIsInferred`.
263
- */
264
- defaultCountryIsInferred: boolean
265
- /**
266
- * The tree's single value-bearing node when it is locality-tagged (the bare-toponym shape), else null. Gates the
267
- * country-placetype sibling race in `#lookupAndPick` — a bare name can be a country the parser tagged `locality`
268
- * ("Japan", "China"), and the locality placetype filter makes the country row unreachable no matter how it ranks.
269
- */
270
- bareLocalityNode: AddressNode | null
271
- parentFallback: boolean
272
- /**
273
- * The address's postcode string, extracted once up front, passed to locality lookups so a coordinate-first backend
274
- * can inject postcode-proximal locality candidates.
275
- */
276
- postcode?: string
277
- /**
278
- * Postcode-containment coherence (#31, Mechanism 2) — forwarded to locality lookups so a coordinate-first backend can
279
- * re-rank name candidates by proximity to the postcode's own centroid. Opt-in; OFF by default.
280
- */
281
- postcodeContainmentCoherence: boolean
282
- /**
283
- * Postcode-prefix prior (#31, Mechanism 3) — on a `postalcode` miss, derive the code's prefix and probe
284
- * `postcodePrefixIndex`. Opt-in; OFF by default.
285
- */
286
- postcodePrefixPrior: boolean
287
- /**
288
- * #1589 — the countries the parsed postcode's FORMAT implies (the #928 singles plus the shared `NNN NN` family). When
289
- * set AND no country constraint survives, the `postalcode` lookup probes exactly these countries and abstains if all
290
- * miss — never falling through to an unconstrained probe, whose space-stripped fold collides across systems (`100 00`
291
- * folded to `10000` answers Troyes FR while Prague sits in the artifact under both keyings).
292
- */
293
- postcodeFormatCountries?: readonly string[]
294
- /**
295
- * #1585 — the locale hint's country, forwarded to the backend as `fuzzyCountry` on every primary lookup. Scopes the
296
- * typo-fuzzy tier only; exact matches stay worldwide. See `ResolveOpts.fuzzyCountryScope`.
297
- */
298
- fuzzyCountryScope?: string
299
- /**
300
- * The injected PFX1 index (structural — `PostcodePrefixIndexLike`, core/resolver/types.ts). Absent = the prior cannot
301
- * fire.
302
- */
303
- postcodePrefixIndex?: PostcodePrefixIndexLike
304
- /**
305
- * Proximity-bias points (viewport, user location) — forwarded to every primary lookup.
306
- */
307
- bias?: Array<{ lat: number; lon: number; weight?: number }>
308
- /**
309
- * Postcode-anchor country posterior (#369). Undefined = no re-rank (byte-stable default).
310
- */
311
- anchorPosterior?: Record<string, number>
312
- /**
313
- * Weight on the posterior in the locality re-rank. Only used when `anchorPosterior` is set.
314
- */
315
- anchorWeight: number
316
- /**
317
- * #1721 resolver-interior trace sink. Undefined (the default) = zero bookkeeping, byte-identical walk.
318
- */
319
- traceSink?: (record: ResolveNodeTrace) => void
320
- /**
321
- * Re-probe a resolved-nothing lookup across the other admin bands and record which hold it. Diagnostic only — never
322
- * reaches the pick. See `ResolveOpts.diagnoseUnreachable`.
323
- */
324
- diagnoseUnreachable?: boolean
325
- /**
326
- * #27 locale-country SOFT prior for the bare-toponym admin walk. Undefined = no prior (the shipped default) →
327
- * byte-stable. See `ResolveOpts.localeCountryPrior` for the calibration and why it ships opt-in.
328
- */
329
- localeCountryPrior?: string
330
- /**
331
- * Weight of that prior in log10-population units. Only consulted when `localeCountryPrior` is set.
332
- */
333
- localeCountryPriorWeight: number
334
- /**
335
- * #1880 capital status per candidate, from `ResolveOpts.capitalLevel`. Undefined → no promotion, byte-stable.
336
- */
337
- capitalLevel?: (place: { name: string; country?: string; lat: number; lon: number }) => number
338
- /**
339
- * #743/#194 confident-placer country as a HARD filter (empty→unresolved, no global retry). Off = undefined.
340
- */
341
- hardCountry?: string
342
- /**
343
- * Dual-role hierarchy completion (#405). Off by default → byte-stable.
344
- */
345
- hierarchyCompletion: boolean
346
- /**
347
- * Attach ancestor lineage to each resolved node (#404). Off by default → byte-stable.
348
- */
349
- includeAncestors: boolean
350
- /**
351
- * Admin-containment re-rank (#1717 stage 2). Off by default → byte-stable. See `ResolveOpts.adminContainmentRerank`.
352
- */
353
- adminContainmentRerank: boolean
354
- /**
355
- * The tree's first parsed region-tagged span, extracted once up front (the `postcode` pattern above — region and
356
- * locality are siblings, so the top-down walk wouldn't otherwise let the locality lookup see it). Only consulted when
357
- * {@link adminContainmentRerank} is on.
358
- */
359
- regionQualifier?: string
360
- /**
361
- * Set while resolving when ANY tree node maps to the `locality` placetype (resolved or not) — the completion only
362
- * fires when the parser emitted no locality at all, never to override one.
363
- */
364
- localityNodePresent: boolean
365
- /**
366
- * The first region that resolved (its place — for the coincident-roles lookup).
367
- */
368
- resolvedRegion: CoordinateOptionalPlace | null
369
- /**
370
- * The decorated region NODE that produced {@link resolvedRegion} — completion pushes the locality interpretation onto
371
- * it in place (no synthesized sibling).
372
- */
373
- resolvedRegionNode: AddressNode | null
374
- }
375
-
376
- /**
377
- * Pick the completion locality when an admin maps to several coincident same-name candidates (#405). REFERENTIAL
378
- * likelihood is the PRIMARY signal — the principal city is the populous one, and it can sit FARTHER from the admin
379
- * centroid than a tiny same-name hamlet (the Niigata case from #403). Nearest centroid breaks a referential tie; a
380
- * genuine tie (same population AND distance) ABSTAINS rather than guess.
381
- *
382
- * ROAD_TO_V9 §2: `compareReferential` is referential DESC with raw population as its own tiebreak, which is the SAME
383
- * ORDER as the plain `b.population - a.population` it replaced — referential is strictly increasing in population below
384
- * saturation and constant above it. The abstention check below still reads raw population, deliberately: two megacities
385
- * that saturate to the same referential score are not tied, and abstaining there would be a new behavior.
386
- */
387
- function pickCompletion(candidates: readonly CoincidentLocality[]): CoincidentLocality | null {
388
- if (!candidates.length) return null
389
-
390
- if (candidates.length === 1) return candidates[0]!
391
-
392
- const ranked = [...candidates]
393
- .map((c) => ({ c, referential: referentialFromPopulation(c.population), population: c.population }))
394
- // oxlint-disable-next-line unicorn/no-array-sort -- sorts a freshly-built array; toSorted would double-allocate on a hot path
395
- .sort((a, b) => compareReferential(a, b) || a.c.distanceKm - b.c.distanceKm)
396
- .map((x) => x.c)
397
-
398
- const [first, second] = ranked
399
-
400
- if (first!.population === second!.population && first!.distanceKm === second!.distanceKm) return null
401
-
402
- return first!
403
- }
404
-
405
- /**
406
- * Find the first postcode value anywhere in the tree (a one-shot pre-scan; postcode and locality are siblings, so the
407
- * top-down walk wouldn't otherwise let the locality lookup see it).
408
- */
409
- function firstPostcodeValue(roots: readonly AddressNode[]): string | undefined {
410
- const stack = [...roots]
411
-
412
- while (stack.length) {
413
- const n = stack.pop()!
414
-
415
- // #31 Mechanism 1: a shape-excluded span keeps its tag but contributes nothing — its code
416
- // must never become the address's postcode (it would poison the country-scope pass's anchor).
417
- if (n.tag === "postcode" && !isShapeExcludedPostcode(n) && n.value.trim().length) return n.value.trim()
418
- stack.push(...n.children)
419
- }
420
-
421
- return undefined
422
- }
423
-
424
- /**
425
- * Span-rescore tier (#370): opt-in last-resort locality recovery. Runs ONLY when the tree resolved NOTHING (the #685
426
- * brake — never disturb a working coordinate). Enumerates raw-token spans, exact- matches the same-country gazetteer
427
- * (longest-wins + postcode-consistency gate; see `span-rescore.ts`), and on a hit INJECTS a resolved `locality` node
428
- * decorated exactly like a normally-resolved one. Default-ON (#370, promoted 2026-06-25); byte-stable opt-out via
429
- * `opts.spanRescore: false`. Async (it queries the backend), so it's awaited.
430
- */
431
- async function applySpanRescore(
432
- roots: AddressNode[],
433
- raw: string,
434
- backend: ResolverBackend,
435
- opts: ResolveOpts
436
- ): Promise<void> {
437
- if (hasResolvedPlace(roots)) return // already resolved — never second-guess a working coordinate
438
- // Default-ON since 2026-06-25, so this runs on every unresolved tree — a backend hiccup here must
439
- // degrade to no-rescore, never crash the resolve (the same fall-through the main walk gives).
440
- let hit
441
-
442
- try {
443
- hit = await findRescoreCandidate(raw, roots, backend, {
444
- country: opts.defaultCountry,
445
- postcode: firstPostcodeValue(roots),
446
- gateKm: opts.spanRescoreGateKm,
447
- // Default-ON (promoted 2026-07-03); explicit `false` opts out — the spanRescore idiom.
448
- postalCompoundRecovery: opts.postalCompoundRecovery !== false,
449
- })
450
- } catch {
451
- return
452
- }
453
-
454
- // #942 postal-compound recovery, part 2: when NO city span matched, decorate the FAILED postcode
455
- // node from its code-shaped token subset ("1382 Kožljek" → the bare "1382" row) — a postcode-tier
456
- // coordinate FLOOR, strictly subordinate to a recovered locality. Only-on-miss matters: a GeoNames
457
- // medoid postcode centroid is COARSER than the exact village centroid, and consumers that rank
458
- // postcode above locality (the eval harness does) would otherwise trade a 0.2 km village pin for a
459
- // 5 km area centroid. Same unresolved tree, so the #685 brake semantics hold.
460
- if (!hit && opts.postalCompoundRecovery !== false) {
461
- try {
462
- await recoverPostcodeNode(roots, backend, opts.defaultCountry, opts.traceSink)
463
- } catch {
464
- // degrade to no-recovery, never crash the resolve
465
- }
466
- }
467
-
468
- if (!hit) return
469
-
470
- const node: AddressNode = {
471
- tag: "locality",
472
- value: hit.text,
473
- start: hit.start,
474
- end: hit.end,
475
- // No model confidence for a post-hoc recovery; a mid-tier value marks it as recovered, not asserted.
476
- confidence: 0.5,
477
- children: [],
478
- }
479
-
480
- // #1537: the same-span namesake runner-ups, not an empty list. A name the model reads as a `street`
481
- // ("Springfield", "Berlin", "Moscow") never reaches the admin walk, so this tier is the ONLY thing that
482
- // resolves it — and decorating with `[]` meant the geocode path's `candidates` held one entry and the
483
- // dominance margin `declared_ambiguity` reads was uncomputable for exactly the famous-homonym class.
484
- // The winner is unchanged (see findRescoreCandidate); this is additive.
485
- decorateNode(node, hit.place, hit.alternatives)
486
- // `rescore_gated` carries the gate's precision signal as an EXPLICIT handle — NOT folded into the
487
- // calibrated `confidence`, which would break the isotonic guarantee (a true calibrated 0.83 must not
488
- // be confused with a rescore plug-in estimate; DeepSeek 2026-06-23). true = postcode gate fired
489
- // (high-precision); false = ungated (no postcode→point coverage for this country, ~83%-precision).
490
- node.metadata = { ...node.metadata, span_rescore: true, rescore_gated: hit.gated }
491
- roots.push(node)
492
-
493
- // #1721 follow-up: this tier answers OFF the walk, and it used to answer off the record too — the famous-name
494
- // class ("Frankfurt") returned a coordinate beside an empty resolver trace, blinding every retrieval account.
495
- // One record per rescue keeps the trace's promise: no resolved coordinate without a lookup record.
496
- if (opts.traceSink) {
497
- const rec = createNodeTraceRecorder(opts.traceSink)
498
-
499
- rec.bind(node, "locality", opts.defaultCountry ? { country: opts.defaultCountry } : {}, 1)
500
- rec.gate("span_rescore")
501
- rec.gate(hit.gated ? "rescore_gated" : "rescore_ungated")
502
- rec.stage("rescore", [hit.place, ...hit.alternatives])
503
- rec.emit({ id: hit.place.id, name: hit.place.name, source: "span_rescore" })
504
- }
505
- }
506
-
507
- /**
508
- * #942: find the first confident-but-UNRESOLVED postcode node whose value is a polluted compound ("1382 Kožljek"),
509
- * resolve its code-shaped token subset as a `postalcode`, and decorate the node from that hit
510
- * (`postal_compound_recovered` metadata marks the provenance). No-op when every postcode node resolved, the value has
511
- * no digit-bearing tokens, or the subset equals the full value (then the walk already tried it).
512
- */
513
- async function recoverPostcodeNode(
514
- roots: AddressNode[],
515
- backend: ResolverBackend,
516
- country: string | undefined,
517
- traceSink?: (record: ResolveNodeTrace) => void
518
- ): Promise<void> {
519
- const stack: AddressNode[] = [...roots]
520
-
521
- while (stack.length) {
522
- const n = stack.pop()!
523
-
524
- if (n.tag === "postcode" && !n.placeID && n.value.trim()) {
525
- const code = postcodeCodeSubset(n.value)
526
-
527
- if (!code || code === n.value.trim()) continue
528
- const hits = await backend.findPlace({ text: code, placetype: "postalcode", country, limit: 1 })
529
- const top = hits.find((h) => h.lat !== 0 || h.lon !== 0)
530
-
531
- if (top) {
532
- decorateNode(n, top, [])
533
- n.metadata = { ...n.metadata, postal_compound_recovered: true }
534
-
535
- // The same off-the-record hole the span-rescore record closes (#1721 follow-up).
536
- if (traceSink) {
537
- const rec = createNodeTraceRecorder(traceSink)
538
-
539
- rec.bind(n, "postalcode", { ...(country ? { country } : {}), limit: 1 }, 1)
540
- rec.gate("postal_compound_recovery")
541
- rec.stage("recovery", hits)
542
- rec.emit({ id: top.id, name: top.name, source: "postal_compound_recovery" })
543
- }
544
- }
545
-
546
- return // first postcode node only — one recovery per tree
547
- }
548
-
549
- if (n.children?.length) {
550
- stack.push(...n.children)
551
- }
552
- }
553
- }
554
-
555
- /**
556
- * Postcode-disambiguated locality selection (#370 "Lever A"). The single biggest miss on the EU/AU panel is a
557
- * same-named town resolved to the WRONG instance — "06260 Saint-Pierre" lands 617 km off — while the postcode that
558
- * would disambiguate it (06260 → Alpes-Maritimes) sits resolved in the same tree, discarded because the
559
- * coordinate-picker prefers the (wrong) locality node and never cross- checks it. This post-walk pass closes that loop,
560
- * backend-agnostically and with no extra query:
561
- *
562
- * 1. Find the resolved postcode's coordinate (the trustworthy anchor — a postcode is unambiguous within a country in a way
563
- * a town name is not).
564
- * 2. For each resolved locality node farther than `gateKm` from it: re-pick the same-named candidate from the node's
565
- * already-captured `alternatives` that is NEAREST the postcode and within the gate. This keeps locality granularity
566
- * at the CORRECT instance.
567
- * 3. If no alternative reconciles, the locality instance is unreliable — fall its coordinate back to the postcode point
568
- * (right area, the safe answer) and flag `postcode_city_mismatch`.
569
- *
570
- * Only fires where the postcode resolved to a point, so it composes with postcode coverage (#193) — add a country's
571
- * postcodes and this immediately disambiguates its same-named towns. **Default-ON** since the #370 operator promotion
572
- * (2026-07-04, commit `0010bb8c`) — `opts.postcodeConsistency: false` opts out, and the pass is byte-stable on every
573
- * tree with no resolved postcode point (the `!anchor` early return below).
574
- */
575
- function applyPostcodeConsistency(roots: readonly AddressNode[], gateKm: number): void {
576
- // The resolved postcode anchor (first one with a real coordinate).
577
- let anchor: { lat: number; lon: number } | null = null
578
- const findAnchor: AddressNode[] = [...roots]
579
-
580
- while (findAnchor.length) {
581
- const n = findAnchor.pop()!
582
-
583
- // #31 Mechanism 1: a shape-excluded span never anchors the consistency re-pick either.
584
- if (n.tag === "postcode" && !isShapeExcludedPostcode(n) && isResolvedWithCoord(n)) {
585
- anchor = { lat: n.lat!, lon: n.lon! }
586
-
587
- break
588
- }
589
-
590
- findAnchor.push(...n.children)
591
- }
592
-
593
- if (!anchor) return // no postcode→point — nothing to disambiguate against (gate can't fire)
594
-
595
- const stack: AddressNode[] = [...roots]
596
-
597
- while (stack.length) {
598
- const node = stack.pop()!
599
- stack.push(...node.children)
600
-
601
- if ((node.tag !== "locality" && node.tag !== "dependent_locality") || !isResolvedWithCoord(node)) continue
602
-
603
- if (haversineKm(anchor.lat, anchor.lon, node.lat!, node.lon!) <= gateKm) continue // already consistent
604
-
605
- // Re-pick: the same-named candidate nearest the postcode, within the gate. `alternatives` is
606
- // typed `unknown[]` on the node (decoder/types.ts can't import resolver types) — they ARE the
607
- // `ResolvedPlace` runner-ups decorateNode attached, so the cast is sound.
608
- const alts = (node.alternatives as ResolvedPlace[] | undefined) ?? []
609
-
610
- const reconciling = alts
611
- .filter((a) => a.lat !== 0 || a.lon !== 0)
612
- .map((a) => ({ a, d: haversineKm(anchor!.lat, anchor!.lon, a.lat, a.lon) }))
613
- .filter((x) => x.d <= gateKm)
614
- // oxlint-disable-next-line unicorn/no-array-sort -- sorts a freshly-built array; toSorted would double-allocate on a hot path
615
- .sort((x, y) => x.d - y.d)[0]
616
-
617
- if (reconciling) {
618
- // Swap to the consistent instance; the displaced winner becomes an alternative.
619
- const displaced: ResolvedPlace = {
620
- id: 0,
621
- name: String(node.metadata?.["resolver_name"] ?? node.value),
622
- placetype: "locality",
623
- country: reconciling.a.country,
624
- lat: node.lat!,
625
- lon: node.lon!,
626
- score: 0,
627
- }
628
-
629
- const rest = alts.filter((a) => a !== reconciling.a)
630
- decorateNode(node, reconciling.a, [displaced, ...rest])
631
- node.metadata = { ...node.metadata, postcode_repicked: true }
632
-
633
- continue
634
- }
635
-
636
- // No same-named instance near the postcode → the town is unreliable; trust the postcode's area.
637
- node.lat = anchor.lat
638
- node.lon = anchor.lon
639
- node.metadata = { ...node.metadata, postcode_city_mismatch: true, coordinate_source: "postcode_fallback" }
640
- }
641
- }
642
-
643
112
  class WOFResolver implements Resolver {
644
113
  readonly #backend: ResolverBackend
645
114
  /**
@@ -766,7 +235,9 @@ class WOFResolver implements Resolver {
766
235
  postcode: state.postcode,
767
236
  defaultCountry: state.defaultCountry,
768
237
  ...(shapeVerdict?.narrowing !== undefined ? { candidateSystems: shapeVerdict.narrowing } : {}),
769
- ...(opts.postcodeCountryCoherenceGateKm !== undefined ? { gateKm: opts.postcodeCountryCoherenceGateKm } : {}),
238
+ ...(opts.postcodeCountryCoherenceThresholdKm !== undefined
239
+ ? { thresholdKm: opts.postcodeCountryCoherenceThresholdKm }
240
+ : {}),
770
241
  })
771
242
 
772
243
  if (postcodeScope) {
@@ -789,9 +260,9 @@ class WOFResolver implements Resolver {
789
260
  }
790
261
 
791
262
  // The pre-scope's receipt (#1735): consumers that select country-scoped artifacts AFTER the walk
792
- // (geocode-core's rooftop-shard second pass) key on a scope stamp. Without this, an address whose
263
+ // (geocode-core's rooftop-extract second pass) key on a scope stamp. Without this, an address whose
793
264
  // country was right FROM THE TREE never writes one — the #42 pass stays silent because the default
794
- // is already coherent — and the FR rooftop shard silently stops loading for "…, France" inputs
265
+ // is already coherent — and the FR rooftop extract silently stops loading for "…, France" inputs
795
266
  // under a non-FR locale (six board venue rows dropped from rooftop to city centroid; the battery
796
267
  // caught it).
797
268
  if (explicitScope) {
@@ -825,16 +296,16 @@ class WOFResolver implements Resolver {
825
296
  // resolve (a foreign subdivision — "Montreal QC" under a US locale). The default filter discarded "QC" and
826
297
  // force-matched the locality to the US namesake; this re-resolves the subdivision + its same-named locality
827
298
  // under the subdivision's OWN country. Disjoint from the two passes above (unresolved region + resolved
828
- // locality); evidence-gated + byte-stable on the domestic path (a US region resolves under `US`).
299
+ // locality); evidence-conditional + byte-stable on the domestic path (a US region resolves under `US`).
829
300
  await applyRegionCountryCoherence(newRoots, this.#backend, state.defaultCountry)
830
301
  }
831
302
 
832
- // Postcode-consistency (#370 "Lever A"): default-ON (promoted 2026-07-04 — the corrected gate:
303
+ // Postcode-consistency (#370 "Change A"): default-ON (promoted 2026-07-04 — the corrected check:
833
304
  // FI 231/0, SI 37/6, CZ 47/2, US byte-flat; see the ResolveOpts docstring). After the admin walk
834
305
  // (needs both the locality and the postcode resolved) and before the street tiers (which key off
835
306
  // the postcode/street, not the locality coordinate this adjusts). `false` opts out, byte-stable.
836
307
  if (opts.postcodeConsistency !== false) {
837
- applyPostcodeConsistency(newRoots, opts.postcodeConsistencyGateKm ?? 50)
308
+ applyPostcodeConsistency(newRoots, opts.postcodeConsistencyThresholdKm ?? 50)
838
309
  }
839
310
 
840
311
  // Address-point tier (#476): opt-in street-level exact match. After the admin walk so the
@@ -845,7 +316,7 @@ class WOFResolver implements Resolver {
845
316
  }
846
317
 
847
318
  // Interpolation tier (#483): strictly AFTER the exact-point block so an estimate can never
848
- // override a real situs point (applyInterpolation also gates on resolution_tier). Opt-in;
319
+ // override a real situs point (applyInterpolation also checks on resolution_tier). Opt-in;
849
320
  // byte-stable when opts.interpolation is absent.
850
321
  if (opts.interpolation) {
851
322
  applyInterpolation(newRoots, opts.interpolation, opts.interpolationRadiusCalibration)
@@ -871,7 +342,7 @@ class WOFResolver implements Resolver {
871
342
  // Street-centroid tier (#1042): LAST, after span-rescore, so it can (a) union the span-rescore-recovered
872
343
  // country into its FR/national country hints (a placer-misrouted street — "Rue Sainte-Catherine" → IT — leaves
873
344
  // admin unresolved, and only span-rescore recovers the FR country signal) and (b) override a coarse recovered
874
- // locality with the exact street centroid. Self-gates on no house number + no existing street-level tier, so a
345
+ // locality with the exact street centroid. Applies only when there is no house number + no existing street-level tier, so a
875
346
  // rooftop query is untouched; byte-stable when opts.streetCentroids absent.
876
347
  if (opts.streetCentroids) {
877
348
  applyStreetCentroid(newRoots, tree.raw, opts.streetCentroids, opts.streetCountryHints ?? [])
@@ -930,7 +401,26 @@ class WOFResolver implements Resolver {
930
401
  // stripped of their resolve contribution — the walk does not look them up. Digit-only excluded
931
402
  // spans were retagged to `house_number` and flow through their correct sibling placetype.
932
403
  if (placetype && state.lookupsRemaining > 0 && node.value.trim().length && !isShapeExcludedPostcode(node)) {
933
- const picked = await this.#lookupAndPick(node, placetype, parentResolved, state)
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
+ }
934
424
 
935
425
  if (picked) {
936
426
  resolved = picked.top
@@ -1048,7 +538,7 @@ class WOFResolver implements Resolver {
1048
538
  }
1049
539
 
1050
540
  // #194: a resolved parent's country wins, then the caller's `defaultCountry`, then the confident
1051
- // placer `hardCountry`. All three are a HARD candidate filter. The placer's `hardCountry` is gated
541
+ // placer `hardCountry`. All three are a HARD candidate filter. The placer's `hardCountry` is conditional
1052
542
  // upstream on high confidence (so it only fires when the model is sure), and on a miss the node is
1053
543
  // left UNRESOLVED rather than re-resolved globally: the off-continent rows are precisely the ones
1054
544
  // whose locality isn't in the country's gazetteer slice, so a global retry would just re-admit the
@@ -1138,7 +628,7 @@ class WOFResolver implements Resolver {
1138
628
  // set — its index is country-scoped by construction, so it is not the fold this branch
1139
629
  // exists to avoid (the B3 tests hold that path).
1140
630
  if (placetype === "postalcode" && !query.country && state.postcodeFormatCountries?.length) {
1141
- rec.gate("postcode_format_probe")
631
+ rec.check("postcode_format_probe")
1142
632
  let best: ResolvedPlace | undefined
1143
633
 
1144
634
  for (const impliedCountry of state.postcodeFormatCountries) {
@@ -1168,13 +658,13 @@ class WOFResolver implements Resolver {
1168
658
  candidates = await this.#backend.findPlace(query)
1169
659
  rec.stage("initial", candidates)
1170
660
 
1171
- // #1731: the backend's interior region-scope fallback, surfaced as a gate — the resolver
661
+ // #1731: the backend's interior region-scope fallback, surfaced as a check — the resolver
1172
662
  // never sees the scoped probe miss, only the stamp the re-admitted rows carry.
1173
663
  if (candidates[0]?.regionScopeMiss) {
1174
- rec.gate("region_scope_miss")
664
+ rec.check("region_scope_miss")
1175
665
  }
1176
666
 
1177
- // Parent soft-gating: `parentID` is a HARD descendant filter in the backend, which wrongly
667
+ // Parent soft-filtering: `parentID` is a HARD descendant filter in the backend, which wrongly
1178
668
  // zeroes the result when the parent resolved wrong OR the gazetteer hierarchy is incomplete
1179
669
  // (a real locality whose `ancestors` chain is missing its region). Rather than turn a
1180
670
  // resolvable node into an unresolved one, retry once WITHOUT the parent constraint — we
@@ -1182,7 +672,7 @@ class WOFResolver implements Resolver {
1182
672
  // this still can't wander to a foreign place. Same logical resolution → no extra budget.
1183
673
  if (!candidates.length && state.parentFallback && query.parentID !== undefined) {
1184
674
  delete query.parentID
1185
- rec.gate("parent_fallback_retry")
675
+ rec.check("parent_fallback_retry")
1186
676
  candidates = await this.#backend.findPlace(query)
1187
677
  rec.stage("parent_fallback", candidates)
1188
678
  }
@@ -1199,10 +689,10 @@ class WOFResolver implements Resolver {
1199
689
  // Defensive: a backend failure should not abort the whole tree walk. Leave the node with
1200
690
  // its classifier attribution intact.
1201
691
  //
1202
- // The reason rides the gate name. A bare `backend_error` cannot tell a closed database from a
692
+ // The reason rides the check name. A bare `backend_error` cannot tell a closed database from a
1203
693
  // finalized statement from a genuine query fault, which is what made three full-board constraint
1204
694
  // runs unreadable — 64 of 591 rows errored and the census could not say why.
1205
- rec.gate(`backend_error: ${(error as Error).message}`)
695
+ rec.check(`backend_error: ${(error as Error).message}`)
1206
696
  rec.emit(null)
1207
697
 
1208
698
  return null
@@ -1228,7 +718,7 @@ class WOFResolver implements Resolver {
1228
718
  : {}),
1229
719
  }
1230
720
 
1231
- rec.gate("postcode_prefix_prior")
721
+ rec.check("postcode_prefix_prior")
1232
722
  const prefixPlace = postcodePrefixResolvedPlace(probe.prefix, probe.node, state.postcodePrefixIndex)
1233
723
 
1234
724
  rec.emit({ id: prefixPlace.id, name: prefixPlace.name, source: "postcode_prefix" })
@@ -1250,7 +740,7 @@ class WOFResolver implements Resolver {
1250
740
  const isBareRace = placetype === "locality" && node === state.bareLocalityNode
1251
741
 
1252
742
  if (isBareRace) {
1253
- rec.gate("bare_race")
743
+ rec.check("bare_race")
1254
744
  }
1255
745
 
1256
746
  const bareCountry = isBareRace ? await bareCountryCandidate(this.#backend, node.value, query.country) : null
@@ -1262,7 +752,7 @@ class WOFResolver implements Resolver {
1262
752
  const admin = pickLargerAdmin(bareCountry, bareRegion)
1263
753
 
1264
754
  if (admin) {
1265
- rec.gate("empty_admin_pick")
755
+ rec.check("empty_admin_pick")
1266
756
  rec.emit({ id: admin.id, name: admin.name, source: "empty_admin" })
1267
757
 
1268
758
  return {
@@ -1320,8 +810,10 @@ class WOFResolver implements Resolver {
1320
810
  const tier = Number(b.exactMatch ?? false) - Number(a.exactMatch ?? false)
1321
811
 
1322
812
  if (tier !== 0) return tier
1323
- const aKey = (a.prominence ?? a.score) + w * (post[a.country] ?? 0)
1324
- const bKey = (b.prominence ?? b.score) + w * (post[b.country] ?? 0)
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))
1325
817
 
1326
818
  return bKey - aKey || b.score - a.score
1327
819
  })
@@ -1329,7 +821,7 @@ class WOFResolver implements Resolver {
1329
821
  rec.stage("anchor", ranked)
1330
822
  }
1331
823
 
1332
- // Locale-country soft prior (#27) — the #912 lever's other half, at the tier that decides a bare
824
+ // Locale-country soft prior (#27) — the #912 change's other half, at the tier that decides a bare
1333
825
  // toponym the model tagged `locality`. `--locale en-GB "Whitby"` answers Whitby, Ontario while
1334
826
  // `--default-country GB "Whitby"` answers the gold, because the CLI DROPS the locale-inferred
1335
827
  // country for this shape rather than choosing between "hard filter" and "nothing". This is the
@@ -1368,16 +860,16 @@ class WOFResolver implements Resolver {
1368
860
  // containment partition (the qualifier is the address's own text; evidence outranks a prior).
1369
861
  // Same stand-down as fame: an anchor posterior is postcode evidence and silences the prior.
1370
862
  if (state.capitalLevel) {
1371
- ranked = promoteCapitals(ranked, state.capitalLevel)
863
+ ranked = promoteCapitalsWithReceipt(ranked, state.capitalLevel, node)
1372
864
  rec.stage("capital", ranked)
1373
865
  }
1374
866
  }
1375
867
 
1376
868
  // Admin-containment partition (#1717 stage 2): the LAST soft re-rank, after the anchor/fame keys
1377
869
  // above, because the qualifier is the address's OWN text — evidence, which outranks a prior. The
1378
- // backend already put contained rows first; this second partition is load-bearing, not belt-and-
870
+ // backend already put contained rows first; this second partition is required, not belt-and-
1379
871
  // braces: `rankByImportance` just re-ordered the exact tier by fame, and Richmond, Virginia
1380
- // outscores Richmond, North Yorkshire on importance — without this the lever loses exactly where
872
+ // outscores Richmond, North Yorkshire on importance — without this the change loses exactly where
1381
873
  // fame disagrees with the qualifier (the shared-function partition, tier-safe + stable, so it can
1382
874
  // never promote a contained partial match over an exact one). No stamps → identity → byte-stable
1383
875
  // on any backend that ignored `regionQualifier`.
@@ -1413,7 +905,7 @@ class WOFResolver implements Resolver {
1413
905
  const top = ranked[0]!
1414
906
 
1415
907
  if (top.score < state.minWinningScore) {
1416
- rec.gate("min_score_reject")
908
+ rec.check("min_score_reject")
1417
909
  rec.emit(null)
1418
910
 
1419
911
  return null
@@ -1424,18 +916,18 @@ class WOFResolver implements Resolver {
1424
916
  // DOMINATE the locality winner by {@link BARE_REGION_DOMINANCE_LOG10} in log-population:
1425
917
  // prominence saturates at the backend's populationBoost cap, so the margin is measured on the
1426
918
  // raw populations, and the margin is what keeps bare "New York" on the city (state 19.6M vs
1427
- // city 8.8M = 0.35, under the cut) while bare "Georgia" promotes to the 11M state over the
919
+ // city 8.8M = 0.35, under the threshold) while bare "Georgia" promotes to the 11M state over the
1428
920
  // Vermont hamlet (margin 3.4). A bare name with no admin namesake never reaches these lines,
1429
921
  // and the displaced locality stays first among the alternatives either way.
1430
922
  if (bareCountry && (bareCountry.prominence ?? bareCountry.score) > (top.prominence ?? top.score)) {
1431
- rec.gate("bare_country_repick")
923
+ rec.check("bare_country_repick")
1432
924
  rec.emit({ id: bareCountry.id, name: bareCountry.name, source: "bare_country" })
1433
925
 
1434
926
  return { top: bareCountry, alternatives: ranked, metadata: { bare_country_repick: true } }
1435
927
  }
1436
928
 
1437
929
  if (bareRegion && logPopulation(bareRegion) >= logPopulation(top) + BARE_REGION_DOMINANCE_LOG10) {
1438
- rec.gate("bare_region_repick")
930
+ rec.check("bare_region_repick")
1439
931
  rec.emit({ id: bareRegion.id, name: bareRegion.name, source: "bare_region" })
1440
932
 
1441
933
  return { top: bareRegion, alternatives: ranked, metadata: { bare_region_repick: true } }
@@ -1446,19 +938,45 @@ class WOFResolver implements Resolver {
1446
938
  // identity/coordinate are unchanged; only `metadata.resolution_quality` is stamped downstream.
1447
939
  if (isPlacetypeFallback(placetype, top.placetype)) {
1448
940
  top.resolutionQuality = "fallback"
1449
- rec.gate("placetype_fallback")
941
+ rec.check("placetype_fallback")
1450
942
  }
1451
943
 
1452
944
  rec.emit({ id: top.id, name: top.name, source: "ranked" })
1453
945
 
1454
- // The lever's trace stamp (#1717 stage 2 / #1719's rule): an opted-in mechanism that cannot fire
1455
- // — a pre-sidecar artifact, an incapable backend — must say so in the result, not degrade
1456
- // silently. The parse-side census cannot see resolver levers, so this stamp is its census
1457
- // surface. Only under the lever: the stamp asserts a question was asked.
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
+
1458
957
  return {
1459
958
  top,
1460
959
  alternatives: ranked.slice(1),
1461
- ...(containmentEligible ? { metadata: { admin_containment: adminContainmentVerdict(ranked) } } : {}),
960
+ ...(Object.keys(pickMetadata).length ? { metadata: pickMetadata } : {}),
1462
961
  }
1463
962
  }
1464
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
+ }