@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.
- package/README.md +89 -0
- package/lib/admin/coherence-passes.ts +435 -0
- package/lib/admin/containment.ts +92 -0
- package/lib/admin/index.ts +10 -0
- package/lib/admin/jp-municipality.ts +97 -0
- package/lib/admin/winner.ts +189 -0
- package/lib/backend-capabilities.ts +88 -0
- package/lib/bare-toponym-race.ts +129 -0
- package/lib/decorate-node.ts +127 -0
- package/lib/fold-name.ts +36 -0
- package/{index.ts → lib/index.ts} +27 -18
- package/{plausibility.ts → lib/plausibility.ts} +5 -4
- package/{postcode-country-coherence.ts → lib/postcode/country-coherence.ts} +173 -86
- package/lib/postcode/index.ts +9 -0
- package/{postcode-prefix.ts → lib/postcode/prefix.ts} +7 -6
- package/{postcode-shape-coherence.ts → lib/postcode/shape-coherence.ts} +10 -24
- package/{remote-resolver.ts → lib/remote-resolver.ts} +13 -4
- package/{rerank.ts → lib/rerank.ts} +2 -2
- package/lib/resolve/index.ts +982 -0
- package/lib/resolve/passes.ts +544 -0
- package/{span-rescore.ts → lib/span-rescore.ts} +114 -99
- package/{street-evidence.ts → lib/street/evidence.ts} +40 -7
- package/lib/street/index.ts +8 -0
- package/{street-tier.ts → lib/street/tier.ts} +138 -99
- package/{toponym-prior.ts → lib/toponym-prior.ts} +97 -8
- package/out/admin/coherence-passes.d.ts +70 -0
- package/out/admin/coherence-passes.d.ts.map +1 -0
- package/out/admin/coherence-passes.js +327 -0
- package/out/admin/coherence-passes.js.map +1 -0
- package/out/admin/containment.d.ts +48 -0
- package/out/admin/containment.d.ts.map +1 -0
- package/out/admin/containment.js +76 -0
- package/out/admin/containment.js.map +1 -0
- package/out/admin/index.d.ts +10 -0
- package/out/admin/index.d.ts.map +1 -0
- package/out/admin/index.js +10 -0
- package/out/admin/index.js.map +1 -0
- package/out/admin/jp-municipality.d.ts +50 -0
- package/out/admin/jp-municipality.d.ts.map +1 -0
- package/out/admin/jp-municipality.js +54 -0
- package/out/admin/jp-municipality.js.map +1 -0
- package/out/admin/winner.d.ts +114 -0
- package/out/admin/winner.d.ts.map +1 -0
- package/out/admin/winner.js +130 -0
- package/out/admin/winner.js.map +1 -0
- package/out/backend-capabilities.d.ts +37 -0
- package/out/backend-capabilities.d.ts.map +1 -0
- package/out/backend-capabilities.js +75 -0
- package/out/backend-capabilities.js.map +1 -0
- package/out/bare-toponym-race.d.ts +55 -0
- package/out/bare-toponym-race.d.ts.map +1 -0
- package/out/bare-toponym-race.js +110 -0
- package/out/bare-toponym-race.js.map +1 -0
- package/out/decorate-node.d.ts +24 -0
- package/out/decorate-node.d.ts.map +1 -0
- package/out/decorate-node.js +103 -0
- package/out/decorate-node.js.map +1 -0
- package/out/fold-name.d.ts +18 -3
- package/out/fold-name.d.ts.map +1 -1
- package/out/fold-name.js +19 -3
- package/out/fold-name.js.map +1 -1
- package/out/index.d.ts +15 -12
- package/out/index.d.ts.map +1 -1
- package/out/index.js +9 -7
- package/out/index.js.map +1 -1
- package/out/plausibility.d.ts +5 -4
- package/out/plausibility.d.ts.map +1 -1
- package/out/plausibility.js +5 -4
- package/out/plausibility.js.map +1 -1
- package/out/{postcode-country-coherence.d.ts → postcode/country-coherence.d.ts} +46 -25
- package/out/postcode/country-coherence.d.ts.map +1 -0
- package/out/{postcode-country-coherence.js → postcode/country-coherence.js} +157 -77
- package/out/postcode/country-coherence.js.map +1 -0
- package/out/postcode/index.d.ts +9 -0
- package/out/postcode/index.d.ts.map +1 -0
- package/out/postcode/index.js +9 -0
- package/out/postcode/index.js.map +1 -0
- package/out/{postcode-prefix.d.ts → postcode/prefix.d.ts} +4 -4
- package/out/postcode/prefix.d.ts.map +1 -0
- package/out/{postcode-prefix.js → postcode/prefix.js} +7 -6
- package/out/postcode/prefix.js.map +1 -0
- package/out/{postcode-shape-coherence.d.ts → postcode/shape-coherence.d.ts} +3 -3
- package/out/postcode/shape-coherence.d.ts.map +1 -0
- package/out/{postcode-shape-coherence.js → postcode/shape-coherence.js} +11 -20
- package/out/postcode/shape-coherence.js.map +1 -0
- package/out/remote-resolver.d.ts +18 -3
- package/out/remote-resolver.d.ts.map +1 -1
- package/out/remote-resolver.js +2 -2
- package/out/remote-resolver.js.map +1 -1
- package/out/rerank.d.ts +1 -1
- package/out/rerank.d.ts.map +1 -1
- package/out/rerank.js +2 -2
- package/out/rerank.js.map +1 -1
- package/out/{resolve.d.ts → resolve/index.d.ts} +2 -2
- package/out/resolve/index.d.ts.map +1 -0
- package/out/resolve/index.js +795 -0
- package/out/resolve/index.js.map +1 -0
- package/out/resolve/passes.d.ts +218 -0
- package/out/resolve/passes.d.ts.map +1 -0
- package/out/resolve/passes.js +333 -0
- package/out/resolve/passes.js.map +1 -0
- package/out/span-rescore.d.ts +16 -16
- package/out/span-rescore.d.ts.map +1 -1
- package/out/span-rescore.js +87 -71
- package/out/span-rescore.js.map +1 -1
- package/out/{street-evidence.d.ts → street/evidence.d.ts} +18 -3
- package/out/street/evidence.d.ts.map +1 -0
- package/out/{street-evidence.js → street/evidence.js} +23 -7
- package/out/street/evidence.js.map +1 -0
- package/out/street/index.d.ts +8 -0
- package/out/street/index.d.ts.map +1 -0
- package/out/street/index.js +8 -0
- package/out/street/index.js.map +1 -0
- package/out/{street-tier.d.ts → street/tier.d.ts} +14 -3
- package/out/street/tier.d.ts.map +1 -0
- package/out/{street-tier.js → street/tier.js} +127 -90
- package/out/street/tier.js.map +1 -0
- package/out/toponym-prior.d.ts +43 -19
- package/out/toponym-prior.d.ts.map +1 -1
- package/out/toponym-prior.js +76 -8
- package/out/toponym-prior.js.map +1 -1
- package/package.json +167 -19
- package/vitest.config.ts +5 -6
- package/fold-name.ts +0 -20
- package/out/postcode-country-coherence.d.ts.map +0 -1
- package/out/postcode-country-coherence.js.map +0 -1
- package/out/postcode-prefix.d.ts.map +0 -1
- package/out/postcode-prefix.js.map +0 -1
- package/out/postcode-shape-coherence.d.ts.map +0 -1
- package/out/postcode-shape-coherence.js.map +0 -1
- package/out/resolve.d.ts.map +0 -1
- package/out/resolve.js +0 -1049
- package/out/resolve.js.map +0 -1
- package/out/street-evidence.d.ts.map +0 -1
- package/out/street-evidence.js.map +0 -1
- package/out/street-tier.d.ts.map +0 -1
- package/out/street-tier.js.map +0 -1
- package/out/vitest.config.d.ts +0 -16
- package/out/vitest.config.d.ts.map +0 -1
- package/out/vitest.config.js +0 -36
- package/out/vitest.config.js.map +0 -1
- package/resolve.ts +0 -1369
package/resolve.ts
DELETED
|
@@ -1,1369 +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
|
-
|
|
15
|
-
import { matchCountry, matchSubdivision } from "@mailwoman/codex/country"
|
|
16
|
-
import { isStreetDirectionalToken } from "@mailwoman/codex/us"
|
|
17
|
-
import type { AddressNode, AddressTree, ComponentTag, Interpretation } from "@mailwoman/core/decoder"
|
|
18
|
-
import {
|
|
19
|
-
type AddressPointLookup,
|
|
20
|
-
type CoincidentLocality,
|
|
21
|
-
compareReferential,
|
|
22
|
-
DEFAULT_PLACETYPE_MAP,
|
|
23
|
-
type InterpolationLookup,
|
|
24
|
-
isPlacetypeFallback,
|
|
25
|
-
type PlacetypeMap,
|
|
26
|
-
type PostcodePrefixIndexLike,
|
|
27
|
-
referentialFromPopulation,
|
|
28
|
-
type ResolvedPlace,
|
|
29
|
-
type ResolveOpts,
|
|
30
|
-
type Resolver,
|
|
31
|
-
type ResolverBackend,
|
|
32
|
-
type StreetCentroidLookup,
|
|
33
|
-
} from "@mailwoman/core/resolver"
|
|
34
|
-
import { haversineKm } from "@mailwoman/spatial"
|
|
35
|
-
|
|
36
|
-
import { foldName } from "./fold-name.ts"
|
|
37
|
-
import {
|
|
38
|
-
findPostcodeCountryScope,
|
|
39
|
-
type PostcodeCountryScope,
|
|
40
|
-
stampPostcodeCountryScope,
|
|
41
|
-
} from "./postcode-country-coherence.ts"
|
|
42
|
-
import { type CoordinateOptionalPlace, postcodePrefixResolvedPlace, probePostcodePrefix } from "./postcode-prefix.ts"
|
|
43
|
-
import { applyPostcodeShapeCoherence, isShapeExcludedPostcode } from "./postcode-shape-coherence.ts"
|
|
44
|
-
import { findRescoreCandidate, hasResolvedPlace, postcodeCodeSubset } from "./span-rescore.ts"
|
|
45
|
-
import { applyAddressPoint, applyInterpolation, applyStreetCentroid } from "./street-tier.ts"
|
|
46
|
-
import { DEFAULT_COUNTRY_PRIOR_WEIGHT, rankByCountryPrior, rankByImportance } from "./toponym-prior.ts"
|
|
47
|
-
|
|
48
|
-
/**
|
|
49
|
-
* Build a `Resolver` backed by a `ResolverBackend`. The backend can be any concrete impl structurally compatible with
|
|
50
|
-
* `PlaceLookup` — e.g. `new WOFSqlitePlaceLookup({ databasePath }).asResolverBackend()` or a fake for tests.
|
|
51
|
-
*/
|
|
52
|
-
export function createWOFResolver(backend: ResolverBackend): Resolver {
|
|
53
|
-
return new WOFResolver(backend)
|
|
54
|
-
}
|
|
55
|
-
|
|
56
|
-
interface ResolutionState {
|
|
57
|
-
lookupsRemaining: number
|
|
58
|
-
placetypeMap: PlacetypeMap
|
|
59
|
-
minWinningScore: number
|
|
60
|
-
candidatesPerLookup: number
|
|
61
|
-
defaultCountry?: string
|
|
62
|
-
parentFallback: boolean
|
|
63
|
-
/**
|
|
64
|
-
* The address's postcode string, extracted once up front, passed to locality lookups so a coordinate-first backend
|
|
65
|
-
* can inject postcode-proximal locality candidates.
|
|
66
|
-
*/
|
|
67
|
-
postcode?: string
|
|
68
|
-
/**
|
|
69
|
-
* Postcode-containment coherence (#31, Mechanism 2) — forwarded to locality lookups so a coordinate-first backend can
|
|
70
|
-
* re-rank name candidates by proximity to the postcode's own centroid. Opt-in; OFF by default.
|
|
71
|
-
*/
|
|
72
|
-
postcodeContainmentCoherence: boolean
|
|
73
|
-
/**
|
|
74
|
-
* Postcode-prefix prior (#31, Mechanism 3) — on a `postalcode` miss, derive the code's prefix and probe
|
|
75
|
-
* `postcodePrefixIndex`. Opt-in; OFF by default.
|
|
76
|
-
*/
|
|
77
|
-
postcodePrefixPrior: boolean
|
|
78
|
-
/**
|
|
79
|
-
* The injected PFX1 index (structural — `PostcodePrefixIndexLike`, core/resolver/types.ts). Absent = the prior cannot
|
|
80
|
-
* fire.
|
|
81
|
-
*/
|
|
82
|
-
postcodePrefixIndex?: PostcodePrefixIndexLike
|
|
83
|
-
/**
|
|
84
|
-
* Proximity-bias points (viewport, user location) — forwarded to every primary lookup.
|
|
85
|
-
*/
|
|
86
|
-
bias?: Array<{ lat: number; lon: number; weight?: number }>
|
|
87
|
-
/**
|
|
88
|
-
* Postcode-anchor country posterior (#369). Undefined = no re-rank (byte-stable default).
|
|
89
|
-
*/
|
|
90
|
-
anchorPosterior?: Record<string, number>
|
|
91
|
-
/**
|
|
92
|
-
* Weight on the posterior in the locality re-rank. Only used when `anchorPosterior` is set.
|
|
93
|
-
*/
|
|
94
|
-
anchorWeight: number
|
|
95
|
-
/**
|
|
96
|
-
* #27 locale-country SOFT prior for the bare-toponym admin walk. Undefined = no prior (the shipped default) →
|
|
97
|
-
* byte-stable. See `ResolveOpts.localeCountryPrior` for the calibration and why it ships opt-in.
|
|
98
|
-
*/
|
|
99
|
-
localeCountryPrior?: string
|
|
100
|
-
/**
|
|
101
|
-
* Weight of that prior in log10-population units. Only consulted when `localeCountryPrior` is set.
|
|
102
|
-
*/
|
|
103
|
-
localeCountryPriorWeight: number
|
|
104
|
-
/**
|
|
105
|
-
* #743/#194 confident-placer country as a HARD filter (empty→unresolved, no global retry). Off = undefined.
|
|
106
|
-
*/
|
|
107
|
-
hardCountry?: string
|
|
108
|
-
/**
|
|
109
|
-
* Dual-role hierarchy completion (#405). Off by default → byte-stable.
|
|
110
|
-
*/
|
|
111
|
-
hierarchyCompletion: boolean
|
|
112
|
-
/**
|
|
113
|
-
* Attach ancestor lineage to each resolved node (#404). Off by default → byte-stable.
|
|
114
|
-
*/
|
|
115
|
-
includeAncestors: boolean
|
|
116
|
-
/**
|
|
117
|
-
* Set while resolving when ANY tree node maps to the `locality` placetype (resolved or not) — the completion only
|
|
118
|
-
* fires when the parser emitted no locality at all, never to override one.
|
|
119
|
-
*/
|
|
120
|
-
localityNodePresent: boolean
|
|
121
|
-
/**
|
|
122
|
-
* The first region that resolved (its place — for the coincident-roles lookup).
|
|
123
|
-
*/
|
|
124
|
-
resolvedRegion: CoordinateOptionalPlace | null
|
|
125
|
-
/**
|
|
126
|
-
* The decorated region NODE that produced {@link resolvedRegion} — completion pushes the locality interpretation onto
|
|
127
|
-
* it in place (no synthesized sibling).
|
|
128
|
-
*/
|
|
129
|
-
resolvedRegionNode: AddressNode | null
|
|
130
|
-
}
|
|
131
|
-
|
|
132
|
-
/**
|
|
133
|
-
* Pick the completion locality when an admin maps to several coincident same-name candidates (#405). REFERENTIAL
|
|
134
|
-
* likelihood is the PRIMARY signal — the principal city is the populous one, and it can sit FARTHER from the admin
|
|
135
|
-
* centroid than a tiny same-name hamlet (the Niigata case from #403). Nearest centroid breaks a referential tie; a
|
|
136
|
-
* genuine tie (same population AND distance) ABSTAINS rather than guess.
|
|
137
|
-
*
|
|
138
|
-
* ROAD_TO_V9 §2: `compareReferential` is referential DESC with raw population as its own tiebreak, which is the SAME
|
|
139
|
-
* ORDER as the plain `b.population - a.population` it replaced — referential is strictly increasing in population below
|
|
140
|
-
* saturation and constant above it. The abstention check below still reads raw population, deliberately: two megacities
|
|
141
|
-
* that saturate to the same referential score are not tied, and abstaining there would be a new behavior.
|
|
142
|
-
*/
|
|
143
|
-
function pickCompletion(candidates: readonly CoincidentLocality[]): CoincidentLocality | null {
|
|
144
|
-
if (!candidates.length) return null
|
|
145
|
-
|
|
146
|
-
if (candidates.length === 1) return candidates[0]!
|
|
147
|
-
|
|
148
|
-
const ranked = [...candidates]
|
|
149
|
-
.map((c) => ({ c, referential: referentialFromPopulation(c.population), population: c.population }))
|
|
150
|
-
// oxlint-disable-next-line unicorn/no-array-sort -- sorts a freshly-built array; toSorted would double-allocate on a hot path
|
|
151
|
-
.sort((a, b) => compareReferential(a, b) || a.c.distanceKm - b.c.distanceKm)
|
|
152
|
-
.map((x) => x.c)
|
|
153
|
-
|
|
154
|
-
const [first, second] = ranked
|
|
155
|
-
|
|
156
|
-
if (first!.population === second!.population && first!.distanceKm === second!.distanceKm) return null
|
|
157
|
-
|
|
158
|
-
return first!
|
|
159
|
-
}
|
|
160
|
-
|
|
161
|
-
/**
|
|
162
|
-
* Find the first postcode value anywhere in the tree (a one-shot pre-scan; postcode and locality are siblings, so the
|
|
163
|
-
* top-down walk wouldn't otherwise let the locality lookup see it).
|
|
164
|
-
*/
|
|
165
|
-
function firstPostcodeValue(roots: readonly AddressNode[]): string | undefined {
|
|
166
|
-
const stack = [...roots]
|
|
167
|
-
|
|
168
|
-
while (stack.length) {
|
|
169
|
-
const n = stack.pop()!
|
|
170
|
-
|
|
171
|
-
// #31 Mechanism 1: a shape-excluded span keeps its tag but contributes nothing — its code
|
|
172
|
-
// must never become the address's postcode (it would poison the country-scope pass's anchor).
|
|
173
|
-
if (n.tag === "postcode" && !isShapeExcludedPostcode(n) && n.value.trim().length) return n.value.trim()
|
|
174
|
-
stack.push(...n.children)
|
|
175
|
-
}
|
|
176
|
-
|
|
177
|
-
return undefined
|
|
178
|
-
}
|
|
179
|
-
|
|
180
|
-
/**
|
|
181
|
-
* Span-rescore tier (#370): opt-in last-resort locality recovery. Runs ONLY when the tree resolved NOTHING (the #685
|
|
182
|
-
* brake — never disturb a working coordinate). Enumerates raw-token spans, exact- matches the same-country gazetteer
|
|
183
|
-
* (longest-wins + postcode-consistency gate; see `span-rescore.ts`), and on a hit INJECTS a resolved `locality` node
|
|
184
|
-
* decorated exactly like a normally-resolved one. Default-ON (#370, promoted 2026-06-25); byte-stable opt-out via
|
|
185
|
-
* `opts.spanRescore: false`. Async (it queries the backend), so it's awaited.
|
|
186
|
-
*/
|
|
187
|
-
async function applySpanRescore(
|
|
188
|
-
roots: AddressNode[],
|
|
189
|
-
raw: string,
|
|
190
|
-
backend: ResolverBackend,
|
|
191
|
-
opts: ResolveOpts
|
|
192
|
-
): Promise<void> {
|
|
193
|
-
if (hasResolvedPlace(roots)) return // already resolved — never second-guess a working coordinate
|
|
194
|
-
// Default-ON since 2026-06-25, so this runs on every unresolved tree — a backend hiccup here must
|
|
195
|
-
// degrade to no-rescore, never crash the resolve (the same fall-through the main walk gives).
|
|
196
|
-
let hit
|
|
197
|
-
|
|
198
|
-
try {
|
|
199
|
-
hit = await findRescoreCandidate(raw, roots, backend, {
|
|
200
|
-
country: opts.defaultCountry,
|
|
201
|
-
postcode: firstPostcodeValue(roots),
|
|
202
|
-
gateKm: opts.spanRescoreGateKm,
|
|
203
|
-
// Default-ON (promoted 2026-07-03); explicit `false` opts out — the spanRescore idiom.
|
|
204
|
-
postalCompoundRecovery: opts.postalCompoundRecovery !== false,
|
|
205
|
-
})
|
|
206
|
-
} catch {
|
|
207
|
-
return
|
|
208
|
-
}
|
|
209
|
-
|
|
210
|
-
// #942 postal-compound recovery, part 2: when NO city span matched, decorate the FAILED postcode
|
|
211
|
-
// node from its code-shaped token subset ("1382 Kožljek" → the bare "1382" row) — a postcode-tier
|
|
212
|
-
// coordinate FLOOR, strictly subordinate to a recovered locality. Only-on-miss matters: a GeoNames
|
|
213
|
-
// medoid postcode centroid is COARSER than the exact village centroid, and consumers that rank
|
|
214
|
-
// postcode above locality (the eval harness does) would otherwise trade a 0.2 km village pin for a
|
|
215
|
-
// 5 km area centroid. Same unresolved tree, so the #685 brake semantics hold.
|
|
216
|
-
if (!hit && opts.postalCompoundRecovery !== false) {
|
|
217
|
-
try {
|
|
218
|
-
await recoverPostcodeNode(roots, backend, opts.defaultCountry)
|
|
219
|
-
} catch {
|
|
220
|
-
// degrade to no-recovery, never crash the resolve
|
|
221
|
-
}
|
|
222
|
-
}
|
|
223
|
-
|
|
224
|
-
if (!hit) return
|
|
225
|
-
|
|
226
|
-
const node: AddressNode = {
|
|
227
|
-
tag: "locality",
|
|
228
|
-
value: hit.text,
|
|
229
|
-
start: hit.start,
|
|
230
|
-
end: hit.end,
|
|
231
|
-
// No model confidence for a post-hoc recovery; a mid-tier value marks it as recovered, not asserted.
|
|
232
|
-
confidence: 0.5,
|
|
233
|
-
children: [],
|
|
234
|
-
}
|
|
235
|
-
|
|
236
|
-
// #1537: the same-span namesake runner-ups, not an empty list. A name the model reads as a `street`
|
|
237
|
-
// ("Springfield", "Berlin", "Moscow") never reaches the admin walk, so this tier is the ONLY thing that
|
|
238
|
-
// resolves it — and decorating with `[]` meant the geocode path's `candidates` held one entry and the
|
|
239
|
-
// dominance margin `declared_ambiguity` reads was uncomputable for exactly the famous-homonym class.
|
|
240
|
-
// The winner is unchanged (see findRescoreCandidate); this is additive.
|
|
241
|
-
decorateNode(node, hit.place, hit.alternatives)
|
|
242
|
-
// `rescore_gated` carries the gate's precision signal as an EXPLICIT handle — NOT folded into the
|
|
243
|
-
// calibrated `confidence`, which would break the isotonic guarantee (a true calibrated 0.83 must not
|
|
244
|
-
// be confused with a rescore plug-in estimate; DeepSeek 2026-06-23). true = postcode gate fired
|
|
245
|
-
// (high-precision); false = ungated (no postcode→point coverage for this country, ~83%-precision).
|
|
246
|
-
node.metadata = { ...node.metadata, span_rescore: true, rescore_gated: hit.gated }
|
|
247
|
-
roots.push(node)
|
|
248
|
-
}
|
|
249
|
-
|
|
250
|
-
/**
|
|
251
|
-
* #942: find the first confident-but-UNRESOLVED postcode node whose value is a polluted compound ("1382 Kožljek"),
|
|
252
|
-
* resolve its code-shaped token subset as a `postalcode`, and decorate the node from that hit
|
|
253
|
-
* (`postal_compound_recovered` metadata marks the provenance). No-op when every postcode node resolved, the value has
|
|
254
|
-
* no digit-bearing tokens, or the subset equals the full value (then the walk already tried it).
|
|
255
|
-
*/
|
|
256
|
-
async function recoverPostcodeNode(
|
|
257
|
-
roots: AddressNode[],
|
|
258
|
-
backend: ResolverBackend,
|
|
259
|
-
country: string | undefined
|
|
260
|
-
): Promise<void> {
|
|
261
|
-
const stack: AddressNode[] = [...roots]
|
|
262
|
-
|
|
263
|
-
while (stack.length) {
|
|
264
|
-
const n = stack.pop()!
|
|
265
|
-
|
|
266
|
-
if (n.tag === "postcode" && !n.placeID && n.value.trim()) {
|
|
267
|
-
const code = postcodeCodeSubset(n.value)
|
|
268
|
-
|
|
269
|
-
if (!code || code === n.value.trim()) continue
|
|
270
|
-
const hits = await backend.findPlace({ text: code, placetype: "postalcode", country, limit: 1 })
|
|
271
|
-
const top = hits.find((h) => h.lat !== 0 || h.lon !== 0)
|
|
272
|
-
|
|
273
|
-
if (top) {
|
|
274
|
-
decorateNode(n, top, [])
|
|
275
|
-
n.metadata = { ...n.metadata, postal_compound_recovered: true }
|
|
276
|
-
}
|
|
277
|
-
|
|
278
|
-
return // first postcode node only — one recovery per tree
|
|
279
|
-
}
|
|
280
|
-
|
|
281
|
-
if (n.children?.length) {
|
|
282
|
-
stack.push(...n.children)
|
|
283
|
-
}
|
|
284
|
-
}
|
|
285
|
-
}
|
|
286
|
-
|
|
287
|
-
/**
|
|
288
|
-
* A resolved node carries a real coordinate (placeID set + non-zero lat/lon).
|
|
289
|
-
*/
|
|
290
|
-
function isResolvedWithCoord(n: AddressNode): boolean {
|
|
291
|
-
return !!(n.placeID && typeof n.lat === "number" && typeof n.lon === "number" && (n.lat !== 0 || n.lon !== 0))
|
|
292
|
-
}
|
|
293
|
-
|
|
294
|
-
/**
|
|
295
|
-
* Postcode-disambiguated locality selection (#370 "Lever A"). The single biggest miss on the EU/AU panel is a
|
|
296
|
-
* same-named town resolved to the WRONG instance — "06260 Saint-Pierre" lands 617 km off — while the postcode that
|
|
297
|
-
* would disambiguate it (06260 → Alpes-Maritimes) sits resolved in the same tree, discarded because the
|
|
298
|
-
* coordinate-picker prefers the (wrong) locality node and never cross- checks it. This post-walk pass closes that loop,
|
|
299
|
-
* backend-agnostically and with no extra query:
|
|
300
|
-
*
|
|
301
|
-
* 1. Find the resolved postcode's coordinate (the trustworthy anchor — a postcode is unambiguous within a country in a way
|
|
302
|
-
* a town name is not).
|
|
303
|
-
* 2. For each resolved locality node farther than `gateKm` from it: re-pick the same-named candidate from the node's
|
|
304
|
-
* already-captured `alternatives` that is NEAREST the postcode and within the gate. This keeps locality granularity
|
|
305
|
-
* at the CORRECT instance.
|
|
306
|
-
* 3. If no alternative reconciles, the locality instance is unreliable — fall its coordinate back to the postcode point
|
|
307
|
-
* (right area, the safe answer) and flag `postcode_city_mismatch`.
|
|
308
|
-
*
|
|
309
|
-
* Only fires where the postcode resolved to a point, so it composes with postcode coverage (#193) — add a country's
|
|
310
|
-
* postcodes and this immediately disambiguates its same-named towns. **Default-ON** since the #370 operator promotion
|
|
311
|
-
* (2026-07-04, commit `0010bb8c`) — `opts.postcodeConsistency: false` opts out, and the pass is byte-stable on every
|
|
312
|
-
* tree with no resolved postcode point (the `!anchor` early return below).
|
|
313
|
-
*/
|
|
314
|
-
function applyPostcodeConsistency(roots: readonly AddressNode[], gateKm: number): void {
|
|
315
|
-
// The resolved postcode anchor (first one with a real coordinate).
|
|
316
|
-
let anchor: { lat: number; lon: number } | null = null
|
|
317
|
-
const findAnchor: AddressNode[] = [...roots]
|
|
318
|
-
|
|
319
|
-
while (findAnchor.length) {
|
|
320
|
-
const n = findAnchor.pop()!
|
|
321
|
-
|
|
322
|
-
// #31 Mechanism 1: a shape-excluded span never anchors the consistency re-pick either.
|
|
323
|
-
if (n.tag === "postcode" && !isShapeExcludedPostcode(n) && isResolvedWithCoord(n)) {
|
|
324
|
-
anchor = { lat: n.lat!, lon: n.lon! }
|
|
325
|
-
|
|
326
|
-
break
|
|
327
|
-
}
|
|
328
|
-
|
|
329
|
-
findAnchor.push(...n.children)
|
|
330
|
-
}
|
|
331
|
-
|
|
332
|
-
if (!anchor) return // no postcode→point — nothing to disambiguate against (gate can't fire)
|
|
333
|
-
|
|
334
|
-
const stack: AddressNode[] = [...roots]
|
|
335
|
-
|
|
336
|
-
while (stack.length) {
|
|
337
|
-
const node = stack.pop()!
|
|
338
|
-
stack.push(...node.children)
|
|
339
|
-
|
|
340
|
-
if ((node.tag !== "locality" && node.tag !== "dependent_locality") || !isResolvedWithCoord(node)) continue
|
|
341
|
-
|
|
342
|
-
if (haversineKm(anchor.lat, anchor.lon, node.lat!, node.lon!) <= gateKm) continue // already consistent
|
|
343
|
-
|
|
344
|
-
// Re-pick: the same-named candidate nearest the postcode, within the gate. `alternatives` is
|
|
345
|
-
// typed `unknown[]` on the node (decoder/types.ts can't import resolver types) — they ARE the
|
|
346
|
-
// `ResolvedPlace` runner-ups decorateNode attached, so the cast is sound.
|
|
347
|
-
const alts = (node.alternatives as ResolvedPlace[] | undefined) ?? []
|
|
348
|
-
|
|
349
|
-
const reconciling = alts
|
|
350
|
-
.filter((a) => a.lat !== 0 || a.lon !== 0)
|
|
351
|
-
.map((a) => ({ a, d: haversineKm(anchor!.lat, anchor!.lon, a.lat, a.lon) }))
|
|
352
|
-
.filter((x) => x.d <= gateKm)
|
|
353
|
-
// oxlint-disable-next-line unicorn/no-array-sort -- sorts a freshly-built array; toSorted would double-allocate on a hot path
|
|
354
|
-
.sort((x, y) => x.d - y.d)[0]
|
|
355
|
-
|
|
356
|
-
if (reconciling) {
|
|
357
|
-
// Swap to the consistent instance; the displaced winner becomes an alternative.
|
|
358
|
-
const displaced: ResolvedPlace = {
|
|
359
|
-
id: 0,
|
|
360
|
-
name: String(node.metadata?.["resolver_name"] ?? node.value),
|
|
361
|
-
placetype: "locality",
|
|
362
|
-
country: reconciling.a.country,
|
|
363
|
-
lat: node.lat!,
|
|
364
|
-
lon: node.lon!,
|
|
365
|
-
score: 0,
|
|
366
|
-
}
|
|
367
|
-
|
|
368
|
-
const rest = alts.filter((a) => a !== reconciling.a)
|
|
369
|
-
decorateNode(node, reconciling.a, [displaced, ...rest])
|
|
370
|
-
node.metadata = { ...node.metadata, postcode_repicked: true }
|
|
371
|
-
|
|
372
|
-
continue
|
|
373
|
-
}
|
|
374
|
-
|
|
375
|
-
// No same-named instance near the postcode → the town is unreliable; trust the postcode's area.
|
|
376
|
-
node.lat = anchor.lat
|
|
377
|
-
node.lon = anchor.lon
|
|
378
|
-
node.metadata = { ...node.metadata, postcode_city_mismatch: true, coordinate_source: "postcode_fallback" }
|
|
379
|
-
}
|
|
380
|
-
}
|
|
381
|
-
|
|
382
|
-
/**
|
|
383
|
-
* Admin descendant-consistency (#263) — the joint-consistency resolve, scoped to the admin assignment. The greedy walk
|
|
384
|
-
* resolves a region on its own (name + population), so "ME" picks Messina (IT) over Maine, then scopes "Portland" to
|
|
385
|
-
* Messina's descendants, finds nothing, and the result falls back to the region centroid (Sicily). The region's
|
|
386
|
-
* same-named runner-ups (Maine, Missouri, …) were already captured as `alternatives`; this pass asks the question the
|
|
387
|
-
* greedy order skipped — _which "ME" has a "Portland" under it?_ — and re-picks the (region, locality) pair where a
|
|
388
|
-
* same-named locality descends from a same-named region candidate. Geography decides; no country prior, no list.
|
|
389
|
-
*
|
|
390
|
-
* Fires ONLY for a resolved region whose child locality fell through (the unresolved-locality signal), so a
|
|
391
|
-
* well-resolved tree ("Springfield, IL" → Illinois, Springfield) is byte-identical. Costs one unscoped locality lookup
|
|
392
|
-
* per triggering pair. Needs {@link ResolverBackend.ancestors}; no-op without it. See `ResolveOpts.adminCoherence`.
|
|
393
|
-
*/
|
|
394
|
-
async function applyAdminCoherence(roots: readonly AddressNode[], backend: ResolverBackend): Promise<void> {
|
|
395
|
-
const visit = async (node: AddressNode, regionAncestor: AddressNode | null): Promise<void> => {
|
|
396
|
-
const regionHere = node.tag === "region" && isResolvedWithCoord(node) ? node : regionAncestor
|
|
397
|
-
|
|
398
|
-
if (
|
|
399
|
-
regionHere &&
|
|
400
|
-
(node.tag === "locality" || node.tag === "dependent_locality") &&
|
|
401
|
-
!isResolvedWithCoord(node) &&
|
|
402
|
-
node.value.trim().length
|
|
403
|
-
) {
|
|
404
|
-
await reconcileAdminPair(regionHere, node, backend)
|
|
405
|
-
}
|
|
406
|
-
|
|
407
|
-
for (const child of node.children) {
|
|
408
|
-
await visit(child, regionHere)
|
|
409
|
-
}
|
|
410
|
-
}
|
|
411
|
-
|
|
412
|
-
for (const root of roots) {
|
|
413
|
-
await visit(root, null)
|
|
414
|
-
}
|
|
415
|
-
}
|
|
416
|
-
|
|
417
|
-
/**
|
|
418
|
-
* Re-pick a (region, locality) pair so the locality descends from the region. `alternatives` on the node are the
|
|
419
|
-
* `ResolvedPlace` runner-ups `decorateNode` attached (typed `unknown[]` in the decoder, which can't import resolver
|
|
420
|
-
* types — the cast is sound). Picks the FIRST same-named locality (already score-ordered) that descends from a
|
|
421
|
-
* same-named region candidate, then swaps both nodes. Leaves both untouched when no consistent pair exists (a genuinely
|
|
422
|
-
* un-gazetteered locality — "Portland, VT" with no Portland in Vermont — stays as the region centroid, not a foreign
|
|
423
|
-
* namesake).
|
|
424
|
-
*/
|
|
425
|
-
async function reconcileAdminPair(
|
|
426
|
-
regionNode: AddressNode,
|
|
427
|
-
localityNode: AddressNode,
|
|
428
|
-
backend: ResolverBackend
|
|
429
|
-
): Promise<void> {
|
|
430
|
-
// EXACT region matches only: the alternatives for a 2-letter token are loose ("ME" also surfaces
|
|
431
|
-
// Missouri/Michigan/Mississippi as fuzzy M-state runner-ups). Restricting to exact name/alias matches
|
|
432
|
-
// (Maine/Messina/Medway for "ME") keeps the join honest. `exactMatch` is stamped by exactMatchTiering.
|
|
433
|
-
const regionCands = ((regionNode.alternatives as ResolvedPlace[] | undefined) ?? []).filter((r) => r.exactMatch)
|
|
434
|
-
|
|
435
|
-
// For each exact region candidate, ask the gazetteer directly: is there a same-named locality UNDER it?
|
|
436
|
-
// The `parentID` scope is the descendant test (over the #832-repaired ancestors table), and it finds the
|
|
437
|
-
// instance regardless of its global population rank — "Springfield, ME" reaches the small Springfield in
|
|
438
|
-
// Maine that an unscoped top-N window would drop. First region with an exact-named descendant wins; the
|
|
439
|
-
// region candidates are score-ordered, so a tie breaks toward the more prominent place.
|
|
440
|
-
for (const region of regionCands) {
|
|
441
|
-
const scoped = await backend.findPlace({
|
|
442
|
-
text: localityNode.value,
|
|
443
|
-
placetype: "locality",
|
|
444
|
-
parentID: region.id,
|
|
445
|
-
limit: 3,
|
|
446
|
-
})
|
|
447
|
-
|
|
448
|
-
const lc = scoped.find((l) => l.exactMatch && !(l.lat === 0 && l.lon === 0))
|
|
449
|
-
|
|
450
|
-
if (lc) {
|
|
451
|
-
decorateNode(
|
|
452
|
-
regionNode,
|
|
453
|
-
region,
|
|
454
|
-
regionCands.filter((r) => r !== region)
|
|
455
|
-
)
|
|
456
|
-
|
|
457
|
-
regionNode.metadata = { ...regionNode.metadata, admin_coherence_repicked: true }
|
|
458
|
-
|
|
459
|
-
decorateNode(
|
|
460
|
-
localityNode,
|
|
461
|
-
lc,
|
|
462
|
-
scoped.filter((l) => l !== lc)
|
|
463
|
-
)
|
|
464
|
-
|
|
465
|
-
localityNode.metadata = { ...localityNode.metadata, admin_coherence_repicked: true }
|
|
466
|
-
|
|
467
|
-
return
|
|
468
|
-
}
|
|
469
|
-
}
|
|
470
|
-
|
|
471
|
-
// #267 follow-up: the token may name a COUNTRY whose namesake is a more-populous foreign region — "Tbilisi,
|
|
472
|
-
// Georgia" parses region("Georgia") → the US state, but Tbilisi descends from Georgia the COUNTRY. When no
|
|
473
|
-
// region candidate holds the locality, try same-named country candidates: a foreign capital under its
|
|
474
|
-
// country out-votes the state namesake. Needs the country + the locality's ancestry in the gazetteer (the
|
|
475
|
-
// #267 admin fold). The re-picked region node then carries the country place; the locality coordinate wins.
|
|
476
|
-
const countryCands = (await backend.findPlace({ text: regionNode.value, placetype: "country", limit: 3 })).filter(
|
|
477
|
-
(c) => c.exactMatch
|
|
478
|
-
)
|
|
479
|
-
|
|
480
|
-
for (const country of countryCands) {
|
|
481
|
-
const scoped = await backend.findPlace({
|
|
482
|
-
text: localityNode.value,
|
|
483
|
-
placetype: "locality",
|
|
484
|
-
parentID: country.id,
|
|
485
|
-
limit: 3,
|
|
486
|
-
})
|
|
487
|
-
|
|
488
|
-
const lc = scoped.find((l) => l.exactMatch && !(l.lat === 0 && l.lon === 0))
|
|
489
|
-
|
|
490
|
-
if (lc) {
|
|
491
|
-
decorateNode(regionNode, country, regionCands)
|
|
492
|
-
regionNode.metadata = { ...regionNode.metadata, admin_coherence_repicked: true }
|
|
493
|
-
|
|
494
|
-
decorateNode(
|
|
495
|
-
localityNode,
|
|
496
|
-
lc,
|
|
497
|
-
scoped.filter((l) => l !== lc)
|
|
498
|
-
)
|
|
499
|
-
|
|
500
|
-
localityNode.metadata = { ...localityNode.metadata, admin_coherence_repicked: true }
|
|
501
|
-
|
|
502
|
-
return
|
|
503
|
-
}
|
|
504
|
-
}
|
|
505
|
-
|
|
506
|
-
// #1023: the admin gazetteer may carry NO `country`-placetype node for the token AND the same-named
|
|
507
|
-
// foreign locality may be ORPHANED (parent_id = -1) — the 2026-07-07 rebuild flattened Georgia's admin
|
|
508
|
-
// hierarchy to localities-only, so the country-node lookup above finds nothing and the `parentID`
|
|
509
|
-
// descendant test can never reach Tbilisi. Fall back to matchCountry: normalize the token to an
|
|
510
|
-
// ISO-3166 alpha-2 and scope the locality by the gazetteer's `country` COLUMN (set even on an orphaned
|
|
511
|
-
// row). Same primitive reconcileExplicitCountry (#822) uses, so the region-parsed namesake path
|
|
512
|
-
// ("Tbilisi, Georgia") converges with the country-parsed one ("Vienna, Austria"). matchCountry returns
|
|
513
|
-
// null for a US state name/abbrev ("Illinois" / "ME" / "IL"), so a real US (region, locality) pair
|
|
514
|
-
// never reaches here — this stays inert on the domestic path.
|
|
515
|
-
const mc = matchCountry(regionNode.value)
|
|
516
|
-
|
|
517
|
-
if (mc) {
|
|
518
|
-
const scoped = await backend.findPlace({
|
|
519
|
-
text: localityNode.value,
|
|
520
|
-
placetype: "locality",
|
|
521
|
-
country: mc.iso2,
|
|
522
|
-
limit: 3,
|
|
523
|
-
})
|
|
524
|
-
|
|
525
|
-
const lc = scoped.find((l) => l.exactMatch && !(l.lat === 0 && l.lon === 0))
|
|
526
|
-
|
|
527
|
-
if (lc) {
|
|
528
|
-
decorateNode(
|
|
529
|
-
localityNode,
|
|
530
|
-
lc,
|
|
531
|
-
scoped.filter((l) => l !== lc)
|
|
532
|
-
)
|
|
533
|
-
|
|
534
|
-
localityNode.metadata = { ...localityNode.metadata, admin_coherence_repicked: true }
|
|
535
|
-
// The token named a foreign country the admin gazetteer has no node for, but the greedy walk had
|
|
536
|
-
// already decorated the region node with the US-state namesake. Revert that stale decoration so the
|
|
537
|
-
// node stops asserting the wrong-country coordinate + `resolver_country` (which would otherwise leak
|
|
538
|
-
// into the result's `countryCode`); the re-picked locality carries the winning coordinate, and the
|
|
539
|
-
// region node falls back to the parsed "Georgia" token, unresolved (the admin DB has nothing truer).
|
|
540
|
-
revertResolverDecoration(regionNode)
|
|
541
|
-
}
|
|
542
|
-
}
|
|
543
|
-
}
|
|
544
|
-
|
|
545
|
-
/**
|
|
546
|
-
* Undo a resolver decoration on a node: restore the classifier attribution {@link decorateNode} displaced into
|
|
547
|
-
* `metadata.classifier_source(_id)` and drop the resolver-supplied coordinate/identity/alternatives. Used by the #1023
|
|
548
|
-
* country fall-through when the region token turns out to name a foreign country the admin gazetteer holds no node for
|
|
549
|
-
* — the greedy walk had bound it to the US-state namesake, and that stale claim must not survive the locality re-pick.
|
|
550
|
-
*/
|
|
551
|
-
function revertResolverDecoration(node: AddressNode): void {
|
|
552
|
-
const meta = { ...node.metadata }
|
|
553
|
-
const priorSource = meta["classifier_source"]
|
|
554
|
-
const priorSourceID = meta["classifier_source_id"]
|
|
555
|
-
node.source = typeof priorSource === "string" ? priorSource : undefined
|
|
556
|
-
node.sourceID = typeof priorSourceID === "string" ? priorSourceID : undefined
|
|
557
|
-
|
|
558
|
-
for (const key of [
|
|
559
|
-
"classifier_source",
|
|
560
|
-
"classifier_source_id",
|
|
561
|
-
"resolver_score",
|
|
562
|
-
"resolver_prominence",
|
|
563
|
-
"resolver_name",
|
|
564
|
-
"resolver_country",
|
|
565
|
-
"resolution_quality",
|
|
566
|
-
"postcode_city_mismatch",
|
|
567
|
-
]) {
|
|
568
|
-
// oxlint-disable-next-line typescript/no-dynamic-delete -- removing one key from a plain record; the object is not on a hot path
|
|
569
|
-
delete meta[key]
|
|
570
|
-
}
|
|
571
|
-
|
|
572
|
-
node.metadata = meta
|
|
573
|
-
node.lat = undefined
|
|
574
|
-
node.lon = undefined
|
|
575
|
-
node.placeID = undefined
|
|
576
|
-
node.alternatives = undefined
|
|
577
|
-
}
|
|
578
|
-
|
|
579
|
-
/**
|
|
580
|
-
* Explicit-country coherence (#822) — the joint-consistency resolve keyed on the query's own EXPLICIT country token.
|
|
581
|
-
* The greedy walk resolves a locality on name + population alone, so "Vienna, Austria" picks the populous US namesake
|
|
582
|
-
* (Vienna WV) and IGNORES the "Austria" the address named. This pass asks the question the greedy order skipped —
|
|
583
|
-
* _which "Vienna" is in the country the address names?_ — and re-picks the locality to the same-named place under that
|
|
584
|
-
* country. The country code comes from the parser's OWN `country` emission via codex's ISO-3166 table (a name→code
|
|
585
|
-
* normalization of a token the model already classified, NOT a routing prior or safelist); the gazetteer's `country`
|
|
586
|
-
* column does the geographic confirmation. No pin, no list; generalizes to every country.
|
|
587
|
-
*
|
|
588
|
-
* Disjoint from {@link applyAdminCoherence} by the region guard: that pass owns the case where a REGION scopes the
|
|
589
|
-
* locality; this one fires only when the explicit country is the locality's nearest admin context (no region between),
|
|
590
|
-
* and then regardless of the locality's resolution state — so it covers both the resolved-but-foreign locality (Sydney
|
|
591
|
-
* → the greedy AU pick was wrong) and the unresolved locality the span-rescore tier would otherwise back-fill with the
|
|
592
|
-
* US namesake (Vienna → Vienna WV). Byte-stable when the locality already resolved in-country (the id guard) or the
|
|
593
|
-
* named country holds no same-named locality (the fail-safe — what also protects "Turkey, TX": no country token ⇒ no
|
|
594
|
-
* trigger; and an in-country lookup that finds nothing keeps the greedy result). Costs one country-scoped locality
|
|
595
|
-
* lookup per triggering pair. See `ResolveOpts.adminCoherence`.
|
|
596
|
-
*/
|
|
597
|
-
async function applyExplicitCountryCoherence(roots: readonly AddressNode[], backend: ResolverBackend): Promise<void> {
|
|
598
|
-
const visit = async (node: AddressNode, countryToken: AddressNode | null, regionAbove: boolean): Promise<void> => {
|
|
599
|
-
const countryHere = node.tag === "country" && node.value.trim().length ? node : countryToken
|
|
600
|
-
const regionHere = regionAbove || node.tag === "region" || node.tag === "subregion"
|
|
601
|
-
|
|
602
|
-
// Fire only when the explicit country is the locality's NEAREST admin context (no region/subregion between).
|
|
603
|
-
// When a region IS present, applyAdminCoherence + the region's `parentID` scope already disambiguate the
|
|
604
|
-
// locality — applying the coarse country filter there would wrongly re-pick "Springfield, IL" to the most
|
|
605
|
-
// populous US "Springfield". Fires regardless of the locality's resolution state, so it PRE-EMPTS the
|
|
606
|
-
// span-rescore tier (which would otherwise back-fill the unresolved locality with the US namesake).
|
|
607
|
-
if (countryHere && !regionHere && (node.tag === "locality" || node.tag === "dependent_locality")) {
|
|
608
|
-
await reconcileExplicitCountry(countryHere, node, backend)
|
|
609
|
-
}
|
|
610
|
-
|
|
611
|
-
for (const child of node.children) {
|
|
612
|
-
await visit(child, countryHere, regionHere)
|
|
613
|
-
}
|
|
614
|
-
}
|
|
615
|
-
|
|
616
|
-
for (const root of roots) {
|
|
617
|
-
await visit(root, null, false)
|
|
618
|
-
}
|
|
619
|
-
}
|
|
620
|
-
|
|
621
|
-
/**
|
|
622
|
-
* Re-pick a resolved locality to its same-named place UNDER the explicitly-named country. `matchCountry` turns the
|
|
623
|
-
* country token into an ISO-3166 alpha-2 (returns null for an unrecognized token → no-op); the backend then surfaces
|
|
624
|
-
* the in-country namesake the population-first unscoped window buried. Leaves the node untouched when the country is
|
|
625
|
-
* unrecognized, the named country has no exact same-named locality (the fail-safe), or the locality already resolved to
|
|
626
|
-
* that place (the id guard → byte-stable). The country node itself stays as the parser emitted it — the named
|
|
627
|
-
* well-covered countries carry no `country`-placetype row in the admin gazetteer, so there is nothing to decorate it
|
|
628
|
-
* with; the locality coordinate is what the re-pick fixes.
|
|
629
|
-
*/
|
|
630
|
-
async function reconcileExplicitCountry(
|
|
631
|
-
countryNode: AddressNode,
|
|
632
|
-
localityNode: AddressNode,
|
|
633
|
-
backend: ResolverBackend
|
|
634
|
-
): Promise<void> {
|
|
635
|
-
const mc = matchCountry(countryNode.value)
|
|
636
|
-
|
|
637
|
-
if (!mc) return
|
|
638
|
-
|
|
639
|
-
const scoped = await backend.findPlace({
|
|
640
|
-
text: localityNode.value,
|
|
641
|
-
placetype: "locality",
|
|
642
|
-
country: mc.iso2,
|
|
643
|
-
limit: 3,
|
|
644
|
-
})
|
|
645
|
-
|
|
646
|
-
const lc = scoped.find((l) => l.exactMatch && !(l.lat === 0 && l.lon === 0))
|
|
647
|
-
|
|
648
|
-
if (!lc) return
|
|
649
|
-
|
|
650
|
-
// Already the in-country place? (placeID encodes the WOF id.) Then the greedy walk was right — byte-stable.
|
|
651
|
-
if (localityNode.placeID === `wof:${lc.id}`) return
|
|
652
|
-
|
|
653
|
-
decorateNode(
|
|
654
|
-
localityNode,
|
|
655
|
-
lc,
|
|
656
|
-
scoped.filter((l) => l !== lc)
|
|
657
|
-
)
|
|
658
|
-
|
|
659
|
-
localityNode.metadata = { ...localityNode.metadata, explicit_country_repicked: true }
|
|
660
|
-
}
|
|
661
|
-
|
|
662
|
-
/**
|
|
663
|
-
* Region-country coherence — the joint-consistency resolve keyed on a REGION token the locale-inferred default-country
|
|
664
|
-
* filter could not resolve. Companion to {@link applyExplicitCountryCoherence} (which keys on an explicit COUNTRY token)
|
|
665
|
-
* and disjoint from {@link applyAdminCoherence} (which needs a region that DID resolve): this pass owns the mirror case,
|
|
666
|
-
* where the region qualifier is a foreign subdivision the default-country hard filter (`spr.country = ?`) discarded.
|
|
667
|
-
*
|
|
668
|
-
* "Montreal QC" under a US locale: the walk applies `defaultCountry="US"` as a hard candidate filter to every admin
|
|
669
|
-
* lookup, so the region "QC" (a Canadian subdivision) resolves to nothing and is dropped — the one signal that would
|
|
670
|
-
* redirect the country to CA — and the locality "Montreal" is force-matched to the populous US namesake (Montreal, WI).
|
|
671
|
-
* The greedy order threw away the evidence that could correct it.
|
|
672
|
-
*
|
|
673
|
-
* The fix expands the region token to its country via codex's ISO-3166-2 subdivision table (`matchSubdivision`: "QC" →
|
|
674
|
-
* `{ name: "Quebec", country: "CA" }`, handling the FTS index's missing "QC" alt-name code-side), then asks the two
|
|
675
|
-
* questions the greedy walk skipped: does that subdivision genuinely resolve UNDER its own country, and is there a
|
|
676
|
-
* same-named locality under it? Only when BOTH hold does it swap the region and locality to the in-country pair.
|
|
677
|
-
* Geography confirms; the subdivision table is a soft name→country prior, not a routing decision.
|
|
678
|
-
*
|
|
679
|
-
* Evidence-gated to stay byte-stable on the domestic path. It fires ONLY when (a) a default country is in force, (b)
|
|
680
|
-
* the region node is UNRESOLVED (the default-country filter came up empty — a US region resolves fine under `US`, so a
|
|
681
|
-
* well-formed US query never trips this), (c) the token is a subdivision of a DIFFERENT country than the default, and
|
|
682
|
-
* (d) both the foreign region and a same-named foreign locality resolve. "Springfield, IL" / "Portland, ME": the region
|
|
683
|
-
* resolves under `US`, so gate (b) fails and the tree is untouched. Costs one region + one locality lookup per
|
|
684
|
-
* triggering pair. See `ResolveOpts.adminCoherence`.
|
|
685
|
-
*/
|
|
686
|
-
async function applyRegionCountryCoherence(
|
|
687
|
-
roots: readonly AddressNode[],
|
|
688
|
-
backend: ResolverBackend,
|
|
689
|
-
defaultCountry: string | undefined
|
|
690
|
-
): Promise<void> {
|
|
691
|
-
// No default country → no hard country filter was applied, so no region qualifier was discarded by one. The bug
|
|
692
|
-
// this pass corrects is specific to the locale-inferred default country; without it, there is nothing to rescue.
|
|
693
|
-
if (!defaultCountry) return
|
|
694
|
-
|
|
695
|
-
const visit = async (node: AddressNode, regionAncestor: AddressNode | null): Promise<void> => {
|
|
696
|
-
// Track the nearest region ancestor regardless of its resolution state (the trigger is an UNRESOLVED region).
|
|
697
|
-
const regionHere = node.tag === "region" || node.tag === "subregion" ? node : regionAncestor
|
|
698
|
-
|
|
699
|
-
// Fire for an UNRESOLVED region (the default-country filter came up empty) whose companion locality node
|
|
700
|
-
// exists — regardless of the locality's resolution state, so it covers both the resolved-but-foreign namesake
|
|
701
|
-
// (Montreal → the greedy US pick, Montreal WI) and the unresolved locality the span-rescore tier would
|
|
702
|
-
// otherwise back-fill with a US namesake. The in-country lookups below are the evidence gate.
|
|
703
|
-
if (
|
|
704
|
-
regionHere &&
|
|
705
|
-
!isResolvedWithCoord(regionHere) &&
|
|
706
|
-
(node.tag === "locality" || node.tag === "dependent_locality") &&
|
|
707
|
-
node.value.trim().length
|
|
708
|
-
) {
|
|
709
|
-
await reconcileRegionCountry(regionHere, node, backend, defaultCountry)
|
|
710
|
-
}
|
|
711
|
-
|
|
712
|
-
for (const child of node.children) {
|
|
713
|
-
await visit(child, regionHere)
|
|
714
|
-
}
|
|
715
|
-
}
|
|
716
|
-
|
|
717
|
-
for (const root of roots) {
|
|
718
|
-
await visit(root, null)
|
|
719
|
-
}
|
|
720
|
-
}
|
|
721
|
-
|
|
722
|
-
/**
|
|
723
|
-
* Re-pick an (unresolved region, resolved-but-foreign-namesake locality) pair to the in-country instance the
|
|
724
|
-
* default-country filter hid. `matchSubdivision` turns the region token into `{ name, country }` (null for anything
|
|
725
|
-
* that isn't a US state or CA province → no-op); the region's full name then resolves it under that country (expanding
|
|
726
|
-
* the abbreviation the gazetteer FTS index lacks), and the locality is re-scoped to the same country. Leaves both nodes
|
|
727
|
-
* untouched unless every gate holds — the subdivision names a different country than the default, the region resolves
|
|
728
|
-
* under it, and a same-named locality exists there — so the domestic path stays byte-identical.
|
|
729
|
-
*/
|
|
730
|
-
async function reconcileRegionCountry(
|
|
731
|
-
regionNode: AddressNode,
|
|
732
|
-
localityNode: AddressNode,
|
|
733
|
-
backend: ResolverBackend,
|
|
734
|
-
defaultCountry: string
|
|
735
|
-
): Promise<void> {
|
|
736
|
-
const sub = matchSubdivision(regionNode.value)
|
|
737
|
-
|
|
738
|
-
if (!sub) return
|
|
739
|
-
|
|
740
|
-
// The subdivision must belong to a DIFFERENT country than the locale default. A US-state token under a US default
|
|
741
|
-
// (sub.country === defaultCountry) never reaches the swap — the pass is inert on the domestic path.
|
|
742
|
-
if (sub.country.toUpperCase() === defaultCountry.toUpperCase()) return
|
|
743
|
-
|
|
744
|
-
// The locality already resolved in the subdivision's country? Then the greedy walk was already right — byte-stable.
|
|
745
|
-
const localityCountry = (localityNode.metadata?.["resolver_country"] as string | undefined)?.toUpperCase()
|
|
746
|
-
|
|
747
|
-
if (localityCountry === sub.country.toUpperCase()) return
|
|
748
|
-
|
|
749
|
-
// Confirm the subdivision genuinely resolves under its own country, by its full name (expands "QC" → "Quebec", the
|
|
750
|
-
// form the FTS index carries). No resolvable region → no evidence the token is a real foreign subdivision; abstain.
|
|
751
|
-
const regionScoped = await backend.findPlace({
|
|
752
|
-
text: sub.name,
|
|
753
|
-
placetype: "region",
|
|
754
|
-
country: sub.country,
|
|
755
|
-
limit: 3,
|
|
756
|
-
})
|
|
757
|
-
|
|
758
|
-
const rc = regionScoped.find((r) => r.exactMatch && !(r.lat === 0 && r.lon === 0))
|
|
759
|
-
|
|
760
|
-
if (!rc) return
|
|
761
|
-
|
|
762
|
-
// Is there a same-named locality under that country? (the descendant test, by country column — the same primitive
|
|
763
|
-
// reconcileExplicitCountry uses.) No in-country namesake → keep the greedy result (fail-safe).
|
|
764
|
-
const scoped = await backend.findPlace({
|
|
765
|
-
text: localityNode.value,
|
|
766
|
-
placetype: "locality",
|
|
767
|
-
country: sub.country,
|
|
768
|
-
limit: 3,
|
|
769
|
-
})
|
|
770
|
-
|
|
771
|
-
const lc = scoped.find((l) => l.exactMatch && !(l.lat === 0 && l.lon === 0))
|
|
772
|
-
|
|
773
|
-
if (!lc) return
|
|
774
|
-
|
|
775
|
-
// Adopt the in-country pair: the region gets the foreign subdivision, the locality its same-named foreign instance.
|
|
776
|
-
decorateNode(
|
|
777
|
-
regionNode,
|
|
778
|
-
rc,
|
|
779
|
-
regionScoped.filter((r) => r !== rc)
|
|
780
|
-
)
|
|
781
|
-
|
|
782
|
-
regionNode.metadata = { ...regionNode.metadata, region_country_repicked: true }
|
|
783
|
-
|
|
784
|
-
decorateNode(
|
|
785
|
-
localityNode,
|
|
786
|
-
lc,
|
|
787
|
-
scoped.filter((l) => l !== lc)
|
|
788
|
-
)
|
|
789
|
-
|
|
790
|
-
localityNode.metadata = { ...localityNode.metadata, region_country_repicked: true }
|
|
791
|
-
}
|
|
792
|
-
|
|
793
|
-
class WOFResolver implements Resolver {
|
|
794
|
-
readonly #backend: ResolverBackend
|
|
795
|
-
/**
|
|
796
|
-
* The gazetteer artifact's self-declared coverage facts, passed through from the backend so pipeline-level consumers
|
|
797
|
-
* read them from the resolver handle they already hold. Absent on artifacts predating the coverage manifest.
|
|
798
|
-
*/
|
|
799
|
-
readonly artifactCoverage: Resolver["artifactCoverage"]
|
|
800
|
-
|
|
801
|
-
constructor(backend: ResolverBackend) {
|
|
802
|
-
this.#backend = backend
|
|
803
|
-
this.artifactCoverage = backend.artifactCoverage
|
|
804
|
-
}
|
|
805
|
-
|
|
806
|
-
async resolveTree(tree: AddressTree, opts: ResolveOpts = {}): Promise<AddressTree> {
|
|
807
|
-
// Postcode-shape coherence (#31, Mechanism 1): the earliest pass in the tree — pure-sync and
|
|
808
|
-
// backend-free, run BEFORE `state.postcode` is read so an excluded span can never become the
|
|
809
|
-
// address's postcode. Opt-in (`postcodeShapeCoherence: true`), OFF by default (D-rule: demotion
|
|
810
|
-
// is the failure mode with teeth). A confirmed span's narrowed systems — the intersection of
|
|
811
|
-
// its codex shape with the tree's confident sibling systems — bound the country-scope pass
|
|
812
|
-
// below; a pure subset of codex's own candidate list, so it can only narrow, never widen.
|
|
813
|
-
// See postcode-shape-coherence.ts.
|
|
814
|
-
const shapeVerdict = opts.postcodeShapeCoherence === true ? applyPostcodeShapeCoherence(tree.roots) : null
|
|
815
|
-
|
|
816
|
-
const state: ResolutionState = {
|
|
817
|
-
lookupsRemaining: opts.maxLookups ?? 10,
|
|
818
|
-
// Full replacement when `placetypeMap` is supplied — callers that want to extend rather
|
|
819
|
-
// than replace should spread DEFAULT_PLACETYPE_MAP themselves.
|
|
820
|
-
placetypeMap: opts.placetypeMap ?? DEFAULT_PLACETYPE_MAP,
|
|
821
|
-
minWinningScore: opts.minWinningScore ?? 0,
|
|
822
|
-
candidatesPerLookup: opts.candidatesPerLookup ?? 5,
|
|
823
|
-
defaultCountry: opts.defaultCountry,
|
|
824
|
-
parentFallback: opts.parentFallback ?? true,
|
|
825
|
-
postcode: firstPostcodeValue(tree.roots),
|
|
826
|
-
// #31 Mechanism 2 — forwarded to locality lookups (see #lookupAndPick). Opt-in, OFF by default.
|
|
827
|
-
postcodeContainmentCoherence: opts.postcodeContainmentCoherence === true,
|
|
828
|
-
// #31 Mechanism 3 — the prefix prior + its injected index (see #lookupAndPick). Opt-in, OFF by default.
|
|
829
|
-
postcodePrefixPrior: opts.postcodePrefixPrior === true,
|
|
830
|
-
postcodePrefixIndex: opts.postcodePrefixIndex,
|
|
831
|
-
bias: opts.bias,
|
|
832
|
-
anchorPosterior: opts.anchorPosterior,
|
|
833
|
-
anchorWeight: opts.anchorWeight ?? 2,
|
|
834
|
-
localeCountryPrior: opts.localeCountryPrior,
|
|
835
|
-
localeCountryPriorWeight: opts.localeCountryPriorWeight ?? DEFAULT_COUNTRY_PRIOR_WEIGHT,
|
|
836
|
-
hardCountry: opts.hardCountry,
|
|
837
|
-
// Default-ON (#402): completion only fires for a dual-role region whose locality the parser
|
|
838
|
-
// dropped, and no-ops entirely when the backend has no relation (the browser WASM resolver, or
|
|
839
|
-
// a gazetteer without `coincident_roles`). Pass `hierarchyCompletion: false` to opt out.
|
|
840
|
-
hierarchyCompletion: opts.hierarchyCompletion ?? true,
|
|
841
|
-
includeAncestors: opts.includeAncestors ?? false,
|
|
842
|
-
localityNodePresent: false,
|
|
843
|
-
resolvedRegion: null,
|
|
844
|
-
resolvedRegionNode: null,
|
|
845
|
-
}
|
|
846
|
-
|
|
847
|
-
// Postcode-country coherence (#42): the one pre-walk LOOKUP pass (the shape verdict above is
|
|
848
|
-
// pure-sync, backend-free), and the only mechanism allowed to override `defaultCountry`. Its three
|
|
849
|
-
// sibling coherence passes re-pick nodes AFTER the walk; that shape cannot work here, because what
|
|
850
|
-
// needs correcting is the walk's country SCOPE — which poisons the postcode node's own resolution,
|
|
851
|
-
// the postcode-consistency fallback that then drags the locality onto it, and the hard `country`
|
|
852
|
-
// filter on every admin lookup. So the verdict is taken once, up front, and the walk runs under the
|
|
853
|
-
// corrected country. Default-ON (operator-promoted 2026-08-05; `false` opts out) — needs a default
|
|
854
|
-
// country to correct and both a postcode and a locality to be coherent about; abstains unless
|
|
855
|
-
// EXACTLY one country (never the already-coherent default) makes the pair consistent. See
|
|
856
|
-
// postcode-country-coherence.ts.
|
|
857
|
-
let postcodeScope: PostcodeCountryScope | null = null
|
|
858
|
-
|
|
859
|
-
if (opts.postcodeCountryCoherence !== false && state.defaultCountry && state.postcode) {
|
|
860
|
-
postcodeScope = await findPostcodeCountryScope(tree.roots, this.#backend, {
|
|
861
|
-
postcode: state.postcode,
|
|
862
|
-
defaultCountry: state.defaultCountry,
|
|
863
|
-
...(shapeVerdict?.narrowing !== undefined ? { candidateSystems: shapeVerdict.narrowing } : {}),
|
|
864
|
-
...(opts.postcodeCountryCoherenceGateKm !== undefined ? { gateKm: opts.postcodeCountryCoherenceGateKm } : {}),
|
|
865
|
-
})
|
|
866
|
-
|
|
867
|
-
if (postcodeScope) {
|
|
868
|
-
// The override. `hardCountry` is not cleared because it is never consulted while a
|
|
869
|
-
// `defaultCountry` is set (`#lookupAndPick`'s precedence chain reaches it only as the last
|
|
870
|
-
// fallback), so replacing the default is sufficient to re-scope the entire walk.
|
|
871
|
-
state.defaultCountry = postcodeScope.country
|
|
872
|
-
}
|
|
873
|
-
}
|
|
874
|
-
|
|
875
|
-
const newRoots: AddressNode[] = []
|
|
876
|
-
|
|
877
|
-
for (const root of tree.roots) {
|
|
878
|
-
newRoots.push(await this.#walk(root, /* parentResolved */ null, state))
|
|
879
|
-
}
|
|
880
|
-
|
|
881
|
-
// Attribution for the override, stamped on the two nodes that bought it. Additive metadata only.
|
|
882
|
-
if (postcodeScope) {
|
|
883
|
-
stampPostcodeCountryScope(newRoots, postcodeScope)
|
|
884
|
-
}
|
|
885
|
-
|
|
886
|
-
// Dual-role hierarchy completion (#405/#415). Only when enabled, a region resolved, and the parser
|
|
887
|
-
// emitted NO locality — record the dropped locality as a SECONDARY ROLE (an interpretation) on the
|
|
888
|
-
// resolved region node, from the backend's precomputed coincident-roles relation (#403). One node,
|
|
889
|
-
// one span, two roles — no synthesized sibling. See ResolveOpts.hierarchyCompletion.
|
|
890
|
-
if (state.hierarchyCompletion && state.resolvedRegion && state.resolvedRegionNode && !state.localityNodePresent) {
|
|
891
|
-
this.#completeRegionRole(state.resolvedRegion, state.resolvedRegionNode)
|
|
892
|
-
}
|
|
893
|
-
|
|
894
|
-
// Admin descendant-consistency (#263): default-ON (#895 settled drift D1; `false` opts out). Re-pick a
|
|
895
|
-
// (region, locality) pair so the locality descends from the region — runs BEFORE postcode-consistency
|
|
896
|
-
// (it resolves the locality the postcode pass may then refine) and before the street tiers (which key
|
|
897
|
-
// off the postcode/street, not the admin coordinate this adjusts). Byte-stable when nothing fell
|
|
898
|
-
// through or the backend lacks `ancestors`.
|
|
899
|
-
if (opts.adminCoherence !== false) {
|
|
900
|
-
await applyAdminCoherence(newRoots, this.#backend)
|
|
901
|
-
// #822 — same joint-consistency family, inverse trigger: an explicit country token whose resolved
|
|
902
|
-
// locality landed in the wrong country (the populous US namesake). Runs after the region pass so the
|
|
903
|
-
// two never contend (region-fallthrough vs resolved-but-foreign are disjoint locality states).
|
|
904
|
-
await applyExplicitCountryCoherence(newRoots, this.#backend)
|
|
905
|
-
// Region-country coherence: a region qualifier the locale-inferred default-country hard filter could not
|
|
906
|
-
// resolve (a foreign subdivision — "Montreal QC" under a US locale). The default filter discarded "QC" and
|
|
907
|
-
// force-matched the locality to the US namesake; this re-resolves the subdivision + its same-named locality
|
|
908
|
-
// under the subdivision's OWN country. Disjoint from the two passes above (unresolved region + resolved
|
|
909
|
-
// locality); evidence-gated + byte-stable on the domestic path (a US region resolves under `US`).
|
|
910
|
-
await applyRegionCountryCoherence(newRoots, this.#backend, state.defaultCountry)
|
|
911
|
-
}
|
|
912
|
-
|
|
913
|
-
// Postcode-consistency (#370 "Lever A"): default-ON (promoted 2026-07-04 — the corrected gate:
|
|
914
|
-
// FI 231/0, SI 37/6, CZ 47/2, US byte-flat; see the ResolveOpts docstring). After the admin walk
|
|
915
|
-
// (needs both the locality and the postcode resolved) and before the street tiers (which key off
|
|
916
|
-
// the postcode/street, not the locality coordinate this adjusts). `false` opts out, byte-stable.
|
|
917
|
-
if (opts.postcodeConsistency !== false) {
|
|
918
|
-
applyPostcodeConsistency(newRoots, opts.postcodeConsistencyGateKm ?? 50)
|
|
919
|
-
}
|
|
920
|
-
|
|
921
|
-
// Address-point tier (#476): opt-in street-level exact match. After the admin walk so the
|
|
922
|
-
// tier can never disturb admin attribution — it only ADDS the precise coordinate. Byte-stable
|
|
923
|
-
// when opts.addressPoints is absent.
|
|
924
|
-
if (opts.addressPoints) {
|
|
925
|
-
applyAddressPoint(newRoots, opts.addressPoints, opts.addressPointBboxFallback)
|
|
926
|
-
}
|
|
927
|
-
|
|
928
|
-
// Interpolation tier (#483): strictly AFTER the exact-point block so an estimate can never
|
|
929
|
-
// override a real situs point (applyInterpolation also gates on resolution_tier). Opt-in;
|
|
930
|
-
// byte-stable when opts.interpolation is absent.
|
|
931
|
-
if (opts.interpolation) {
|
|
932
|
-
applyInterpolation(newRoots, opts.interpolation, opts.interpolationRadiusCalibration)
|
|
933
|
-
}
|
|
934
|
-
|
|
935
|
-
// Span-rescore tier (#370): default-ON (promoted 2026-06-25 — same-harness EU+AU +1pp @25km,
|
|
936
|
-
// zero regressions: CZ 90→95, AT 70→73, PL 88→90, IT/PT/FR/AU flat, no-result 4→3%; fires last
|
|
937
|
-
// so it only runs when every other tier left the tree unresolved, hence inert on the well-resolved
|
|
938
|
-
// US path). Explicit opt-OUT via `spanRescore: false`; byte-stable then.
|
|
939
|
-
if (opts.spanRescore !== false) {
|
|
940
|
-
await applySpanRescore(newRoots, tree.raw, this.#backend, opts)
|
|
941
|
-
}
|
|
942
|
-
|
|
943
|
-
// A failed admin walk can leave the exact-point tier without a locality even though span-rescore
|
|
944
|
-
// recovers one immediately afterward (for example, a locality the model tagged as `region`). Give
|
|
945
|
-
// the exact register one bounded retry with that newly established scope. An existing situs hit is
|
|
946
|
-
// returned early by applyAddressPoint, so the normal path performs no duplicate lookup; interpolation
|
|
947
|
-
// remains subordinate because an exact point is allowed to replace its estimate.
|
|
948
|
-
if (opts.addressPoints) {
|
|
949
|
-
applyAddressPoint(newRoots, opts.addressPoints, opts.addressPointBboxFallback)
|
|
950
|
-
}
|
|
951
|
-
|
|
952
|
-
// Street-centroid tier (#1042): LAST, after span-rescore, so it can (a) union the span-rescore-recovered
|
|
953
|
-
// country into its FR/national country hints (a placer-misrouted street — "Rue Sainte-Catherine" → IT — leaves
|
|
954
|
-
// admin unresolved, and only span-rescore recovers the FR country signal) and (b) override a coarse recovered
|
|
955
|
-
// locality with the exact street centroid. Self-gates on no house number + no existing street-level tier, so a
|
|
956
|
-
// rooftop query is untouched; byte-stable when opts.streetCentroids absent.
|
|
957
|
-
if (opts.streetCentroids) {
|
|
958
|
-
applyStreetCentroid(newRoots, tree.raw, opts.streetCentroids, opts.streetCountryHints ?? [])
|
|
959
|
-
}
|
|
960
|
-
|
|
961
|
-
return { raw: tree.raw, roots: newRoots }
|
|
962
|
-
}
|
|
963
|
-
|
|
964
|
-
/**
|
|
965
|
-
* Record a dropped dual-role locality as a `locality` INTERPRETATION on the resolved region node (#415, generalizes
|
|
966
|
-
* #405's synthesized node). Consults `coincidentLocalitiesFor(regionID)` (O(1) map lookup — no distance math, no
|
|
967
|
-
* backend query), picks the principal city ({@link pickCompletion}: population-primary, distance tiebreak, abstain on
|
|
968
|
-
* a genuine tie), and appends an interpretation to `regionNode.interpretations`. No-op when the backend has no
|
|
969
|
-
* relation, the region isn't a dual-role place, or it abstains. The region node's primary role stays `region`; the
|
|
970
|
-
* locality rides alongside.
|
|
971
|
-
*/
|
|
972
|
-
#completeRegionRole(region: CoordinateOptionalPlace, regionNode: AddressNode): void {
|
|
973
|
-
if (typeof region.id !== "number" || !this.#backend.coincidentLocalitiesFor) return
|
|
974
|
-
const loc = pickCompletion(this.#backend.coincidentLocalitiesFor(region.id))
|
|
975
|
-
|
|
976
|
-
if (!loc) return
|
|
977
|
-
|
|
978
|
-
const interpretation: Interpretation = {
|
|
979
|
-
tag: "locality",
|
|
980
|
-
placeID: `wof:${loc.id}`,
|
|
981
|
-
sourceID: `${loc.placetype}:${loc.id}`,
|
|
982
|
-
lat: loc.lat,
|
|
983
|
-
lon: loc.lon,
|
|
984
|
-
confidence: 0,
|
|
985
|
-
metadata: { relationship_type: loc.relationshipType, resolver_completed: true, resolver_name: loc.name },
|
|
986
|
-
}
|
|
987
|
-
|
|
988
|
-
regionNode.interpretations = [...(regionNode.interpretations ?? []), interpretation]
|
|
989
|
-
}
|
|
990
|
-
|
|
991
|
-
async #walk(
|
|
992
|
-
node: AddressNode,
|
|
993
|
-
parentResolved: CoordinateOptionalPlace | null,
|
|
994
|
-
state: ResolutionState
|
|
995
|
-
): Promise<AddressNode> {
|
|
996
|
-
// Always clone — never mutate input nodes.
|
|
997
|
-
const decorated: AddressNode = { ...node, children: [] }
|
|
998
|
-
|
|
999
|
-
const placetype = state.placetypeMap[node.tag as ComponentTag]
|
|
1000
|
-
|
|
1001
|
-
// Track locality presence for hierarchy completion (#405): completion must NOT fire if the parser
|
|
1002
|
-
// already emitted a locality node (even one that failed to resolve) — it only fills a genuine
|
|
1003
|
-
// gap. Cheap and always-on; only consulted when hierarchyCompletion is set.
|
|
1004
|
-
if (placetype === "locality") {
|
|
1005
|
-
state.localityNodePresent = true
|
|
1006
|
-
}
|
|
1007
|
-
|
|
1008
|
-
let resolved: CoordinateOptionalPlace | null = null
|
|
1009
|
-
|
|
1010
|
-
// Shape-excluded postcode spans (letter-bearing ones keep their tag; #31 Mechanism 1) are
|
|
1011
|
-
// stripped of their resolve contribution — the walk does not look them up. Digit-only excluded
|
|
1012
|
-
// spans were retagged to `house_number` and flow through their correct sibling placetype.
|
|
1013
|
-
if (placetype && state.lookupsRemaining > 0 && node.value.trim().length && !isShapeExcludedPostcode(node)) {
|
|
1014
|
-
const picked = await this.#lookupAndPick(node, placetype, parentResolved, state)
|
|
1015
|
-
|
|
1016
|
-
if (picked) {
|
|
1017
|
-
resolved = picked.top
|
|
1018
|
-
decorateNode(decorated, picked.top, picked.alternatives)
|
|
1019
|
-
|
|
1020
|
-
if (picked.metadata) {
|
|
1021
|
-
decorated.metadata = { ...decorated.metadata, ...picked.metadata }
|
|
1022
|
-
}
|
|
1023
|
-
|
|
1024
|
-
// Lineage attachment (#404): stamp the resolved place's ancestor chain onto metadata. Opt-in
|
|
1025
|
-
// + only when the backend supplies it, so the default stays byte-identical (no extra query).
|
|
1026
|
-
if (state.includeAncestors && this.#backend.ancestors) {
|
|
1027
|
-
decorated.metadata = { ...decorated.metadata, ancestors: this.#backend.ancestors(picked.top.id) }
|
|
1028
|
-
}
|
|
1029
|
-
|
|
1030
|
-
// Capture the first resolved region (place + node) for hierarchy completion — the locality
|
|
1031
|
-
// interpretation is pushed onto this node in the post-walk pass.
|
|
1032
|
-
if (placetype === "region" && state.resolvedRegion === null) {
|
|
1033
|
-
state.resolvedRegion = picked.top
|
|
1034
|
-
state.resolvedRegionNode = decorated
|
|
1035
|
-
}
|
|
1036
|
-
}
|
|
1037
|
-
}
|
|
1038
|
-
|
|
1039
|
-
const carryParent = resolved ?? parentResolved
|
|
1040
|
-
|
|
1041
|
-
for (const child of node.children) {
|
|
1042
|
-
decorated.children.push(await this.#walk(child, carryParent, state))
|
|
1043
|
-
}
|
|
1044
|
-
|
|
1045
|
-
return decorated
|
|
1046
|
-
}
|
|
1047
|
-
|
|
1048
|
-
async #lookupAndPick(
|
|
1049
|
-
node: AddressNode,
|
|
1050
|
-
placetype: string,
|
|
1051
|
-
parentResolved: CoordinateOptionalPlace | null,
|
|
1052
|
-
state: ResolutionState
|
|
1053
|
-
): Promise<{
|
|
1054
|
-
top: CoordinateOptionalPlace
|
|
1055
|
-
alternatives: ResolvedPlace[]
|
|
1056
|
-
metadata?: Record<string, unknown>
|
|
1057
|
-
} | null> {
|
|
1058
|
-
state.lookupsRemaining--
|
|
1059
|
-
|
|
1060
|
-
const query: Parameters<ResolverBackend["findPlace"]>[0] = {
|
|
1061
|
-
text: node.value,
|
|
1062
|
-
placetype,
|
|
1063
|
-
limit: state.candidatesPerLookup,
|
|
1064
|
-
}
|
|
1065
|
-
|
|
1066
|
-
// Proximity bias (viewport center, user location, …) — a SOFT re-rank the backend folds into
|
|
1067
|
-
// its exact-tier prominence; never a filter, so recall is untouched. This is how an ambiguous
|
|
1068
|
-
// bare postcode ("48026") follows the map view instead of a global population coin-flip.
|
|
1069
|
-
if (state.bias && state.bias.length) {
|
|
1070
|
-
query.bias = state.bias
|
|
1071
|
-
}
|
|
1072
|
-
|
|
1073
|
-
// Pass the inherited parent constraint to the backend when available — `parentID` scopes to
|
|
1074
|
-
// the resolved parent's descendants. For `country`: a resolved parent's country wins, else
|
|
1075
|
-
// fall back to the caller's `defaultCountry`. Without this top-level hint a bare "IL" over a
|
|
1076
|
-
// multi-country gazetteer fuzzy-matches a foreign place (e.g. a French region) — see the
|
|
1077
|
-
// Direction-C resolver eval.
|
|
1078
|
-
if (parentResolved && typeof parentResolved.id === "number") {
|
|
1079
|
-
query.parentID = parentResolved.id
|
|
1080
|
-
}
|
|
1081
|
-
|
|
1082
|
-
// #194: a resolved parent's country wins, then the caller's `defaultCountry`, then the confident
|
|
1083
|
-
// placer `hardCountry`. All three are a HARD candidate filter. The placer's `hardCountry` is gated
|
|
1084
|
-
// upstream on high confidence (so it only fires when the model is sure), and on a miss the node is
|
|
1085
|
-
// left UNRESOLVED rather than re-resolved globally: the off-continent rows are precisely the ones
|
|
1086
|
-
// whose locality isn't in the country's gazetteer slice, so a global retry would just re-admit the
|
|
1087
|
-
// wrong-continent guess the hard filter exists to drop ("in-region or unresolved"). Measured: a
|
|
1088
|
-
// global fallback collapses back to the soft-prior baseline (FI p90 3050, PL p90 1078); pure-hard
|
|
1089
|
-
// collapses the tail (FI 18 km, PL p99 8172→494) at a coverage-bounded recall cost.
|
|
1090
|
-
// #833 forward linkage: a node's own `country_hint` (an address-system recognizer's derived country —
|
|
1091
|
-
// today `recognizeUSRegions` stamping "US" on a recognized closed-set US state) constrains THIS node's
|
|
1092
|
-
// lookup when the caller supplied no locale/default country. A caller scope outranks this derived hint:
|
|
1093
|
-
// `WA` is both Washington and Western Australia, so en-AU must reach the AU candidate instead of being
|
|
1094
|
-
// overwritten by the US-only recognizer. A genuine foreign subdivision under the wrong locale is recovered
|
|
1095
|
-
// later by region-country coherence after the scoped lookup abstains.
|
|
1096
|
-
const countryHint = node.metadata?.["country_hint"]
|
|
1097
|
-
|
|
1098
|
-
const country =
|
|
1099
|
-
parentResolved?.country ??
|
|
1100
|
-
state.defaultCountry ??
|
|
1101
|
-
(typeof countryHint === "string" ? countryHint : undefined) ??
|
|
1102
|
-
state.hardCountry
|
|
1103
|
-
|
|
1104
|
-
if (country) {
|
|
1105
|
-
query.country = country
|
|
1106
|
-
}
|
|
1107
|
-
|
|
1108
|
-
// Coordinate-first: hand the sibling postcode to locality lookups so the backend can inject
|
|
1109
|
-
// postcode-proximal candidates the name-match would miss. Only for locality (the placetype both
|
|
1110
|
-
// `locality` and `dependent_locality` map to); other placetypes ignore it. The containment flag
|
|
1111
|
-
// (#31, Mechanism 2) asks a coordinate-first backend to re-rank the candidates by proximity to
|
|
1112
|
-
// the postcode's own centroid — opt-in, OFF by default.
|
|
1113
|
-
if (placetype === "locality" && state.postcode) {
|
|
1114
|
-
query.postcode = state.postcode
|
|
1115
|
-
|
|
1116
|
-
if (state.postcodeContainmentCoherence) {
|
|
1117
|
-
query.postcodeContainmentCoherence = true
|
|
1118
|
-
}
|
|
1119
|
-
}
|
|
1120
|
-
|
|
1121
|
-
let candidates: ResolvedPlace[]
|
|
1122
|
-
|
|
1123
|
-
try {
|
|
1124
|
-
candidates = await this.#backend.findPlace(query)
|
|
1125
|
-
|
|
1126
|
-
// Parent soft-gating: `parentID` is a HARD descendant filter in the backend, which wrongly
|
|
1127
|
-
// zeroes the result when the parent resolved wrong OR the gazetteer hierarchy is incomplete
|
|
1128
|
-
// (a real locality whose `ancestors` chain is missing its region). Rather than turn a
|
|
1129
|
-
// resolvable node into an unresolved one, retry once WITHOUT the parent constraint — we
|
|
1130
|
-
// prefer a parent-scoped hit but never sacrifice recall. The country constraint is kept, so
|
|
1131
|
-
// this still can't wander to a foreign place. Same logical resolution → no extra budget.
|
|
1132
|
-
if (!candidates.length && state.parentFallback && query.parentID !== undefined) {
|
|
1133
|
-
delete query.parentID
|
|
1134
|
-
candidates = await this.#backend.findPlace(query)
|
|
1135
|
-
}
|
|
1136
|
-
} catch {
|
|
1137
|
-
// Defensive: a backend failure should not abort the whole tree walk. Leave the node with
|
|
1138
|
-
// its classifier attribution intact.
|
|
1139
|
-
return null
|
|
1140
|
-
}
|
|
1141
|
-
|
|
1142
|
-
// Postcode-prefix prior (#31, Mechanism 3): when a `postalcode` node misses the gazetteer, derive
|
|
1143
|
-
// the code's prefix and probe the injected PFX1 index (structural — never a model input). A hit
|
|
1144
|
-
// resolves the node to a synthetic place (id 0), carrying a coordinate ONLY when the index node
|
|
1145
|
-
// does — the ancestry-only tier stays coordinate-free (B3-3's 0% half, meaning-of-zero). The
|
|
1146
|
-
// prior's payload is returned as node metadata for #walk to stamp. Opt-in via `postcodePrefixPrior`
|
|
1147
|
-
// + `postcodePrefixIndex`; OFF by default (D-rule: the PCN1 posture).
|
|
1148
|
-
if (!candidates.length && placetype === "postalcode" && state.postcodePrefixPrior && state.postcodePrefixIndex) {
|
|
1149
|
-
const probe = probePostcodePrefix(node.value, state.postcodePrefixIndex, query.country)
|
|
1150
|
-
|
|
1151
|
-
if (probe) {
|
|
1152
|
-
const metadata: Record<string, unknown> = {
|
|
1153
|
-
postcode_prefix: probe.prefix,
|
|
1154
|
-
postcode_prefix_ancestors: probe.node.ancestors,
|
|
1155
|
-
...(probe.node.radiusP95Km !== undefined ? { postcode_prefix_radius_p95_km: probe.node.radiusP95Km } : {}),
|
|
1156
|
-
...(probe.node.lat !== undefined && probe.node.lon !== undefined
|
|
1157
|
-
? { coordinate_source: "postcode_prefix" }
|
|
1158
|
-
: {}),
|
|
1159
|
-
}
|
|
1160
|
-
|
|
1161
|
-
return {
|
|
1162
|
-
top: postcodePrefixResolvedPlace(probe.prefix, probe.node, state.postcodePrefixIndex),
|
|
1163
|
-
alternatives: [],
|
|
1164
|
-
metadata,
|
|
1165
|
-
}
|
|
1166
|
-
}
|
|
1167
|
-
}
|
|
1168
|
-
|
|
1169
|
-
if (!candidates.length) return null
|
|
1170
|
-
// Postcode-anchor re-rank (#369): when a country posterior is supplied (from the address's
|
|
1171
|
-
// postcode), boost candidates by `anchorWeight * posterior[candidate.country]` and re-sort, so a
|
|
1172
|
-
// postcode that pins the country pulls the right-country place over a higher-BM25 foreign namesake
|
|
1173
|
-
// (the "Berlin DE vs Berlin US" class the #59 harness measured). No-op when `anchorPosterior` is
|
|
1174
|
-
// undefined (the default) → byte-identical resolution.
|
|
1175
|
-
//
|
|
1176
|
-
// Applied to BOTH region and locality — the two placetypes that suffer cross-country namesake/
|
|
1177
|
-
// abbreviation collisions a country posterior can break. The region case is the one #447's window
|
|
1178
|
-
// fix couldn't reach: a bare 2-letter abbreviation is shared across countries ("VT" is
|
|
1179
|
-
// both Vermont and Viterbo; "ME" both Maine and Messina), so with no country signal the score
|
|
1180
|
-
// picks the wrong one — and because resolveTree resolves region FIRST and inherits its country
|
|
1181
|
-
// down, a wrong region poisons the locality too. The postcode posterior breaks the tie at the
|
|
1182
|
-
// region, and the right country then flows to the locality. (Country/macroregion/county are
|
|
1183
|
-
// excluded: they don't exhibit this collision class and carry country via `parentID` when nested.)
|
|
1184
|
-
//
|
|
1185
|
-
// Tier-SAFE ordering: the candidate's exact-match flag is the PRIMARY key, so the country pin
|
|
1186
|
-
// never crosses the exact/partial boundary. WITHIN a tier, `score + anchorWeight * posterior`
|
|
1187
|
-
// applies the (soft) country boost. So a confident US postcode keeps the US EXACT region
|
|
1188
|
-
// ("ME" → Maine) ahead of a more-populous US PARTIAL match (Missouri) AND, within the exact
|
|
1189
|
-
// tier, ahead of a foreign exact match (Messina IT); a soft posterior still blends with score.
|
|
1190
|
-
// (A plain additive re-rank loses the tier — it isn't encoded in `score` — and flips
|
|
1191
|
-
// "ME" → Missouri / "PA" → Alabama. Backends that don't set `exactMatch` degrade to additive.)
|
|
1192
|
-
const anchorEligible = placetype === "region" || placetype === "locality"
|
|
1193
|
-
let ranked = candidates
|
|
1194
|
-
|
|
1195
|
-
if (state.anchorPosterior && anchorEligible && candidates.length > 1) {
|
|
1196
|
-
const post = state.anchorPosterior
|
|
1197
|
-
const w = state.anchorWeight
|
|
1198
|
-
|
|
1199
|
-
// #928 root cause: this sort's within-tier key was `score + w·posterior` — RAW SCORE order,
|
|
1200
|
-
// the exact metric #910 deprecated inside the exact tier as bm25-length-poisoned (a famous
|
|
1201
|
-
// place's alias-heavy doc reads ~15 pts WORSE than a tiny namesake's clean one; #905
|
|
1202
|
-
// measured it). Before #910 the anchor-off path also sorted by score, so the two paths
|
|
1203
|
-
// agreed; after, anchor-ON silently reverted to the poisoned metric — a CORRECT GB@1.00
|
|
1204
|
-
// pin flipped "London SE15 1DD" to a US namesake because +w·1.0 can't bridge the bm25 gap.
|
|
1205
|
-
// The within-tier key is now the backend's PROMINENCE (population + proximity, #938 units)
|
|
1206
|
-
// with the posterior as the additive country pin; score stays the final tiebreak. Backends
|
|
1207
|
-
// that don't populate `prominence` degrade to the additive score behavior.
|
|
1208
|
-
// oxlint-disable-next-line unicorn/no-array-sort -- sorts a freshly-built array; toSorted would double-allocate on a hot path
|
|
1209
|
-
ranked = [...candidates].sort((a, b) => {
|
|
1210
|
-
const tier = Number(b.exactMatch ?? false) - Number(a.exactMatch ?? false)
|
|
1211
|
-
|
|
1212
|
-
if (tier !== 0) return tier
|
|
1213
|
-
const aKey = (a.prominence ?? a.score) + w * (post[a.country] ?? 0)
|
|
1214
|
-
const bKey = (b.prominence ?? b.score) + w * (post[b.country] ?? 0)
|
|
1215
|
-
|
|
1216
|
-
return bKey - aKey || b.score - a.score
|
|
1217
|
-
})
|
|
1218
|
-
}
|
|
1219
|
-
|
|
1220
|
-
// Locale-country soft prior (#27) — the #912 lever's other half, at the tier that decides a bare
|
|
1221
|
-
// toponym the model tagged `locality`. `--locale en-GB "Whitby"` answers Whitby, Ontario while
|
|
1222
|
-
// `--default-country GB "Whitby"` answers the gold, because the CLI DROPS the locale-inferred
|
|
1223
|
-
// country for this shape rather than choosing between "hard filter" and "nothing". This is the
|
|
1224
|
-
// third option: an additive bonus inside the exact tier, never a filter.
|
|
1225
|
-
//
|
|
1226
|
-
// Three stand-downs, in the order they matter. A `defaultCountry` makes the prior a no-op by
|
|
1227
|
-
// construction (every candidate is already in it), so we skip the work rather than pretend. An
|
|
1228
|
-
// `anchorPosterior` is derived from the address's OWN postcode — evidence, which outranks a guess
|
|
1229
|
-
// about where the user is sitting. And an absent prior is the SHIPPED default: `ResolveOpts`
|
|
1230
|
-
// documents why (the weight that flips the four bare GB rows and the weight that holds the en-US
|
|
1231
|
-
// board are disjoint intervals), so this is inert unless a caller opts in.
|
|
1232
|
-
//
|
|
1233
|
-
// Runs BEFORE the importance key deliberately, matching span-rescore: fame is the stronger signal
|
|
1234
|
-
// wherever it has been measured, and it leaves an unscored candidate exactly where the prior put it.
|
|
1235
|
-
if (state.localeCountryPrior && !state.defaultCountry && !state.anchorPosterior && anchorEligible) {
|
|
1236
|
-
ranked = rankByCountryPrior(ranked, state.localeCountryPrior, state.localeCountryPriorWeight)
|
|
1237
|
-
}
|
|
1238
|
-
|
|
1239
|
-
// Importance-first (#17/#28). Before this key a bare famous name was decided on POPULATION
|
|
1240
|
-
// alone, which is measurably the wrong prior for the class: `Whitby` answered Whitby, Ontario
|
|
1241
|
-
// (128,377) over Whitby, North Yorkshire (13,130), 5,508 km from where the person meant. Fame is
|
|
1242
|
-
// what a bare toponym is asking about, and the candidate build's blended `importance` column
|
|
1243
|
-
// measures it. Tier-safe and positive-evidence-only (an UNSCORED candidate keeps the rank
|
|
1244
|
-
// population gave it; only the scored ones permute), so it abstains byte-stably on an artifact
|
|
1245
|
-
// that predates the column.
|
|
1246
|
-
//
|
|
1247
|
-
// Skipped outright when an anchor posterior is in force. Fame is the prior of LAST resort: it answers
|
|
1248
|
-
// "which one did you probably mean" only when nothing in the query answered it, and a #369 posterior is
|
|
1249
|
-
// derived from the address's OWN postcode. Evidence outranks a prior. See `toponym-prior.ts`.
|
|
1250
|
-
if (!state.anchorPosterior) {
|
|
1251
|
-
ranked = rankByImportance(ranked)
|
|
1252
|
-
}
|
|
1253
|
-
|
|
1254
|
-
// Exact-type preference (#718): when the placetype-equivalence group let a broader admin tier
|
|
1255
|
-
// (`macroregion`/`macrocounty`) into the candidate pool, prefer a candidate of the EXACT
|
|
1256
|
-
// requested type over the macro fallback — a real `region` (US state, DE Bundesland, ES
|
|
1257
|
-
// provincia) must win over a same-name macroregion namesake, so no real region silently
|
|
1258
|
-
// downgrades to a macro. STABLE partition: exact-type candidates keep their (already-ranked)
|
|
1259
|
-
// relative order ahead of fallbacks, so the score / anchor re-rank survives WITHIN each tier.
|
|
1260
|
-
// No-op for placetypes without a macro fallback (the byte-stable default) and when every
|
|
1261
|
-
// candidate is the same tier.
|
|
1262
|
-
const hasFallbackCandidate = ranked.some((c) => isPlacetypeFallback(placetype, c.placetype))
|
|
1263
|
-
|
|
1264
|
-
if (hasFallbackCandidate && ranked.length > 1) {
|
|
1265
|
-
ranked = [
|
|
1266
|
-
...ranked.filter((c) => !isPlacetypeFallback(placetype, c.placetype)),
|
|
1267
|
-
...ranked.filter((c) => isPlacetypeFallback(placetype, c.placetype)),
|
|
1268
|
-
]
|
|
1269
|
-
}
|
|
1270
|
-
|
|
1271
|
-
const top = ranked[0]!
|
|
1272
|
-
|
|
1273
|
-
if (top.score < state.minWinningScore) return null
|
|
1274
|
-
|
|
1275
|
-
// Fallback-observability (#718): if the winner is a macro-type AND no exact-type candidate
|
|
1276
|
-
// existed for this span, annotate that a broader tier stood in for the true one. Additive —
|
|
1277
|
-
// identity/coordinate are unchanged; only `metadata.resolution_quality` is stamped downstream.
|
|
1278
|
-
if (isPlacetypeFallback(placetype, top.placetype)) {
|
|
1279
|
-
top.resolutionQuality = "fallback"
|
|
1280
|
-
}
|
|
1281
|
-
|
|
1282
|
-
return { top, alternatives: ranked.slice(1) }
|
|
1283
|
-
}
|
|
1284
|
-
}
|
|
1285
|
-
|
|
1286
|
-
/**
|
|
1287
|
-
* Stamp a node with resolver-supplied attribution. Displaces any prior classifier `source` / `sourceID` into
|
|
1288
|
-
* `metadata.classifier_source` / `metadata.classifier_source_id` so debugging tools can still see who made the original
|
|
1289
|
-
* assertion. Surfaces the runner-up candidates on `alternatives` so callers can disambiguate (Springfield-class
|
|
1290
|
-
* failures, [#8 in the failure catalogue]).
|
|
1291
|
-
*/
|
|
1292
|
-
function decorateNode(node: AddressNode, resolved: CoordinateOptionalPlace, alternatives: ResolvedPlace[]): void {
|
|
1293
|
-
if (node.source !== undefined || node.sourceID !== undefined) {
|
|
1294
|
-
const meta = { ...node.metadata }
|
|
1295
|
-
|
|
1296
|
-
if (node.source !== undefined) {
|
|
1297
|
-
meta["classifier_source"] = node.source
|
|
1298
|
-
}
|
|
1299
|
-
|
|
1300
|
-
if (node.sourceID !== undefined) {
|
|
1301
|
-
meta["classifier_source_id"] = node.sourceID
|
|
1302
|
-
}
|
|
1303
|
-
|
|
1304
|
-
node.metadata = meta
|
|
1305
|
-
}
|
|
1306
|
-
|
|
1307
|
-
node.source = "resolver"
|
|
1308
|
-
node.sourceID = `${resolved.placetype}:${resolved.id}`
|
|
1309
|
-
node.lat = resolved.lat
|
|
1310
|
-
node.lon = resolved.lon
|
|
1311
|
-
node.placeID = `wof:${resolved.id}` // v1: only WOF resolvers; the URI scheme stays this simple
|
|
1312
|
-
// Record the resolver's ranking score AND the resolved place's CANONICAL name. The name is the
|
|
1313
|
-
// gazetteer's truth for the place we picked — distinct from `node.value` (the raw input span). It
|
|
1314
|
-
// lets consumers display the canonical name and lets the end-to-end eval check the resolver chose
|
|
1315
|
-
// the right PLACE (gazetteer-name vs ground-truth) rather than merely echoing the parser's text.
|
|
1316
|
-
node.metadata = { ...node.metadata, resolver_score: resolved.score, resolver_name: resolved.name }
|
|
1317
|
-
|
|
1318
|
-
// The winner's PROMINENCE, when the backend computed one. `alternatives` below are full `ResolvedPlace`s and
|
|
1319
|
-
// already carry theirs; without this stamp the WINNER's is the one value in the ranked list that gets dropped,
|
|
1320
|
-
// which makes a top-1-vs-top-2 margin uncomputable from the tree — and that margin is what
|
|
1321
|
-
// `mailwoman/query-intent.ts` reads to decide whether a bare-toponym answer was a clear win. Additive metadata
|
|
1322
|
-
// only; nothing in the resolve reads it back.
|
|
1323
|
-
if (resolved.prominence !== undefined) {
|
|
1324
|
-
node.metadata["resolver_prominence"] = resolved.prominence
|
|
1325
|
-
}
|
|
1326
|
-
|
|
1327
|
-
// The resolved place's ISO-3166 alpha-2 country (from the gazetteer/candidate row), when known. #1014: lets a
|
|
1328
|
-
// forward consumer fill country/countrycode without an ancestry walk — the candidate backend carries this even
|
|
1329
|
-
// though it has no `ancestors()` table.
|
|
1330
|
-
if (resolved.country) {
|
|
1331
|
-
node.metadata["resolver_country"] = resolved.country
|
|
1332
|
-
}
|
|
1333
|
-
|
|
1334
|
-
// The score-channel carries (ROAD_TO_V9 §2 + #28). Written ONLY when the backend actually has a
|
|
1335
|
-
// value: an absent score means "unmeasured" or "pre-split gazetteer", and a `resolver_*: 0` on the
|
|
1336
|
-
// node would assert a measurement nobody made. Nothing in the resolve path reads these keys back —
|
|
1337
|
-
// they exist for annotation / API surfaces downstream. `resolver_importance` is the blended #28
|
|
1338
|
-
// prior (the value the ranking consulted); `resolver_encyclopedic` is the strict channel, reserved
|
|
1339
|
-
// until a strict-channel source ships.
|
|
1340
|
-
if (resolved.referential !== undefined) {
|
|
1341
|
-
node.metadata["resolver_referential"] = resolved.referential
|
|
1342
|
-
}
|
|
1343
|
-
|
|
1344
|
-
if (resolved.encyclopedic !== undefined) {
|
|
1345
|
-
node.metadata["resolver_encyclopedic"] = resolved.encyclopedic
|
|
1346
|
-
}
|
|
1347
|
-
|
|
1348
|
-
if (resolved.importance !== undefined) {
|
|
1349
|
-
node.metadata["resolver_importance"] = resolved.importance
|
|
1350
|
-
}
|
|
1351
|
-
|
|
1352
|
-
// The postcode/locality conflict flag (the falsehood differentiator): the postcode pointed to a
|
|
1353
|
-
// geographically different place than the parsed city name. Surface it so callers can warn rather
|
|
1354
|
-
// than silently trust the resolved point.
|
|
1355
|
-
if (resolved.mismatch) {
|
|
1356
|
-
node.metadata["postcode_city_mismatch"] = true
|
|
1357
|
-
}
|
|
1358
|
-
|
|
1359
|
-
// Fallback-observability (#718): a broader admin tier (macroregion/macrocounty) stood in for the
|
|
1360
|
-
// true region/county because no exact-type candidate existed. Additive annotation only — the
|
|
1361
|
-
// resolved coordinate/identity above is untouched; this just lets a consumer / QA pass see it.
|
|
1362
|
-
if (resolved.resolutionQuality) {
|
|
1363
|
-
node.metadata["resolution_quality"] = resolved.resolutionQuality
|
|
1364
|
-
}
|
|
1365
|
-
|
|
1366
|
-
if (alternatives.length) {
|
|
1367
|
-
node.alternatives = alternatives
|
|
1368
|
-
}
|
|
1369
|
-
}
|