@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/out/resolve.js CHANGED
@@ -12,23 +12,160 @@
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 { compareReferential, DEFAULT_PLACETYPE_MAP, isPlacetypeFallback, referentialFromPopulation, } 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";
20
24
  import { postcodePrefixResolvedPlace, probePostcodePrefix } from "./postcode-prefix.js";
21
25
  import { applyPostcodeShapeCoherence, isShapeExcludedPostcode } from "./postcode-shape-coherence.js";
22
26
  import { findRescoreCandidate, hasResolvedPlace, postcodeCodeSubset } from "./span-rescore.js";
23
27
  import { applyAddressPoint, applyInterpolation, applyStreetCentroid } from "./street-tier.js";
24
- import { DEFAULT_COUNTRY_PRIOR_WEIGHT, rankByCountryPrior, rankByImportance } from "./toponym-prior.js";
28
+ import { DEFAULT_COUNTRY_PRIOR_WEIGHT, promoteCapitals, rankByCountryPrior, rankByImportance } from "./toponym-prior.js";
25
29
  /**
26
30
  * Build a `Resolver` backed by a `ResolverBackend`. The backend can be any concrete impl structurally compatible with
27
- * `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.
28
32
  */
29
33
  export function createWOFResolver(backend) {
30
34
  return new WOFResolver(backend);
31
35
  }
36
+ /**
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
+ }
32
169
  /**
33
170
  * Pick the completion locality when an admin maps to several coincident same-name candidates (#405). REFERENTIAL
34
171
  * likelihood is the PRIMARY signal — the principal city is the populous one, and it can sit FARTHER from the admin
@@ -104,7 +241,7 @@ async function applySpanRescore(roots, raw, backend, opts) {
104
241
  // 5 km area centroid. Same unresolved tree, so the #685 brake semantics hold.
105
242
  if (!hit && opts.postalCompoundRecovery !== false) {
106
243
  try {
107
- await recoverPostcodeNode(roots, backend, opts.defaultCountry);
244
+ await recoverPostcodeNode(roots, backend, opts.defaultCountry, opts.traceSink);
108
245
  }
109
246
  catch {
110
247
  // degrade to no-recovery, never crash the resolve
@@ -133,6 +270,17 @@ async function applySpanRescore(roots, raw, backend, opts) {
133
270
  // (high-precision); false = ungated (no postcode→point coverage for this country, ~83%-precision).
134
271
  node.metadata = { ...node.metadata, span_rescore: true, rescore_gated: hit.gated };
135
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
+ }
136
284
  }
137
285
  /**
138
286
  * #942: find the first confident-but-UNRESOLVED postcode node whose value is a polluted compound ("1382 Kožljek"),
@@ -140,7 +288,7 @@ async function applySpanRescore(roots, raw, backend, opts) {
140
288
  * (`postal_compound_recovered` metadata marks the provenance). No-op when every postcode node resolved, the value has
141
289
  * no digit-bearing tokens, or the subset equals the full value (then the walk already tried it).
142
290
  */
143
- async function recoverPostcodeNode(roots, backend, country) {
291
+ async function recoverPostcodeNode(roots, backend, country, traceSink) {
144
292
  const stack = [...roots];
145
293
  while (stack.length) {
146
294
  const n = stack.pop();
@@ -153,6 +301,14 @@ async function recoverPostcodeNode(roots, backend, country) {
153
301
  if (top) {
154
302
  decorateNode(n, top, []);
155
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
+ }
156
312
  }
157
313
  return; // first postcode node only — one recovery per tree
158
314
  }
@@ -161,12 +317,6 @@ async function recoverPostcodeNode(roots, backend, country) {
161
317
  }
162
318
  }
163
319
  }
