@mailwoman/resolver 9.0.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 (79) 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 +91 -14
  43. package/out/postcode-country-coherence.d.ts.map +1 -1
  44. package/out/postcode-country-coherence.js +279 -42
  45. package/out/postcode-country-coherence.js.map +1 -1
  46. package/out/postcode-prefix.d.ts +101 -0
  47. package/out/postcode-prefix.d.ts.map +1 -0
  48. package/out/postcode-prefix.js +125 -0
  49. package/out/postcode-prefix.js.map +1 -0
  50. package/out/postcode-shape-coherence.d.ts +113 -0
  51. package/out/postcode-shape-coherence.d.ts.map +1 -0
  52. package/out/postcode-shape-coherence.js +193 -0
  53. package/out/postcode-shape-coherence.js.map +1 -0
  54. package/out/resolve.d.ts +1 -1
  55. package/out/resolve.d.ts.map +1 -1
  56. package/out/resolve.js +592 -410
  57. package/out/resolve.js.map +1 -1
  58. package/out/span-rescore.d.ts +28 -0
  59. package/out/span-rescore.d.ts.map +1 -1
  60. package/out/span-rescore.js +151 -17
  61. package/out/span-rescore.js.map +1 -1
  62. package/out/street-evidence.js +1 -1
  63. package/out/street-evidence.js.map +1 -1
  64. package/out/street-tier.d.ts.map +1 -1
  65. package/out/street-tier.js +28 -5
  66. package/out/street-tier.js.map +1 -1
  67. package/out/toponym-prior.d.ts +139 -0
  68. package/out/toponym-prior.d.ts.map +1 -0
  69. package/out/toponym-prior.js +308 -0
  70. package/out/toponym-prior.js.map +1 -0
  71. package/package.json +98 -7
  72. package/postcode-country-coherence.ts +355 -50
  73. package/postcode-prefix.ts +166 -0
  74. package/postcode-shape-coherence.ts +248 -0
  75. package/resolve.ts +809 -527
  76. package/span-rescore.ts +206 -19
  77. package/street-evidence.ts +1 -1
  78. package/street-tier.ts +31 -5
  79. package/toponym-prior.ts +367 -0
package/out/resolve.js CHANGED
@@ -12,33 +12,181 @@
12
12
  * not the MA one.
13
13
  */
14
14
  import { matchCountry, matchSubdivision } from "@mailwoman/codex/country";
15
- import { isStreetDirectionalToken } from "@mailwoman/codex/us";
16
- import { DEFAULT_PLACETYPE_MAP, isPlacetypeFallback, } from "@mailwoman/core/resolver";
15
+ import { compareReferential, DEFAULT_PLACETYPE_MAP, isPlacetypeFallback, referentialFromPopulation, countriesFromPostcodeFormat, } from "@mailwoman/core/resolver";
16
+ import { PLACETYPE_SPECIFICITY } from "@mailwoman/core/resources/whosonfirst/specificity";
17
17
  import { haversineKm } from "@mailwoman/spatial";
18
- import { foldName } from "./fold-name.js";
18
+ import { applyAdminCoherence, applyExplicitCountryCoherence, applyRegionCountryCoherence, } from "./admin-coherence-passes.js";
19
+ import { adminContainmentVerdict, firstRegionQualifier, partitionByContainment } from "./admin-containment.js";
20
+ import { describeCapabilityGaps, reportCapabilityGaps } from "./backend-capabilities.js";
21
+ import { BARE_REGION_DOMINANCE_LOG10, bareCountryCandidate, bareRegionCandidate, logPopulation, loneBareLocalityNode, pickLargerAdmin, } from "./bare-toponym-race.js";
22
+ import { decorateNode, isResolvedWithCoord } from "./decorate-node.js";
19
23
  import { findPostcodeCountryScope, stampPostcodeCountryScope, } from "./postcode-country-coherence.js";
24
+ import { postcodePrefixResolvedPlace, probePostcodePrefix } from "./postcode-prefix.js";
25
+ import { applyPostcodeShapeCoherence, isShapeExcludedPostcode } from "./postcode-shape-coherence.js";
20
26
  import { findRescoreCandidate, hasResolvedPlace, postcodeCodeSubset } from "./span-rescore.js";
21
27
  import { applyAddressPoint, applyInterpolation, applyStreetCentroid } from "./street-tier.js";
28
+ import { DEFAULT_COUNTRY_PRIOR_WEIGHT, promoteCapitals, rankByCountryPrior, rankByImportance } from "./toponym-prior.js";
22
29
  /**
23
30
  * Build a `Resolver` backed by a `ResolverBackend`. The backend can be any concrete impl structurally compatible with
24
- * `PlaceLookup` — e.g. `new WOFSqlitePlaceLookup({ databasePath }).asResolverBackend()` or a fake for tests.
31
+ * `PlaceLookup` — e.g. `new WOFSQLitePlaceLookup({ databasePath }).asResolverBackend()` or a fake for tests.
25
32
  */
26
33
  export function createWOFResolver(backend) {
27
34
  return new WOFResolver(backend);
28
35
  }
29
36
  /**
30
- * Pick the completion locality when an admin maps to several coincident same-name candidates (#405). Population is the
31
- * PRIMARY signal — the principal city is the populous one, and it can sit FARTHER from the admin centroid than a tiny
32
- * same-name hamlet (the Niigata case from #403). Nearest centroid breaks a population tie; a genuine tie (same
33
- * population AND distance) ABSTAINS rather than guess.
37
+ * #1735 (second half) — the tree's own country statement, when it is unambiguous.
38
+ *
39
+ * "SW1A 1AA, UK" under the en-US default parsed correctly and still failed: the walk resolved the country NODE to GB,
40
+ * but a sibling's resolution never scopes a sibling — the postcode lookup ran under the locale-inferred `country=US`
41
+ * hard filter and missed. An explicit country token is the address's OWN scope declaration, which outranks a locale
42
+ * inference the same way the #912 posture ranks explicit over inferred.
43
+ *
44
+ * Deterministically guarded: exactly ONE country-tagged node, whose value `matchCountry` maps to one ISO country, and
45
+ * whose value is NOT also a subdivision name — "Georgia" maps to GE _and_ names a US state, so it never pre-scopes (the
46
+ * existing coherence passes keep handling it). Returns the alpha-2 or null.
47
+ */
48
+ function explicitCountryScope(roots) {
49
+ const countryNodes = [];
50
+ const stack = [...roots];
51
+ while (stack.length) {
52
+ const node = stack.pop();
53
+ if (node.tag === "country" && node.value.trim()) {
54
+ countryNodes.push(node);
55
+ }
56
+ stack.push(...node.children);
57
+ }
58
+ if (countryNodes.length !== 1)
59
+ return null;
60
+ const value = countryNodes[0].value.trim();
61
+ const matched = matchCountry(value);
62
+ if (!matched)
63
+ return null;
64
+ if (matchSubdivision(value))
65
+ return null;
66
+ return matched.iso2;
67
+ }
68
+ /**
69
+ * Cap on candidates recorded per {@link ResolveNodeTrace} — the trace is a record, not a dump. The count past the cap is
70
+ * reported in `candidatesTruncated`, so absence of a row is never silent.
71
+ */
72
+ const TRACE_CANDIDATE_CAP = 10;
73
+ /**
74
+ * The fine end of the probe window: `microhood` and no finer.
75
+ *
76
+ * Everything above it — `postalcode`, `venue`, `campus`, `building`, `address` — is excluded because a mislabeled ADMIN
77
+ * span lands on another admin band, and probing every venue in a country per miss buys a long tail of coincidental name
78
+ * matches for a diagnostic that is meant to be read.
79
+ */
80
+ const FINEST_DIAGNOSTIC_BAND = PLACETYPE_SPECIFICITY["microhood"];
81
+ /**
82
+ * The coarse end of the probe window. `country` and no coarser: a name matching at `continent` or `planet` says nothing
83
+ * about a mislabeled admin span, and the walk resolves the country from its own node anyway.
84
+ */
85
+ const COARSEST_DIAGNOSTIC_BAND = PLACETYPE_SPECIFICITY["country"];
86
+ /**
87
+ * The admin bands `ResolveOpts.diagnoseUnreachable` re-probes, coarse to fine.
88
+ *
89
+ * Derived from `PLACETYPE_SPECIFICITY` rather than typed out, so a placetype added there is probed here without anyone
90
+ * remembering to.
91
+ */
92
+ const DIAGNOSTIC_BANDS = Object.entries(PLACETYPE_SPECIFICITY)
93
+ .filter(([, rank]) => rank !== undefined && rank <= FINEST_DIAGNOSTIC_BAND && rank >= COARSEST_DIAGNOSTIC_BAND)
94
+ .toSorted((a, b) => a[1] - b[1])
95
+ .map(([placetype]) => placetype);
96
+ const NOOP_TRACE_RECORDER = Object.freeze({
97
+ bind() { },
98
+ gate() { },
99
+ stage() { },
100
+ reachable() { },
101
+ emit() { },
102
+ });
103
+ function createNodeTraceRecorder(sink) {
104
+ const gates = [];
105
+ const stageOrders = [];
106
+ let reachableIn;
107
+ let ctx = null;
108
+ return {
109
+ bind(node, placetype, query, defaultLimit) {
110
+ ctx = { node, placetype, query, defaultLimit };
111
+ },
112
+ gate(name) {
113
+ gates.push(name);
114
+ },
115
+ stage(name, order) {
116
+ stageOrders.push([name, order]);
117
+ },
118
+ reachable(bands) {
119
+ reachableIn = bands;
120
+ },
121
+ emit(picked) {
122
+ if (!ctx)
123
+ return;
124
+ const rankMap = new Map();
125
+ for (const [stage, order] of stageOrders) {
126
+ order.forEach((candidate, index) => {
127
+ let ranks = rankMap.get(candidate);
128
+ if (!ranks) {
129
+ ranks = {};
130
+ rankMap.set(candidate, ranks);
131
+ }
132
+ ranks[stage] = index + 1;
133
+ });
134
+ }
135
+ const finalOrder = stageOrders.at(-1)?.[1] ?? [];
136
+ const rows = finalOrder.slice(0, TRACE_CANDIDATE_CAP).map((c) => ({
137
+ id: c.id,
138
+ name: c.name,
139
+ country: c.country,
140
+ placetype: c.placetype,
141
+ score: c.score,
142
+ ...(c.prominence !== undefined ? { prominence: c.prominence } : {}),
143
+ ...(c.importance !== undefined ? { importance: c.importance } : {}),
144
+ ...(c.population !== undefined ? { population: c.population } : {}),
145
+ ...(c.exactMatch !== undefined ? { exactMatch: c.exactMatch } : {}),
146
+ ...(c.containedByQualifier !== undefined ? { containedByQualifier: c.containedByQualifier } : {}),
147
+ ranks: rankMap.get(c) ?? {},
148
+ }));
149
+ sink({
150
+ tag: ctx.node.tag,
151
+ value: ctx.node.value,
152
+ placetype: ctx.placetype,
153
+ query: {
154
+ ...(ctx.query.country ? { country: ctx.query.country } : {}),
155
+ ...(ctx.query.parentID !== undefined ? { parentID: ctx.query.parentID } : {}),
156
+ ...(ctx.query.postcode ? { postcode: ctx.query.postcode } : {}),
157
+ ...(ctx.query.regionQualifier ? { regionQualifier: ctx.query.regionQualifier } : {}),
158
+ limit: ctx.query.limit ?? ctx.defaultLimit,
159
+ },
160
+ gates,
161
+ ...(reachableIn ? { reachableIn } : {}),
162
+ candidates: rows,
163
+ candidatesTruncated: Math.max(0, finalOrder.length - TRACE_CANDIDATE_CAP),
164
+ picked,
165
+ });
166
+ },
167
+ };
168
+ }
169
+ /**
170
+ * Pick the completion locality when an admin maps to several coincident same-name candidates (#405). REFERENTIAL
171
+ * likelihood is the PRIMARY signal — the principal city is the populous one, and it can sit FARTHER from the admin
172
+ * centroid than a tiny same-name hamlet (the Niigata case from #403). Nearest centroid breaks a referential tie; a
173
+ * genuine tie (same population AND distance) ABSTAINS rather than guess.
174
+ *
175
+ * ROAD_TO_V9 §2: `compareReferential` is referential DESC with raw population as its own tiebreak, which is the SAME
176
+ * ORDER as the plain `b.population - a.population` it replaced — referential is strictly increasing in population below
177
+ * saturation and constant above it. The abstention check below still reads raw population, deliberately: two megacities
178
+ * that saturate to the same referential score are not tied, and abstaining there would be a new behavior.
34
179
  */
