@mailwoman/resolver 9.1.0 → 9.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 (74) hide show
  1. package/README.md +89 -0
  2. package/admin-coherence-passes.ts +435 -0
  3. package/admin-containment.ts +101 -0
  4. package/admin-winner.ts +178 -0
  5. package/backend-capabilities.ts +88 -0
  6. package/bare-toponym-race.ts +129 -0
  7. package/decorate-node.ts +127 -0
  8. package/fold-name.ts +19 -3
  9. package/index.ts +14 -0
  10. package/out/admin-coherence-passes.d.ts +70 -0
  11. package/out/admin-coherence-passes.d.ts.map +1 -0
  12. package/out/admin-coherence-passes.js +327 -0
  13. package/out/admin-coherence-passes.js.map +1 -0
  14. package/out/admin-containment.d.ts +48 -0
  15. package/out/admin-containment.d.ts.map +1 -0
  16. package/out/admin-containment.js +82 -0
  17. package/out/admin-containment.js.map +1 -0
  18. package/out/admin-winner.d.ts +109 -0
  19. package/out/admin-winner.d.ts.map +1 -0
  20. package/out/admin-winner.js +119 -0
  21. package/out/admin-winner.js.map +1 -0
  22. package/out/backend-capabilities.d.ts +37 -0
  23. package/out/backend-capabilities.d.ts.map +1 -0
  24. package/out/backend-capabilities.js +75 -0
  25. package/out/backend-capabilities.js.map +1 -0
  26. package/out/bare-toponym-race.d.ts +55 -0
  27. package/out/bare-toponym-race.d.ts.map +1 -0
  28. package/out/bare-toponym-race.js +110 -0
  29. package/out/bare-toponym-race.js.map +1 -0
  30. package/out/decorate-node.d.ts +24 -0
  31. package/out/decorate-node.d.ts.map +1 -0
  32. package/out/decorate-node.js +103 -0
  33. package/out/decorate-node.js.map +1 -0
  34. package/out/fold-name.d.ts +18 -3
  35. package/out/fold-name.d.ts.map +1 -1
  36. package/out/fold-name.js +19 -3
  37. package/out/fold-name.js.map +1 -1
  38. package/out/index.d.ts +4 -1
  39. package/out/index.d.ts.map +1 -1
  40. package/out/index.js +3 -1
  41. package/out/index.js.map +1 -1
  42. package/out/postcode-country-coherence.d.ts +31 -10
  43. package/out/postcode-country-coherence.d.ts.map +1 -1
  44. package/out/postcode-country-coherence.js +137 -56
  45. package/out/postcode-country-coherence.js.map +1 -1
  46. package/out/postcode-prefix.d.ts.map +1 -1
  47. package/out/postcode-prefix.js +3 -2
  48. package/out/postcode-prefix.js.map +1 -1
  49. package/out/postcode-shape-coherence.js.map +1 -1
  50. package/out/resolve.d.ts +1 -1
  51. package/out/resolve.d.ts.map +1 -1
  52. package/out/resolve.js +461 -416
  53. package/out/resolve.js.map +1 -1
  54. package/out/span-rescore.d.ts.map +1 -1
  55. package/out/span-rescore.js +55 -13
  56. package/out/span-rescore.js.map +1 -1
  57. package/out/street-evidence.js +1 -1
  58. package/out/street-evidence.js.map +1 -1
  59. package/out/street-tier.d.ts.map +1 -1
  60. package/out/street-tier.js +26 -5
  61. package/out/street-tier.js.map +1 -1
  62. package/out/toponym-prior.d.ts +42 -18
  63. package/out/toponym-prior.d.ts.map +1 -1
  64. package/out/toponym-prior.js +75 -7
  65. package/out/toponym-prior.js.map +1 -1
  66. package/package.json +98 -7
  67. package/postcode-country-coherence.ts +150 -58
  68. package/postcode-prefix.ts +3 -2
  69. package/postcode-shape-coherence.ts +1 -1
  70. package/resolve.ts +626 -531
  71. package/span-rescore.ts +64 -15
  72. package/street-evidence.ts +1 -1
  73. package/street-tier.ts +29 -5
  74. package/toponym-prior.ts +96 -7
package/resolve.ts CHANGED
@@ -13,14 +13,14 @@
13
13
  */
14
14
 
15
15
  import { matchCountry, matchSubdivision } from "@mailwoman/codex/country"
16
- import { isStreetDirectionalToken } from "@mailwoman/codex/us"
17
16
  import type { AddressNode, AddressTree, ComponentTag, Interpretation } from "@mailwoman/core/decoder"
