@mailwoman/resolver 9.1.0 → 9.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (142) hide show
  1. package/README.md +89 -0
  2. package/lib/admin/coherence-passes.ts +435 -0
  3. package/lib/admin/containment.ts +92 -0
  4. package/lib/admin/index.ts +10 -0
  5. package/lib/admin/jp-municipality.ts +97 -0
  6. package/lib/admin/winner.ts +189 -0
  7. package/lib/backend-capabilities.ts +88 -0
  8. package/lib/bare-toponym-race.ts +129 -0
  9. package/lib/decorate-node.ts +127 -0
  10. package/lib/fold-name.ts +36 -0
  11. package/{index.ts → lib/index.ts} +27 -18
  12. package/{plausibility.ts → lib/plausibility.ts} +5 -4
  13. package/{postcode-country-coherence.ts → lib/postcode/country-coherence.ts} +173 -86
  14. package/lib/postcode/index.ts +9 -0
  15. package/{postcode-prefix.ts → lib/postcode/prefix.ts} +7 -6
  16. package/{postcode-shape-coherence.ts → lib/postcode/shape-coherence.ts} +10 -24
  17. package/{remote-resolver.ts → lib/remote-resolver.ts} +13 -4
  18. package/{rerank.ts → lib/rerank.ts} +2 -2
  19. package/lib/resolve/index.ts +982 -0
  20. package/lib/resolve/passes.ts +544 -0
  21. package/{span-rescore.ts → lib/span-rescore.ts} +114 -99
  22. package/{street-evidence.ts → lib/street/evidence.ts} +40 -7
  23. package/lib/street/index.ts +8 -0
  24. package/{street-tier.ts → lib/street/tier.ts} +138 -99
  25. package/{toponym-prior.ts → lib/toponym-prior.ts} +97 -8
  26. package/out/admin/coherence-passes.d.ts +70 -0
  27. package/out/admin/coherence-passes.d.ts.map +1 -0
  28. package/out/admin/coherence-passes.js +327 -0
  29. package/out/admin/coherence-passes.js.map +1 -0
  30. package/out/admin/containment.d.ts +48 -0
  31. package/out/admin/containment.d.ts.map +1 -0
  32. package/out/admin/containment.js +76 -0
  33. package/out/admin/containment.js.map +1 -0
  34. package/out/admin/index.d.ts +10 -0
  35. package/out/admin/index.d.ts.map +1 -0
  36. package/out/admin/index.js +10 -0
  37. package/out/admin/index.js.map +1 -0
  38. package/out/admin/jp-municipality.d.ts +50 -0
  39. package/out/admin/jp-municipality.d.ts.map +1 -0
  40. package/out/admin/jp-municipality.js +54 -0
  41. package/out/admin/jp-municipality.js.map +1 -0
  42. package/out/admin/winner.d.ts +114 -0
  43. package/out/admin/winner.d.ts.map +1 -0
  44. package/out/admin/winner.js +130 -0
  45. package/out/admin/winner.js.map +1 -0
  46. package/out/backend-capabilities.d.ts +37 -0
  47. package/out/backend-capabilities.d.ts.map +1 -0
  48. package/out/backend-capabilities.js +75 -0
  49. package/out/backend-capabilities.js.map +1 -0
  50. package/out/bare-toponym-race.d.ts +55 -0
  51. package/out/bare-toponym-race.d.ts.map +1 -0
  52. package/out/bare-toponym-race.js +110 -0
  53. package/out/bare-toponym-race.js.map +1 -0
  54. package/out/decorate-node.d.ts +24 -0
  55. package/out/decorate-node.d.ts.map +1 -0
  56. package/out/decorate-node.js +103 -0
  57. package/out/decorate-node.js.map +1 -0
  58. package/out/fold-name.d.ts +18 -3
  59. package/out/fold-name.d.ts.map +1 -1
  60. package/out/fold-name.js +19 -3
  61. package/out/fold-name.js.map +1 -1
  62. package/out/index.d.ts +15 -12
  63. package/out/index.d.ts.map +1 -1
  64. package/out/index.js +9 -7
  65. package/out/index.js.map +1 -1
  66. package/out/plausibility.d.ts +5 -4
  67. package/out/plausibility.d.ts.map +1 -1
  68. package/out/plausibility.js +5 -4
  69. package/out/plausibility.js.map +1 -1
  70. package/out/{postcode-country-coherence.d.ts → postcode/country-coherence.d.ts} +46 -25
  71. package/out/postcode/country-coherence.d.ts.map +1 -0
  72. package/out/{postcode-country-coherence.js → postcode/country-coherence.js} +157 -77
  73. package/out/postcode/country-coherence.js.map +1 -0
  74. package/out/postcode/index.d.ts +9 -0
  75. package/out/postcode/index.d.ts.map +1 -0
  76. package/out/postcode/index.js +9 -0
  77. package/out/postcode/index.js.map +1 -0
  78. package/out/{postcode-prefix.d.ts → postcode/prefix.d.ts} +4 -4
  79. package/out/postcode/prefix.d.ts.map +1 -0
  80. package/out/{postcode-prefix.js → postcode/prefix.js} +7 -6
  81. package/out/postcode/prefix.js.map +1 -0
  82. package/out/{postcode-shape-coherence.d.ts → postcode/shape-coherence.d.ts} +3 -3
  83. package/out/postcode/shape-coherence.d.ts.map +1 -0
  84. package/out/{postcode-shape-coherence.js → postcode/shape-coherence.js} +11 -20
  85. package/out/postcode/shape-coherence.js.map +1 -0
  86. package/out/remote-resolver.d.ts +18 -3
  87. package/out/remote-resolver.d.ts.map +1 -1
  88. package/out/remote-resolver.js +2 -2
  89. package/out/remote-resolver.js.map +1 -1
  90. package/out/rerank.d.ts +1 -1
  91. package/out/rerank.d.ts.map +1 -1
  92. package/out/rerank.js +2 -2
  93. package/out/rerank.js.map +1 -1
  94. package/out/{resolve.d.ts → resolve/index.d.ts} +2 -2
  95. package/out/resolve/index.d.ts.map +1 -0
  96. package/out/resolve/index.js +795 -0
  97. package/out/resolve/index.js.map +1 -0
  98. package/out/resolve/passes.d.ts +218 -0
  99. package/out/resolve/passes.d.ts.map +1 -0
  100. package/out/resolve/passes.js +333 -0
  101. package/out/resolve/passes.js.map +1 -0
  102. package/out/span-rescore.d.ts +16 -16
  103. package/out/span-rescore.d.ts.map +1 -1
  104. package/out/span-rescore.js +87 -71
  105. package/out/span-rescore.js.map +1 -1
  106. package/out/{street-evidence.d.ts → street/evidence.d.ts} +18 -3
  107. package/out/street/evidence.d.ts.map +1 -0
  108. package/out/{street-evidence.js → street/evidence.js} +23 -7
  109. package/out/street/evidence.js.map +1 -0
  110. package/out/street/index.d.ts +8 -0
  111. package/out/street/index.d.ts.map +1 -0
  112. package/out/street/index.js +8 -0
  113. package/out/street/index.js.map +1 -0
  114. package/out/{street-tier.d.ts → street/tier.d.ts} +14 -3
  115. package/out/street/tier.d.ts.map +1 -0
  116. package/out/{street-tier.js → street/tier.js} +127 -90
  117. package/out/street/tier.js.map +1 -0
  118. package/out/toponym-prior.d.ts +43 -19
  119. package/out/toponym-prior.d.ts.map +1 -1
  120. package/out/toponym-prior.js +76 -8
  121. package/out/toponym-prior.js.map +1 -1
  122. package/package.json +167 -19
  123. package/vitest.config.ts +5 -6
  124. package/fold-name.ts +0 -20
  125. package/out/postcode-country-coherence.d.ts.map +0 -1
  126. package/out/postcode-country-coherence.js.map +0 -1
  127. package/out/postcode-prefix.d.ts.map +0 -1
  128. package/out/postcode-prefix.js.map +0 -1
  129. package/out/postcode-shape-coherence.d.ts.map +0 -1
  130. package/out/postcode-shape-coherence.js.map +0 -1
  131. package/out/resolve.d.ts.map +0 -1
  132. package/out/resolve.js +0 -1049
  133. package/out/resolve.js.map +0 -1
  134. package/out/street-evidence.d.ts.map +0 -1
  135. package/out/street-evidence.js.map +0 -1
  136. package/out/street-tier.d.ts.map +0 -1
  137. package/out/street-tier.js.map +0 -1
  138. package/out/vitest.config.d.ts +0 -16
  139. package/out/vitest.config.d.ts.map +0 -1
  140. package/out/vitest.config.js +0 -36
  141. package/out/vitest.config.js.map +0 -1
  142. package/resolve.ts +0 -1369