35
180
  function pickCompletion(candidates) {
36
181
  if (!candidates.length)
37
182
  return null;
38
183
  if (candidates.length === 1)
39
184
  return candidates[0];
40
- // oxlint-disable-next-line unicorn/no-array-sort -- sorts a freshly-built array; toSorted would double-allocate on a hot path
41
- const ranked = [...candidates].sort((a, b) => b.population - a.population || a.distanceKm - b.distanceKm);
185
+ const ranked = [...candidates]
186
+ .map((c) => ({ c, referential: referentialFromPopulation(c.population), population: c.population }))
187
+ // oxlint-disable-next-line unicorn/no-array-sort -- sorts a freshly-built array; toSorted would double-allocate on a hot path
188
+ .sort((a, b) => compareReferential(a, b) || a.c.distanceKm - b.c.distanceKm)
189
+ .map((x) => x.c);
42
190
  const [first, second] = ranked;
43
191
  if (first.population === second.population && first.distanceKm === second.distanceKm)
44
192
  return null;
@@ -52,7 +200,9 @@ function firstPostcodeValue(roots) {
52
200
  const stack = [...roots];
53
201
  while (stack.length) {
54
202
  const n = stack.pop();
55
- if (n.tag === "postcode" && n.value.trim().length)
203
+ // #31 Mechanism 1: a shape-excluded span keeps its tag but contributes nothing — its code
204
+ // must never become the address's postcode (it would poison the country-scope pass's anchor).
205
+ if (n.tag === "postcode" && !isShapeExcludedPostcode(n) && n.value.trim().length)
56
206
  return n.value.trim();
57
207
  stack.push(...n.children);
58
208
  }
@@ -91,7 +241,7 @@ async function applySpanRescore(roots, raw, backend, opts) {
91
241
  // 5 km area centroid. Same unresolved tree, so the #685 brake semantics hold.
92
242
  if (!hit && opts.postalCompoundRecovery !== false) {
93
243
  try {
94
- await recoverPostcodeNode(roots, backend, opts.defaultCountry);
244
+ await recoverPostcodeNode(roots, backend, opts.defaultCountry, opts.traceSink);
95
245
  }
96
246
  catch {
97
247
  // degrade to no-recovery, never crash the resolve
@@ -108,13 +258,29 @@ async function applySpanRescore(roots, raw, backend, opts) {
108
258
  confidence: 0.5,
109
259
  children: [],
110
260
  };
111
- decorateNode(node, hit.place, []);
261
+ // #1537: the same-span namesake runner-ups, not an empty list. A name the model reads as a `street`
262
+ // ("Springfield", "Berlin", "Moscow") never reaches the admin walk, so this tier is the ONLY thing that
263
+ // resolves it — and decorating with `[]` meant the geocode path's `candidates` held one entry and the
264
+ // dominance margin `declared_ambiguity` reads was uncomputable for exactly the famous-homonym class.
265
+ // The winner is unchanged (see findRescoreCandidate); this is additive.
266
+ decorateNode(node, hit.place, hit.alternatives);
112
267
  // `rescore_gated` carries the gate's precision signal as an EXPLICIT handle — NOT folded into the
113
268
  // calibrated `confidence`, which would break the isotonic guarantee (a true calibrated 0.83 must not
114
269
  // be confused with a rescore plug-in estimate; DeepSeek 2026-06-23). true = postcode gate fired
115
270
  // (high-precision); false = ungated (no postcode→point coverage for this country, ~83%-precision).
116
271
  node.metadata = { ...node.metadata, span_rescore: true, rescore_gated: hit.gated };
117
272
  roots.push(node);
273
+ // #1721 follow-up: this tier answers OFF the walk, and it used to answer off the record too — the famous-name
274
+ // class ("Frankfurt") returned a coordinate beside an empty resolver trace, blinding every retrieval account.
275
+ // One record per rescue keeps the trace's promise: no resolved coordinate without a lookup record.
276
+ if (opts.traceSink) {
277
+ const rec = createNodeTraceRecorder(opts.traceSink);
278
+ rec.bind(node, "locality", opts.defaultCountry ? { country: opts.defaultCountry } : {}, 1);
279
+ rec.gate("span_rescore");
280
+ rec.gate(hit.gated ? "rescore_gated" : "rescore_ungated");
281
+ rec.stage("rescore", [hit.place, ...hit.alternatives]);
282
+ rec.emit({ id: hit.place.id, name: hit.place.name, source: "span_rescore" });
283
+ }
118
284
  }
119
285
  /**
120
286
  * #942: find the first confident-but-UNRESOLVED postcode node whose value is a polluted compound ("1382 Kožljek"),
@@ -122,7 +288,7 @@ async function applySpanRescore(roots, raw, backend, opts) {
122
288
  * (`postal_compound_recovered` metadata marks the provenance). No-op when every postcode node resolved, the value has
123
289
  * no digit-bearing tokens, or the subset equals the full value (then the walk already tried it).
124
290
  */
125
- async function recoverPostcodeNode(roots, backend, country) {
291
+ async function recoverPostcodeNode(roots, backend, country, traceSink) {
126
292
  const stack = [...roots];
127
293
  while (stack.length) {
128
294
  const n = stack.pop();
@@ -135,6 +301,14 @@ async function recoverPostcodeNode(roots, backend, country) {
135
301
  if (top) {
136
302
  decorateNode(n, top, []);
137
303
  n.metadata = { ...n.metadata, postal_compound_recovered: true };
304
+ // The same off-the-record hole the span-rescore record closes (#1721 follow-up).
305
+ if (traceSink) {
306
+ const rec = createNodeTraceRecorder(traceSink);
307
+ rec.bind(n, "postalcode", { ...(country ? { country } : {}), limit: 1 }, 1);
308
+ rec.gate("postal_compound_recovery");
309
+ rec.stage("recovery", hits);
310
+ rec.emit({ id: top.id, name: top.name, source: "postal_compound_recovery" });
311
+ }
138
312
  }
139
313
  return; // first postcode node only — one recovery per tree
140
314
  }
@@ -143,12 +317,6 @@ async function recoverPostcodeNode(roots, backend, country) {
143
317
  }
144
318
  }
145
319
  }
146
- /**
147
- * A resolved node carries a real coordinate (placeID set + non-zero lat/lon).
148
- */
149
- function isResolvedWithCoord(n) {
150
- return !!(n.placeID && typeof n.lat === "number" && typeof n.lon === "number" && (n.lat !== 0 || n.lon !== 0));
151
- }
152
320
  /**
153
321
  * Postcode-disambiguated locality selection (#370 "Lever A"). The single biggest miss on the EU/AU panel is a
154
322
  * same-named town resolved to the WRONG instance — "06260 Saint-Pierre" lands 617 km off — while the postcode that
@@ -175,7 +343,8 @@ function applyPostcodeConsistency(roots, gateKm) {
175
343
  const findAnchor = [...roots];
176
344
  while (findAnchor.length) {
177
345
  const n = findAnchor.pop();
178
- if (n.tag === "postcode" && isResolvedWithCoord(n)) {
346
+ // #31 Mechanism 1: a shape-excluded span never anchors the consistency re-pick either.
347
+ if (n.tag === "postcode" && !isShapeExcludedPostcode(n) && isResolvedWithCoord(n)) {
179
348
  anchor = { lat: n.lat, lon: n.lon };
180
349
  break;
181
350
  }
@@ -223,315 +392,6 @@ function applyPostcodeConsistency(roots, gateKm) {
223
392
  node.metadata = { ...node.metadata, postcode_city_mismatch: true, coordinate_source: "postcode_fallback" };
224
393
  }
225
394
  }
226
- /**
227
- * Admin descendant-consistency (#263) — the joint-consistency resolve, scoped to the admin assignment. The greedy walk
228
- * resolves a region on its own (name + population), so "ME" picks Messina (IT) over Maine, then scopes "Portland" to
229
- * Messina's descendants, finds nothing, and the result falls back to the region centroid (Sicily). The region's
230
- * same-named runner-ups (Maine, Missouri, …) were already captured as `alternatives`; this pass asks the question the
231
- * greedy order skipped — _which "ME" has a "Portland" under it?_ — and re-picks the (region, locality) pair where a
232
- * same-named locality descends from a same-named region candidate. Geography decides; no country prior, no list.
233
- *
234
- * Fires ONLY for a resolved region whose child locality fell through (the unresolved-locality signal), so a
235
- * well-resolved tree ("Springfield, IL" → Illinois, Springfield) is byte-identical. Costs one unscoped locality lookup
236
- * per triggering pair. Needs {@link ResolverBackend.ancestors}; no-op without it. See `ResolveOpts.adminCoherence`.
237
- */
238
- async function applyAdminCoherence(roots, backend) {
239
- const visit = async (node, regionAncestor) => {
240
- const regionHere = node.tag === "region" && isResolvedWithCoord(node) ? node : regionAncestor;
241
- if (regionHere &&
242
- (node.tag === "locality" || node.tag === "dependent_locality") &&
243
- !isResolvedWithCoord(node) &&
244
- node.value.trim().length) {
245
- await reconcileAdminPair(regionHere, node, backend);
246
- }
247
- for (const child of node.children) {
248
- await visit(child, regionHere);
249
- }
250
- };
251
- for (const root of roots) {
252
- await visit(root, null);
253
- }
254
- }
255
- /**
256
- * Re-pick a (region, locality) pair so the locality descends from the region. `alternatives` on the node are the
257
- * `ResolvedPlace` runner-ups `decorateNode` attached (typed `unknown[]` in the decoder, which can't import resolver
258
- * types — the cast is sound). Picks the FIRST same-named locality (already score-ordered) that descends from a
259
- * same-named region candidate, then swaps both nodes. Leaves both untouched when no consistent pair exists (a genuinely
260
- * un-gazetteered locality — "Portland, VT" with no Portland in Vermont — stays as the region centroid, not a foreign
261
- * namesake).
262
- */
263
- async function reconcileAdminPair(regionNode, localityNode, backend) {
264
- // EXACT region matches only: the alternatives for a 2-letter token are loose ("ME" also surfaces
265
- // Missouri/Michigan/Mississippi as fuzzy M-state runner-ups). Restricting to exact name/alias matches
266
- // (Maine/Messina/Medway for "ME") keeps the join honest. `exactMatch` is stamped by exactMatchTiering.
267
- const regionCands = (regionNode.alternatives ?? []).filter((r) => r.exactMatch);
268
- // For each exact region candidate, ask the gazetteer directly: is there a same-named locality UNDER it?
269
- // The `parentID` scope is the descendant test (over the #832-repaired ancestors table), and it finds the
270
- // instance regardless of its global population rank — "Springfield, ME" reaches the small Springfield in
271
- // Maine that an unscoped top-N window would drop. First region with an exact-named descendant wins; the
272
- // region candidates are score-ordered, so a tie breaks toward the more prominent place.
273
- for (const region of regionCands) {
274
- const scoped = await backend.findPlace({
275
- text: localityNode.value,
276
- placetype: "locality",
277
- parentID: region.id,
278
- limit: 3,
279
- });
280
- const lc = scoped.find((l) => l.exactMatch && !(l.lat === 0 && l.lon === 0));
281
- if (lc) {
282
- decorateNode(regionNode, region, regionCands.filter((r) => r !== region));
283
- regionNode.metadata = { ...regionNode.metadata, admin_coherence_repicked: true };
284
- decorateNode(localityNode, lc, scoped.filter((l) => l !== lc));
285
- localityNode.metadata = { ...localityNode.metadata, admin_coherence_repicked: true };
286
- return;
287
- }
288
- }
289
- // #267 follow-up: the token may name a COUNTRY whose namesake is a more-populous foreign region — "Tbilisi,
290
- // Georgia" parses region("Georgia") → the US state, but Tbilisi descends from Georgia the COUNTRY. When no
291
- // region candidate holds the locality, try same-named country candidates: a foreign capital under its
292
- // country out-votes the state namesake. Needs the country + the locality's ancestry in the gazetteer (the
293
- // #267 admin fold). The re-picked region node then carries the country place; the locality coordinate wins.
294
- const countryCands = (await backend.findPlace({ text: regionNode.value, placetype: "country", limit: 3 })).filter((c) => c.exactMatch);
295
- for (const country of countryCands) {
296
- const scoped = await backend.findPlace({
297
- text: localityNode.value,
298
- placetype: "locality",
299
- parentID: country.id,
300
- limit: 3,
301
- });
302
- const lc = scoped.find((l) => l.exactMatch && !(l.lat === 0 && l.lon === 0));
303
- if (lc) {
304
- decorateNode(regionNode, country, regionCands);
305
- regionNode.metadata = { ...regionNode.metadata, admin_coherence_repicked: true };
306
- decorateNode(localityNode, lc, scoped.filter((l) => l !== lc));
307
- localityNode.metadata = { ...localityNode.metadata, admin_coherence_repicked: true };
308
- return;
309
- }
310
- }
311
- // #1023: the admin gazetteer may carry NO `country`-placetype node for the token AND the same-named
312
- // foreign locality may be ORPHANED (parent_id = -1) — the 2026-07-07 rebuild flattened Georgia's admin
313
- // hierarchy to localities-only, so the country-node lookup above finds nothing and the `parentID`
314
- // descendant test can never reach Tbilisi. Fall back to matchCountry: normalize the token to an
315
- // ISO-3166 alpha-2 and scope the locality by the gazetteer's `country` COLUMN (set even on an orphaned
316
- // row). Same primitive reconcileExplicitCountry (#822) uses, so the region-parsed namesake path
317
- // ("Tbilisi, Georgia") converges with the country-parsed one ("Vienna, Austria"). matchCountry returns
318
- // null for a US state name/abbrev ("Illinois" / "ME" / "IL"), so a real US (region, locality) pair
319
- // never reaches here — this stays inert on the domestic path.
320
- const mc = matchCountry(regionNode.value);
321
- if (mc) {
322
- const scoped = await backend.findPlace({
323
- text: localityNode.value,
324
- placetype: "locality",
325
- country: mc.iso2,
326
- limit: 3,
327
- });
328
- const lc = scoped.find((l) => l.exactMatch && !(l.lat === 0 && l.lon === 0));
329
- if (lc) {
330
- decorateNode(localityNode, lc, scoped.filter((l) => l !== lc));
331
- localityNode.metadata = { ...localityNode.metadata, admin_coherence_repicked: true };
332
- // The token named a foreign country the admin gazetteer has no node for, but the greedy walk had
333
- // already decorated the region node with the US-state namesake. Revert that stale decoration so the
334
- // node stops asserting the wrong-country coordinate + `resolver_country` (which would otherwise leak
335
- // into the result's `countryCode`); the re-picked locality carries the winning coordinate, and the
336
- // region node falls back to the parsed "Georgia" token, unresolved (the admin DB has nothing truer).
337
- revertResolverDecoration(regionNode);
338
- }
339
- }
340
- }
341
- /**
342
- * Undo a resolver decoration on a node: restore the classifier attribution {@link decorateNode} displaced into
343
- * `metadata.classifier_source(_id)` and drop the resolver-supplied coordinate/identity/alternatives. Used by the #1023
344
- * country fall-through when the region token turns out to name a foreign country the admin gazetteer holds no node for
345
- * — the greedy walk had bound it to the US-state namesake, and that stale claim must not survive the locality re-pick.
346
- */
347
- function revertResolverDecoration(node) {
348
- const meta = { ...node.metadata };
349
- const priorSource = meta["classifier_source"];
350
- const priorSourceID = meta["classifier_source_id"];
351
- node.source = typeof priorSource === "string" ? priorSource : undefined;
352
- node.sourceID = typeof priorSourceID === "string" ? priorSourceID : undefined;
353
- for (const key of [
354
- "classifier_source",
355
- "classifier_source_id",
356
- "resolver_score",
357
- "resolver_name",
358
- "resolver_country",
359
- "resolution_quality",
360
- "postcode_city_mismatch",
361
- ]) {
362
- // oxlint-disable-next-line typescript/no-dynamic-delete -- removing one key from a plain record; the object is not on a hot path
363
- delete meta[key];
364
- }
365
- node.metadata = meta;
366
- node.lat = undefined;
367
- node.lon = undefined;
368
- node.placeID = undefined;
369
- node.alternatives = undefined;
370
- }
371
- /**
372
- * Explicit-country coherence (#822) — the joint-consistency resolve keyed on the query's own EXPLICIT country token.
373
- * The greedy walk resolves a locality on name + population alone, so "Vienna, Austria" picks the populous US namesake
374
- * (Vienna WV) and IGNORES the "Austria" the address named. This pass asks the question the greedy order skipped —
375
- * _which "Vienna" is in the country the address names?_ — and re-picks the locality to the same-named place under that
376
- * country. The country code comes from the parser's OWN `country` emission via codex's ISO-3166 table (a name→code
377
- * normalization of a token the model already classified, NOT a routing prior or safelist); the gazetteer's `country`
378
- * column does the geographic confirmation. No pin, no list; generalizes to every country.
379
- *
380
- * Disjoint from {@link applyAdminCoherence} by the region guard: that pass owns the case where a REGION scopes the
381
- * locality; this one fires only when the explicit country is the locality's nearest admin context (no region between),
382
- * and then regardless of the locality's resolution state — so it covers both the resolved-but-foreign locality (Sydney
383
- * → the greedy AU pick was wrong) and the unresolved locality the span-rescore tier would otherwise back-fill with the
384
- * US namesake (Vienna → Vienna WV). Byte-stable when the locality already resolved in-country (the id guard) or the
385
- * named country holds no same-named locality (the fail-safe — what also protects "Turkey, TX": no country token ⇒ no
386
- * trigger; and an in-country lookup that finds nothing keeps the greedy result). Costs one country-scoped locality
387
- * lookup per triggering pair. See `ResolveOpts.adminCoherence`.
388
- */
389
- async function applyExplicitCountryCoherence(roots, backend) {
390
- const visit = async (node, countryToken, regionAbove) => {
391
- const countryHere = node.tag === "country" && node.value.trim().length ? node : countryToken;
392
- const regionHere = regionAbove || node.tag === "region" || node.tag === "subregion";
393
- // Fire only when the explicit country is the locality's NEAREST admin context (no region/subregion between).
394
- // When a region IS present, applyAdminCoherence + the region's `parentID` scope already disambiguate the
395
- // locality — applying the coarse country filter there would wrongly re-pick "Springfield, IL" to the most
396
- // populous US "Springfield". Fires regardless of the locality's resolution state, so it PRE-EMPTS the
397
- // span-rescore tier (which would otherwise back-fill the unresolved locality with the US namesake).
398
- if (countryHere && !regionHere && (node.tag === "locality" || node.tag === "dependent_locality")) {
399
- await reconcileExplicitCountry(countryHere, node, backend);
400
- }
401
- for (const child of node.children) {
402
- await visit(child, countryHere, regionHere);
403
- }
404
- };
405
- for (const root of roots) {
406
- await visit(root, null, false);
407
- }
408
- }
409
- /**
410
- * Re-pick a resolved locality to its same-named place UNDER the explicitly-named country. `matchCountry` turns the
411
- * country token into an ISO-3166 alpha-2 (returns null for an unrecognized token → no-op); the backend then surfaces
412
- * the in-country namesake the population-first unscoped window buried. Leaves the node untouched when the country is
413
- * unrecognized, the named country has no exact same-named locality (the fail-safe), or the locality already resolved to
414
- * that place (the id guard → byte-stable). The country node itself stays as the parser emitted it — the named
415
- * well-covered countries carry no `country`-placetype row in the admin gazetteer, so there is nothing to decorate it
416
- * with; the locality coordinate is what the re-pick fixes.
417
- */
418
- async function reconcileExplicitCountry(countryNode, localityNode, backend) {
419
- const mc = matchCountry(countryNode.value);
420
- if (!mc)
421
- return;
422
- const scoped = await backend.findPlace({
423
- text: localityNode.value,
424
- placetype: "locality",
425
- country: mc.iso2,
426
- limit: 3,
427
- });
428
- const lc = scoped.find((l) => l.exactMatch && !(l.lat === 0 && l.lon === 0));
429
- if (!lc)
430
- return;
431
- // Already the in-country place? (placeID encodes the WOF id.) Then the greedy walk was right — byte-stable.
432
- if (localityNode.placeID === `wof:${lc.id}`)
433
- return;
434
- decorateNode(localityNode, lc, scoped.filter((l) => l !== lc));
435
- localityNode.metadata = { ...localityNode.metadata, explicit_country_repicked: true };
436
- }
437
- /**
438
- * Region-country coherence — the joint-consistency resolve keyed on a REGION token the locale-inferred default-country
439
- * filter could not resolve. Companion to {@link applyExplicitCountryCoherence} (which keys on an explicit COUNTRY token)
440
- * and disjoint from {@link applyAdminCoherence} (which needs a region that DID resolve): this pass owns the mirror case,
441
- * where the region qualifier is a foreign subdivision the default-country hard filter (`spr.country = ?`) discarded.
442
- *
443
- * "Montreal QC" under a US locale: the walk applies `defaultCountry="US"` as a hard candidate filter to every admin
444
- * lookup, so the region "QC" (a Canadian subdivision) resolves to nothing and is dropped — the one signal that would
445
- * redirect the country to CA — and the locality "Montreal" is force-matched to the populous US namesake (Montreal, WI).
446
- * The greedy order threw away the evidence that could correct it.
447
- *
448
- * The fix expands the region token to its country via codex's ISO-3166-2 subdivision table (`matchSubdivision`: "QC" →
449
- * `{ name: "Quebec", country: "CA" }`, handling the FTS index's missing "QC" alt-name code-side), then asks the two
450
- * questions the greedy walk skipped: does that subdivision genuinely resolve UNDER its own country, and is there a
451
- * same-named locality under it? Only when BOTH hold does it swap the region and locality to the in-country pair.
452
- * Geography confirms; the subdivision table is a soft name→country prior, not a routing decision.
453
- *
454
- * Evidence-gated to stay byte-stable on the domestic path. It fires ONLY when (a) a default country is in force, (b)
455
- * the region node is UNRESOLVED (the default-country filter came up empty — a US region resolves fine under `US`, so a
456
- * well-formed US query never trips this), (c) the token is a subdivision of a DIFFERENT country than the default, and
457
- * (d) both the foreign region and a same-named foreign locality resolve. "Springfield, IL" / "Portland, ME": the region
458
- * resolves under `US`, so gate (b) fails and the tree is untouched. Costs one region + one locality lookup per
459
- * triggering pair. See `ResolveOpts.adminCoherence`.
460
- */
461
- async function applyRegionCountryCoherence(roots, backend, defaultCountry) {
462
- // No default country → no hard country filter was applied, so no region qualifier was discarded by one. The bug
463
- // this pass corrects is specific to the locale-inferred default country; without it, there is nothing to rescue.
464
- if (!defaultCountry)
465
- return;
466
- const visit = async (node, regionAncestor) => {
467
- // Track the nearest region ancestor regardless of its resolution state (the trigger is an UNRESOLVED region).
468
- const regionHere = node.tag === "region" || node.tag === "subregion" ? node : regionAncestor;
469
- // Fire for an UNRESOLVED region (the default-country filter came up empty) whose companion locality node
470
- // exists — regardless of the locality's resolution state, so it covers both the resolved-but-foreign namesake
471
- // (Montreal → the greedy US pick, Montreal WI) and the unresolved locality the span-rescore tier would
472
- // otherwise back-fill with a US namesake. The in-country lookups below are the evidence gate.
473
- if (regionHere &&
474
- !isResolvedWithCoord(regionHere) &&
475
- (node.tag === "locality" || node.tag === "dependent_locality") &&
476
- node.value.trim().length) {
477
- await reconcileRegionCountry(regionHere, node, backend, defaultCountry);
478
- }
479
- for (const child of node.children) {
480
- await visit(child, regionHere);
481
- }
482
- };
483
- for (const root of roots) {
484
- await visit(root, null);
485
- }
486
- }
487
- /**
488
- * Re-pick an (unresolved region, resolved-but-foreign-namesake locality) pair to the in-country instance the
489
- * default-country filter hid. `matchSubdivision` turns the region token into `{ name, country }` (null for anything
490
- * that isn't a US state or CA province → no-op); the region's full name then resolves it under that country (expanding
491
- * the abbreviation the gazetteer FTS index lacks), and the locality is re-scoped to the same country. Leaves both nodes
492
- * untouched unless every gate holds — the subdivision names a different country than the default, the region resolves
493
- * under it, and a same-named locality exists there — so the domestic path stays byte-identical.
494
- */
495
- async function reconcileRegionCountry(regionNode, localityNode, backend, defaultCountry) {
496
- const sub = matchSubdivision(regionNode.value);
497
- if (!sub)
498
- return;
499
- // The subdivision must belong to a DIFFERENT country than the locale default. A US-state token under a US default
500
- // (sub.country === defaultCountry) never reaches the swap — the pass is inert on the domestic path.
501
- if (sub.country.toUpperCase() === defaultCountry.toUpperCase())
502
- return;
503
- // The locality already resolved in the subdivision's country? Then the greedy walk was already right — byte-stable.
504
- const localityCountry = localityNode.metadata?.["resolver_country"]?.toUpperCase();
505
- if (localityCountry === sub.country.toUpperCase())
506
- return;
507
- // Confirm the subdivision genuinely resolves under its own country, by its full name (expands "QC" → "Quebec", the
508
- // form the FTS index carries). No resolvable region → no evidence the token is a real foreign subdivision; abstain.
509
- const regionScoped = await backend.findPlace({
510
- text: sub.name,
511
- placetype: "region",
512
- country: sub.country,
513
- limit: 3,
514
- });
515
- const rc = regionScoped.find((r) => r.exactMatch && !(r.lat === 0 && r.lon === 0));
516
- if (!rc)
517
- return;
518
- // Is there a same-named locality under that country? (the descendant test, by country column — the same primitive
519
- // reconcileExplicitCountry uses.) No in-country namesake → keep the greedy result (fail-safe).
520
- const scoped = await backend.findPlace({
521
- text: localityNode.value,
522
- placetype: "locality",
523
- country: sub.country,
524
- limit: 3,
525
- });
526
- const lc = scoped.find((l) => l.exactMatch && !(l.lat === 0 && l.lon === 0));
527
- if (!lc)
528
- return;
529
- // Adopt the in-country pair: the region gets the foreign subdivision, the locality its same-named foreign instance.
530
- decorateNode(regionNode, rc, regionScoped.filter((r) => r !== rc));
531
- regionNode.metadata = { ...regionNode.metadata, region_country_repicked: true };
532
- decorateNode(localityNode, lc, scoped.filter((l) => l !== lc));
533
- localityNode.metadata = { ...localityNode.metadata, region_country_repicked: true };
534
- }
535
395
  class WOFResolver {
536
396
  #backend;
537
397
  /**
@@ -539,11 +399,32 @@ class WOFResolver {
539
399
  * read them from the resolver handle they already hold. Absent on artifacts predating the coverage manifest.
540
400
  */
541
401
  artifactCoverage;
402
+ /**
403
+ * Optional backend methods this backend omits, each naming the default-ON option it silently disables. Computed once
404
+ * here rather than at each guard site so a caller can read the gap before running a query that would quietly skip the
405
+ * feature. See `backend-capabilities.ts`.
406
+ */
407
+ capabilityGaps;
542
408
  constructor(backend) {
543
409
  this.#backend = backend;
544
410
  this.artifactCoverage = backend.artifactCoverage;
411
+ this.capabilityGaps = describeCapabilityGaps(backend);
412
+ reportCapabilityGaps(this.capabilityGaps);
545
413
  }
414
+ /**
415
+ * The `Resolver.findPlace` passthrough — one direct gazetteer probe for pipeline-level consumers (#1738's
416
+ * dominant-bearer guard). Bound as a method so `this.#backend` stays private.
417
+ */
418
+ findPlace = (query) => this.#backend.findPlace(query);
546
419
  async resolveTree(tree, opts = {}) {
420
+ // Postcode-shape coherence (#31, Mechanism 1): the earliest pass in the tree — pure-sync and
421
+ // backend-free, run BEFORE `state.postcode` is read so an excluded span can never become the
422
+ // address's postcode. Opt-in (`postcodeShapeCoherence: true`), OFF by default (D-rule: demotion
423
+ // is the failure mode with teeth). A confirmed span's narrowed systems — the intersection of
424
+ // its codex shape with the tree's confident sibling systems — bound the country-scope pass
425
+ // below; a pure subset of codex's own candidate list, so it can only narrow, never widen.
426
+ // See postcode-shape-coherence.ts.
427
+ const shapeVerdict = opts.postcodeShapeCoherence === true ? applyPostcodeShapeCoherence(tree.roots) : null;
547
428
  const state = {
548
429
  lookupsRemaining: opts.maxLookups ?? 10,
549
430
  // Full replacement when `placetypeMap` is supplied — callers that want to extend rather
@@ -552,35 +433,81 @@ class WOFResolver {
552
433
  minWinningScore: opts.minWinningScore ?? 0,
553
434
  candidatesPerLookup: opts.candidatesPerLookup ?? 5,
554
435
  defaultCountry: opts.defaultCountry,
436
+ defaultCountryIsInferred: opts.defaultCountryIsInferred === true,
437
+ bareLocalityNode: loneBareLocalityNode(tree, opts.placetypeMap ?? DEFAULT_PLACETYPE_MAP),
555
438
  parentFallback: opts.parentFallback ?? true,
439
+ // Requires a sink: with nowhere to record the answer the probes would be pure cost.
440
+ ...(opts.diagnoseUnreachable && opts.traceSink ? { diagnoseUnreachable: true } : {}),
556
441
  postcode: firstPostcodeValue(tree.roots),
442
+ // #31 Mechanism 2 — forwarded to locality lookups (see #lookupAndPick). Opt-in, OFF by default.
443
+ postcodeContainmentCoherence: opts.postcodeContainmentCoherence === true,
444
+ // #31 Mechanism 3 — the prefix prior + its injected index (see #lookupAndPick). Opt-in, OFF by default.
445
+ postcodePrefixPrior: opts.postcodePrefixPrior === true,
446
+ postcodePrefixIndex: opts.postcodePrefixIndex,
447
+ // #1589: derived here when the caller didn't thread it, so the browser cascade and the
448
+ // drop-ins get the implied-set probe without per-caller wiring (the staged-repoint e2e
449
+ // caught `100 00` resolving in Node and not in the browser over the same artifact).
450
+ postcodeFormatCountries: opts.postcodeFormatCountries ?? countriesFromPostcodeFormat(firstPostcodeValue(tree.roots)),
451
+ fuzzyCountryScope: opts.fuzzyCountryScope,
557
452
  bias: opts.bias,
558
453
  anchorPosterior: opts.anchorPosterior,
559
454
  anchorWeight: opts.anchorWeight ?? 2,
455
+ localeCountryPrior: opts.localeCountryPrior,
456
+ localeCountryPriorWeight: opts.localeCountryPriorWeight ?? DEFAULT_COUNTRY_PRIOR_WEIGHT,
457
+ capitalLevel: opts.capitalLevel,
560
458
  hardCountry: opts.hardCountry,
561
459
  // Default-ON (#402): completion only fires for a dual-role region whose locality the parser
562
460
  // dropped, and no-ops entirely when the backend has no relation (the browser WASM resolver, or
563
461
  // a gazetteer without `coincident_roles`). Pass `hierarchyCompletion: false` to opt out.
462
+ //
463
+ // Default-ON is nominal on the SHIPPED backend: `WOFCandidateTableLookup` implements no
464
+ // `coincidentLocalitiesFor`, so this attaches nothing there. Measured 2026-08-15 on FTS, which
465
+ // does implement it, the flag changed 0 of 837 board inputs — see ResolveOpts.hierarchyCompletion.
564
466
  hierarchyCompletion: opts.hierarchyCompletion ?? true,
565
467
  includeAncestors: opts.includeAncestors ?? false,
468
+ // #1717 stage 2 — default OFF (D-rule); the qualifier is pre-scanned like `postcode` above
469
+ // because region and locality are siblings the walk visits independently.
470
+ adminContainmentRerank: opts.adminContainmentRerank === true,
471
+ regionQualifier: firstRegionQualifier(tree.roots),
472
+ ...(opts.traceSink ? { traceSink: opts.traceSink } : {}),
566
473
  localityNodePresent: false,
567
474
  resolvedRegion: null,
568
475
  resolvedRegionNode: null,
569
476
  };
570
- // Postcode-country coherence (#42): the ONE pre-walk pass, and the only mechanism allowed to override
571
- // `defaultCountry`. Its three sibling coherence passes re-pick nodes AFTER the walk; that shape cannot
572
- // work here, because what needs correcting is the walk's country SCOPE — which poisons the postcode
573
- // node's own resolution, the postcode-consistency fallback that then drags the locality onto it, and
574
- // the hard `country` filter on every admin lookup. So the verdict is taken once, up front, and the
575
- // walk runs under the corrected country. Default-ON (operator-promoted 2026-08-05; `false` opts out) —
576
- // needs a default country to correct and both a postcode and a locality to be coherent about; abstains
577
- // unless EXACTLY one country (never the already-coherent default) makes the pair consistent. See
477
+ // Postcode-country coherence (#42): the one pre-walk LOOKUP pass (the shape verdict above is
478
+ // pure-sync, backend-free), and the only mechanism allowed to override `defaultCountry`. Its three
479
+ // sibling coherence passes re-pick nodes AFTER the walk; that shape cannot work here, because what
480
+ // needs correcting is the walk's country SCOPE — which poisons the postcode node's own resolution,
481
+ // the postcode-consistency fallback that then drags the locality onto it, and the hard `country`
482
+ // filter on every admin lookup. So the verdict is taken once, up front, and the walk runs under the
483
+ // corrected country. Default-ON (operator-promoted 2026-08-05; `false` opts out) — needs a default
484
+ // country to correct and both a postcode and a locality to be coherent about; abstains unless
485
+ // EXACTLY one country (never the already-coherent default) makes the pair consistent. See
578
486
  // postcode-country-coherence.ts.
579
487
  let postcodeScope = null;
580
- if (opts.postcodeCountryCoherence !== false && state.defaultCountry && state.postcode) {
488
+ // The pass also runs with NO default in force (#1585/#861 convergence): there is nothing to
489
+ // override, but the same exactly-one-country abstention lets the postcode+locality pair
490
+ // CONSTRAIN an otherwise population-first walk — `Zabiče 8, 6250 Zabiče` picks the SI row
491
+ // coherent with the SI 6250 centroid instead of the more-populous Polish namesake. The
492
+ // browser cascade (which sets no default by design) is the consumer this exists for.
493
+ // #1735 second half: the address's own country statement scopes the walk BEFORE anything
494
+ // resolves — a sibling's resolution never reaches a sibling, so without this the postcode
495
+ // lookup in "RM10 8AB, UK" ran under the locale-inferred US filter while the country node
496
+ // resolved to GB beside it. Explicit-over-inferred, the #912 precedence, decided from the
497
+ // tree's own text; an EXPLICIT caller scope is never overridden.
498
+ let explicitScope = null;
499
+ if (!state.defaultCountry || state.defaultCountryIsInferred) {
500
+ explicitScope = explicitCountryScope(tree.roots);
501
+ if (explicitScope) {
502
+ state.defaultCountry = explicitScope;
503
+ state.defaultCountryIsInferred = false;
504
+ }
505
+ }
506
+ if (opts.postcodeCountryCoherence !== false && state.postcode) {
581
507
  postcodeScope = await findPostcodeCountryScope(tree.roots, this.#backend, {
582
508
  postcode: state.postcode,
583
509
  defaultCountry: state.defaultCountry,
510
+ ...(shapeVerdict?.narrowing !== undefined ? { candidateSystems: shapeVerdict.narrowing } : {}),
584
511
  ...(opts.postcodeCountryCoherenceGateKm !== undefined ? { gateKm: opts.postcodeCountryCoherenceGateKm } : {}),
585
512
  });
586
513
  if (postcodeScope) {
@@ -598,6 +525,19 @@ class WOFResolver {
598
525
  if (postcodeScope) {
599
526
  stampPostcodeCountryScope(newRoots, postcodeScope);
600
527
  }
528
+ // The pre-scope's receipt (#1735): consumers that select country-scoped artifacts AFTER the walk
529
+ // (geocode-core's rooftop-shard second pass) key on a scope stamp. Without this, an address whose
530
+ // country was right FROM THE TREE never writes one — the #42 pass stays silent because the default
531
+ // is already coherent — and the FR rooftop shard silently stops loading for "…, France" inputs
532
+ // under a non-FR locale (six board venue rows dropped from rooftop to city centroid; the battery
533
+ // caught it).
534
+ if (explicitScope) {
535
+ for (const root of newRoots) {
536
+ if (root.tag === "country") {
537
+ root.metadata = { ...root.metadata, explicit_country_scope: explicitScope };
538
+ }
539
+ }
540
+ }
601
541
  // Dual-role hierarchy completion (#405/#415). Only when enabled, a region resolved, and the parser
602
542
  // emitted NO locality — record the dropped locality as a SECONDARY ROLE (an interpretation) on the
603
543
  // resolved region node, from the backend's precomputed coincident-roles relation (#403). One node,
@@ -649,6 +589,14 @@ class WOFResolver {
649
589
  if (opts.spanRescore !== false) {
650
590
  await applySpanRescore(newRoots, tree.raw, this.#backend, opts);
651
591
  }
592
+ // A failed admin walk can leave the exact-point tier without a locality even though span-rescore
593
+ // recovers one immediately afterward (for example, a locality the model tagged as `region`). Give
594
+ // the exact register one bounded retry with that newly established scope. An existing situs hit is
595
+ // returned early by applyAddressPoint, so the normal path performs no duplicate lookup; interpolation
596
+ // remains subordinate because an exact point is allowed to replace its estimate.
597
+ if (opts.addressPoints) {
598
+ applyAddressPoint(newRoots, opts.addressPoints, opts.addressPointBboxFallback);
599
+ }
652
600
  // Street-centroid tier (#1042): LAST, after span-rescore, so it can (a) union the span-rescore-recovered
653
601
  // country into its FR/national country hints (a placer-misrouted street — "Rue Sainte-Catherine" → IT — leaves
654
602
  // admin unresolved, and only span-rescore recovers the FR country signal) and (b) override a coarse recovered
@@ -695,11 +643,34 @@ class WOFResolver {
695
643
  state.localityNodePresent = true;
696
644
  }
697
645
  let resolved = null;
698
- if (placetype && state.lookupsRemaining > 0 && node.value.trim().length) {
646
+ // Shape-excluded postcode spans (letter-bearing ones keep their tag; #31 Mechanism 1) are
647
+ // stripped of their resolve contribution — the walk does not look them up. Digit-only excluded
648
+ // spans were retagged to `house_number` and flow through their correct sibling placetype.
649
+ if (placetype && state.lookupsRemaining > 0 && node.value.trim().length && !isShapeExcludedPostcode(node)) {
699
650
  const picked = await this.#lookupAndPick(node, placetype, parentResolved, state);
700
651
  if (picked) {
701
652
  resolved = picked.top;
702
653
  decorateNode(decorated, picked.top, picked.alternatives);
654
+ if (picked.metadata) {
655
+ decorated.metadata = { ...decorated.metadata, ...picked.metadata };
656
+ }
657
+ // #1678 thread 2 — the parse half, resolved from the atlas rather than trained in.
658
+ //
659
+ // The bare-toponym race exists because the model reads a lone country or region name as a
660
+ // `locality`; the race finds the right PLACE and the node keeps the wrong TAG. So
661
+ // `mw geocode 格鲁吉亚` lands on Georgia the country and reports `{"locality": "格鲁吉亚"}`,
662
+ // which is a correct coordinate under a label that will mislead the moment the same toponym
663
+ // appears inside a longer address.
664
+ //
665
+ // The repick metadata already marks exactly these nodes, so the correction is free: retrieval
666
+ // established the placetype, and the tag follows it. Only the race's own picks are retagged —
667
+ // an ordinary locality that resolved to a locality is untouched.
668
+ if (decorated.metadata?.["bare_country_repick"]) {
669
+ decorated.tag = "country";
670
+ }
671
+ else if (decorated.metadata?.["bare_region_repick"]) {
672
+ decorated.tag = "region";
673
+ }
703
674
  // Lineage attachment (#404): stamp the resolved place's ancestor chain onto metadata. Opt-in
704
675
  // + only when the backend supplies it, so the default stays byte-identical (no extra query).
705
676
  if (state.includeAncestors && this.#backend.ancestors) {
@@ -719,6 +690,32 @@ class WOFResolver {
719
690
  }
720
691
  return decorated;
721
692
  }
693
+ /**
694
+ * Which admin bands hold a value the probed band did not, keeping the country and dropping the parent.
695
+ *
696
+ * Bands come from `PLACETYPE_SPECIFICITY` rather than a list typed here: that table is already the repo's answer to
697
+ * how coarse a placetype is, and a second hand-kept copy would agree right up until a placetype is added. Probed
698
+ * coarse-to-fine so the report reads down the admin ladder.
699
+ */
700
+ async #probeOtherBands(query, probed) {
701
+ const found = [];
702
+ for (const band of DIAGNOSTIC_BANDS) {
703
+ if (band === probed)
704
+ continue;
705
+ try {
706
+ const hits = await this.#backend.findPlace({ ...query, placetype: band, parentID: undefined });
707
+ if (hits.length) {
708
+ found.push({ placetype: band, n: hits.length });
709
+ }
710
+ }
711
+ catch {
712
+ // A band the backend cannot answer for is not evidence that the key is absent from it, so it is
713
+ // skipped rather than recorded as an empty result.
714
+ continue;
715
+ }
716
+ }
717
+ return found;
718
+ }
722
719
  async #lookupAndPick(node, placetype, parentResolved, state) {
723
720
  state.lookupsRemaining--;
724
721
  const query = {
@@ -750,43 +747,191 @@ class WOFResolver {
750
747
  // collapses the tail (FI 18 km, PL p99 8172→494) at a coverage-bounded recall cost.
751
748
  // #833 forward linkage: a node's own `country_hint` (an address-system recognizer's derived country —
752
749
  // today `recognizeUSRegions` stamping "US" on a recognized closed-set US state) constrains THIS node's
753
- // lookup, below a resolved parent's country but above the global defaults. It breaks the two-consistent-
754
- // pairs tie ("Augusta, ME" → Maine, not Augusta/Messina) that pure geographic consistency cannot.
750
+ // lookup when the caller supplied no locale/default country. A caller scope outranks this derived hint:
751
+ // `WA` is both Washington and Western Australia, so en-AU must reach the AU candidate instead of being
752
+ // overwritten by the US-only recognizer. A genuine foreign subdivision under the wrong locale is recovered
753
+ // later by region-country coherence after the scoped lookup abstains.
755
754
  const countryHint = node.metadata?.["country_hint"];
755
+ // A locale-INFERRED default country never filters a `country`-placetype lookup: the span names a
756
+ // country outright, and the filter can only admit the scope country itself (bare "Germany" under
757
+ // the en-US default filtered out the DE row; the unresolved span then fell to a US locality whose
758
+ // historical alias is "Germany, Ohio"). An EXPLICIT caller scope stays supreme, matching the #912
759
+ // posture; parent evidence and the confident placer are untouched.
760
+ const defaultCountryForLookup = placetype === "country" && state.defaultCountryIsInferred ? undefined : state.defaultCountry;
756
761
  const country = parentResolved?.country ??
762
+ defaultCountryForLookup ??
757
763
  (typeof countryHint === "string" ? countryHint : undefined) ??
758
- state.defaultCountry ??
759
764
  state.hardCountry;
760
765
  if (country) {
761
766
  query.country = country;
762
767
  }
768
+ // #1585: the locale hint's country rides on every primary lookup as the TYPO-FUZZY tier's scope.
769
+ // Deliberately set even when `query.country` is (the backend ignores it there — the hard filter
770
+ // is already narrower): the field's contract lives in one place, the backend.
771
+ if (state.fuzzyCountryScope) {
772
+ query.fuzzyCountry = state.fuzzyCountryScope;
773
+ }
774
+ // Admin-containment re-rank (#1717 stage 2): thread the tree's region qualifier onto locality
775
+ // lookups so a capable backend can vouch for (and surface) the candidates that sit UNDER it.
776
+ // Stands down under an EXPLICIT caller country scope (the #912 posture — only a locale-INFERRED
777
+ // scope is bypassable by the address's own evidence); the resolved-parent and placer scopes are
778
+ // left alone, since a resolved parent usually IS the qualifier and the injection dedupes.
779
+ const containmentEligible = state.adminContainmentRerank &&
780
+ placetype === "locality" &&
781
+ state.regionQualifier !== undefined &&
782
+ (!state.defaultCountry || state.defaultCountryIsInferred);
783
+ if (containmentEligible) {
784
+ query.regionQualifier = state.regionQualifier;
785
+ }
763
786
  // Coordinate-first: hand the sibling postcode to locality lookups so the backend can inject
764
787
  // postcode-proximal candidates the name-match would miss. Only for locality (the placetype both
765
- // `locality` and `dependent_locality` map to); other placetypes ignore it.
788
+ // `locality` and `dependent_locality` map to); other placetypes ignore it. The containment flag
789
+ // (#31, Mechanism 2) asks a coordinate-first backend to re-rank the candidates by proximity to
790
+ // the postcode's own centroid — opt-in, OFF by default.
766
791
  if (placetype === "locality" && state.postcode) {
767
792
  query.postcode = state.postcode;
793
+ if (state.postcodeContainmentCoherence) {
794
+ query.postcodeContainmentCoherence = true;
795
+ }
768
796
  }
797
+ // #1721 resolver-interior trace. Stage orders hold the SAME candidate objects across re-ranks
798
+ // (every stage reorders, never clones), which is what lets emit assemble a per-stage rank
799
+ // vector per row. The no-sink walk talks to the frozen no-op recorder — zero per-event branches.
800
+ const rec = state.traceSink ? createNodeTraceRecorder(state.traceSink) : NOOP_TRACE_RECORDER;
801
+ // The query is SNAPSHOT, not bound live. `emit` reads `ctx.query.parentID` at the END of the walk, and the
802
+ // parent-fallback retry `delete`s that key mid-lookup — so binding the object itself lets a later mutation
803
+ // rewrite history. That is how 196 lookups which every one of them carried a parent came out of the
804
+ // constraint census reading `parentID: absent`.
805
+ rec.bind(node, placetype, { ...query }, state.candidatesPerLookup);
769
806
  let candidates;
770
- try {
771
- candidates = await this.#backend.findPlace(query);
772
- // Parent soft-gating: `parentID` is a HARD descendant filter in the backend, which wrongly
773
- // zeroes the result when the parent resolved wrong OR the gazetteer hierarchy is incomplete
774
- // (a real locality whose `ancestors` chain is missing its region). Rather than turn a
775
- // resolvable node into an unresolved one, retry once WITHOUT the parent constraint — we
776
- // prefer a parent-scoped hit but never sacrifice recall. The country constraint is kept, so
777
- // this still can't wander to a foreign place. Same logical resolution → no extra budget.
778
- if (!candidates.length && state.parentFallback && query.parentID !== undefined) {
779
- delete query.parentID;
807
+ // #1589: a `postalcode` whose FORMAT implies specific countries, with no surviving country
808
+ // constraint, probes exactly the implied set — most populous hit wins, and an all-miss
809
+ // leaves the candidate set EMPTY rather than falling through to the unconstrained fold:
810
+ // `100 00` space-strips to `10000`, which answers Troyes FR while the CZ rows sit in the
811
+ // artifact under both keyings; a scoped empty must stay empty (the same contract as the
812
+ // fuzzy tier's, #1585). The postcode-prefix prior below still gets its turn on the empty
813
+ // set — its index is country-scoped by construction, so it is not the fold this branch
814
+ // exists to avoid (the B3 tests hold that path).
815
+ if (placetype === "postalcode" && !query.country && state.postcodeFormatCountries?.length) {
816
+ rec.gate("postcode_format_probe");
817
+ let best;
818
+ for (const impliedCountry of state.postcodeFormatCountries) {
819
+ try {
820
+ const hits = await this.#backend.findPlace({ ...query, country: impliedCountry });
821
+ const top = hits[0];
822
+ // `score` is the backend's own population-first ranking metric, so comparing the
823
+ // per-country winners by it keeps the cross-country pick population-first too.
824
+ if (top && (!best || top.score > best.score)) {
825
+ best = top;
826
+ }
827
+ }
828
+ catch {
829
+ // A per-country probe failure reads as a miss for that country, never an abort.
830
+ }
831
+ }
832
+ if (best) {
833
+ rec.emit({ id: best.id, name: best.name, source: "postcode_format_probe" });
834
+ return { top: best, alternatives: [] };
835
+ }
836
+ candidates = [];
837
+ }
838
+ else {
839
+ try {
780
840
  candidates = await this.#backend.findPlace(query);
841
+ rec.stage("initial", candidates);
842
+ // #1731: the backend's interior region-scope fallback, surfaced as a gate — the resolver
843
+ // never sees the scoped probe miss, only the stamp the re-admitted rows carry.
844
+ if (candidates[0]?.regionScopeMiss) {
845
+ rec.gate("region_scope_miss");
846
+ }
847
+ // Parent soft-gating: `parentID` is a HARD descendant filter in the backend, which wrongly
848
+ // zeroes the result when the parent resolved wrong OR the gazetteer hierarchy is incomplete
849
+ // (a real locality whose `ancestors` chain is missing its region). Rather than turn a
850
+ // resolvable node into an unresolved one, retry once WITHOUT the parent constraint — we
851
+ // prefer a parent-scoped hit but never sacrifice recall. The country constraint is kept, so
852
+ // this still can't wander to a foreign place. Same logical resolution → no extra budget.
853
+ if (!candidates.length && state.parentFallback && query.parentID !== undefined) {
854
+ delete query.parentID;
855
+ rec.gate("parent_fallback_retry");
856
+ candidates = await this.#backend.findPlace(query);
857
+ rec.stage("parent_fallback", candidates);
858
+ }
859
+ // DIAGNOSTIC ONLY, and after every real attempt: which OTHER bands hold this value. The answer never
860
+ // becomes the pick — a band the model did not ask for is not evidence about what the string means —
861
+ // but it separates the two facts a `null` cannot: a key we hold under another placetype is a
862
+ // reachability failure the tag caused, while a key nowhere is coverage. Off by default; one extra call
863
+ // per band per miss.
864
+ if (!candidates.length && state.diagnoseUnreachable) {
865
+ rec.reachable(await this.#probeOtherBands(query, placetype));
866
+ }
867
+ }
868
+ catch (error) {
869
+ // Defensive: a backend failure should not abort the whole tree walk. Leave the node with
870
+ // its classifier attribution intact.
871
+ //
872
+ // The reason rides the gate name. A bare `backend_error` cannot tell a closed database from a
873
+ // finalized statement from a genuine query fault, which is what made three full-board constraint
874
+ // runs unreadable — 64 of 591 rows errored and the census could not say why.
875
+ rec.gate(`backend_error: ${error.message}`);
876
+ rec.emit(null);
877
+ return null;
781
878
  }
782
879
  }
783
- catch {
784
- // Defensive: a backend failure should not abort the whole tree walk. Leave the node with
785
- // its classifier attribution intact.
786
- return null;
880
+ // Postcode-prefix prior (#31, Mechanism 3): when a `postalcode` node misses the gazetteer, derive
881
+ // the code's prefix and probe the injected PFX1 index (structural — never a model input). A hit
882
+ // resolves the node to a synthetic place (id 0), carrying a coordinate ONLY when the index node
883
+ // does — the ancestry-only tier stays coordinate-free (B3-3's 0% half, meaning-of-zero). The
884
+ // prior's payload is returned as node metadata for #walk to stamp. Opt-in via `postcodePrefixPrior`
885
+ // + `postcodePrefixIndex`; OFF by default (D-rule: the PCN1 posture).
886
+ if (!candidates.length && placetype === "postalcode" && state.postcodePrefixPrior && state.postcodePrefixIndex) {
887
+ const probe = probePostcodePrefix(node.value, state.postcodePrefixIndex, query.country);
888
+ if (probe) {
889
+ const metadata = {
890
+ postcode_prefix: probe.prefix,
891
+ postcode_prefix_ancestors: probe.node.ancestors,
892
+ ...(probe.node.radiusP95Km !== undefined ? { postcode_prefix_radius_p95_km: probe.node.radiusP95Km } : {}),
893
+ ...(probe.node.lat !== undefined && probe.node.lon !== undefined
894
+ ? { coordinate_source: "postcode_prefix" }
895
+ : {}),
896
+ };
897
+ rec.gate("postcode_prefix_prior");
898
+ const prefixPlace = postcodePrefixResolvedPlace(probe.prefix, probe.node, state.postcodePrefixIndex);
899
+ rec.emit({ id: prefixPlace.id, name: prefixPlace.name, source: "postcode_prefix" });
900
+ return {
901
+ top: prefixPlace,
902
+ alternatives: [],
903
+ metadata,
904
+ };
905
+ }
906
+ }
907
+ // The bare-toponym country race (fix B of the bare-country class): a lone locality-tagged span
908
+ // also races the `country` placetype, because the parser tags bare country names `locality`
909
+ // about half the time ("Japan", "China") and the locality filter makes the country row
910
+ // unreachable at any rank. Runs ONLY for the tree's single value-bearing node, so every
911
+ // address-shaped input is byte-stable. The locality winner's prominence arbitrates below;
912
+ // with no locality candidates at all, a country hit resolves the span outright.
913
+ const isBareRace = placetype === "locality" && node === state.bareLocalityNode;
914
+ if (isBareRace) {
915
+ rec.gate("bare_race");
787
916
  }
788
- if (!candidates.length)
917
+ const bareCountry = isBareRace ? await bareCountryCandidate(this.#backend, node.value, query.country) : null;
918
+ const bareRegion = isBareRace ? await bareRegionCandidate(this.#backend, node.value, query.country) : null;
919
+ if (!candidates.length) {
920
+ // With no locality candidates at all, the admin namesake with the larger population answers
921
+ // outright (the same precedence the dominance rule below applies).
922
+ const admin = pickLargerAdmin(bareCountry, bareRegion);
923
+ if (admin) {
924
+ rec.gate("empty_admin_pick");
925
+ rec.emit({ id: admin.id, name: admin.name, source: "empty_admin" });
926
+ return {
927
+ top: admin,
928
+ alternatives: [],
929
+ metadata: admin === bareRegion ? { bare_region_repick: true } : { bare_country_repick: true },
930
+ };
931
+ }
932
+ rec.emit(null);
789
933
  return null;
934
+ }
790
935
  // Postcode-anchor re-rank (#369): when a country posterior is supplied (from the address's
791
936
  // postcode), boost candidates by `anchorWeight * posterior[candidate.country]` and re-sort, so a
792
937
  // postcode that pins the country pulls the right-country place over a higher-BM25 foreign namesake
@@ -832,6 +977,60 @@ class WOFResolver {
832
977
  const bKey = (b.prominence ?? b.score) + w * (post[b.country] ?? 0);
833
978
  return bKey - aKey || b.score - a.score;
834
979
  });
980
+ rec.stage("anchor", ranked);
981
+ }
982
+ // Locale-country soft prior (#27) — the #912 lever's other half, at the tier that decides a bare
983
+ // toponym the model tagged `locality`. `--locale en-GB "Whitby"` answers Whitby, Ontario while
984
+ // `--default-country GB "Whitby"` answers the gold, because the CLI DROPS the locale-inferred
985
+ // country for this shape rather than choosing between "hard filter" and "nothing". This is the
986
+ // third option: an additive bonus inside the exact tier, never a filter.
987
+ //
988
+ // Three stand-downs, in the order they matter. A `defaultCountry` makes the prior a no-op by
989
+ // construction (every candidate is already in it), so we skip the work rather than pretend. An
990
+ // `anchorPosterior` is derived from the address's OWN postcode — evidence, which outranks a guess
991
+ // about where the user is sitting. And an absent prior is the SHIPPED default: `ResolveOpts`
992
+ // documents why (the weight that flips the four bare GB rows and the weight that holds the en-US
993
+ // board are disjoint intervals), so this is inert unless a caller opts in.
994
+ //
995
+ // Runs BEFORE the importance key deliberately, matching span-rescore: fame is the stronger signal
996
+ // wherever it has been measured, and it leaves an unscored candidate exactly where the prior put it.
997
+ if (state.localeCountryPrior && !state.defaultCountry && !state.anchorPosterior && anchorEligible) {
998
+ ranked = rankByCountryPrior(ranked, state.localeCountryPrior, state.localeCountryPriorWeight);
999
+ rec.stage("locale_prior", ranked);
1000
+ }
1001
+ // Importance-first (#17/#28). Before this key a bare famous name was decided on POPULATION
1002
+ // alone, which is measurably the wrong prior for the class: `Whitby` answered Whitby, Ontario
1003
+ // (128,377) over Whitby, North Yorkshire (13,130), 5,508 km from where the person meant. Fame is
1004
+ // what a bare toponym is asking about, and the candidate build's blended `importance` column
1005
+ // measures it. Tier-safe and positive-evidence-only (an UNSCORED candidate keeps the rank
1006
+ // population gave it; only the scored ones permute), so it abstains byte-stably on an artifact
1007
+ // that predates the column.
1008
+ //
1009
+ // Skipped outright when an anchor posterior is in force. Fame is the prior of LAST resort: it answers
1010
+ // "which one did you probably mean" only when nothing in the query answered it, and a #369 posterior is
1011
+ // derived from the address's OWN postcode. Evidence outranks a prior. See `toponym-prior.ts`.
1012
+ if (!state.anchorPosterior) {
1013
+ ranked = rankByImportance(ranked);
1014
+ rec.stage("importance", ranked);
1015
+ // #1880 — bounded capital promotion, directly above the fame key it corrects and below the
1016
+ // containment partition (the qualifier is the address's own text; evidence outranks a prior).
1017
+ // Same stand-down as fame: an anchor posterior is postcode evidence and silences the prior.
1018
+ if (state.capitalLevel) {
1019
+ ranked = promoteCapitals(ranked, state.capitalLevel);
1020
+ rec.stage("capital", ranked);
1021
+ }
1022
+ }
1023
+ // Admin-containment partition (#1717 stage 2): the LAST soft re-rank, after the anchor/fame keys
1024
+ // above, because the qualifier is the address's OWN text — evidence, which outranks a prior. The
1025
+ // backend already put contained rows first; this second partition is load-bearing, not belt-and-
1026
+ // braces: `rankByImportance` just re-ordered the exact tier by fame, and Richmond, Virginia
1027
+ // outscores Richmond, North Yorkshire on importance — without this the lever loses exactly where
1028
+ // fame disagrees with the qualifier (the shared-function partition, tier-safe + stable, so it can
1029
+ // never promote a contained partial match over an exact one). No stamps → identity → byte-stable
1030
+ // on any backend that ignored `regionQualifier`.
1031
+ if (containmentEligible) {
1032
+ ranked = partitionByContainment(ranked, (c) => c.containedByQualifier === true, (c) => c.exactMatch === true);
1033
+ rec.stage("containment", ranked);
835
1034
  }
836
1035
  // Exact-type preference (#718): when the placetype-equivalence group let a broader admin tier
837
1036
  // (`macroregion`/`macrocounty`) into the candidate pool, prefer a candidate of the EXACT
@@ -847,66 +1046,49 @@ class WOFResolver {
847
1046
  ...ranked.filter((c) => !isPlacetypeFallback(placetype, c.placetype)),
848
1047
  ...ranked.filter((c) => isPlacetypeFallback(placetype, c.placetype)),
849
1048
  ];
1049
+ rec.stage("exact_type", ranked);
850
1050
  }
851
1051
  const top = ranked[0];
852
- if (top.score < state.minWinningScore)
1052
+ if (top.score < state.minWinningScore) {
1053
+ rec.gate("min_score_reject");
1054
+ rec.emit(null);
853
1055
  return null;
1056
+ }
1057
+ // The admin side of the bare-toponym race. The COUNTRY row wins on prominence alone —
1058
+ // Japan-the-country (pop 126M) over Japan, Pennsylvania (pop 0) — while the REGION row must
1059
+ // DOMINATE the locality winner by {@link BARE_REGION_DOMINANCE_LOG10} in log-population:
1060
+ // prominence saturates at the backend's populationBoost cap, so the margin is measured on the
1061
+ // raw populations, and the margin is what keeps bare "New York" on the city (state 19.6M vs
1062
+ // city 8.8M = 0.35, under the cut) while bare "Georgia" promotes to the 11M state over the
1063
+ // Vermont hamlet (margin 3.4). A bare name with no admin namesake never reaches these lines,
1064
+ // and the displaced locality stays first among the alternatives either way.
1065
+ if (bareCountry && (bareCountry.prominence ?? bareCountry.score) > (top.prominence ?? top.score)) {
1066
+ rec.gate("bare_country_repick");
1067
+ rec.emit({ id: bareCountry.id, name: bareCountry.name, source: "bare_country" });
1068
+ return { top: bareCountry, alternatives: ranked, metadata: { bare_country_repick: true } };
1069
+ }
1070
+ if (bareRegion && logPopulation(bareRegion) >= logPopulation(top) + BARE_REGION_DOMINANCE_LOG10) {
1071
+ rec.gate("bare_region_repick");
1072
+ rec.emit({ id: bareRegion.id, name: bareRegion.name, source: "bare_region" });
1073
+ return { top: bareRegion, alternatives: ranked, metadata: { bare_region_repick: true } };
1074
+ }
854
1075
  // Fallback-observability (#718): if the winner is a macro-type AND no exact-type candidate
855
1076
  // existed for this span, annotate that a broader tier stood in for the true one. Additive —
856
1077
  // identity/coordinate are unchanged; only `metadata.resolution_quality` is stamped downstream.
857
1078
  if (isPlacetypeFallback(placetype, top.placetype)) {
858
1079
  top.resolutionQuality = "fallback";
1080
+ rec.gate("placetype_fallback");
859
1081
  }
860
- return { top, alternatives: ranked.slice(1) };
861
- }
862
- }
863
- /**
864
- * Stamp a node with resolver-supplied attribution. Displaces any prior classifier `source` / `sourceID` into
865
- * `metadata.classifier_source` / `metadata.classifier_source_id` so debugging tools can still see who made the original
866
- * assertion. Surfaces the runner-up candidates on `alternatives` so callers can disambiguate (Springfield-class
867
- * failures, [#8 in the failure catalogue]).
868
- */
869
- function decorateNode(node, resolved, alternatives) {
870
- if (node.source !== undefined || node.sourceID !== undefined) {
871
- const meta = { ...node.metadata };
872
- if (node.source !== undefined) {
873
- meta["classifier_source"] = node.source;
874
- }
875
- if (node.sourceID !== undefined) {
876
- meta["classifier_source_id"] = node.sourceID;
877
- }
878
- node.metadata = meta;
879
- }
880
- node.source = "resolver";
881
- node.sourceID = `${resolved.placetype}:${resolved.id}`;
882
- node.lat = resolved.lat;
883
- node.lon = resolved.lon;
884
- node.placeID = `wof:${resolved.id}`; // v1: only WOF resolvers; the URI scheme stays this simple
885
- // Record the resolver's ranking score AND the resolved place's CANONICAL name. The name is the
886
- // gazetteer's truth for the place we picked — distinct from `node.value` (the raw input span). It
887
- // lets consumers display the canonical name and lets the end-to-end eval check the resolver chose
888
- // the right PLACE (gazetteer-name vs ground-truth) rather than merely echoing the parser's text.
889
- node.metadata = { ...node.metadata, resolver_score: resolved.score, resolver_name: resolved.name };
890
- // The resolved place's ISO-3166 alpha-2 country (from the gazetteer/candidate row), when known. #1014: lets a
891
- // forward consumer fill country/countrycode without an ancestry walk — the candidate backend carries this even
892
- // though it has no `ancestors()` table.
893
- if (resolved.country) {
894
- node.metadata["resolver_country"] = resolved.country;
895
- }
896
- // The postcode/locality conflict flag (the falsehood differentiator): the postcode pointed to a
897
- // geographically different place than the parsed city name. Surface it so callers can warn rather
898
- // than silently trust the resolved point.
899
- if (resolved.mismatch) {
900
- node.metadata["postcode_city_mismatch"] = true;
901
- }
902
- // Fallback-observability (#718): a broader admin tier (macroregion/macrocounty) stood in for the
903
- // true region/county because no exact-type candidate existed. Additive annotation only — the
904
- // resolved coordinate/identity above is untouched; this just lets a consumer / QA pass see it.
905
- if (resolved.resolutionQuality) {
906
- node.metadata["resolution_quality"] = resolved.resolutionQuality;
907
- }
908
- if (alternatives.length) {
909
- node.alternatives = alternatives;
1082
+ rec.emit({ id: top.id, name: top.name, source: "ranked" });
1083
+ // The lever's trace stamp (#1717 stage 2 / #1719's rule): an opted-in mechanism that cannot fire
1084
+ // — a pre-sidecar artifact, an incapable backend — must say so in the result, not degrade
1085
+ // silently. The parse-side census cannot see resolver levers, so this stamp is its census
1086
+ // surface. Only under the lever: the stamp asserts a question was asked.
1087
+ return {
1088
+ top,
1089
+ alternatives: ranked.slice(1),
1090
+ ...(containmentEligible ? { metadata: { admin_containment: adminContainmentVerdict(ranked) } } : {}),
1091
+ };
910
1092
  }
911
1093
  }
912
1094
  //# sourceMappingURL=resolve.js.map