18
17
  import {
19
- type AddressPointLookup,
18
+ type BackendCapabilityGap,
20
19
  type CoincidentLocality,
21
20
  compareReferential,
21
+ type ResolveCandidateTrace,
22
+ type ResolveNodeTrace,
22
23
  DEFAULT_PLACETYPE_MAP,
23
- type InterpolationLookup,
24
24
  isPlacetypeFallback,
25
25
  type PlacetypeMap,
26
26
  type PostcodePrefixIndexLike,
@@ -29,11 +29,27 @@ import {
29
29
  type ResolveOpts,
30
30
  type Resolver,
31
31
  type ResolverBackend,
32
- type StreetCentroidLookup,
32
+ countriesFromPostcodeFormat,
33
33
  } from "@mailwoman/core/resolver"
34
+ import { PLACETYPE_SPECIFICITY } from "@mailwoman/core/resources/whosonfirst/specificity"
34
35
  import { haversineKm } from "@mailwoman/spatial"
35
36
 
36
- import { foldName } from "./fold-name.ts"
37
+ import {
38
+ applyAdminCoherence,
39
+ applyExplicitCountryCoherence,
40
+ applyRegionCountryCoherence,
41
+ } from "./admin-coherence-passes.ts"
42
+ import { adminContainmentVerdict, firstRegionQualifier, partitionByContainment } from "./admin-containment.ts"
43
+ import { describeCapabilityGaps, reportCapabilityGaps } from "./backend-capabilities.ts"
44
+ import {
45
+ BARE_REGION_DOMINANCE_LOG10,
46
+ bareCountryCandidate,
47
+ bareRegionCandidate,
48
+ logPopulation,
49
+ loneBareLocalityNode,
50
+ pickLargerAdmin,
51
+ } from "./bare-toponym-race.ts"
52
+ import { decorateNode, isResolvedWithCoord } from "./decorate-node.ts"
37
53
  import {
38
54
  findPostcodeCountryScope,
39
55
  type PostcodeCountryScope,
@@ -43,22 +59,215 @@ import { type CoordinateOptionalPlace, postcodePrefixResolvedPlace, probePostcod
43
59
  import { applyPostcodeShapeCoherence, isShapeExcludedPostcode } from "./postcode-shape-coherence.ts"
44
60
  import { findRescoreCandidate, hasResolvedPlace, postcodeCodeSubset } from "./span-rescore.ts"
45
61
  import { applyAddressPoint, applyInterpolation, applyStreetCentroid } from "./street-tier.ts"
46
- import { DEFAULT_COUNTRY_PRIOR_WEIGHT, rankByCountryPrior, rankByImportance } from "./toponym-prior.ts"
62
+ import { DEFAULT_COUNTRY_PRIOR_WEIGHT, promoteCapitals, rankByCountryPrior, rankByImportance } from "./toponym-prior.ts"
47
63
 
48
64
  /**
49
65
  * Build a `Resolver` backed by a `ResolverBackend`. The backend can be any concrete impl structurally compatible with
50
- * `PlaceLookup` — e.g. `new WOFSqlitePlaceLookup({ databasePath }).asResolverBackend()` or a fake for tests.
66
+ * `PlaceLookup` — e.g. `new WOFSQLitePlaceLookup({ databasePath }).asResolverBackend()` or a fake for tests.
51
67
  */
52
68
  export function createWOFResolver(backend: ResolverBackend): Resolver {
53
69
  return new WOFResolver(backend)
54
70
  }
55
71
 
72
+ /**
73
+ * #1735 (second half) — the tree's own country statement, when it is unambiguous.
74
+ *
75
+ * "SW1A 1AA, UK" under the en-US default parsed correctly and still failed: the walk resolved the country NODE to GB,
76
+ * but a sibling's resolution never scopes a sibling — the postcode lookup ran under the locale-inferred `country=US`
77
+ * hard filter and missed. An explicit country token is the address's OWN scope declaration, which outranks a locale
78
+ * inference the same way the #912 posture ranks explicit over inferred.
79
+ *
80
+ * Deterministically guarded: exactly ONE country-tagged node, whose value `matchCountry` maps to one ISO country, and
81
+ * whose value is NOT also a subdivision name — "Georgia" maps to GE _and_ names a US state, so it never pre-scopes (the
82
+ * existing coherence passes keep handling it). Returns the alpha-2 or null.
83
+ */
84
+ 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
+ }
97
+
98
+ if (countryNodes.length !== 1) return null
99
+ const value = countryNodes[0]!.value.trim()
100
+ const matched = matchCountry(value)
101
+
102
+ if (!matched) return null
103
+
104
+ if (matchSubdivision(value)) return null
105
+
106
+ return matched.iso2
107
+ }
108
+
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
+
56
254
  interface ResolutionState {
57
255
  lookupsRemaining: number
58
256
  placetypeMap: PlacetypeMap
59
257
  minWinningScore: number
60
258
  candidatesPerLookup: number
61
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
62
271
  parentFallback: boolean
63
272
  /**
64
273
  * The address's postcode string, extracted once up front, passed to locality lookups so a coordinate-first backend
@@ -75,6 +284,18 @@ interface ResolutionState {
75
284
  * `postcodePrefixIndex`. Opt-in; OFF by default.
76
285
  */
77
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
78
299
  /**
79
300
  * The injected PFX1 index (structural — `PostcodePrefixIndexLike`, core/resolver/types.ts). Absent = the prior cannot
80
301
  * fire.
@@ -92,6 +313,15 @@ interface ResolutionState {
92
313
  * Weight on the posterior in the locality re-rank. Only used when `anchorPosterior` is set.
93
314
  */
94
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
95
325
  /**
96
326
  * #27 locale-country SOFT prior for the bare-toponym admin walk. Undefined = no prior (the shipped default) →
97
327
  * byte-stable. See `ResolveOpts.localeCountryPrior` for the calibration and why it ships opt-in.
@@ -101,6 +331,10 @@ interface ResolutionState {
101
331
  * Weight of that prior in log10-population units. Only consulted when `localeCountryPrior` is set.
102
332
  */
103
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
104
338
  /**
105
339
  * #743/#194 confident-placer country as a HARD filter (empty→unresolved, no global retry). Off = undefined.
106
340
  */
@@ -113,6 +347,16 @@ interface ResolutionState {
113
347
  * Attach ancestor lineage to each resolved node (#404). Off by default → byte-stable.
114
348
  */
115
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
116
360
  /**
117
361
  * Set while resolving when ANY tree node maps to the `locality` placetype (resolved or not) — the completion only
118
362
  * fires when the parser emitted no locality at all, never to override one.
@@ -215,7 +459,7 @@ async function applySpanRescore(
215
459
  // 5 km area centroid. Same unresolved tree, so the #685 brake semantics hold.
216
460
  if (!hit && opts.postalCompoundRecovery !== false) {
217
461
  try {
218
- await recoverPostcodeNode(roots, backend, opts.defaultCountry)
462
+ await recoverPostcodeNode(roots, backend, opts.defaultCountry, opts.traceSink)
219
463
  } catch {
220
464
  // degrade to no-recovery, never crash the resolve
221
465
  }
@@ -245,6 +489,19 @@ async function applySpanRescore(
245
489
  // (high-precision); false = ungated (no postcode→point coverage for this country, ~83%-precision).
246
490
  node.metadata = { ...node.metadata, span_rescore: true, rescore_gated: hit.gated }
247
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
+ }
248
505
  }
249
506
 
250
507
  /**
@@ -256,7 +513,8 @@ async function applySpanRescore(
256
513
  async function recoverPostcodeNode(
257
514
  roots: AddressNode[],
258
515
  backend: ResolverBackend,
259
- country: string | undefined
516
+ country: string | undefined,
517
+ traceSink?: (record: ResolveNodeTrace) => void
260
518
  ): Promise<void> {
261
519
  const stack: AddressNode[] = [...roots]
262
520
 
@@ -273,6 +531,16 @@ async function recoverPostcodeNode(
273
531
  if (top) {
274
532
  decorateNode(n, top, [])
275
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
+ }
276
544
  }
277
545
 
278
546
  return // first postcode node only — one recovery per tree
@@ -284,13 +552,6 @@ async function recoverPostcodeNode(
284
552
  }
285
553
  }
286
554
 
287
- /**
288
- * A resolved node carries a real coordinate (placeID set + non-zero lat/lon).
289
- */
290
- function isResolvedWithCoord(n: AddressNode): boolean {
291
- return !!(n.placeID && typeof n.lat === "number" && typeof n.lon === "number" && (n.lat !== 0 || n.lon !== 0))
292
- }
293
-
294
555
  /**
295
556
  * Postcode-disambiguated locality selection (#370 "Lever A"). The single biggest miss on the EU/AU panel is a
296
557
  * same-named town resolved to the WRONG instance — "06260 Saint-Pierre" lands 617 km off — while the postcode that
@@ -379,417 +640,6 @@ function applyPostcodeConsistency(roots: readonly AddressNode[], gateKm: number)
379
640
  }
380
641
  }
381
642
 
382
- /**
383
- * Admin descendant-consistency (#263) — the joint-consistency resolve, scoped to the admin assignment. The greedy walk
384
- * resolves a region on its own (name + population), so "ME" picks Messina (IT) over Maine, then scopes "Portland" to
385
- * Messina's descendants, finds nothing, and the result falls back to the region centroid (Sicily). The region's
386
- * same-named runner-ups (Maine, Missouri, …) were already captured as `alternatives`; this pass asks the question the
387
- * greedy order skipped — _which "ME" has a "Portland" under it?_ — and re-picks the (region, locality) pair where a
388
- * same-named locality descends from a same-named region candidate. Geography decides; no country prior, no list.
389
- *
390
- * Fires ONLY for a resolved region whose child locality fell through (the unresolved-locality signal), so a
391
- * well-resolved tree ("Springfield, IL" → Illinois, Springfield) is byte-identical. Costs one unscoped locality lookup
392
- * per triggering pair. Needs {@link ResolverBackend.ancestors}; no-op without it. See `ResolveOpts.adminCoherence`.
393
- */
394
- async function applyAdminCoherence(roots: readonly AddressNode[], backend: ResolverBackend): Promise<void> {
395
- const visit = async (node: AddressNode, regionAncestor: AddressNode | null): Promise<void> => {
396
- const regionHere = node.tag === "region" && isResolvedWithCoord(node) ? node : regionAncestor
397
-
398
- if (
399
- regionHere &&
400
- (node.tag === "locality" || node.tag === "dependent_locality") &&
401
- !isResolvedWithCoord(node) &&
402
- node.value.trim().length
403
- ) {
404
- await reconcileAdminPair(regionHere, node, backend)
405
- }
406
-
407
- for (const child of node.children) {
408
- await visit(child, regionHere)
409
- }
410
- }
411
-
412
- for (const root of roots) {
413
- await visit(root, null)
414
- }
415
- }
416
-
417
- /**
418
- * Re-pick a (region, locality) pair so the locality descends from the region. `alternatives` on the node are the
419
- * `ResolvedPlace` runner-ups `decorateNode` attached (typed `unknown[]` in the decoder, which can't import resolver
420
- * types — the cast is sound). Picks the FIRST same-named locality (already score-ordered) that descends from a
421
- * same-named region candidate, then swaps both nodes. Leaves both untouched when no consistent pair exists (a genuinely
422
- * un-gazetteered locality — "Portland, VT" with no Portland in Vermont — stays as the region centroid, not a foreign
423
- * namesake).
424
- */
425
- async function reconcileAdminPair(
426
- regionNode: AddressNode,
427
- localityNode: AddressNode,
428
- backend: ResolverBackend
429
- ): Promise<void> {
430
- // EXACT region matches only: the alternatives for a 2-letter token are loose ("ME" also surfaces
431
- // Missouri/Michigan/Mississippi as fuzzy M-state runner-ups). Restricting to exact name/alias matches
432
- // (Maine/Messina/Medway for "ME") keeps the join honest. `exactMatch` is stamped by exactMatchTiering.
433
- const regionCands = ((regionNode.alternatives as ResolvedPlace[] | undefined) ?? []).filter((r) => r.exactMatch)
434
-
435
- // For each exact region candidate, ask the gazetteer directly: is there a same-named locality UNDER it?
436
- // The `parentID` scope is the descendant test (over the #832-repaired ancestors table), and it finds the
437
- // instance regardless of its global population rank — "Springfield, ME" reaches the small Springfield in
438
- // Maine that an unscoped top-N window would drop. First region with an exact-named descendant wins; the
439
- // region candidates are score-ordered, so a tie breaks toward the more prominent place.
440
- for (const region of regionCands) {
441
- const scoped = await backend.findPlace({
442
- text: localityNode.value,
443
- placetype: "locality",
444
- parentID: region.id,
445
- limit: 3,
446
- })
447
-
448
- const lc = scoped.find((l) => l.exactMatch && !(l.lat === 0 && l.lon === 0))
449
-
450
- if (lc) {
451
- decorateNode(
452
- regionNode,
453
- region,
454
- regionCands.filter((r) => r !== region)
455
- )
456
-
457
- regionNode.metadata = { ...regionNode.metadata, admin_coherence_repicked: true }
458
-
459
- decorateNode(
460
- localityNode,
461
- lc,
462
- scoped.filter((l) => l !== lc)
463
- )
464
-
465
- localityNode.metadata = { ...localityNode.metadata, admin_coherence_repicked: true }
466
-
467
- return
468
- }
469
- }
470
-
471
- // #267 follow-up: the token may name a COUNTRY whose namesake is a more-populous foreign region — "Tbilisi,
472
- // Georgia" parses region("Georgia") → the US state, but Tbilisi descends from Georgia the COUNTRY. When no
473
- // region candidate holds the locality, try same-named country candidates: a foreign capital under its
474
- // country out-votes the state namesake. Needs the country + the locality's ancestry in the gazetteer (the
475
- // #267 admin fold). The re-picked region node then carries the country place; the locality coordinate wins.
476
- const countryCands = (await backend.findPlace({ text: regionNode.value, placetype: "country", limit: 3 })).filter(
477
- (c) => c.exactMatch
478
- )
479
-
480
- for (const country of countryCands) {
481
- const scoped = await backend.findPlace({
482
- text: localityNode.value,
483
- placetype: "locality",
484
- parentID: country.id,
485
- limit: 3,
486
- })
487
-
488
- const lc = scoped.find((l) => l.exactMatch && !(l.lat === 0 && l.lon === 0))
489
-
490
- if (lc) {
491
- decorateNode(regionNode, country, regionCands)
492
- regionNode.metadata = { ...regionNode.metadata, admin_coherence_repicked: true }
493
-
494
- decorateNode(
495
- localityNode,
496
- lc,
497
- scoped.filter((l) => l !== lc)
498
- )
499
-
500
- localityNode.metadata = { ...localityNode.metadata, admin_coherence_repicked: true }
501
-
502
- return
503
- }
504
- }
505
-
506
- // #1023: the admin gazetteer may carry NO `country`-placetype node for the token AND the same-named
507
- // foreign locality may be ORPHANED (parent_id = -1) — the 2026-07-07 rebuild flattened Georgia's admin
508
- // hierarchy to localities-only, so the country-node lookup above finds nothing and the `parentID`
509
- // descendant test can never reach Tbilisi. Fall back to matchCountry: normalize the token to an
510
- // ISO-3166 alpha-2 and scope the locality by the gazetteer's `country` COLUMN (set even on an orphaned
511
- // row). Same primitive reconcileExplicitCountry (#822) uses, so the region-parsed namesake path
512
- // ("Tbilisi, Georgia") converges with the country-parsed one ("Vienna, Austria"). matchCountry returns
513
- // null for a US state name/abbrev ("Illinois" / "ME" / "IL"), so a real US (region, locality) pair
514
- // never reaches here — this stays inert on the domestic path.
515
- const mc = matchCountry(regionNode.value)
516
-
517
- if (mc) {
518
- const scoped = await backend.findPlace({
519
- text: localityNode.value,
520
- placetype: "locality",
521
- country: mc.iso2,
522
- limit: 3,
523
- })
524
-
525
- const lc = scoped.find((l) => l.exactMatch && !(l.lat === 0 && l.lon === 0))
526
-
527
- if (lc) {
528
- decorateNode(
529
- localityNode,
530
- lc,
531
- scoped.filter((l) => l !== lc)
532
- )
533
-
534
- localityNode.metadata = { ...localityNode.metadata, admin_coherence_repicked: true }
535
- // The token named a foreign country the admin gazetteer has no node for, but the greedy walk had
536
- // already decorated the region node with the US-state namesake. Revert that stale decoration so the
537
- // node stops asserting the wrong-country coordinate + `resolver_country` (which would otherwise leak
538
- // into the result's `countryCode`); the re-picked locality carries the winning coordinate, and the
539
- // region node falls back to the parsed "Georgia" token, unresolved (the admin DB has nothing truer).
540
- revertResolverDecoration(regionNode)
541
- }
542
- }
543
- }
544
-
545
- /**
546
- * Undo a resolver decoration on a node: restore the classifier attribution {@link decorateNode} displaced into
547
- * `metadata.classifier_source(_id)` and drop the resolver-supplied coordinate/identity/alternatives. Used by the #1023
548
- * country fall-through when the region token turns out to name a foreign country the admin gazetteer holds no node for
549
- * — the greedy walk had bound it to the US-state namesake, and that stale claim must not survive the locality re-pick.
550
- */
551
- function revertResolverDecoration(node: AddressNode): void {
552
- const meta = { ...node.metadata }
553
- const priorSource = meta["classifier_source"]
554
- const priorSourceID = meta["classifier_source_id"]
555
- node.source = typeof priorSource === "string" ? priorSource : undefined
556
- node.sourceID = typeof priorSourceID === "string" ? priorSourceID : undefined
557
-
558
- for (const key of [
559
- "classifier_source",
560
- "classifier_source_id",
561
- "resolver_score",
562
- "resolver_prominence",
563
- "resolver_name",
564
- "resolver_country",
565
- "resolution_quality",
566
- "postcode_city_mismatch",
567
- ]) {
568
- // oxlint-disable-next-line typescript/no-dynamic-delete -- removing one key from a plain record; the object is not on a hot path
569
- delete meta[key]
570
- }
571
-
572
- node.metadata = meta
573
- node.lat = undefined
574
- node.lon = undefined
575
- node.placeID = undefined
576
- node.alternatives = undefined
577
- }
578
-
579
- /**
580
- * Explicit-country coherence (#822) — the joint-consistency resolve keyed on the query's own EXPLICIT country token.
581
- * The greedy walk resolves a locality on name + population alone, so "Vienna, Austria" picks the populous US namesake
582
- * (Vienna WV) and IGNORES the "Austria" the address named. This pass asks the question the greedy order skipped —
583
- * _which "Vienna" is in the country the address names?_ — and re-picks the locality to the same-named place under that
584
- * country. The country code comes from the parser's OWN `country` emission via codex's ISO-3166 table (a name→code
585
- * normalization of a token the model already classified, NOT a routing prior or safelist); the gazetteer's `country`
586
- * column does the geographic confirmation. No pin, no list; generalizes to every country.
587
- *
588
- * Disjoint from {@link applyAdminCoherence} by the region guard: that pass owns the case where a REGION scopes the
589
- * locality; this one fires only when the explicit country is the locality's nearest admin context (no region between),
590
- * and then regardless of the locality's resolution state — so it covers both the resolved-but-foreign locality (Sydney
591
- * → the greedy AU pick was wrong) and the unresolved locality the span-rescore tier would otherwise back-fill with the
592
- * US namesake (Vienna → Vienna WV). Byte-stable when the locality already resolved in-country (the id guard) or the
593
- * named country holds no same-named locality (the fail-safe — what also protects "Turkey, TX": no country token ⇒ no
594
- * trigger; and an in-country lookup that finds nothing keeps the greedy result). Costs one country-scoped locality
595
- * lookup per triggering pair. See `ResolveOpts.adminCoherence`.
596
- */
597
- async function applyExplicitCountryCoherence(roots: readonly AddressNode[], backend: ResolverBackend): Promise<void> {
598
- const visit = async (node: AddressNode, countryToken: AddressNode | null, regionAbove: boolean): Promise<void> => {
599
- const countryHere = node.tag === "country" && node.value.trim().length ? node : countryToken
600
- const regionHere = regionAbove || node.tag === "region" || node.tag === "subregion"
601
-
602
- // Fire only when the explicit country is the locality's NEAREST admin context (no region/subregion between).
603
- // When a region IS present, applyAdminCoherence + the region's `parentID` scope already disambiguate the
604
- // locality — applying the coarse country filter there would wrongly re-pick "Springfield, IL" to the most
605
- // populous US "Springfield". Fires regardless of the locality's resolution state, so it PRE-EMPTS the
606
- // span-rescore tier (which would otherwise back-fill the unresolved locality with the US namesake).
607
- if (countryHere && !regionHere && (node.tag === "locality" || node.tag === "dependent_locality")) {
608
- await reconcileExplicitCountry(countryHere, node, backend)
609
- }
610
-
611
- for (const child of node.children) {
612
- await visit(child, countryHere, regionHere)
613
- }
614
- }
615
-
616
- for (const root of roots) {
617
- await visit(root, null, false)
618
- }
619
- }
620
-
621
- /**
622
- * Re-pick a resolved locality to its same-named place UNDER the explicitly-named country. `matchCountry` turns the
623
- * country token into an ISO-3166 alpha-2 (returns null for an unrecognized token → no-op); the backend then surfaces
624
- * the in-country namesake the population-first unscoped window buried. Leaves the node untouched when the country is
625
- * unrecognized, the named country has no exact same-named locality (the fail-safe), or the locality already resolved to
626
- * that place (the id guard → byte-stable). The country node itself stays as the parser emitted it — the named
627
- * well-covered countries carry no `country`-placetype row in the admin gazetteer, so there is nothing to decorate it
628
- * with; the locality coordinate is what the re-pick fixes.
629
- */
630
- async function reconcileExplicitCountry(
631
- countryNode: AddressNode,
632
- localityNode: AddressNode,
633
- backend: ResolverBackend
634
- ): Promise<void> {
635
- const mc = matchCountry(countryNode.value)
636
-
637
- if (!mc) return
638
-
639
- const scoped = await backend.findPlace({
640
- text: localityNode.value,
641
- placetype: "locality",
642
- country: mc.iso2,
643
- limit: 3,
644
- })
645
-
646
- const lc = scoped.find((l) => l.exactMatch && !(l.lat === 0 && l.lon === 0))
647
-
648
- if (!lc) return
649
-
650
- // Already the in-country place? (placeID encodes the WOF id.) Then the greedy walk was right — byte-stable.
651
- if (localityNode.placeID === `wof:${lc.id}`) return
652
-
653
- decorateNode(
654
- localityNode,
655
- lc,
656
- scoped.filter((l) => l !== lc)
657
- )
658
-
659
- localityNode.metadata = { ...localityNode.metadata, explicit_country_repicked: true }
660
- }
661
-
662
- /**
663
- * Region-country coherence — the joint-consistency resolve keyed on a REGION token the locale-inferred default-country
664
- * filter could not resolve. Companion to {@link applyExplicitCountryCoherence} (which keys on an explicit COUNTRY token)
665
- * and disjoint from {@link applyAdminCoherence} (which needs a region that DID resolve): this pass owns the mirror case,
666
- * where the region qualifier is a foreign subdivision the default-country hard filter (`spr.country = ?`) discarded.
667
- *
668
- * "Montreal QC" under a US locale: the walk applies `defaultCountry="US"` as a hard candidate filter to every admin
669
- * lookup, so the region "QC" (a Canadian subdivision) resolves to nothing and is dropped — the one signal that would
670
- * redirect the country to CA — and the locality "Montreal" is force-matched to the populous US namesake (Montreal, WI).
671
- * The greedy order threw away the evidence that could correct it.
672
- *
673
- * The fix expands the region token to its country via codex's ISO-3166-2 subdivision table (`matchSubdivision`: "QC" →
674
- * `{ name: "Quebec", country: "CA" }`, handling the FTS index's missing "QC" alt-name code-side), then asks the two
675
- * questions the greedy walk skipped: does that subdivision genuinely resolve UNDER its own country, and is there a
676
- * same-named locality under it? Only when BOTH hold does it swap the region and locality to the in-country pair.
677
- * Geography confirms; the subdivision table is a soft name→country prior, not a routing decision.
678
- *
679
- * Evidence-gated to stay byte-stable on the domestic path. It fires ONLY when (a) a default country is in force, (b)
680
- * the region node is UNRESOLVED (the default-country filter came up empty — a US region resolves fine under `US`, so a
681
- * well-formed US query never trips this), (c) the token is a subdivision of a DIFFERENT country than the default, and
682
- * (d) both the foreign region and a same-named foreign locality resolve. "Springfield, IL" / "Portland, ME": the region
683
- * resolves under `US`, so gate (b) fails and the tree is untouched. Costs one region + one locality lookup per
684
- * triggering pair. See `ResolveOpts.adminCoherence`.
685
- */
686
- async function applyRegionCountryCoherence(
687
- roots: readonly AddressNode[],
688
- backend: ResolverBackend,
689
- defaultCountry: string | undefined
690
- ): Promise<void> {
691
- // No default country → no hard country filter was applied, so no region qualifier was discarded by one. The bug
692
- // this pass corrects is specific to the locale-inferred default country; without it, there is nothing to rescue.
693
- if (!defaultCountry) return
694
-
695
- const visit = async (node: AddressNode, regionAncestor: AddressNode | null): Promise<void> => {
696
- // Track the nearest region ancestor regardless of its resolution state (the trigger is an UNRESOLVED region).
697
- const regionHere = node.tag === "region" || node.tag === "subregion" ? node : regionAncestor
698
-
699
- // Fire for an UNRESOLVED region (the default-country filter came up empty) whose companion locality node
700
- // exists — regardless of the locality's resolution state, so it covers both the resolved-but-foreign namesake
701
- // (Montreal → the greedy US pick, Montreal WI) and the unresolved locality the span-rescore tier would
702
- // otherwise back-fill with a US namesake. The in-country lookups below are the evidence gate.
703
- if (
704
- regionHere &&
705
- !isResolvedWithCoord(regionHere) &&
706
- (node.tag === "locality" || node.tag === "dependent_locality") &&
707
- node.value.trim().length
708
- ) {
709
- await reconcileRegionCountry(regionHere, node, backend, defaultCountry)
710
- }
711
-
712
- for (const child of node.children) {
713
- await visit(child, regionHere)
714
- }
715
- }
716
-
717
- for (const root of roots) {
718
- await visit(root, null)
719
- }
720
- }
721
-
722
- /**
723
- * Re-pick an (unresolved region, resolved-but-foreign-namesake locality) pair to the in-country instance the
724
- * default-country filter hid. `matchSubdivision` turns the region token into `{ name, country }` (null for anything
725
- * that isn't a US state or CA province → no-op); the region's full name then resolves it under that country (expanding
726
- * the abbreviation the gazetteer FTS index lacks), and the locality is re-scoped to the same country. Leaves both nodes
727
- * untouched unless every gate holds — the subdivision names a different country than the default, the region resolves
728
- * under it, and a same-named locality exists there — so the domestic path stays byte-identical.
729
- */
730
- async function reconcileRegionCountry(
731
- regionNode: AddressNode,
732
- localityNode: AddressNode,
733
- backend: ResolverBackend,
734
- defaultCountry: string
735
- ): Promise<void> {
736
- const sub = matchSubdivision(regionNode.value)
737
-
738
- if (!sub) return
739
-
740
- // The subdivision must belong to a DIFFERENT country than the locale default. A US-state token under a US default
741
- // (sub.country === defaultCountry) never reaches the swap — the pass is inert on the domestic path.
742
- if (sub.country.toUpperCase() === defaultCountry.toUpperCase()) return
743
-
744
- // The locality already resolved in the subdivision's country? Then the greedy walk was already right — byte-stable.
745
- const localityCountry = (localityNode.metadata?.["resolver_country"] as string | undefined)?.toUpperCase()
746
-
747
- if (localityCountry === sub.country.toUpperCase()) return
748
-
749
- // Confirm the subdivision genuinely resolves under its own country, by its full name (expands "QC" → "Quebec", the
750
- // form the FTS index carries). No resolvable region → no evidence the token is a real foreign subdivision; abstain.
751
- const regionScoped = await backend.findPlace({
752
- text: sub.name,
753
- placetype: "region",
754
- country: sub.country,
755
- limit: 3,
756
- })
757
-
758
- const rc = regionScoped.find((r) => r.exactMatch && !(r.lat === 0 && r.lon === 0))
759
-
760
- if (!rc) return
761
-
762
- // Is there a same-named locality under that country? (the descendant test, by country column — the same primitive
763
- // reconcileExplicitCountry uses.) No in-country namesake → keep the greedy result (fail-safe).
764
- const scoped = await backend.findPlace({
765
- text: localityNode.value,
766
- placetype: "locality",
767
- country: sub.country,
768
- limit: 3,
769
- })
770
-
771
- const lc = scoped.find((l) => l.exactMatch && !(l.lat === 0 && l.lon === 0))
772
-
773
- if (!lc) return
774
-
775
- // Adopt the in-country pair: the region gets the foreign subdivision, the locality its same-named foreign instance.
776
- decorateNode(
777
- regionNode,
778
- rc,
779
- regionScoped.filter((r) => r !== rc)
780
- )
781
-
782
- regionNode.metadata = { ...regionNode.metadata, region_country_repicked: true }
783
-
784
- decorateNode(
785
- localityNode,
786
- lc,
787
- scoped.filter((l) => l !== lc)
788
- )
789
-
790
- localityNode.metadata = { ...localityNode.metadata, region_country_repicked: true }
791
- }
792
-
793
643
  class WOFResolver implements Resolver {
794
644
  readonly #backend: ResolverBackend
795
645
  /**
@@ -797,12 +647,26 @@ class WOFResolver implements Resolver {
797
647
  * read them from the resolver handle they already hold. Absent on artifacts predating the coverage manifest.
798
648
  */
799
649
  readonly artifactCoverage: Resolver["artifactCoverage"]
650
+ /**
651
+ * Optional backend methods this backend omits, each naming the default-ON option it silently disables. Computed once
652
+ * here rather than at each guard site so a caller can read the gap before running a query that would quietly skip the
653
+ * feature. See `backend-capabilities.ts`.
654
+ */
655
+ readonly capabilityGaps: readonly BackendCapabilityGap[]
800
656
 
801
657
  constructor(backend: ResolverBackend) {
802
658
  this.#backend = backend
803
659
  this.artifactCoverage = backend.artifactCoverage
660
+ this.capabilityGaps = describeCapabilityGaps(backend)
661
+ reportCapabilityGaps(this.capabilityGaps)
804
662
  }
805
663
 
664
+ /**
665
+ * The `Resolver.findPlace` passthrough — one direct gazetteer probe for pipeline-level consumers (#1738's
666
+ * dominant-bearer guard). Bound as a method so `this.#backend` stays private.
667
+ */
668
+ findPlace: Resolver["findPlace"] = (query) => this.#backend.findPlace(query)
669
+
806
670
  async resolveTree(tree: AddressTree, opts: ResolveOpts = {}): Promise<AddressTree> {
807
671
  // Postcode-shape coherence (#31, Mechanism 1): the earliest pass in the tree — pure-sync and
808
672
  // backend-free, run BEFORE `state.postcode` is read so an excluded span can never become the
@@ -821,24 +685,44 @@ class WOFResolver implements Resolver {
821
685
  minWinningScore: opts.minWinningScore ?? 0,
822
686
  candidatesPerLookup: opts.candidatesPerLookup ?? 5,
823
687
  defaultCountry: opts.defaultCountry,
688
+ defaultCountryIsInferred: opts.defaultCountryIsInferred === true,
689
+ bareLocalityNode: loneBareLocalityNode(tree, opts.placetypeMap ?? DEFAULT_PLACETYPE_MAP),
824
690
  parentFallback: opts.parentFallback ?? true,
691
+ // Requires a sink: with nowhere to record the answer the probes would be pure cost.
692
+ ...(opts.diagnoseUnreachable && opts.traceSink ? { diagnoseUnreachable: true } : {}),
825
693
  postcode: firstPostcodeValue(tree.roots),
826
694
  // #31 Mechanism 2 — forwarded to locality lookups (see #lookupAndPick). Opt-in, OFF by default.
827
695
  postcodeContainmentCoherence: opts.postcodeContainmentCoherence === true,
828
696
  // #31 Mechanism 3 — the prefix prior + its injected index (see #lookupAndPick). Opt-in, OFF by default.
829
697
  postcodePrefixPrior: opts.postcodePrefixPrior === true,
830
698
  postcodePrefixIndex: opts.postcodePrefixIndex,
699
+ // #1589: derived here when the caller didn't thread it, so the browser cascade and the
700
+ // drop-ins get the implied-set probe without per-caller wiring (the staged-repoint e2e
701
+ // caught `100 00` resolving in Node and not in the browser over the same artifact).
702
+ postcodeFormatCountries:
703
+ opts.postcodeFormatCountries ?? countriesFromPostcodeFormat(firstPostcodeValue(tree.roots)),
704
+ fuzzyCountryScope: opts.fuzzyCountryScope,
831
705
  bias: opts.bias,
832
706
  anchorPosterior: opts.anchorPosterior,
833
707
  anchorWeight: opts.anchorWeight ?? 2,
834
708
  localeCountryPrior: opts.localeCountryPrior,
835
709
  localeCountryPriorWeight: opts.localeCountryPriorWeight ?? DEFAULT_COUNTRY_PRIOR_WEIGHT,
710
+ capitalLevel: opts.capitalLevel,
836
711
  hardCountry: opts.hardCountry,
837
712
  // Default-ON (#402): completion only fires for a dual-role region whose locality the parser
838
713
  // dropped, and no-ops entirely when the backend has no relation (the browser WASM resolver, or
839
714
  // a gazetteer without `coincident_roles`). Pass `hierarchyCompletion: false` to opt out.
715
+ //
716
+ // Default-ON is nominal on the SHIPPED backend: `WOFCandidateTableLookup` implements no
717
+ // `coincidentLocalitiesFor`, so this attaches nothing there. Measured 2026-08-15 on FTS, which
718
+ // does implement it, the flag changed 0 of 837 board inputs — see ResolveOpts.hierarchyCompletion.
840
719
  hierarchyCompletion: opts.hierarchyCompletion ?? true,
841
720
  includeAncestors: opts.includeAncestors ?? false,
721
+ // #1717 stage 2 — default OFF (D-rule); the qualifier is pre-scanned like `postcode` above
722
+ // because region and locality are siblings the walk visits independently.
723
+ adminContainmentRerank: opts.adminContainmentRerank === true,
724
+ regionQualifier: firstRegionQualifier(tree.roots),
725
+ ...(opts.traceSink ? { traceSink: opts.traceSink } : {}),
842
726
  localityNodePresent: false,
843
727
  resolvedRegion: null,
844
728
  resolvedRegionNode: null,
@@ -856,7 +740,28 @@ class WOFResolver implements Resolver {
856
740
  // postcode-country-coherence.ts.
857
741
  let postcodeScope: PostcodeCountryScope | null = null
858
742
 
859
- if (opts.postcodeCountryCoherence !== false && state.defaultCountry && state.postcode) {
743
+ // The pass also runs with NO default in force (#1585/#861 convergence): there is nothing to
744
+ // override, but the same exactly-one-country abstention lets the postcode+locality pair
745
+ // CONSTRAIN an otherwise population-first walk — `Zabiče 8, 6250 Zabiče` picks the SI row
746
+ // coherent with the SI 6250 centroid instead of the more-populous Polish namesake. The
747
+ // browser cascade (which sets no default by design) is the consumer this exists for.
748
+ // #1735 second half: the address's own country statement scopes the walk BEFORE anything
749
+ // resolves — a sibling's resolution never reaches a sibling, so without this the postcode
750
+ // lookup in "RM10 8AB, UK" ran under the locale-inferred US filter while the country node
751
+ // resolved to GB beside it. Explicit-over-inferred, the #912 precedence, decided from the
752
+ // tree's own text; an EXPLICIT caller scope is never overridden.
753
+ let explicitScope: string | null = null
754
+
755
+ if (!state.defaultCountry || state.defaultCountryIsInferred) {
756
+ explicitScope = explicitCountryScope(tree.roots)
757
+
758
+ if (explicitScope) {
759
+ state.defaultCountry = explicitScope
760
+ state.defaultCountryIsInferred = false
761
+ }
762
+ }
763
+
764
+ if (opts.postcodeCountryCoherence !== false && state.postcode) {
860
765
  postcodeScope = await findPostcodeCountryScope(tree.roots, this.#backend, {
861
766
  postcode: state.postcode,
862
767
  defaultCountry: state.defaultCountry,
@@ -883,6 +788,20 @@ class WOFResolver implements Resolver {
883
788
  stampPostcodeCountryScope(newRoots, postcodeScope)
884
789
  }
885
790
 
791
+ // 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
793
+ // 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
795
+ // under a non-FR locale (six board venue rows dropped from rooftop to city centroid; the battery
796
+ // caught it).
797
+ if (explicitScope) {
798
+ for (const root of newRoots) {
799
+ if (root.tag === "country") {
800
+ root.metadata = { ...root.metadata, explicit_country_scope: explicitScope }
801
+ }
802
+ }
803
+ }
804
+
886
805
  // Dual-role hierarchy completion (#405/#415). Only when enabled, a region resolved, and the parser
887
806
  // emitted NO locality — record the dropped locality as a SECONDARY ROLE (an interpretation) on the
888
807
  // resolved region node, from the backend's precomputed coincident-roles relation (#403). One node,
@@ -1021,6 +940,23 @@ class WOFResolver implements Resolver {
1021
940
  decorated.metadata = { ...decorated.metadata, ...picked.metadata }
1022
941
  }
1023
942
 
943
+ // #1678 thread 2 — the parse half, resolved from the atlas rather than trained in.
944
+ //
945
+ // The bare-toponym race exists because the model reads a lone country or region name as a
946
+ // `locality`; the race finds the right PLACE and the node keeps the wrong TAG. So
947
+ // `mw geocode 格鲁吉亚` lands on Georgia the country and reports `{"locality": "格鲁吉亚"}`,
948
+ // which is a correct coordinate under a label that will mislead the moment the same toponym
949
+ // appears inside a longer address.
950
+ //
951
+ // The repick metadata already marks exactly these nodes, so the correction is free: retrieval
952
+ // established the placetype, and the tag follows it. Only the race's own picks are retagged —
953
+ // an ordinary locality that resolved to a locality is untouched.
954
+ if (decorated.metadata?.["bare_country_repick"]) {
955
+ decorated.tag = "country"
956
+ } else if (decorated.metadata?.["bare_region_repick"]) {
957
+ decorated.tag = "region"
958
+ }
959
+
1024
960
  // Lineage attachment (#404): stamp the resolved place's ancestor chain onto metadata. Opt-in
1025
961
  // + only when the backend supplies it, so the default stays byte-identical (no extra query).
1026
962
  if (state.includeAncestors && this.#backend.ancestors) {
@@ -1045,6 +981,38 @@ class WOFResolver implements Resolver {
1045
981
  return decorated
1046
982
  }
1047
983
 
984
+ /**
985
+ * Which admin bands hold a value the probed band did not, keeping the country and dropping the parent.
986
+ *
987
+ * Bands come from `PLACETYPE_SPECIFICITY` rather than a list typed here: that table is already the repo's answer to
988
+ * how coarse a placetype is, and a second hand-kept copy would agree right up until a placetype is added. Probed
989
+ * coarse-to-fine so the report reads down the admin ladder.
990
+ */
991
+ async #probeOtherBands(
992
+ query: Parameters<ResolverBackend["findPlace"]>[0],
993
+ probed: string
994
+ ): Promise<NonNullable<ResolveNodeTrace["reachableIn"]>> {
995
+ const found: NonNullable<ResolveNodeTrace["reachableIn"]> = []
996
+
997
+ for (const band of DIAGNOSTIC_BANDS) {
998
+ if (band === probed) continue
999
+
1000
+ try {
1001
+ const hits = await this.#backend.findPlace({ ...query, placetype: band, parentID: undefined })
1002
+
1003
+ if (hits.length) {
1004
+ found.push({ placetype: band, n: hits.length })
1005
+ }
1006
+ } catch {
1007
+ // A band the backend cannot answer for is not evidence that the key is absent from it, so it is
1008
+ // skipped rather than recorded as an empty result.
1009
+ continue
1010
+ }
1011
+ }
1012
+
1013
+ return found
1014
+ }
1015
+
1048
1016
  async #lookupAndPick(
1049
1017
  node: AddressNode,
1050
1018
  placetype: string,
@@ -1095,9 +1063,17 @@ class WOFResolver implements Resolver {
1095
1063
  // later by region-country coherence after the scoped lookup abstains.
1096
1064
  const countryHint = node.metadata?.["country_hint"]
1097
1065
 
1066
+ // A locale-INFERRED default country never filters a `country`-placetype lookup: the span names a
1067
+ // country outright, and the filter can only admit the scope country itself (bare "Germany" under
1068
+ // the en-US default filtered out the DE row; the unresolved span then fell to a US locality whose
1069
+ // historical alias is "Germany, Ohio"). An EXPLICIT caller scope stays supreme, matching the #912
1070
+ // posture; parent evidence and the confident placer are untouched.
1071
+ const defaultCountryForLookup =
1072
+ placetype === "country" && state.defaultCountryIsInferred ? undefined : state.defaultCountry
1073
+
1098
1074
  const country =
1099
1075
  parentResolved?.country ??
1100
- state.defaultCountry ??
1076
+ defaultCountryForLookup ??
1101
1077
  (typeof countryHint === "string" ? countryHint : undefined) ??
1102
1078
  state.hardCountry
1103
1079
 
@@ -1105,6 +1081,28 @@ class WOFResolver implements Resolver {
1105
1081
  query.country = country
1106
1082
  }
1107
1083
 
1084
+ // #1585: the locale hint's country rides on every primary lookup as the TYPO-FUZZY tier's scope.
1085
+ // Deliberately set even when `query.country` is (the backend ignores it there — the hard filter
1086
+ // is already narrower): the field's contract lives in one place, the backend.
1087
+ if (state.fuzzyCountryScope) {
1088
+ query.fuzzyCountry = state.fuzzyCountryScope
1089
+ }
1090
+
1091
+ // Admin-containment re-rank (#1717 stage 2): thread the tree's region qualifier onto locality
1092
+ // lookups so a capable backend can vouch for (and surface) the candidates that sit UNDER it.
1093
+ // Stands down under an EXPLICIT caller country scope (the #912 posture — only a locale-INFERRED
1094
+ // scope is bypassable by the address's own evidence); the resolved-parent and placer scopes are
1095
+ // left alone, since a resolved parent usually IS the qualifier and the injection dedupes.
1096
+ const containmentEligible =
1097
+ state.adminContainmentRerank &&
1098
+ placetype === "locality" &&
1099
+ state.regionQualifier !== undefined &&
1100
+ (!state.defaultCountry || state.defaultCountryIsInferred)
1101
+
1102
+ if (containmentEligible) {
1103
+ query.regionQualifier = state.regionQualifier
1104
+ }
1105
+
1108
1106
  // Coordinate-first: hand the sibling postcode to locality lookups so the backend can inject
1109
1107
  // postcode-proximal candidates the name-match would miss. Only for locality (the placetype both
1110
1108
  // `locality` and `dependent_locality` map to); other placetypes ignore it. The containment flag
@@ -1118,25 +1116,97 @@ class WOFResolver implements Resolver {
1118
1116
  }
1119
1117
  }
1120
1118
 
1119
+ // #1721 resolver-interior trace. Stage orders hold the SAME candidate objects across re-ranks
1120
+ // (every stage reorders, never clones), which is what lets emit assemble a per-stage rank
1121
+ // vector per row. The no-sink walk talks to the frozen no-op recorder — zero per-event branches.
1122
+ const rec = state.traceSink ? createNodeTraceRecorder(state.traceSink) : NOOP_TRACE_RECORDER
1123
+
1124
+ // The query is SNAPSHOT, not bound live. `emit` reads `ctx.query.parentID` at the END of the walk, and the
1125
+ // parent-fallback retry `delete`s that key mid-lookup — so binding the object itself lets a later mutation
1126
+ // rewrite history. That is how 196 lookups which every one of them carried a parent came out of the
1127
+ // constraint census reading `parentID: absent`.
1128
+ rec.bind(node, placetype, { ...query }, state.candidatesPerLookup)
1129
+
1121
1130
  let candidates: ResolvedPlace[]
1122
1131
 
1123
- try {
1124
- candidates = await this.#backend.findPlace(query)
1125
-
1126
- // Parent soft-gating: `parentID` is a HARD descendant filter in the backend, which wrongly
1127
- // zeroes the result when the parent resolved wrong OR the gazetteer hierarchy is incomplete
1128
- // (a real locality whose `ancestors` chain is missing its region). Rather than turn a
1129
- // resolvable node into an unresolved one, retry once WITHOUT the parent constraint — we
1130
- // prefer a parent-scoped hit but never sacrifice recall. The country constraint is kept, so
1131
- // this still can't wander to a foreign place. Same logical resolution → no extra budget.
1132
- if (!candidates.length && state.parentFallback && query.parentID !== undefined) {
1133
- delete query.parentID
1132
+ // #1589: a `postalcode` whose FORMAT implies specific countries, with no surviving country
1133
+ // constraint, probes exactly the implied set — most populous hit wins, and an all-miss
1134
+ // leaves the candidate set EMPTY rather than falling through to the unconstrained fold:
1135
+ // `100 00` space-strips to `10000`, which answers Troyes FR while the CZ rows sit in the
1136
+ // artifact under both keyings; a scoped empty must stay empty (the same contract as the
1137
+ // fuzzy tier's, #1585). The postcode-prefix prior below still gets its turn on the empty
1138
+ // set — its index is country-scoped by construction, so it is not the fold this branch
1139
+ // exists to avoid (the B3 tests hold that path).
1140
+ if (placetype === "postalcode" && !query.country && state.postcodeFormatCountries?.length) {
1141
+ rec.gate("postcode_format_probe")
1142
+ let best: ResolvedPlace | undefined
1143
+
1144
+ for (const impliedCountry of state.postcodeFormatCountries) {
1145
+ try {
1146
+ const hits = await this.#backend.findPlace({ ...query, country: impliedCountry })
1147
+ const top = hits[0]
1148
+
1149
+ // `score` is the backend's own population-first ranking metric, so comparing the
1150
+ // per-country winners by it keeps the cross-country pick population-first too.
1151
+ if (top && (!best || top.score > best.score)) {
1152
+ best = top
1153
+ }
1154
+ } catch {
1155
+ // A per-country probe failure reads as a miss for that country, never an abort.
1156
+ }
1157
+ }
1158
+
1159
+ if (best) {
1160
+ rec.emit({ id: best.id, name: best.name, source: "postcode_format_probe" })
1161
+
1162
+ return { top: best, alternatives: [] }
1163
+ }
1164
+
1165
+ candidates = []
1166
+ } else {
1167
+ try {
1134
1168
  candidates = await this.#backend.findPlace(query)
1169
+ rec.stage("initial", candidates)
1170
+
1171
+ // #1731: the backend's interior region-scope fallback, surfaced as a gate — the resolver
1172
+ // never sees the scoped probe miss, only the stamp the re-admitted rows carry.
1173
+ if (candidates[0]?.regionScopeMiss) {
1174
+ rec.gate("region_scope_miss")
1175
+ }
1176
+
1177
+ // Parent soft-gating: `parentID` is a HARD descendant filter in the backend, which wrongly
1178
+ // zeroes the result when the parent resolved wrong OR the gazetteer hierarchy is incomplete
1179
+ // (a real locality whose `ancestors` chain is missing its region). Rather than turn a
1180
+ // resolvable node into an unresolved one, retry once WITHOUT the parent constraint — we
1181
+ // prefer a parent-scoped hit but never sacrifice recall. The country constraint is kept, so
1182
+ // this still can't wander to a foreign place. Same logical resolution → no extra budget.
1183
+ if (!candidates.length && state.parentFallback && query.parentID !== undefined) {
1184
+ delete query.parentID
1185
+ rec.gate("parent_fallback_retry")
1186
+ candidates = await this.#backend.findPlace(query)
1187
+ rec.stage("parent_fallback", candidates)
1188
+ }
1189
+
1190
+ // DIAGNOSTIC ONLY, and after every real attempt: which OTHER bands hold this value. The answer never
1191
+ // becomes the pick — a band the model did not ask for is not evidence about what the string means —
1192
+ // but it separates the two facts a `null` cannot: a key we hold under another placetype is a
1193
+ // reachability failure the tag caused, while a key nowhere is coverage. Off by default; one extra call
1194
+ // per band per miss.
1195
+ if (!candidates.length && state.diagnoseUnreachable) {
1196
+ rec.reachable(await this.#probeOtherBands(query, placetype))
1197
+ }
1198
+ } catch (error) {
1199
+ // Defensive: a backend failure should not abort the whole tree walk. Leave the node with
1200
+ // its classifier attribution intact.
1201
+ //
1202
+ // The reason rides the gate name. A bare `backend_error` cannot tell a closed database from a
1203
+ // finalized statement from a genuine query fault, which is what made three full-board constraint
1204
+ // runs unreadable — 64 of 591 rows errored and the census could not say why.
1205
+ rec.gate(`backend_error: ${(error as Error).message}`)
1206
+ rec.emit(null)
1207
+
1208
+ return null
1135
1209
  }
1136
- } catch {
1137
- // Defensive: a backend failure should not abort the whole tree walk. Leave the node with
1138
- // its classifier attribution intact.
1139
- return null
1140
1210
  }
1141
1211
 
1142
1212
  // Postcode-prefix prior (#31, Mechanism 3): when a `postalcode` node misses the gazetteer, derive
@@ -1158,15 +1228,55 @@ class WOFResolver implements Resolver {
1158
1228
  : {}),
1159
1229
  }
1160
1230
 
1231
+ rec.gate("postcode_prefix_prior")
1232
+ const prefixPlace = postcodePrefixResolvedPlace(probe.prefix, probe.node, state.postcodePrefixIndex)
1233
+
1234
+ rec.emit({ id: prefixPlace.id, name: prefixPlace.name, source: "postcode_prefix" })
1235
+
1161
1236
  return {
1162
- top: postcodePrefixResolvedPlace(probe.prefix, probe.node, state.postcodePrefixIndex),
1237
+ top: prefixPlace,
1163
1238
  alternatives: [],
1164
1239
  metadata,
1165
1240
  }
1166
1241
  }
1167
1242
  }
1168
1243
 
1169
- if (!candidates.length) return null
1244
+ // The bare-toponym country race (fix B of the bare-country class): a lone locality-tagged span
1245
+ // also races the `country` placetype, because the parser tags bare country names `locality`
1246
+ // about half the time ("Japan", "China") and the locality filter makes the country row
1247
+ // unreachable at any rank. Runs ONLY for the tree's single value-bearing node, so every
1248
+ // address-shaped input is byte-stable. The locality winner's prominence arbitrates below;
1249
+ // with no locality candidates at all, a country hit resolves the span outright.
1250
+ const isBareRace = placetype === "locality" && node === state.bareLocalityNode
1251
+
1252
+ if (isBareRace) {
1253
+ rec.gate("bare_race")
1254
+ }
1255
+
1256
+ const bareCountry = isBareRace ? await bareCountryCandidate(this.#backend, node.value, query.country) : null
1257
+ const bareRegion = isBareRace ? await bareRegionCandidate(this.#backend, node.value, query.country) : null
1258
+
1259
+ if (!candidates.length) {
1260
+ // With no locality candidates at all, the admin namesake with the larger population answers
1261
+ // outright (the same precedence the dominance rule below applies).
1262
+ const admin = pickLargerAdmin(bareCountry, bareRegion)
1263
+
1264
+ if (admin) {
1265
+ rec.gate("empty_admin_pick")
1266
+ rec.emit({ id: admin.id, name: admin.name, source: "empty_admin" })
1267
+
1268
+ return {
1269
+ top: admin,
1270
+ alternatives: [],
1271
+ metadata: admin === bareRegion ? { bare_region_repick: true } : { bare_country_repick: true },
1272
+ }
1273
+ }
1274
+
1275
+ rec.emit(null)
1276
+
1277
+ return null
1278
+ }
1279
+
1170
1280
  // Postcode-anchor re-rank (#369): when a country posterior is supplied (from the address's
1171
1281
  // postcode), boost candidates by `anchorWeight * posterior[candidate.country]` and re-sort, so a
1172
1282
  // postcode that pins the country pulls the right-country place over a higher-BM25 foreign namesake
@@ -1215,6 +1325,8 @@ class WOFResolver implements Resolver {
1215
1325
 
1216
1326
  return bKey - aKey || b.score - a.score
1217
1327
  })
1328
+
1329
+ rec.stage("anchor", ranked)
1218
1330
  }
1219
1331
 
1220
1332
  // Locale-country soft prior (#27) — the #912 lever's other half, at the tier that decides a bare
@@ -1234,6 +1346,7 @@ class WOFResolver implements Resolver {
1234
1346
  // wherever it has been measured, and it leaves an unscored candidate exactly where the prior put it.
1235
1347
  if (state.localeCountryPrior && !state.defaultCountry && !state.anchorPosterior && anchorEligible) {
1236
1348
  ranked = rankByCountryPrior(ranked, state.localeCountryPrior, state.localeCountryPriorWeight)
1349
+ rec.stage("locale_prior", ranked)
1237
1350
  }
1238
1351
 
1239
1352
  // Importance-first (#17/#28). Before this key a bare famous name was decided on POPULATION
@@ -1249,6 +1362,33 @@ class WOFResolver implements Resolver {
1249
1362
  // derived from the address's OWN postcode. Evidence outranks a prior. See `toponym-prior.ts`.
1250
1363
  if (!state.anchorPosterior) {
1251
1364
  ranked = rankByImportance(ranked)
1365
+ rec.stage("importance", ranked)
1366
+
1367
+ // #1880 — bounded capital promotion, directly above the fame key it corrects and below the
1368
+ // containment partition (the qualifier is the address's own text; evidence outranks a prior).
1369
+ // Same stand-down as fame: an anchor posterior is postcode evidence and silences the prior.
1370
+ if (state.capitalLevel) {
1371
+ ranked = promoteCapitals(ranked, state.capitalLevel)
1372
+ rec.stage("capital", ranked)
1373
+ }
1374
+ }
1375
+
1376
+ // Admin-containment partition (#1717 stage 2): the LAST soft re-rank, after the anchor/fame keys
1377
+ // 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-
1379
+ // 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
1381
+ // fame disagrees with the qualifier (the shared-function partition, tier-safe + stable, so it can
1382
+ // never promote a contained partial match over an exact one). No stamps → identity → byte-stable
1383
+ // on any backend that ignored `regionQualifier`.
1384
+ if (containmentEligible) {
1385
+ ranked = partitionByContainment(
1386
+ ranked,
1387
+ (c) => c.containedByQualifier === true,
1388
+ (c) => c.exactMatch === true
1389
+ )
1390
+
1391
+ rec.stage("containment", ranked)
1252
1392
  }
1253
1393
 
1254
1394
  // Exact-type preference (#718): when the placetype-equivalence group let a broader admin tier
@@ -1266,104 +1406,59 @@ class WOFResolver implements Resolver {
1266
1406
  ...ranked.filter((c) => !isPlacetypeFallback(placetype, c.placetype)),
1267
1407
  ...ranked.filter((c) => isPlacetypeFallback(placetype, c.placetype)),
1268
1408
  ]
1409
+
1410
+ rec.stage("exact_type", ranked)
1269
1411
  }
1270
1412
 
1271
1413
  const top = ranked[0]!
1272
1414
 
1273
- if (top.score < state.minWinningScore) return null
1415
+ if (top.score < state.minWinningScore) {
1416
+ rec.gate("min_score_reject")
1417
+ rec.emit(null)
1274
1418
 
1275
- // Fallback-observability (#718): if the winner is a macro-type AND no exact-type candidate
1276
- // existed for this span, annotate that a broader tier stood in for the true one. Additive —
1277
- // identity/coordinate are unchanged; only `metadata.resolution_quality` is stamped downstream.
1278
- if (isPlacetypeFallback(placetype, top.placetype)) {
1279
- top.resolutionQuality = "fallback"
1419
+ return null
1280
1420
  }
1281
1421
 
1282
- return { top, alternatives: ranked.slice(1) }
1283
- }
1284
- }
1422
+ // The admin side of the bare-toponym race. The COUNTRY row wins on prominence alone —
1423
+ // Japan-the-country (pop 126M) over Japan, Pennsylvania (pop 0) — while the REGION row must
1424
+ // DOMINATE the locality winner by {@link BARE_REGION_DOMINANCE_LOG10} in log-population:
1425
+ // prominence saturates at the backend's populationBoost cap, so the margin is measured on the
1426
+ // 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
1428
+ // Vermont hamlet (margin 3.4). A bare name with no admin namesake never reaches these lines,
1429
+ // and the displaced locality stays first among the alternatives either way.
1430
+ if (bareCountry && (bareCountry.prominence ?? bareCountry.score) > (top.prominence ?? top.score)) {
1431
+ rec.gate("bare_country_repick")
1432
+ rec.emit({ id: bareCountry.id, name: bareCountry.name, source: "bare_country" })
1433
+
1434
+ return { top: bareCountry, alternatives: ranked, metadata: { bare_country_repick: true } }
1435
+ }
1285
1436
 
1286
- /**
1287
- * Stamp a node with resolver-supplied attribution. Displaces any prior classifier `source` / `sourceID` into
1288
- * `metadata.classifier_source` / `metadata.classifier_source_id` so debugging tools can still see who made the original
1289
- * assertion. Surfaces the runner-up candidates on `alternatives` so callers can disambiguate (Springfield-class
1290
- * failures, [#8 in the failure catalogue]).
1291
- */
1292
- function decorateNode(node: AddressNode, resolved: CoordinateOptionalPlace, alternatives: ResolvedPlace[]): void {
1293
- if (node.source !== undefined || node.sourceID !== undefined) {
1294
- const meta = { ...node.metadata }
1437
+ if (bareRegion && logPopulation(bareRegion) >= logPopulation(top) + BARE_REGION_DOMINANCE_LOG10) {
1438
+ rec.gate("bare_region_repick")
1439
+ rec.emit({ id: bareRegion.id, name: bareRegion.name, source: "bare_region" })
1295
1440
 
1296
- if (node.source !== undefined) {
1297
- meta["classifier_source"] = node.source
1441
+ return { top: bareRegion, alternatives: ranked, metadata: { bare_region_repick: true } }
1298
1442
  }
1299
1443
 
1300
- if (node.sourceID !== undefined) {
1301
- meta["classifier_source_id"] = node.sourceID
1444
+ // Fallback-observability (#718): if the winner is a macro-type AND no exact-type candidate
1445
+ // existed for this span, annotate that a broader tier stood in for the true one. Additive —
1446
+ // identity/coordinate are unchanged; only `metadata.resolution_quality` is stamped downstream.
1447
+ if (isPlacetypeFallback(placetype, top.placetype)) {
1448
+ top.resolutionQuality = "fallback"
1449
+ rec.gate("placetype_fallback")
1302
1450
  }
1303
1451
 
1304
- node.metadata = meta
1305
- }
1306
-
1307
- node.source = "resolver"
1308
- node.sourceID = `${resolved.placetype}:${resolved.id}`
1309
- node.lat = resolved.lat
1310
- node.lon = resolved.lon
1311
- node.placeID = `wof:${resolved.id}` // v1: only WOF resolvers; the URI scheme stays this simple
1312
- // Record the resolver's ranking score AND the resolved place's CANONICAL name. The name is the
1313
- // gazetteer's truth for the place we picked — distinct from `node.value` (the raw input span). It
1314
- // lets consumers display the canonical name and lets the end-to-end eval check the resolver chose
1315
- // the right PLACE (gazetteer-name vs ground-truth) rather than merely echoing the parser's text.
1316
- node.metadata = { ...node.metadata, resolver_score: resolved.score, resolver_name: resolved.name }
1317
-
1318
- // The winner's PROMINENCE, when the backend computed one. `alternatives` below are full `ResolvedPlace`s and
1319
- // already carry theirs; without this stamp the WINNER's is the one value in the ranked list that gets dropped,
1320
- // which makes a top-1-vs-top-2 margin uncomputable from the tree — and that margin is what
1321
- // `mailwoman/query-intent.ts` reads to decide whether a bare-toponym answer was a clear win. Additive metadata
1322
- // only; nothing in the resolve reads it back.
1323
- if (resolved.prominence !== undefined) {
1324
- node.metadata["resolver_prominence"] = resolved.prominence
1325
- }
1326
-
1327
- // The resolved place's ISO-3166 alpha-2 country (from the gazetteer/candidate row), when known. #1014: lets a
1328
- // forward consumer fill country/countrycode without an ancestry walk — the candidate backend carries this even
1329
- // though it has no `ancestors()` table.
1330
- if (resolved.country) {
1331
- node.metadata["resolver_country"] = resolved.country
1332
- }
1333
-
1334
- // The score-channel carries (ROAD_TO_V9 §2 + #28). Written ONLY when the backend actually has a
1335
- // value: an absent score means "unmeasured" or "pre-split gazetteer", and a `resolver_*: 0` on the
1336
- // node would assert a measurement nobody made. Nothing in the resolve path reads these keys back —
1337
- // they exist for annotation / API surfaces downstream. `resolver_importance` is the blended #28
1338
- // prior (the value the ranking consulted); `resolver_encyclopedic` is the strict channel, reserved
1339
- // until a strict-channel source ships.
1340
- if (resolved.referential !== undefined) {
1341
- node.metadata["resolver_referential"] = resolved.referential
1342
- }
1343
-
1344
- if (resolved.encyclopedic !== undefined) {
1345
- node.metadata["resolver_encyclopedic"] = resolved.encyclopedic
1346
- }
1452
+ rec.emit({ id: top.id, name: top.name, source: "ranked" })
1347
1453
 
1348
- if (resolved.importance !== undefined) {
1349
- node.metadata["resolver_importance"] = resolved.importance
1350
- }
1351
-
1352
- // The postcode/locality conflict flag (the falsehood differentiator): the postcode pointed to a
1353
- // geographically different place than the parsed city name. Surface it so callers can warn rather
1354
- // than silently trust the resolved point.
1355
- if (resolved.mismatch) {
1356
- node.metadata["postcode_city_mismatch"] = true
1357
- }
1358
-
1359
- // Fallback-observability (#718): a broader admin tier (macroregion/macrocounty) stood in for the
1360
- // true region/county because no exact-type candidate existed. Additive annotation only — the
1361
- // resolved coordinate/identity above is untouched; this just lets a consumer / QA pass see it.
1362
- if (resolved.resolutionQuality) {
1363
- node.metadata["resolution_quality"] = resolved.resolutionQuality
1364
- }
1365
-
1366
- if (alternatives.length) {
1367
- node.alternatives = alternatives
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.
1458
+ return {
1459
+ top,
1460
+ alternatives: ranked.slice(1),
1461
+ ...(containmentEligible ? { metadata: { admin_containment: adminContainmentVerdict(ranked) } } : {}),
1462
+ }
1368
1463
  }
1369
1464
  }