164
- /**
165
- * A resolved node carries a real coordinate (placeID set + non-zero lat/lon).
166
- */
167
- function isResolvedWithCoord(n) {
168
- return !!(n.placeID && typeof n.lat === "number" && typeof n.lon === "number" && (n.lat !== 0 || n.lon !== 0));
169
- }
170
320
  /**
171
321
  * Postcode-disambiguated locality selection (#370 "Lever A"). The single biggest miss on the EU/AU panel is a
172
322
  * same-named town resolved to the WRONG instance — "06260 Saint-Pierre" lands 617 km off — while the postcode that
@@ -242,316 +392,6 @@ function applyPostcodeConsistency(roots, gateKm) {
242
392
  node.metadata = { ...node.metadata, postcode_city_mismatch: true, coordinate_source: "postcode_fallback" };
243
393
  }
244
394
  }
245
- /**
246
- * Admin descendant-consistency (#263) — the joint-consistency resolve, scoped to the admin assignment. The greedy walk
247
- * resolves a region on its own (name + population), so "ME" picks Messina (IT) over Maine, then scopes "Portland" to
248
- * Messina's descendants, finds nothing, and the result falls back to the region centroid (Sicily). The region's
249
- * same-named runner-ups (Maine, Missouri, …) were already captured as `alternatives`; this pass asks the question the
250
- * greedy order skipped — _which "ME" has a "Portland" under it?_ — and re-picks the (region, locality) pair where a
251
- * same-named locality descends from a same-named region candidate. Geography decides; no country prior, no list.
252
- *
253
- * Fires ONLY for a resolved region whose child locality fell through (the unresolved-locality signal), so a
254
- * well-resolved tree ("Springfield, IL" → Illinois, Springfield) is byte-identical. Costs one unscoped locality lookup
255
- * per triggering pair. Needs {@link ResolverBackend.ancestors}; no-op without it. See `ResolveOpts.adminCoherence`.
256
- */
257
- async function applyAdminCoherence(roots, backend) {
258
- const visit = async (node, regionAncestor) => {
259
- const regionHere = node.tag === "region" && isResolvedWithCoord(node) ? node : regionAncestor;
260
- if (regionHere &&
261
- (node.tag === "locality" || node.tag === "dependent_locality") &&
262
- !isResolvedWithCoord(node) &&
263
- node.value.trim().length) {
264
- await reconcileAdminPair(regionHere, node, backend);
265
- }
266
- for (const child of node.children) {
267
- await visit(child, regionHere);
268
- }
269
- };
270
- for (const root of roots) {
271
- await visit(root, null);
272
- }
273
- }
274
- /**
275
- * Re-pick a (region, locality) pair so the locality descends from the region. `alternatives` on the node are the
276
- * `ResolvedPlace` runner-ups `decorateNode` attached (typed `unknown[]` in the decoder, which can't import resolver
277
- * types — the cast is sound). Picks the FIRST same-named locality (already score-ordered) that descends from a
278
- * same-named region candidate, then swaps both nodes. Leaves both untouched when no consistent pair exists (a genuinely
279
- * un-gazetteered locality — "Portland, VT" with no Portland in Vermont — stays as the region centroid, not a foreign
280
- * namesake).
281
- */
282
- async function reconcileAdminPair(regionNode, localityNode, backend) {
283
- // EXACT region matches only: the alternatives for a 2-letter token are loose ("ME" also surfaces
284
- // Missouri/Michigan/Mississippi as fuzzy M-state runner-ups). Restricting to exact name/alias matches
285
- // (Maine/Messina/Medway for "ME") keeps the join honest. `exactMatch` is stamped by exactMatchTiering.
286
- const regionCands = (regionNode.alternatives ?? []).filter((r) => r.exactMatch);
287
- // For each exact region candidate, ask the gazetteer directly: is there a same-named locality UNDER it?
288
- // The `parentID` scope is the descendant test (over the #832-repaired ancestors table), and it finds the
289
- // instance regardless of its global population rank — "Springfield, ME" reaches the small Springfield in
290
- // Maine that an unscoped top-N window would drop. First region with an exact-named descendant wins; the
291
- // region candidates are score-ordered, so a tie breaks toward the more prominent place.
292
- for (const region of regionCands) {
293
- const scoped = await backend.findPlace({
294
- text: localityNode.value,
295
- placetype: "locality",
296
- parentID: region.id,
297
- limit: 3,
298
- });
299
- const lc = scoped.find((l) => l.exactMatch && !(l.lat === 0 && l.lon === 0));
300
- if (lc) {
301
- decorateNode(regionNode, region, regionCands.filter((r) => r !== region));
302
- regionNode.metadata = { ...regionNode.metadata, admin_coherence_repicked: true };
303
- decorateNode(localityNode, lc, scoped.filter((l) => l !== lc));
304
- localityNode.metadata = { ...localityNode.metadata, admin_coherence_repicked: true };
305
- return;
306
- }
307
- }
308
- // #267 follow-up: the token may name a COUNTRY whose namesake is a more-populous foreign region — "Tbilisi,
309
- // Georgia" parses region("Georgia") → the US state, but Tbilisi descends from Georgia the COUNTRY. When no
310
- // region candidate holds the locality, try same-named country candidates: a foreign capital under its
311
- // country out-votes the state namesake. Needs the country + the locality's ancestry in the gazetteer (the
312
- // #267 admin fold). The re-picked region node then carries the country place; the locality coordinate wins.
313
- const countryCands = (await backend.findPlace({ text: regionNode.value, placetype: "country", limit: 3 })).filter((c) => c.exactMatch);
314
- for (const country of countryCands) {
315
- const scoped = await backend.findPlace({
316
- text: localityNode.value,
317
- placetype: "locality",
318
- parentID: country.id,
319
- limit: 3,
320
- });
321
- const lc = scoped.find((l) => l.exactMatch && !(l.lat === 0 && l.lon === 0));
322
- if (lc) {
323
- decorateNode(regionNode, country, regionCands);
324
- regionNode.metadata = { ...regionNode.metadata, admin_coherence_repicked: true };
325
- decorateNode(localityNode, lc, scoped.filter((l) => l !== lc));
326
- localityNode.metadata = { ...localityNode.metadata, admin_coherence_repicked: true };
327
- return;
328
- }
329
- }
330
- // #1023: the admin gazetteer may carry NO `country`-placetype node for the token AND the same-named
331
- // foreign locality may be ORPHANED (parent_id = -1) — the 2026-07-07 rebuild flattened Georgia's admin
332
- // hierarchy to localities-only, so the country-node lookup above finds nothing and the `parentID`
333
- // descendant test can never reach Tbilisi. Fall back to matchCountry: normalize the token to an
334
- // ISO-3166 alpha-2 and scope the locality by the gazetteer's `country` COLUMN (set even on an orphaned
335
- // row). Same primitive reconcileExplicitCountry (#822) uses, so the region-parsed namesake path
336
- // ("Tbilisi, Georgia") converges with the country-parsed one ("Vienna, Austria"). matchCountry returns
337
- // null for a US state name/abbrev ("Illinois" / "ME" / "IL"), so a real US (region, locality) pair
338
- // never reaches here — this stays inert on the domestic path.
339
- const mc = matchCountry(regionNode.value);
340
- if (mc) {
341
- const scoped = await backend.findPlace({
342
- text: localityNode.value,
343
- placetype: "locality",
344
- country: mc.iso2,
345
- limit: 3,
346
- });
347
- const lc = scoped.find((l) => l.exactMatch && !(l.lat === 0 && l.lon === 0));
348
- if (lc) {
349
- decorateNode(localityNode, lc, scoped.filter((l) => l !== lc));
350
- localityNode.metadata = { ...localityNode.metadata, admin_coherence_repicked: true };
351
- // The token named a foreign country the admin gazetteer has no node for, but the greedy walk had
352
- // already decorated the region node with the US-state namesake. Revert that stale decoration so the
353
- // node stops asserting the wrong-country coordinate + `resolver_country` (which would otherwise leak
354
- // into the result's `countryCode`); the re-picked locality carries the winning coordinate, and the
355
- // region node falls back to the parsed "Georgia" token, unresolved (the admin DB has nothing truer).
356
- revertResolverDecoration(regionNode);
357
- }
358
- }
359
- }
360
- /**
361
- * Undo a resolver decoration on a node: restore the classifier attribution {@link decorateNode} displaced into
362
- * `metadata.classifier_source(_id)` and drop the resolver-supplied coordinate/identity/alternatives. Used by the #1023
363
- * country fall-through when the region token turns out to name a foreign country the admin gazetteer holds no node for
364
- * — the greedy walk had bound it to the US-state namesake, and that stale claim must not survive the locality re-pick.
365
- */
366
- function revertResolverDecoration(node) {
367
- const meta = { ...node.metadata };
368
- const priorSource = meta["classifier_source"];
369
- const priorSourceID = meta["classifier_source_id"];
370
- node.source = typeof priorSource === "string" ? priorSource : undefined;
371
- node.sourceID = typeof priorSourceID === "string" ? priorSourceID : undefined;
372
- for (const key of [
373
- "classifier_source",
374
- "classifier_source_id",
375
- "resolver_score",
376
- "resolver_prominence",
377
- "resolver_name",
378
- "resolver_country",
379
- "resolution_quality",
380
- "postcode_city_mismatch",
381
- ]) {
382
- // oxlint-disable-next-line typescript/no-dynamic-delete -- removing one key from a plain record; the object is not on a hot path
383
- delete meta[key];
384
- }
385
- node.metadata = meta;
386
- node.lat = undefined;
387
- node.lon = undefined;
388
- node.placeID = undefined;
389
- node.alternatives = undefined;
390
- }
391
- /**
392
- * Explicit-country coherence (#822) — the joint-consistency resolve keyed on the query's own EXPLICIT country token.
393
- * The greedy walk resolves a locality on name + population alone, so "Vienna, Austria" picks the populous US namesake
394
- * (Vienna WV) and IGNORES the "Austria" the address named. This pass asks the question the greedy order skipped —
395
- * _which "Vienna" is in the country the address names?_ — and re-picks the locality to the same-named place under that
396
- * country. The country code comes from the parser's OWN `country` emission via codex's ISO-3166 table (a name→code
397
- * normalization of a token the model already classified, NOT a routing prior or safelist); the gazetteer's `country`
398
- * column does the geographic confirmation. No pin, no list; generalizes to every country.
399
- *
400
- * Disjoint from {@link applyAdminCoherence} by the region guard: that pass owns the case where a REGION scopes the
401
- * locality; this one fires only when the explicit country is the locality's nearest admin context (no region between),
402
- * and then regardless of the locality's resolution state — so it covers both the resolved-but-foreign locality (Sydney
403
- * → the greedy AU pick was wrong) and the unresolved locality the span-rescore tier would otherwise back-fill with the
404
- * US namesake (Vienna → Vienna WV). Byte-stable when the locality already resolved in-country (the id guard) or the
405
- * named country holds no same-named locality (the fail-safe — what also protects "Turkey, TX": no country token ⇒ no
406
- * trigger; and an in-country lookup that finds nothing keeps the greedy result). Costs one country-scoped locality
407
- * lookup per triggering pair. See `ResolveOpts.adminCoherence`.
408
- */
409
- async function applyExplicitCountryCoherence(roots, backend) {
410
- const visit = async (node, countryToken, regionAbove) => {
411
- const countryHere = node.tag === "country" && node.value.trim().length ? node : countryToken;
412
- const regionHere = regionAbove || node.tag === "region" || node.tag === "subregion";
413
- // Fire only when the explicit country is the locality's NEAREST admin context (no region/subregion between).
414
- // When a region IS present, applyAdminCoherence + the region's `parentID` scope already disambiguate the
415
- // locality — applying the coarse country filter there would wrongly re-pick "Springfield, IL" to the most
416
- // populous US "Springfield". Fires regardless of the locality's resolution state, so it PRE-EMPTS the
417
- // span-rescore tier (which would otherwise back-fill the unresolved locality with the US namesake).
418
- if (countryHere && !regionHere && (node.tag === "locality" || node.tag === "dependent_locality")) {
419
- await reconcileExplicitCountry(countryHere, node, backend);
420
- }
421
- for (const child of node.children) {
422
- await visit(child, countryHere, regionHere);
423
- }
424
- };
425
- for (const root of roots) {
426
- await visit(root, null, false);
427
- }
428
- }
429
- /**
430
- * Re-pick a resolved locality to its same-named place UNDER the explicitly-named country. `matchCountry` turns the
431
- * country token into an ISO-3166 alpha-2 (returns null for an unrecognized token → no-op); the backend then surfaces
432
- * the in-country namesake the population-first unscoped window buried. Leaves the node untouched when the country is
433
- * unrecognized, the named country has no exact same-named locality (the fail-safe), or the locality already resolved to
434
- * that place (the id guard → byte-stable). The country node itself stays as the parser emitted it — the named
435
- * well-covered countries carry no `country`-placetype row in the admin gazetteer, so there is nothing to decorate it
436
- * with; the locality coordinate is what the re-pick fixes.
437
- */
438
- async function reconcileExplicitCountry(countryNode, localityNode, backend) {
439
- const mc = matchCountry(countryNode.value);
440
- if (!mc)
441
- return;
442
- const scoped = await backend.findPlace({
443
- text: localityNode.value,
444
- placetype: "locality",
445
- country: mc.iso2,
446
- limit: 3,
447
- });
448
- const lc = scoped.find((l) => l.exactMatch && !(l.lat === 0 && l.lon === 0));
449
- if (!lc)
450
- return;
451
- // Already the in-country place? (placeID encodes the WOF id.) Then the greedy walk was right — byte-stable.
452
- if (localityNode.placeID === `wof:${lc.id}`)
453
- return;
454
- decorateNode(localityNode, lc, scoped.filter((l) => l !== lc));
455
- localityNode.metadata = { ...localityNode.metadata, explicit_country_repicked: true };
456
- }
457
- /**
458
- * Region-country coherence — the joint-consistency resolve keyed on a REGION token the locale-inferred default-country
459
- * filter could not resolve. Companion to {@link applyExplicitCountryCoherence} (which keys on an explicit COUNTRY token)
460
- * and disjoint from {@link applyAdminCoherence} (which needs a region that DID resolve): this pass owns the mirror case,
461
- * where the region qualifier is a foreign subdivision the default-country hard filter (`spr.country = ?`) discarded.
462
- *
463
- * "Montreal QC" under a US locale: the walk applies `defaultCountry="US"` as a hard candidate filter to every admin
464
- * lookup, so the region "QC" (a Canadian subdivision) resolves to nothing and is dropped — the one signal that would
465
- * redirect the country to CA — and the locality "Montreal" is force-matched to the populous US namesake (Montreal, WI).
466
- * The greedy order threw away the evidence that could correct it.
467
- *
468
- * The fix expands the region token to its country via codex's ISO-3166-2 subdivision table (`matchSubdivision`: "QC" →
469
- * `{ name: "Quebec", country: "CA" }`, handling the FTS index's missing "QC" alt-name code-side), then asks the two
470
- * questions the greedy walk skipped: does that subdivision genuinely resolve UNDER its own country, and is there a
471
- * same-named locality under it? Only when BOTH hold does it swap the region and locality to the in-country pair.
472
- * Geography confirms; the subdivision table is a soft name→country prior, not a routing decision.
473
- *
474
- * Evidence-gated to stay byte-stable on the domestic path. It fires ONLY when (a) a default country is in force, (b)
475
- * the region node is UNRESOLVED (the default-country filter came up empty — a US region resolves fine under `US`, so a
476
- * well-formed US query never trips this), (c) the token is a subdivision of a DIFFERENT country than the default, and
477
- * (d) both the foreign region and a same-named foreign locality resolve. "Springfield, IL" / "Portland, ME": the region
478
- * resolves under `US`, so gate (b) fails and the tree is untouched. Costs one region + one locality lookup per
479
- * triggering pair. See `ResolveOpts.adminCoherence`.
480
- */
481
- async function applyRegionCountryCoherence(roots, backend, defaultCountry) {
482
- // No default country → no hard country filter was applied, so no region qualifier was discarded by one. The bug
483
- // this pass corrects is specific to the locale-inferred default country; without it, there is nothing to rescue.
484
- if (!defaultCountry)
485
- return;
486
- const visit = async (node, regionAncestor) => {
487
- // Track the nearest region ancestor regardless of its resolution state (the trigger is an UNRESOLVED region).
488
- const regionHere = node.tag === "region" || node.tag === "subregion" ? node : regionAncestor;
489
- // Fire for an UNRESOLVED region (the default-country filter came up empty) whose companion locality node
490
- // exists — regardless of the locality's resolution state, so it covers both the resolved-but-foreign namesake
491
- // (Montreal → the greedy US pick, Montreal WI) and the unresolved locality the span-rescore tier would
492
- // otherwise back-fill with a US namesake. The in-country lookups below are the evidence gate.
493
- if (regionHere &&
494
- !isResolvedWithCoord(regionHere) &&
495
- (node.tag === "locality" || node.tag === "dependent_locality") &&
496
- node.value.trim().length) {
497
- await reconcileRegionCountry(regionHere, node, backend, defaultCountry);
498
- }
499
- for (const child of node.children) {
500
- await visit(child, regionHere);
501
- }
502
- };
503
- for (const root of roots) {
504
- await visit(root, null);
505
- }
506
- }
507
- /**
508
- * Re-pick an (unresolved region, resolved-but-foreign-namesake locality) pair to the in-country instance the
509
- * default-country filter hid. `matchSubdivision` turns the region token into `{ name, country }` (null for anything
510
- * that isn't a US state or CA province → no-op); the region's full name then resolves it under that country (expanding
511
- * the abbreviation the gazetteer FTS index lacks), and the locality is re-scoped to the same country. Leaves both nodes
512
- * untouched unless every gate holds — the subdivision names a different country than the default, the region resolves
513
- * under it, and a same-named locality exists there — so the domestic path stays byte-identical.
514
- */
515
- async function reconcileRegionCountry(regionNode, localityNode, backend, defaultCountry) {
516
- const sub = matchSubdivision(regionNode.value);
517
- if (!sub)
518
- return;
519
- // The subdivision must belong to a DIFFERENT country than the locale default. A US-state token under a US default
520
- // (sub.country === defaultCountry) never reaches the swap — the pass is inert on the domestic path.
521
- if (sub.country.toUpperCase() === defaultCountry.toUpperCase())
522
- return;
523
- // The locality already resolved in the subdivision's country? Then the greedy walk was already right — byte-stable.
524
- const localityCountry = localityNode.metadata?.["resolver_country"]?.toUpperCase();
525
- if (localityCountry === sub.country.toUpperCase())
526
- return;
527
- // Confirm the subdivision genuinely resolves under its own country, by its full name (expands "QC" → "Quebec", the
528
- // form the FTS index carries). No resolvable region → no evidence the token is a real foreign subdivision; abstain.
529
- const regionScoped = await backend.findPlace({
530
- text: sub.name,
531
- placetype: "region",
532
- country: sub.country,
533
- limit: 3,
534
- });
535
- const rc = regionScoped.find((r) => r.exactMatch && !(r.lat === 0 && r.lon === 0));
536
- if (!rc)
537
- return;
538
- // Is there a same-named locality under that country? (the descendant test, by country column — the same primitive
539
- // reconcileExplicitCountry uses.) No in-country namesake → keep the greedy result (fail-safe).
540
- const scoped = await backend.findPlace({
541
- text: localityNode.value,
542
- placetype: "locality",
543
- country: sub.country,
544
- limit: 3,
545
- });
546
- const lc = scoped.find((l) => l.exactMatch && !(l.lat === 0 && l.lon === 0));
547
- if (!lc)
548
- return;
549
- // Adopt the in-country pair: the region gets the foreign subdivision, the locality its same-named foreign instance.
550
- decorateNode(regionNode, rc, regionScoped.filter((r) => r !== rc));
551
- regionNode.metadata = { ...regionNode.metadata, region_country_repicked: true };
552
- decorateNode(localityNode, lc, scoped.filter((l) => l !== lc));
553
- localityNode.metadata = { ...localityNode.metadata, region_country_repicked: true };
554
- }
555
395
  class WOFResolver {
556
396
  #backend;
557
397
  /**
@@ -559,10 +399,23 @@ class WOFResolver {
559
399
  * read them from the resolver handle they already hold. Absent on artifacts predating the coverage manifest.
560
400
  */
561
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;
562
408
  constructor(backend) {
563
409
  this.#backend = backend;
564
410
  this.artifactCoverage = backend.artifactCoverage;
411
+ this.capabilityGaps = describeCapabilityGaps(backend);
412
+ reportCapabilityGaps(this.capabilityGaps);
565
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);
566
419
  async resolveTree(tree, opts = {}) {
567
420
  // Postcode-shape coherence (#31, Mechanism 1): the earliest pass in the tree — pure-sync and
568
421
  // backend-free, run BEFORE `state.postcode` is read so an excluded span can never become the
@@ -580,24 +433,43 @@ class WOFResolver {
580
433
  minWinningScore: opts.minWinningScore ?? 0,
581
434
  candidatesPerLookup: opts.candidatesPerLookup ?? 5,
582
435
  defaultCountry: opts.defaultCountry,
436
+ defaultCountryIsInferred: opts.defaultCountryIsInferred === true,
437
+ bareLocalityNode: loneBareLocalityNode(tree, opts.placetypeMap ?? DEFAULT_PLACETYPE_MAP),
583
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 } : {}),
584
441
  postcode: firstPostcodeValue(tree.roots),
585
442
  // #31 Mechanism 2 — forwarded to locality lookups (see #lookupAndPick). Opt-in, OFF by default.
586
443
  postcodeContainmentCoherence: opts.postcodeContainmentCoherence === true,
587
444
  // #31 Mechanism 3 — the prefix prior + its injected index (see #lookupAndPick). Opt-in, OFF by default.
588
445
  postcodePrefixPrior: opts.postcodePrefixPrior === true,
589
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,
590
452
  bias: opts.bias,
591
453
  anchorPosterior: opts.anchorPosterior,
592
454
  anchorWeight: opts.anchorWeight ?? 2,
593
455
  localeCountryPrior: opts.localeCountryPrior,
594
456
  localeCountryPriorWeight: opts.localeCountryPriorWeight ?? DEFAULT_COUNTRY_PRIOR_WEIGHT,
457
+ capitalLevel: opts.capitalLevel,
595
458
  hardCountry: opts.hardCountry,
596
459
  // Default-ON (#402): completion only fires for a dual-role region whose locality the parser
597
460
  // dropped, and no-ops entirely when the backend has no relation (the browser WASM resolver, or
598
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.
599
466
  hierarchyCompletion: opts.hierarchyCompletion ?? true,
600
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 } : {}),
601
473
  localityNodePresent: false,