package/out/resolve.js DELETED
@@ -1,1049 +0,0 @@
1
- /**
2
- * @copyright Sister Software
3
- * @license AGPL-3.0
4
- * @author Teffen Ellis, et al.
5
- *
6
- * `resolveTree` — walk an `AddressTree` top-down and decorate matched nodes with resolver- supplied
7
- * attribution + coordinates.
8
- *
9
- * The walk is parent-constraint-aware: when a parent node resolves to a place id, its children's
10
- * lookups are scoped to descendants of that parent. This dramatically narrows the search space
11
- * for ambiguous names — `Springfield` under a resolved `Illinois` parent resolves to the IL one,
12
- * not the MA one.
13
- */
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";
17
- import { haversineKm } from "@mailwoman/spatial";
18
- import { foldName } from "./fold-name.js";
19
- import { findPostcodeCountryScope, stampPostcodeCountryScope, } from "./postcode-country-coherence.js";
20
- import { postcodePrefixResolvedPlace, probePostcodePrefix } from "./postcode-prefix.js";
21
- import { applyPostcodeShapeCoherence, isShapeExcludedPostcode } from "./postcode-shape-coherence.js";
22
- import { findRescoreCandidate, hasResolvedPlace, postcodeCodeSubset } from "./span-rescore.js";
23
- import { applyAddressPoint, applyInterpolation, applyStreetCentroid } from "./street-tier.js";
24
- import { DEFAULT_COUNTRY_PRIOR_WEIGHT, rankByCountryPrior, rankByImportance } from "./toponym-prior.js";
25
- /**
26
- * 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.
28
- */
29
- export function createWOFResolver(backend) {
30
- return new WOFResolver(backend);
31
- }
32
- /**
33
- * Pick the completion locality when an admin maps to several coincident same-name candidates (#405). REFERENTIAL
34
- * likelihood is the PRIMARY signal — the principal city is the populous one, and it can sit FARTHER from the admin
35
- * centroid than a tiny same-name hamlet (the Niigata case from #403). Nearest centroid breaks a referential tie; a
36
- * genuine tie (same population AND distance) ABSTAINS rather than guess.
37
- *
38
- * ROAD_TO_V9 §2: `compareReferential` is referential DESC with raw population as its own tiebreak, which is the SAME
39
- * ORDER as the plain `b.population - a.population` it replaced — referential is strictly increasing in population below
40
- * saturation and constant above it. The abstention check below still reads raw population, deliberately: two megacities
41
- * that saturate to the same referential score are not tied, and abstaining there would be a new behavior.
42
- */
43
- function pickCompletion(candidates) {
44
- if (!candidates.length)
45
- return null;
46
- if (candidates.length === 1)
47
- return candidates[0];
48
- const ranked = [...candidates]
49
- .map((c) => ({ c, referential: referentialFromPopulation(c.population), population: c.population }))
50
- // oxlint-disable-next-line unicorn/no-array-sort -- sorts a freshly-built array; toSorted would double-allocate on a hot path
51
- .sort((a, b) => compareReferential(a, b) || a.c.distanceKm - b.c.distanceKm)
52
- .map((x) => x.c);
53
- const [first, second] = ranked;
54
- if (first.population === second.population && first.distanceKm === second.distanceKm)
55
- return null;
56
- return first;
57
- }
58
- /**
59
- * Find the first postcode value anywhere in the tree (a one-shot pre-scan; postcode and locality are siblings, so the
60
- * top-down walk wouldn't otherwise let the locality lookup see it).
61
- */
62
- function firstPostcodeValue(roots) {
63
- const stack = [...roots];
64
- while (stack.length) {
65
- const n = stack.pop();
66
- // #31 Mechanism 1: a shape-excluded span keeps its tag but contributes nothing — its code
67
- // must never become the address's postcode (it would poison the country-scope pass's anchor).
68
- if (n.tag === "postcode" && !isShapeExcludedPostcode(n) && n.value.trim().length)
69
- return n.value.trim();
70
- stack.push(...n.children);
71
- }
72
- return undefined;
73
- }
74
- /**
75
- * Span-rescore tier (#370): opt-in last-resort locality recovery. Runs ONLY when the tree resolved NOTHING (the #685
76
- * brake — never disturb a working coordinate). Enumerates raw-token spans, exact- matches the same-country gazetteer
77
- * (longest-wins + postcode-consistency gate; see `span-rescore.ts`), and on a hit INJECTS a resolved `locality` node
78
- * decorated exactly like a normally-resolved one. Default-ON (#370, promoted 2026-06-25); byte-stable opt-out via
79
- * `opts.spanRescore: false`. Async (it queries the backend), so it's awaited.
80
- */
81
- async function applySpanRescore(roots, raw, backend, opts) {
82
- if (hasResolvedPlace(roots))
83
- return; // already resolved — never second-guess a working coordinate
84
- // Default-ON since 2026-06-25, so this runs on every unresolved tree — a backend hiccup here must
85
- // degrade to no-rescore, never crash the resolve (the same fall-through the main walk gives).
86
- let hit;
87
- try {
88
- hit = await findRescoreCandidate(raw, roots, backend, {
89
- country: opts.defaultCountry,
90
- postcode: firstPostcodeValue(roots),
91
- gateKm: opts.spanRescoreGateKm,
92
- // Default-ON (promoted 2026-07-03); explicit `false` opts out — the spanRescore idiom.
93
- postalCompoundRecovery: opts.postalCompoundRecovery !== false,
94
- });
95
- }
96
- catch {
97
- return;
98
- }
99
- // #942 postal-compound recovery, part 2: when NO city span matched, decorate the FAILED postcode
100
- // node from its code-shaped token subset ("1382 Kožljek" → the bare "1382" row) — a postcode-tier
101
- // coordinate FLOOR, strictly subordinate to a recovered locality. Only-on-miss matters: a GeoNames
102
- // medoid postcode centroid is COARSER than the exact village centroid, and consumers that rank
103
- // postcode above locality (the eval harness does) would otherwise trade a 0.2 km village pin for a
104
- // 5 km area centroid. Same unresolved tree, so the #685 brake semantics hold.
105
- if (!hit && opts.postalCompoundRecovery !== false) {
106
- try {
107
- await recoverPostcodeNode(roots, backend, opts.defaultCountry);
108
- }
109
- catch {
110
- // degrade to no-recovery, never crash the resolve
111
- }
112
- }
113
- if (!hit)
114
- return;
115
- const node = {
116
- tag: "locality",
117
- value: hit.text,
118
- start: hit.start,
119
- end: hit.end,
120
- // No model confidence for a post-hoc recovery; a mid-tier value marks it as recovered, not asserted.
121
- confidence: 0.5,
122
- children: [],
123
- };
124
- // #1537: the same-span namesake runner-ups, not an empty list. A name the model reads as a `street`
125
- // ("Springfield", "Berlin", "Moscow") never reaches the admin walk, so this tier is the ONLY thing that
126
- // resolves it — and decorating with `[]` meant the geocode path's `candidates` held one entry and the
127
- // dominance margin `declared_ambiguity` reads was uncomputable for exactly the famous-homonym class.
128
- // The winner is unchanged (see findRescoreCandidate); this is additive.
129
- decorateNode(node, hit.place, hit.alternatives);
130
- // `rescore_gated` carries the gate's precision signal as an EXPLICIT handle — NOT folded into the
131
- // calibrated `confidence`, which would break the isotonic guarantee (a true calibrated 0.83 must not
132
- // be confused with a rescore plug-in estimate; DeepSeek 2026-06-23). true = postcode gate fired
133
- // (high-precision); false = ungated (no postcode→point coverage for this country, ~83%-precision).
134
- node.metadata = { ...node.metadata, span_rescore: true, rescore_gated: hit.gated };
135
- roots.push(node);
136
- }
137
- /**
138
- * #942: find the first confident-but-UNRESOLVED postcode node whose value is a polluted compound ("1382 Kožljek"),
139
- * resolve its code-shaped token subset as a `postalcode`, and decorate the node from that hit
140
- * (`postal_compound_recovered` metadata marks the provenance). No-op when every postcode node resolved, the value has
141
- * no digit-bearing tokens, or the subset equals the full value (then the walk already tried it).
142
- */
143
- async function recoverPostcodeNode(roots, backend, country) {
144
- const stack = [...roots];
145
- while (stack.length) {
146
- const n = stack.pop();
147
- if (n.tag === "postcode" && !n.placeID && n.value.trim()) {
148
- const code = postcodeCodeSubset(n.value);
149
- if (!code || code === n.value.trim())
150
- continue;
151
- const hits = await backend.findPlace({ text: code, placetype: "postalcode", country, limit: 1 });
152
- const top = hits.find((h) => h.lat !== 0 || h.lon !== 0);
153
- if (top) {
154
- decorateNode(n, top, []);
155
- n.metadata = { ...n.metadata, postal_compound_recovered: true };
156
- }
157
- return; // first postcode node only — one recovery per tree
158
- }
159
- if (n.children?.length) {
160
- stack.push(...n.children);
161
- }
162
- }
163
- }
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
- /**
171
- * Postcode-disambiguated locality selection (#370 "Lever A"). The single biggest miss on the EU/AU panel is a
172
- * same-named town resolved to the WRONG instance — "06260 Saint-Pierre" lands 617 km off — while the postcode that
173
- * would disambiguate it (06260 → Alpes-Maritimes) sits resolved in the same tree, discarded because the
174
- * coordinate-picker prefers the (wrong) locality node and never cross- checks it. This post-walk pass closes that loop,
175
- * backend-agnostically and with no extra query:
176
- *
177
- * 1. Find the resolved postcode's coordinate (the trustworthy anchor — a postcode is unambiguous within a country in a way
178
- * a town name is not).
179
- * 2. For each resolved locality node farther than `gateKm` from it: re-pick the same-named candidate from the node's
180
- * already-captured `alternatives` that is NEAREST the postcode and within the gate. This keeps locality granularity
181
- * at the CORRECT instance.
182
- * 3. If no alternative reconciles, the locality instance is unreliable — fall its coordinate back to the postcode point
183
- * (right area, the safe answer) and flag `postcode_city_mismatch`.
184
- *
185
- * Only fires where the postcode resolved to a point, so it composes with postcode coverage (#193) — add a country's
186
- * postcodes and this immediately disambiguates its same-named towns. **Default-ON** since the #370 operator promotion
187
- * (2026-07-04, commit `0010bb8c`) — `opts.postcodeConsistency: false` opts out, and the pass is byte-stable on every
188
- * tree with no resolved postcode point (the `!anchor` early return below).
189
- */
190
- function applyPostcodeConsistency(roots, gateKm) {
191
- // The resolved postcode anchor (first one with a real coordinate).
192
- let anchor = null;
193
- const findAnchor = [...roots];
194
- while (findAnchor.length) {
195
- const n = findAnchor.pop();
196
- // #31 Mechanism 1: a shape-excluded span never anchors the consistency re-pick either.
197
- if (n.tag === "postcode" && !isShapeExcludedPostcode(n) && isResolvedWithCoord(n)) {
198
- anchor = { lat: n.lat, lon: n.lon };
199
- break;
200
- }
201
- findAnchor.push(...n.children);
202
- }
203
- if (!anchor)
204
- return; // no postcode→point — nothing to disambiguate against (gate can't fire)
205
- const stack = [...roots];
206
- while (stack.length) {
207
- const node = stack.pop();
208
- stack.push(...node.children);
209
- if ((node.tag !== "locality" && node.tag !== "dependent_locality") || !isResolvedWithCoord(node))
210
- continue;
211
- if (haversineKm(anchor.lat, anchor.lon, node.lat, node.lon) <= gateKm)
212
- continue; // already consistent
213
- // Re-pick: the same-named candidate nearest the postcode, within the gate. `alternatives` is
214
- // typed `unknown[]` on the node (decoder/types.ts can't import resolver types) — they ARE the
215
- // `ResolvedPlace` runner-ups decorateNode attached, so the cast is sound.
216
- const alts = node.alternatives ?? [];
217
- const reconciling = alts
218
- .filter((a) => a.lat !== 0 || a.lon !== 0)
219
- .map((a) => ({ a, d: haversineKm(anchor.lat, anchor.lon, a.lat, a.lon) }))
220
- .filter((x) => x.d <= gateKm)
221
- // oxlint-disable-next-line unicorn/no-array-sort -- sorts a freshly-built array; toSorted would double-allocate on a hot path
222
- .sort((x, y) => x.d - y.d)[0];
223
- if (reconciling) {
224
- // Swap to the consistent instance; the displaced winner becomes an alternative.
225
- const displaced = {
226
- id: 0,
227
- name: String(node.metadata?.["resolver_name"] ?? node.value),
228
- placetype: "locality",
229
- country: reconciling.a.country,
230
- lat: node.lat,
231
- lon: node.lon,
232
- score: 0,
233
- };
234
- const rest = alts.filter((a) => a !== reconciling.a);
235
- decorateNode(node, reconciling.a, [displaced, ...rest]);
236
- node.metadata = { ...node.metadata, postcode_repicked: true };
237
- continue;
238
- }
239
- // No same-named instance near the postcode → the town is unreliable; trust the postcode's area.
240
- node.lat = anchor.lat;
241
- node.lon = anchor.lon;
242
- node.metadata = { ...node.metadata, postcode_city_mismatch: true, coordinate_source: "postcode_fallback" };
243
- }
244
- }
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
- class WOFResolver {
556
- #backend;
557
- /**
558
- * The gazetteer artifact's self-declared coverage facts, passed through from the backend so pipeline-level consumers
559
- * read them from the resolver handle they already hold. Absent on artifacts predating the coverage manifest.
560
- */
561
- artifactCoverage;
562
- constructor(backend) {
563
- this.#backend = backend;
564
- this.artifactCoverage = backend.artifactCoverage;
565
- }
566
- async resolveTree(tree, opts = {}) {
567
- // Postcode-shape coherence (#31, Mechanism 1): the earliest pass in the tree — pure-sync and
568
- // backend-free, run BEFORE `state.postcode` is read so an excluded span can never become the
569
- // address's postcode. Opt-in (`postcodeShapeCoherence: true`), OFF by default (D-rule: demotion
570
- // is the failure mode with teeth). A confirmed span's narrowed systems — the intersection of
571
- // its codex shape with the tree's confident sibling systems — bound the country-scope pass
572
- // below; a pure subset of codex's own candidate list, so it can only narrow, never widen.
573
- // See postcode-shape-coherence.ts.
574
- const shapeVerdict = opts.postcodeShapeCoherence === true ? applyPostcodeShapeCoherence(tree.roots) : null;
575
- const state = {
576
- lookupsRemaining: opts.maxLookups ?? 10,
577
- // Full replacement when `placetypeMap` is supplied — callers that want to extend rather
578
- // than replace should spread DEFAULT_PLACETYPE_MAP themselves.
579
- placetypeMap: opts.placetypeMap ?? DEFAULT_PLACETYPE_MAP,
580
- minWinningScore: opts.minWinningScore ?? 0,
581
- candidatesPerLookup: opts.candidatesPerLookup ?? 5,
582
- defaultCountry: opts.defaultCountry,
583
- parentFallback: opts.parentFallback ?? true,
584
- postcode: firstPostcodeValue(tree.roots),
585
- // #31 Mechanism 2 — forwarded to locality lookups (see #lookupAndPick). Opt-in, OFF by default.
586
- postcodeContainmentCoherence: opts.postcodeContainmentCoherence === true,
587
- // #31 Mechanism 3 — the prefix prior + its injected index (see #lookupAndPick). Opt-in, OFF by default.
588
- postcodePrefixPrior: opts.postcodePrefixPrior === true,
589
- postcodePrefixIndex: opts.postcodePrefixIndex,
590
- bias: opts.bias,
591
- anchorPosterior: opts.anchorPosterior,
592
- anchorWeight: opts.anchorWeight ?? 2,
593
- localeCountryPrior: opts.localeCountryPrior,
594
- localeCountryPriorWeight: opts.localeCountryPriorWeight ?? DEFAULT_COUNTRY_PRIOR_WEIGHT,
595
- hardCountry: opts.hardCountry,
596
- // Default-ON (#402): completion only fires for a dual-role region whose locality the parser
597
- // dropped, and no-ops entirely when the backend has no relation (the browser WASM resolver, or
598
- // a gazetteer without `coincident_roles`). Pass `hierarchyCompletion: false` to opt out.
599
- hierarchyCompletion: opts.hierarchyCompletion ?? true,
600
- includeAncestors: opts.includeAncestors ?? false,
601
- localityNodePresent: false,
602
- resolvedRegion: null,
603
- resolvedRegionNode: null,
604
- };
605
- // Postcode-country coherence (#42): the one pre-walk LOOKUP pass (the shape verdict above is
606
- // pure-sync, backend-free), and the only mechanism allowed to override `defaultCountry`. Its three
607
- // sibling coherence passes re-pick nodes AFTER the walk; that shape cannot work here, because what
608
- // needs correcting is the walk's country SCOPE — which poisons the postcode node's own resolution,
609
- // the postcode-consistency fallback that then drags the locality onto it, and the hard `country`
610
- // filter on every admin lookup. So the verdict is taken once, up front, and the walk runs under the
611
- // corrected country. Default-ON (operator-promoted 2026-08-05; `false` opts out) — needs a default
612
- // country to correct and both a postcode and a locality to be coherent about; abstains unless
613
- // EXACTLY one country (never the already-coherent default) makes the pair consistent. See
614
- // postcode-country-coherence.ts.
615
- let postcodeScope = null;
616
- if (opts.postcodeCountryCoherence !== false && state.defaultCountry && state.postcode) {
617
- postcodeScope = await findPostcodeCountryScope(tree.roots, this.#backend, {
618
- postcode: state.postcode,
619
- defaultCountry: state.defaultCountry,
620
- ...(shapeVerdict?.narrowing !== undefined ? { candidateSystems: shapeVerdict.narrowing } : {}),
621
- ...(opts.postcodeCountryCoherenceGateKm !== undefined ? { gateKm: opts.postcodeCountryCoherenceGateKm } : {}),
622
- });
623
- if (postcodeScope) {
624
- // The override. `hardCountry` is not cleared because it is never consulted while a
625
- // `defaultCountry` is set (`#lookupAndPick`'s precedence chain reaches it only as the last
626
- // fallback), so replacing the default is sufficient to re-scope the entire walk.
627
- state.defaultCountry = postcodeScope.country;
628
- }
629
- }
630
- const newRoots = [];
631
- for (const root of tree.roots) {
632
- newRoots.push(await this.#walk(root, /* parentResolved */ null, state));
633
- }
634
- // Attribution for the override, stamped on the two nodes that bought it. Additive metadata only.
635
- if (postcodeScope) {
636
- stampPostcodeCountryScope(newRoots, postcodeScope);
637
- }
638
- // Dual-role hierarchy completion (#405/#415). Only when enabled, a region resolved, and the parser
639
- // emitted NO locality — record the dropped locality as a SECONDARY ROLE (an interpretation) on the
640
- // resolved region node, from the backend's precomputed coincident-roles relation (#403). One node,
641
- // one span, two roles — no synthesized sibling. See ResolveOpts.hierarchyCompletion.
642
- if (state.hierarchyCompletion && state.resolvedRegion && state.resolvedRegionNode && !state.localityNodePresent) {
643
- this.#completeRegionRole(state.resolvedRegion, state.resolvedRegionNode);
644
- }
645
- // Admin descendant-consistency (#263): default-ON (#895 settled drift D1; `false` opts out). Re-pick a
646
- // (region, locality) pair so the locality descends from the region — runs BEFORE postcode-consistency
647
- // (it resolves the locality the postcode pass may then refine) and before the street tiers (which key
648
- // off the postcode/street, not the admin coordinate this adjusts). Byte-stable when nothing fell
649
- // through or the backend lacks `ancestors`.
650
- if (opts.adminCoherence !== false) {
651
- await applyAdminCoherence(newRoots, this.#backend);
652
- // #822 — same joint-consistency family, inverse trigger: an explicit country token whose resolved
653
- // locality landed in the wrong country (the populous US namesake). Runs after the region pass so the
654
- // two never contend (region-fallthrough vs resolved-but-foreign are disjoint locality states).
655
- await applyExplicitCountryCoherence(newRoots, this.#backend);
656
- // Region-country coherence: a region qualifier the locale-inferred default-country hard filter could not
657
- // resolve (a foreign subdivision — "Montreal QC" under a US locale). The default filter discarded "QC" and
658
- // force-matched the locality to the US namesake; this re-resolves the subdivision + its same-named locality
659
- // under the subdivision's OWN country. Disjoint from the two passes above (unresolved region + resolved
660
- // locality); evidence-gated + byte-stable on the domestic path (a US region resolves under `US`).
661
- await applyRegionCountryCoherence(newRoots, this.#backend, state.defaultCountry);
662
- }
663
- // Postcode-consistency (#370 "Lever A"): default-ON (promoted 2026-07-04 — the corrected gate:
664
- // FI 231/0, SI 37/6, CZ 47/2, US byte-flat; see the ResolveOpts docstring). After the admin walk
665
- // (needs both the locality and the postcode resolved) and before the street tiers (which key off
666
- // the postcode/street, not the locality coordinate this adjusts). `false` opts out, byte-stable.
667
- if (opts.postcodeConsistency !== false) {
668
- applyPostcodeConsistency(newRoots, opts.postcodeConsistencyGateKm ?? 50);
669
- }
670
- // Address-point tier (#476): opt-in street-level exact match. After the admin walk so the
671
- // tier can never disturb admin attribution — it only ADDS the precise coordinate. Byte-stable
672
- // when opts.addressPoints is absent.
673
- if (opts.addressPoints) {
674
- applyAddressPoint(newRoots, opts.addressPoints, opts.addressPointBboxFallback);
675
- }
676
- // Interpolation tier (#483): strictly AFTER the exact-point block so an estimate can never
677
- // override a real situs point (applyInterpolation also gates on resolution_tier). Opt-in;
678
- // byte-stable when opts.interpolation is absent.
679
- if (opts.interpolation) {
680
- applyInterpolation(newRoots, opts.interpolation, opts.interpolationRadiusCalibration);
681
- }
682
- // Span-rescore tier (#370): default-ON (promoted 2026-06-25 — same-harness EU+AU +1pp @25km,
683
- // zero regressions: CZ 90→95, AT 70→73, PL 88→90, IT/PT/FR/AU flat, no-result 4→3%; fires last
684
- // so it only runs when every other tier left the tree unresolved, hence inert on the well-resolved
685
- // US path). Explicit opt-OUT via `spanRescore: false`; byte-stable then.
686
- if (opts.spanRescore !== false) {
687
- await applySpanRescore(newRoots, tree.raw, this.#backend, opts);
688
- }
689
- // A failed admin walk can leave the exact-point tier without a locality even though span-rescore
690
- // recovers one immediately afterward (for example, a locality the model tagged as `region`). Give
691
- // the exact register one bounded retry with that newly established scope. An existing situs hit is
692
- // returned early by applyAddressPoint, so the normal path performs no duplicate lookup; interpolation
693
- // remains subordinate because an exact point is allowed to replace its estimate.
694
- if (opts.addressPoints) {
695
- applyAddressPoint(newRoots, opts.addressPoints, opts.addressPointBboxFallback);
696
- }
697
- // Street-centroid tier (#1042): LAST, after span-rescore, so it can (a) union the span-rescore-recovered
698
- // country into its FR/national country hints (a placer-misrouted street — "Rue Sainte-Catherine" → IT — leaves
699
- // admin unresolved, and only span-rescore recovers the FR country signal) and (b) override a coarse recovered
700
- // locality with the exact street centroid. Self-gates on no house number + no existing street-level tier, so a
701
- // rooftop query is untouched; byte-stable when opts.streetCentroids absent.
702
- if (opts.streetCentroids) {
703
- applyStreetCentroid(newRoots, tree.raw, opts.streetCentroids, opts.streetCountryHints ?? []);
704
- }
705
- return { raw: tree.raw, roots: newRoots };
706
- }
707
- /**
708
- * Record a dropped dual-role locality as a `locality` INTERPRETATION on the resolved region node (#415, generalizes
709
- * #405's synthesized node). Consults `coincidentLocalitiesFor(regionID)` (O(1) map lookup — no distance math, no
710
- * backend query), picks the principal city ({@link pickCompletion}: population-primary, distance tiebreak, abstain on
711
- * a genuine tie), and appends an interpretation to `regionNode.interpretations`. No-op when the backend has no
712
- * relation, the region isn't a dual-role place, or it abstains. The region node's primary role stays `region`; the
713
- * locality rides alongside.
714
- */
715
- #completeRegionRole(region, regionNode) {
716
- if (typeof region.id !== "number" || !this.#backend.coincidentLocalitiesFor)
717
- return;
718
- const loc = pickCompletion(this.#backend.coincidentLocalitiesFor(region.id));
719
- if (!loc)
720
- return;
721
- const interpretation = {
722
- tag: "locality",
723
- placeID: `wof:${loc.id}`,
724
- sourceID: `${loc.placetype}:${loc.id}`,
725
- lat: loc.lat,
726
- lon: loc.lon,
727
- confidence: 0,
728
- metadata: { relationship_type: loc.relationshipType, resolver_completed: true, resolver_name: loc.name },
729
- };
730
- regionNode.interpretations = [...(regionNode.interpretations ?? []), interpretation];
731
- }
732
- async #walk(node, parentResolved, state) {
733
- // Always clone — never mutate input nodes.
734
- const decorated = { ...node, children: [] };
735
- const placetype = state.placetypeMap[node.tag];
736
- // Track locality presence for hierarchy completion (#405): completion must NOT fire if the parser
737
- // already emitted a locality node (even one that failed to resolve) — it only fills a genuine
738
- // gap. Cheap and always-on; only consulted when hierarchyCompletion is set.
739
- if (placetype === "locality") {
740
- state.localityNodePresent = true;
741
- }
742
- let resolved = null;
743
- // Shape-excluded postcode spans (letter-bearing ones keep their tag; #31 Mechanism 1) are
744
- // stripped of their resolve contribution — the walk does not look them up. Digit-only excluded
745
- // spans were retagged to `house_number` and flow through their correct sibling placetype.
746
- if (placetype && state.lookupsRemaining > 0 && node.value.trim().length && !isShapeExcludedPostcode(node)) {
747
- const picked = await this.#lookupAndPick(node, placetype, parentResolved, state);
748
- if (picked) {
749
- resolved = picked.top;
750
- decorateNode(decorated, picked.top, picked.alternatives);
751
- if (picked.metadata) {
752
- decorated.metadata = { ...decorated.metadata, ...picked.metadata };
753
- }
754
- // Lineage attachment (#404): stamp the resolved place's ancestor chain onto metadata. Opt-in
755
- // + only when the backend supplies it, so the default stays byte-identical (no extra query).
756
- if (state.includeAncestors && this.#backend.ancestors) {
757
- decorated.metadata = { ...decorated.metadata, ancestors: this.#backend.ancestors(picked.top.id) };
758
- }
759
- // Capture the first resolved region (place + node) for hierarchy completion — the locality
760
- // interpretation is pushed onto this node in the post-walk pass.
761
- if (placetype === "region" && state.resolvedRegion === null) {
762
- state.resolvedRegion = picked.top;
763
- state.resolvedRegionNode = decorated;
764
- }
765
- }
766
- }
767
- const carryParent = resolved ?? parentResolved;
768
- for (const child of node.children) {
769
- decorated.children.push(await this.#walk(child, carryParent, state));
770
- }
771
- return decorated;
772
- }
773
- async #lookupAndPick(node, placetype, parentResolved, state) {
774
- state.lookupsRemaining--;
775
- const query = {
776
- text: node.value,
777
- placetype,
778
- limit: state.candidatesPerLookup,
779
- };
780
- // Proximity bias (viewport center, user location, …) — a SOFT re-rank the backend folds into
781
- // its exact-tier prominence; never a filter, so recall is untouched. This is how an ambiguous
782
- // bare postcode ("48026") follows the map view instead of a global population coin-flip.
783
- if (state.bias && state.bias.length) {
784
- query.bias = state.bias;
785
- }
786
- // Pass the inherited parent constraint to the backend when available — `parentID` scopes to
787
- // the resolved parent's descendants. For `country`: a resolved parent's country wins, else
788
- // fall back to the caller's `defaultCountry`. Without this top-level hint a bare "IL" over a
789
- // multi-country gazetteer fuzzy-matches a foreign place (e.g. a French region) — see the
790
- // Direction-C resolver eval.
791
- if (parentResolved && typeof parentResolved.id === "number") {
792
- query.parentID = parentResolved.id;
793
- }
794
- // #194: a resolved parent's country wins, then the caller's `defaultCountry`, then the confident
795
- // placer `hardCountry`. All three are a HARD candidate filter. The placer's `hardCountry` is gated
796
- // upstream on high confidence (so it only fires when the model is sure), and on a miss the node is
797
- // left UNRESOLVED rather than re-resolved globally: the off-continent rows are precisely the ones
798
- // whose locality isn't in the country's gazetteer slice, so a global retry would just re-admit the
799
- // wrong-continent guess the hard filter exists to drop ("in-region or unresolved"). Measured: a
800
- // global fallback collapses back to the soft-prior baseline (FI p90 3050, PL p90 1078); pure-hard
801
- // collapses the tail (FI 18 km, PL p99 8172→494) at a coverage-bounded recall cost.
802
- // #833 forward linkage: a node's own `country_hint` (an address-system recognizer's derived country —
803
- // today `recognizeUSRegions` stamping "US" on a recognized closed-set US state) constrains THIS node's
804
- // lookup when the caller supplied no locale/default country. A caller scope outranks this derived hint:
805
- // `WA` is both Washington and Western Australia, so en-AU must reach the AU candidate instead of being
806
- // overwritten by the US-only recognizer. A genuine foreign subdivision under the wrong locale is recovered
807
- // later by region-country coherence after the scoped lookup abstains.
808
- const countryHint = node.metadata?.["country_hint"];
809
- const country = parentResolved?.country ??
810
- state.defaultCountry ??
811
- (typeof countryHint === "string" ? countryHint : undefined) ??
812
- state.hardCountry;
813
- if (country) {
814
- query.country = country;
815
- }
816
- // Coordinate-first: hand the sibling postcode to locality lookups so the backend can inject
817
- // postcode-proximal candidates the name-match would miss. Only for locality (the placetype both
818
- // `locality` and `dependent_locality` map to); other placetypes ignore it. The containment flag
819
- // (#31, Mechanism 2) asks a coordinate-first backend to re-rank the candidates by proximity to
820
- // the postcode's own centroid — opt-in, OFF by default.
821
- if (placetype === "locality" && state.postcode) {
822
- query.postcode = state.postcode;
823
- if (state.postcodeContainmentCoherence) {
824
- query.postcodeContainmentCoherence = true;
825
- }
826
- }
827
- 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);
839
- }
840
- }
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;
845
- }
846
- // Postcode-prefix prior (#31, Mechanism 3): when a `postalcode` node misses the gazetteer, derive
847
- // the code's prefix and probe the injected PFX1 index (structural — never a model input). A hit
848
- // resolves the node to a synthetic place (id 0), carrying a coordinate ONLY when the index node
849
- // does — the ancestry-only tier stays coordinate-free (B3-3's 0% half, meaning-of-zero). The
850
- // prior's payload is returned as node metadata for #walk to stamp. Opt-in via `postcodePrefixPrior`
851
- // + `postcodePrefixIndex`; OFF by default (D-rule: the PCN1 posture).
852
- if (!candidates.length && placetype === "postalcode" && state.postcodePrefixPrior && state.postcodePrefixIndex) {
853
- const probe = probePostcodePrefix(node.value, state.postcodePrefixIndex, query.country);
854
- if (probe) {
855
- const metadata = {
856
- postcode_prefix: probe.prefix,
857
- postcode_prefix_ancestors: probe.node.ancestors,
858
- ...(probe.node.radiusP95Km !== undefined ? { postcode_prefix_radius_p95_km: probe.node.radiusP95Km } : {}),
859
- ...(probe.node.lat !== undefined && probe.node.lon !== undefined
860
- ? { coordinate_source: "postcode_prefix" }
861
- : {}),
862
- };
863
- return {
864
- top: postcodePrefixResolvedPlace(probe.prefix, probe.node, state.postcodePrefixIndex),
865
- alternatives: [],
866
- metadata,
867
- };
868
- }
869
- }
870
- if (!candidates.length)
871
- return null;
872
- // Postcode-anchor re-rank (#369): when a country posterior is supplied (from the address's
873
- // postcode), boost candidates by `anchorWeight * posterior[candidate.country]` and re-sort, so a
874
- // postcode that pins the country pulls the right-country place over a higher-BM25 foreign namesake
875
- // (the "Berlin DE vs Berlin US" class the #59 harness measured). No-op when `anchorPosterior` is
876
- // undefined (the default) → byte-identical resolution.
877
- //
878
- // Applied to BOTH region and locality — the two placetypes that suffer cross-country namesake/
879
- // abbreviation collisions a country posterior can break. The region case is the one #447's window
880
- // fix couldn't reach: a bare 2-letter abbreviation is shared across countries ("VT" is
881
- // both Vermont and Viterbo; "ME" both Maine and Messina), so with no country signal the score
882
- // picks the wrong one — and because resolveTree resolves region FIRST and inherits its country
883
- // down, a wrong region poisons the locality too. The postcode posterior breaks the tie at the
884
- // region, and the right country then flows to the locality. (Country/macroregion/county are
885
- // excluded: they don't exhibit this collision class and carry country via `parentID` when nested.)
886
- //
887
- // Tier-SAFE ordering: the candidate's exact-match flag is the PRIMARY key, so the country pin
888
- // never crosses the exact/partial boundary. WITHIN a tier, `score + anchorWeight * posterior`
889
- // applies the (soft) country boost. So a confident US postcode keeps the US EXACT region
890
- // ("ME" → Maine) ahead of a more-populous US PARTIAL match (Missouri) AND, within the exact
891
- // tier, ahead of a foreign exact match (Messina IT); a soft posterior still blends with score.
892
- // (A plain additive re-rank loses the tier — it isn't encoded in `score` — and flips
893
- // "ME" → Missouri / "PA" → Alabama. Backends that don't set `exactMatch` degrade to additive.)
894
- const anchorEligible = placetype === "region" || placetype === "locality";
895
- let ranked = candidates;
896
- if (state.anchorPosterior && anchorEligible && candidates.length > 1) {
897
- const post = state.anchorPosterior;
898
- const w = state.anchorWeight;
899
- // #928 root cause: this sort's within-tier key was `score + w·posterior` — RAW SCORE order,
900
- // the exact metric #910 deprecated inside the exact tier as bm25-length-poisoned (a famous
901
- // place's alias-heavy doc reads ~15 pts WORSE than a tiny namesake's clean one; #905
902
- // measured it). Before #910 the anchor-off path also sorted by score, so the two paths
903
- // agreed; after, anchor-ON silently reverted to the poisoned metric — a CORRECT GB@1.00
904
- // pin flipped "London SE15 1DD" to a US namesake because +w·1.0 can't bridge the bm25 gap.
905
- // The within-tier key is now the backend's PROMINENCE (population + proximity, #938 units)
906
- // with the posterior as the additive country pin; score stays the final tiebreak. Backends
907
- // that don't populate `prominence` degrade to the additive score behavior.
908
- // oxlint-disable-next-line unicorn/no-array-sort -- sorts a freshly-built array; toSorted would double-allocate on a hot path
909
- ranked = [...candidates].sort((a, b) => {
910
- const tier = Number(b.exactMatch ?? false) - Number(a.exactMatch ?? false);
911
- if (tier !== 0)
912
- return tier;
913
- const aKey = (a.prominence ?? a.score) + w * (post[a.country] ?? 0);
914
- const bKey = (b.prominence ?? b.score) + w * (post[b.country] ?? 0);
915
- return bKey - aKey || b.score - a.score;
916
- });
917
- }
918
- // Locale-country soft prior (#27) — the #912 lever's other half, at the tier that decides a bare
919
- // toponym the model tagged `locality`. `--locale en-GB "Whitby"` answers Whitby, Ontario while
920
- // `--default-country GB "Whitby"` answers the gold, because the CLI DROPS the locale-inferred
921
- // country for this shape rather than choosing between "hard filter" and "nothing". This is the
922
- // third option: an additive bonus inside the exact tier, never a filter.
923
- //
924
- // Three stand-downs, in the order they matter. A `defaultCountry` makes the prior a no-op by
925
- // construction (every candidate is already in it), so we skip the work rather than pretend. An
926
- // `anchorPosterior` is derived from the address's OWN postcode — evidence, which outranks a guess
927
- // about where the user is sitting. And an absent prior is the SHIPPED default: `ResolveOpts`
928
- // documents why (the weight that flips the four bare GB rows and the weight that holds the en-US
929
- // board are disjoint intervals), so this is inert unless a caller opts in.
930
- //
931
- // Runs BEFORE the importance key deliberately, matching span-rescore: fame is the stronger signal
932
- // wherever it has been measured, and it leaves an unscored candidate exactly where the prior put it.
933
- if (state.localeCountryPrior && !state.defaultCountry && !state.anchorPosterior && anchorEligible) {
934
- ranked = rankByCountryPrior(ranked, state.localeCountryPrior, state.localeCountryPriorWeight);
935
- }
936
- // Importance-first (#17/#28). Before this key a bare famous name was decided on POPULATION
937
- // alone, which is measurably the wrong prior for the class: `Whitby` answered Whitby, Ontario
938
- // (128,377) over Whitby, North Yorkshire (13,130), 5,508 km from where the person meant. Fame is
939
- // what a bare toponym is asking about, and the candidate build's blended `importance` column
940
- // measures it. Tier-safe and positive-evidence-only (an UNSCORED candidate keeps the rank
941
- // population gave it; only the scored ones permute), so it abstains byte-stably on an artifact
942
- // that predates the column.
943
- //
944
- // Skipped outright when an anchor posterior is in force. Fame is the prior of LAST resort: it answers
945
- // "which one did you probably mean" only when nothing in the query answered it, and a #369 posterior is
946
- // derived from the address's OWN postcode. Evidence outranks a prior. See `toponym-prior.ts`.
947
- if (!state.anchorPosterior) {
948
- ranked = rankByImportance(ranked);
949
- }
950
- // Exact-type preference (#718): when the placetype-equivalence group let a broader admin tier
951
- // (`macroregion`/`macrocounty`) into the candidate pool, prefer a candidate of the EXACT
952
- // requested type over the macro fallback — a real `region` (US state, DE Bundesland, ES
953
- // provincia) must win over a same-name macroregion namesake, so no real region silently
954
- // downgrades to a macro. STABLE partition: exact-type candidates keep their (already-ranked)
955
- // relative order ahead of fallbacks, so the score / anchor re-rank survives WITHIN each tier.
956
- // No-op for placetypes without a macro fallback (the byte-stable default) and when every
957
- // candidate is the same tier.
958
- const hasFallbackCandidate = ranked.some((c) => isPlacetypeFallback(placetype, c.placetype));
959
- if (hasFallbackCandidate && ranked.length > 1) {
960
- ranked = [
961
- ...ranked.filter((c) => !isPlacetypeFallback(placetype, c.placetype)),
962
- ...ranked.filter((c) => isPlacetypeFallback(placetype, c.placetype)),
963
- ];
964
- }
965
- const top = ranked[0];
966
- if (top.score < state.minWinningScore)
967
- return null;
968
- // Fallback-observability (#718): if the winner is a macro-type AND no exact-type candidate
969
- // existed for this span, annotate that a broader tier stood in for the true one. Additive —
970
- // identity/coordinate are unchanged; only `metadata.resolution_quality` is stamped downstream.
971
- if (isPlacetypeFallback(placetype, top.placetype)) {
972
- top.resolutionQuality = "fallback";
973
- }
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;
1047
- }
1048
- }
1049
- //# sourceMappingURL=resolve.js.map