602
474
  resolvedRegion: null,
603
475
  resolvedRegionNode: null,
@@ -613,7 +485,25 @@ class WOFResolver {
613
485
  // EXACTLY one country (never the already-coherent default) makes the pair consistent. See
614
486
  // postcode-country-coherence.ts.
615
487
  let postcodeScope = null;
616
- 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) {
617
507
  postcodeScope = await findPostcodeCountryScope(tree.roots, this.#backend, {
618
508
  postcode: state.postcode,
619
509
  defaultCountry: state.defaultCountry,
@@ -635,6 +525,19 @@ class WOFResolver {
635
525
  if (postcodeScope) {
636
526
  stampPostcodeCountryScope(newRoots, postcodeScope);
637
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
+ }
638
541
  // Dual-role hierarchy completion (#405/#415). Only when enabled, a region resolved, and the parser
639
542
  // emitted NO locality — record the dropped locality as a SECONDARY ROLE (an interpretation) on the
640
543
  // resolved region node, from the backend's precomputed coincident-roles relation (#403). One node,
@@ -751,6 +654,23 @@ class WOFResolver {
751
654
  if (picked.metadata) {
752
655
  decorated.metadata = { ...decorated.metadata, ...picked.metadata };
753
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
+ }
754
674
  // Lineage attachment (#404): stamp the resolved place's ancestor chain onto metadata. Opt-in
755
675
  // + only when the backend supplies it, so the default stays byte-identical (no extra query).
756
676
  if (state.includeAncestors && this.#backend.ancestors) {
@@ -770,6 +690,32 @@ class WOFResolver {
770
690
  }
771
691
  return decorated;
772
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
+ }
773
719
  async #lookupAndPick(node, placetype, parentResolved, state) {
774
720
  state.lookupsRemaining--;
775
721
  const query = {
@@ -806,13 +752,37 @@ class WOFResolver {
806
752
  // overwritten by the US-only recognizer. A genuine foreign subdivision under the wrong locale is recovered
807
753
  // later by region-country coherence after the scoped lookup abstains.
808
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;
809
761
  const country = parentResolved?.country ??
810
- state.defaultCountry ??
762
+ defaultCountryForLookup ??
811
763
  (typeof countryHint === "string" ? countryHint : undefined) ??
812
764
  state.hardCountry;
813
765
  if (country) {
814
766
  query.country = country;
815
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
+ }
816
786
  // Coordinate-first: hand the sibling postcode to locality lookups so the backend can inject
817
787
  // postcode-proximal candidates the name-match would miss. Only for locality (the placetype both
818
788
  // `locality` and `dependent_locality` map to); other placetypes ignore it. The containment flag
@@ -824,24 +794,88 @@ class WOFResolver {
824
794
  query.postcodeContainmentCoherence = true;
825
795
  }
826
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);
827
806
  let candidates;
828
- try {
829
- candidates = await this.#backend.findPlace(query);
830
- // Parent soft-gating: `parentID` is a HARD descendant filter in the backend, which wrongly
831
- // zeroes the result when the parent resolved wrong OR the gazetteer hierarchy is incomplete
832
- // (a real locality whose `ancestors` chain is missing its region). Rather than turn a
833
- // resolvable node into an unresolved one, retry once WITHOUT the parent constraint — we
834
- // prefer a parent-scoped hit but never sacrifice recall. The country constraint is kept, so
835
- // this still can't wander to a foreign place. Same logical resolution → no extra budget.
836
- if (!candidates.length && state.parentFallback && query.parentID !== undefined) {
837
- delete query.parentID;
838
- candidates = await this.#backend.findPlace(query);
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: [] };
839
835
  }
836
+ candidates = [];
840
837
  }
841
- catch {
842
- // Defensive: a backend failure should not abort the whole tree walk. Leave the node with
843
- // its classifier attribution intact.
844
- return null;
838
+ else {
839
+ try {
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;
878
+ }
845
879
  }
846
880
  // Postcode-prefix prior (#31, Mechanism 3): when a `postalcode` node misses the gazetteer, derive
847
881
  // the code's prefix and probe the injected PFX1 index (structural — never a model input). A hit
@@ -860,15 +894,44 @@ class WOFResolver {
860
894
  ? { coordinate_source: "postcode_prefix" }
861
895
  : {}),
862
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" });
863
900
  return {
864
- top: postcodePrefixResolvedPlace(probe.prefix, probe.node, state.postcodePrefixIndex),
901
+ top: prefixPlace,
865
902
  alternatives: [],
866
903
  metadata,
867
904
  };
868
905
  }
869
906
  }
870
- if (!candidates.length)
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");
916
+ }
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);
871
933
  return null;
934
+ }
872
935
  // Postcode-anchor re-rank (#369): when a country posterior is supplied (from the address's
873
936
  // postcode), boost candidates by `anchorWeight * posterior[candidate.country]` and re-sort, so a
874
937
  // postcode that pins the country pulls the right-country place over a higher-BM25 foreign namesake
@@ -914,6 +977,7 @@ class WOFResolver {
914
977
  const bKey = (b.prominence ?? b.score) + w * (post[b.country] ?? 0);
915
978
  return bKey - aKey || b.score - a.score;
916
979
  });
980
+ rec.stage("anchor", ranked);
917
981
  }
918
982
  // Locale-country soft prior (#27) — the #912 lever's other half, at the tier that decides a bare
919
983
  // toponym the model tagged `locality`. `--locale en-GB "Whitby"` answers Whitby, Ontario while
@@ -932,6 +996,7 @@ class WOFResolver {
932
996
  // wherever it has been measured, and it leaves an unscored candidate exactly where the prior put it.
933
997
  if (state.localeCountryPrior && !state.defaultCountry && !state.anchorPosterior && anchorEligible) {
934
998
  ranked = rankByCountryPrior(ranked, state.localeCountryPrior, state.localeCountryPriorWeight);
999
+ rec.stage("locale_prior", ranked);
935
1000
  }
936
1001
  // Importance-first (#17/#28). Before this key a bare famous name was decided on POPULATION
937
1002
  // alone, which is measurably the wrong prior for the class: `Whitby` answered Whitby, Ontario
@@ -946,6 +1011,26 @@ class WOFResolver {
946
1011
  // derived from the address's OWN postcode. Evidence outranks a prior. See `toponym-prior.ts`.
947
1012
  if (!state.anchorPosterior) {
948
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);
949
1034
  }
950
1035
  // Exact-type preference (#718): when the placetype-equivalence group let a broader admin tier
951
1036
  // (`macroregion`/`macrocounty`) into the candidate pool, prefer a candidate of the EXACT
@@ -961,89 +1046,49 @@ class WOFResolver {
961
1046
  ...ranked.filter((c) => !isPlacetypeFallback(placetype, c.placetype)),
962
1047
  ...ranked.filter((c) => isPlacetypeFallback(placetype, c.placetype)),
963
1048
  ];
1049
+ rec.stage("exact_type", ranked);
964
1050
  }
965
1051
  const top = ranked[0];
966
- if (top.score < state.minWinningScore)
1052
+ if (top.score < state.minWinningScore) {
1053
+ rec.gate("min_score_reject");
1054
+ rec.emit(null);
967
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
+ }
968
1075
  // Fallback-observability (#718): if the winner is a macro-type AND no exact-type candidate
969
1076
  // existed for this span, annotate that a broader tier stood in for the true one. Additive —
970
1077
  // identity/coordinate are unchanged; only `metadata.resolution_quality` is stamped downstream.
971
1078
  if (isPlacetypeFallback(placetype, top.placetype)) {
972
1079
  top.resolutionQuality = "fallback";
1080
+ rec.gate("placetype_fallback");
973
1081
  }
974
- return { top, alternatives: ranked.slice(1) };
975
- }
976
- }
977
- /**
978
- * Stamp a node with resolver-supplied attribution. Displaces any prior classifier `source` / `sourceID` into
979
- * `metadata.classifier_source` / `metadata.classifier_source_id` so debugging tools can still see who made the original
980
- * assertion. Surfaces the runner-up candidates on `alternatives` so callers can disambiguate (Springfield-class
981
- * failures, [#8 in the failure catalogue]).
982
- */
983
- function decorateNode(node, resolved, alternatives) {
984
- if (node.source !== undefined || node.sourceID !== undefined) {
985
- const meta = { ...node.metadata };
986
- if (node.source !== undefined) {
987
- meta["classifier_source"] = node.source;
988
- }
989
- if (node.sourceID !== undefined) {
990
- meta["classifier_source_id"] = node.sourceID;
991
- }
992
- node.metadata = meta;
993
- }
994
- node.source = "resolver";
995
- node.sourceID = `${resolved.placetype}:${resolved.id}`;
996
- node.lat = resolved.lat;
997
- node.lon = resolved.lon;
998
- node.placeID = `wof:${resolved.id}`; // v1: only WOF resolvers; the URI scheme stays this simple
999
- // Record the resolver's ranking score AND the resolved place's CANONICAL name. The name is the
1000
- // gazetteer's truth for the place we picked — distinct from `node.value` (the raw input span). It
1001
- // lets consumers display the canonical name and lets the end-to-end eval check the resolver chose
1002
- // the right PLACE (gazetteer-name vs ground-truth) rather than merely echoing the parser's text.
1003
- node.metadata = { ...node.metadata, resolver_score: resolved.score, resolver_name: resolved.name };
1004
- // The winner's PROMINENCE, when the backend computed one. `alternatives` below are full `ResolvedPlace`s and
1005
- // already carry theirs; without this stamp the WINNER's is the one value in the ranked list that gets dropped,
1006
- // which makes a top-1-vs-top-2 margin uncomputable from the tree — and that margin is what
1007
- // `mailwoman/query-intent.ts` reads to decide whether a bare-toponym answer was a clear win. Additive metadata
1008
- // only; nothing in the resolve reads it back.
1009
- if (resolved.prominence !== undefined) {
1010
- node.metadata["resolver_prominence"] = resolved.prominence;
1011
- }
1012
- // The resolved place's ISO-3166 alpha-2 country (from the gazetteer/candidate row), when known. #1014: lets a
1013
- // forward consumer fill country/countrycode without an ancestry walk — the candidate backend carries this even
1014
- // though it has no `ancestors()` table.
1015
- if (resolved.country) {
1016
- node.metadata["resolver_country"] = resolved.country;
1017
- }
1018
- // The score-channel carries (ROAD_TO_V9 §2 + #28). Written ONLY when the backend actually has a
1019
- // value: an absent score means "unmeasured" or "pre-split gazetteer", and a `resolver_*: 0` on the
1020
- // node would assert a measurement nobody made. Nothing in the resolve path reads these keys back —
1021
- // they exist for annotation / API surfaces downstream. `resolver_importance` is the blended #28
1022
- // prior (the value the ranking consulted); `resolver_encyclopedic` is the strict channel, reserved
1023
- // until a strict-channel source ships.
1024
- if (resolved.referential !== undefined) {
1025
- node.metadata["resolver_referential"] = resolved.referential;
1026
- }
1027
- if (resolved.encyclopedic !== undefined) {
1028
- node.metadata["resolver_encyclopedic"] = resolved.encyclopedic;
1029
- }
1030
- if (resolved.importance !== undefined) {
1031
- node.metadata["resolver_importance"] = resolved.importance;
1032
- }
1033
- // The postcode/locality conflict flag (the falsehood differentiator): the postcode pointed to a
1034
- // geographically different place than the parsed city name. Surface it so callers can warn rather
1035
- // than silently trust the resolved point.
1036
- if (resolved.mismatch) {
1037
- node.metadata["postcode_city_mismatch"] = true;
1038
- }
1039
- // Fallback-observability (#718): a broader admin tier (macroregion/macrocounty) stood in for the
1040
- // true region/county because no exact-type candidate existed. Additive annotation only — the
1041
- // resolved coordinate/identity above is untouched; this just lets a consumer / QA pass see it.
1042
- if (resolved.resolutionQuality) {
1043
- node.metadata["resolution_quality"] = resolved.resolutionQuality;
1044
- }
1045
- if (alternatives.length) {
1046
- 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
+ };
1047
1092
  }
1048
1093
  }
1049
1094
  //# sourceMappingURL=resolve.js.map