@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
|
@@ -0,0 +1,795 @@
|
|
|
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 { collectNodes, } from "@mailwoman/core/decoder";
|
|
16
|
+
import { DEFAULT_PLACETYPE_MAP, isPlacetypeFallback, countriesFromPostcodeFormat, } from "@mailwoman/core/resolver";
|
|
17
|
+
import { applyAdminCoherence, applyExplicitCountryCoherence, applyRegionCountryCoherence, } from "#admin/coherence-passes";
|
|
18
|
+
import { adminContainmentVerdict, firstRegionQualifier, partitionByContainment } from "#admin/containment";
|
|
19
|
+
import { resolveCompoundMunicipality } from "#admin/jp-municipality";
|
|
20
|
+
import { describeCapabilityGaps, reportCapabilityGaps } from "#backend-capabilities";
|
|
21
|
+
import { BARE_REGION_DOMINANCE_LOG10, bareCountryCandidate, bareRegionCandidate, logPopulation, loneBareLocalityNode, pickLargerAdmin, } from "#bare-toponym-race";
|
|
22
|
+
import { decorateNode } from "#decorate-node";
|
|
23
|
+
import { findPostcodeCountryScope, stampPostcodeCountryScope, } from "#postcode/country-coherence";
|
|
24
|
+
import { postcodePrefixResolvedPlace, probePostcodePrefix } from "#postcode/prefix";
|
|
25
|
+
import { applyPostcodeShapeCoherence, isShapeExcludedPostcode } from "#postcode/shape-coherence";
|
|
26
|
+
import { applyPostcodeConsistency, applySpanRescore, createNodeTraceRecorder, DIAGNOSTIC_BANDS, firstPostcodeValue, NOOP_TRACE_RECORDER, pickCompletion, } from "#resolve/passes";
|
|
27
|
+
import { applyAddressPoint, applyInterpolation, applyStreetCentroid } from "#street/tier";
|
|
28
|
+
import { DEFAULT_COUNTRY_PRIOR_WEIGHT, promoteCapitals, rankByCountryPrior, rankByImportance, } from "#toponym-prior";
|
|
29
|
+
/**
|
|
30
|
+
* Build a `Resolver` backed by a `ResolverBackend`. The backend can be any concrete impl structurally compatible with
|
|
31
|
+
* `PlaceLookup` — e.g. `new WOFSQLitePlaceLookup({ databasePath }).asResolverBackend()` or a fake for tests.
|
|
32
|
+
*/
|
|
33
|
+
export function createWOFResolver(backend) {
|
|
34
|
+
return new WOFResolver(backend);
|
|
35
|
+
}
|
|
36
|
+
/**
|
|
37
|
+
* #1735 (second half) — the tree's own country statement, when it is unambiguous.
|
|
38
|
+
*
|
|
39
|
+
* "SW1A 1AA, UK" under the en-US default parsed correctly and still failed: the walk resolved the country NODE to GB,
|
|
40
|
+
* but a sibling's resolution never scopes a sibling — the postcode lookup ran under the locale-inferred `country=US`
|
|
41
|
+
* hard filter and missed. An explicit country token is the address's OWN scope declaration, which outranks a locale
|
|
42
|
+
* inference the same way the #912 posture ranks explicit over inferred.
|
|
43
|
+
*
|
|
44
|
+
* Deterministically guarded: exactly ONE country-tagged node, whose value `matchCountry` maps to one ISO country, and
|
|
45
|
+
* whose value is NOT also a subdivision name — "Georgia" maps to GE _and_ names a US state, so it never pre-scopes (the
|
|
46
|
+
* existing coherence passes keep handling it). Returns the alpha-2 or null.
|
|
47
|
+
*/
|
|
48
|
+
function explicitCountryScope(roots) {
|
|
49
|
+
const countryNodes = collectNodes(roots, (node) => node.tag === "country" && node.value.trim().length > 0);
|
|
50
|
+
if (countryNodes.length !== 1)
|
|
51
|
+
return null;
|
|
52
|
+
const value = countryNodes[0].value.trim();
|
|
53
|
+
const matched = matchCountry(value);
|
|
54
|
+
if (!matched)
|
|
55
|
+
return null;
|
|
56
|
+
if (matchSubdivision(value))
|
|
57
|
+
return null;
|
|
58
|
+
return matched.iso2;
|
|
59
|
+
}
|
|
60
|
+
class WOFResolver {
|
|
61
|
+
#backend;
|
|
62
|
+
/**
|
|
63
|
+
* The gazetteer artifact's self-declared coverage facts, passed through from the backend so pipeline-level consumers
|
|
64
|
+
* read them from the resolver handle they already hold. Absent on artifacts predating the coverage manifest.
|
|
65
|
+
*/
|
|
66
|
+
artifactCoverage;
|
|
67
|
+
/**
|
|
68
|
+
* Optional backend methods this backend omits, each naming the default-ON option it silently disables. Computed once
|
|
69
|
+
* here rather than at each guard site so a caller can read the gap before running a query that would quietly skip the
|
|
70
|
+
* feature. See `backend-capabilities.ts`.
|
|
71
|
+
*/
|
|
72
|
+
capabilityGaps;
|
|
73
|
+
constructor(backend) {
|
|
74
|
+
this.#backend = backend;
|
|
75
|
+
this.artifactCoverage = backend.artifactCoverage;
|
|
76
|
+
this.capabilityGaps = describeCapabilityGaps(backend);
|
|
77
|
+
reportCapabilityGaps(this.capabilityGaps);
|
|
78
|
+
}
|
|
79
|
+
/**
|
|
80
|
+
* The `Resolver.findPlace` passthrough — one direct gazetteer probe for pipeline-level consumers (#1738's
|
|
81
|
+
* dominant-bearer guard). Bound as a method so `this.#backend` stays private.
|
|
82
|
+
*/
|
|
83
|
+
findPlace = (query) => this.#backend.findPlace(query);
|
|
84
|
+
async resolveTree(tree, opts = {}) {
|
|
85
|
+
// Postcode-shape coherence (#31, Mechanism 1): the earliest pass in the tree — pure-sync and
|
|
86
|
+
// backend-free, run BEFORE `state.postcode` is read so an excluded span can never become the
|
|
87
|
+
// address's postcode. Opt-in (`postcodeShapeCoherence: true`), OFF by default (D-rule: demotion
|
|
88
|
+
// is the failure mode with teeth). A confirmed span's narrowed systems — the intersection of
|
|
89
|
+
// its codex shape with the tree's confident sibling systems — bound the country-scope pass
|
|
90
|
+
// below; a pure subset of codex's own candidate list, so it can only narrow, never widen.
|
|
91
|
+
// See postcode-shape-coherence.ts.
|
|
92
|
+
const shapeVerdict = opts.postcodeShapeCoherence === true ? applyPostcodeShapeCoherence(tree.roots) : null;
|
|
93
|
+
const state = {
|
|
94
|
+
lookupsRemaining: opts.maxLookups ?? 10,
|
|
95
|
+
// Full replacement when `placetypeMap` is supplied — callers that want to extend rather
|
|
96
|
+
// than replace should spread DEFAULT_PLACETYPE_MAP themselves.
|
|
97
|
+
placetypeMap: opts.placetypeMap ?? DEFAULT_PLACETYPE_MAP,
|
|
98
|
+
minWinningScore: opts.minWinningScore ?? 0,
|
|
99
|
+
candidatesPerLookup: opts.candidatesPerLookup ?? 5,
|
|
100
|
+
defaultCountry: opts.defaultCountry,
|
|
101
|
+
defaultCountryIsInferred: opts.defaultCountryIsInferred === true,
|
|
102
|
+
bareLocalityNode: loneBareLocalityNode(tree, opts.placetypeMap ?? DEFAULT_PLACETYPE_MAP),
|
|
103
|
+
parentFallback: opts.parentFallback ?? true,
|
|
104
|
+
// Requires a sink: with nowhere to record the answer the probes would be pure cost.
|
|
105
|
+
...(opts.diagnoseUnreachable && opts.traceSink ? { diagnoseUnreachable: true } : {}),
|
|
106
|
+
postcode: firstPostcodeValue(tree.roots),
|
|
107
|
+
// #31 Mechanism 2 — forwarded to locality lookups (see #lookupAndPick). Opt-in, OFF by default.
|
|
108
|
+
postcodeContainmentCoherence: opts.postcodeContainmentCoherence === true,
|
|
109
|
+
// #31 Mechanism 3 — the prefix prior + its injected index (see #lookupAndPick). Opt-in, OFF by default.
|
|
110
|
+
postcodePrefixPrior: opts.postcodePrefixPrior === true,
|
|
111
|
+
postcodePrefixIndex: opts.postcodePrefixIndex,
|
|
112
|
+
// #1589: derived here when the caller didn't thread it, so the browser cascade and the
|
|
113
|
+
// drop-ins get the implied-set probe without per-caller wiring (the staged-repoint e2e
|
|
114
|
+
// caught `100 00` resolving in Node and not in the browser over the same artifact).
|
|
115
|
+
postcodeFormatCountries: opts.postcodeFormatCountries ?? countriesFromPostcodeFormat(firstPostcodeValue(tree.roots)),
|
|
116
|
+
fuzzyCountryScope: opts.fuzzyCountryScope,
|
|
117
|
+
bias: opts.bias,
|
|
118
|
+
anchorPosterior: opts.anchorPosterior,
|
|
119
|
+
anchorWeight: opts.anchorWeight ?? 2,
|
|
120
|
+
localeCountryPrior: opts.localeCountryPrior,
|
|
121
|
+
localeCountryPriorWeight: opts.localeCountryPriorWeight ?? DEFAULT_COUNTRY_PRIOR_WEIGHT,
|
|
122
|
+
capitalLevel: opts.capitalLevel,
|
|
123
|
+
hardCountry: opts.hardCountry,
|
|
124
|
+
// Default-ON (#402): completion only fires for a dual-role region whose locality the parser
|
|
125
|
+
// dropped, and no-ops entirely when the backend has no relation (the browser WASM resolver, or
|
|
126
|
+
// a gazetteer without `coincident_roles`). Pass `hierarchyCompletion: false` to opt out.
|
|
127
|
+
//
|
|
128
|
+
// Default-ON is nominal on the SHIPPED backend: `WOFCandidateTableLookup` implements no
|
|
129
|
+
// `coincidentLocalitiesFor`, so this attaches nothing there. Measured 2026-08-15 on FTS, which
|
|
130
|
+
// does implement it, the flag changed 0 of 837 board inputs — see ResolveOpts.hierarchyCompletion.
|
|
131
|
+
hierarchyCompletion: opts.hierarchyCompletion ?? true,
|
|
132
|
+
includeAncestors: opts.includeAncestors ?? false,
|
|
133
|
+
// #1717 stage 2 — default OFF (D-rule); the qualifier is pre-scanned like `postcode` above
|
|
134
|
+
// because region and locality are siblings the walk visits independently.
|
|
135
|
+
adminContainmentRerank: opts.adminContainmentRerank === true,
|
|
136
|
+
regionQualifier: firstRegionQualifier(tree.roots),
|
|
137
|
+
...(opts.traceSink ? { traceSink: opts.traceSink } : {}),
|
|
138
|
+
localityNodePresent: false,
|
|
139
|
+
resolvedRegion: null,
|
|
140
|
+
resolvedRegionNode: null,
|
|
141
|
+
};
|
|
142
|
+
// Postcode-country coherence (#42): the one pre-walk LOOKUP pass (the shape verdict above is
|
|
143
|
+
// pure-sync, backend-free), and the only mechanism allowed to override `defaultCountry`. Its three
|
|
144
|
+
// sibling coherence passes re-pick nodes AFTER the walk; that shape cannot work here, because what
|
|
145
|
+
// needs correcting is the walk's country SCOPE — which poisons the postcode node's own resolution,
|
|
146
|
+
// the postcode-consistency fallback that then drags the locality onto it, and the hard `country`
|
|
147
|
+
// filter on every admin lookup. So the verdict is taken once, up front, and the walk runs under the
|
|
148
|
+
// corrected country. Default-ON (operator-promoted 2026-08-05; `false` opts out) — needs a default
|
|
149
|
+
// country to correct and both a postcode and a locality to be coherent about; abstains unless
|
|
150
|
+
// EXACTLY one country (never the already-coherent default) makes the pair consistent. See
|
|
151
|
+
// postcode-country-coherence.ts.
|
|
152
|
+
let postcodeScope = null;
|
|
153
|
+
// The pass also runs with NO default in force (#1585/#861 convergence): there is nothing to
|
|
154
|
+
// override, but the same exactly-one-country abstention lets the postcode+locality pair
|
|
155
|
+
// CONSTRAIN an otherwise population-first walk — `Zabiče 8, 6250 Zabiče` picks the SI row
|
|
156
|
+
// coherent with the SI 6250 centroid instead of the more-populous Polish namesake. The
|
|
157
|
+
// browser cascade (which sets no default by design) is the consumer this exists for.
|
|
158
|
+
// #1735 second half: the address's own country statement scopes the walk BEFORE anything
|
|
159
|
+
// resolves — a sibling's resolution never reaches a sibling, so without this the postcode
|
|
160
|
+
// lookup in "RM10 8AB, UK" ran under the locale-inferred US filter while the country node
|
|
161
|
+
// resolved to GB beside it. Explicit-over-inferred, the #912 precedence, decided from the
|
|
162
|
+
// tree's own text; an EXPLICIT caller scope is never overridden.
|
|
163
|
+
let explicitScope = null;
|
|
164
|
+
if (!state.defaultCountry || state.defaultCountryIsInferred) {
|
|
165
|
+
explicitScope = explicitCountryScope(tree.roots);
|
|
166
|
+
if (explicitScope) {
|
|
167
|
+
state.defaultCountry = explicitScope;
|
|
168
|
+
state.defaultCountryIsInferred = false;
|
|
169
|
+
}
|
|
170
|
+
}
|
|
171
|
+
if (opts.postcodeCountryCoherence !== false && state.postcode) {
|
|
172
|
+
postcodeScope = await findPostcodeCountryScope(tree.roots, this.#backend, {
|
|
173
|
+
postcode: state.postcode,
|
|
174
|
+
defaultCountry: state.defaultCountry,
|
|
175
|
+
...(shapeVerdict?.narrowing !== undefined ? { candidateSystems: shapeVerdict.narrowing } : {}),
|
|
176
|
+
...(opts.postcodeCountryCoherenceThresholdKm !== undefined
|
|
177
|
+
? { thresholdKm: opts.postcodeCountryCoherenceThresholdKm }
|
|
178
|
+
: {}),
|
|
179
|
+
});
|
|
180
|
+
if (postcodeScope) {
|
|
181
|
+
// The override. `hardCountry` is not cleared because it is never consulted while a
|
|
182
|
+
// `defaultCountry` is set (`#lookupAndPick`'s precedence chain reaches it only as the last
|
|
183
|
+
// fallback), so replacing the default is sufficient to re-scope the entire walk.
|
|
184
|
+
state.defaultCountry = postcodeScope.country;
|
|
185
|
+
}
|
|
186
|
+
}
|
|
187
|
+
const newRoots = [];
|
|
188
|
+
for (const root of tree.roots) {
|
|
189
|
+
newRoots.push(await this.#walk(root, /* parentResolved */ null, state));
|
|
190
|
+
}
|
|
191
|
+
// Attribution for the override, stamped on the two nodes that bought it. Additive metadata only.
|
|
192
|
+
if (postcodeScope) {
|
|
193
|
+
stampPostcodeCountryScope(newRoots, postcodeScope);
|
|
194
|
+
}
|
|
195
|
+
// The pre-scope's receipt (#1735): consumers that select country-scoped artifacts AFTER the walk
|
|
196
|
+
// (geocode-core's rooftop-extract second pass) key on a scope stamp. Without this, an address whose
|
|
197
|
+
// country was right FROM THE TREE never writes one — the #42 pass stays silent because the default
|
|
198
|
+
// is already coherent — and the FR rooftop extract silently stops loading for "…, France" inputs
|
|
199
|
+
// under a non-FR locale (six board venue rows dropped from rooftop to city centroid; the battery
|
|
200
|
+
// caught it).
|
|
201
|
+
if (explicitScope) {
|
|
202
|
+
for (const root of newRoots) {
|
|
203
|
+
if (root.tag === "country") {
|
|
204
|
+
root.metadata = { ...root.metadata, explicit_country_scope: explicitScope };
|
|
205
|
+
}
|
|
206
|
+
}
|
|
207
|
+
}
|
|
208
|
+
// Dual-role hierarchy completion (#405/#415). Only when enabled, a region resolved, and the parser
|
|
209
|
+
// emitted NO locality — record the dropped locality as a SECONDARY ROLE (an interpretation) on the
|
|
210
|
+
// resolved region node, from the backend's precomputed coincident-roles relation (#403). One node,
|
|
211
|
+
// one span, two roles — no synthesized sibling. See ResolveOpts.hierarchyCompletion.
|
|
212
|
+
if (state.hierarchyCompletion && state.resolvedRegion && state.resolvedRegionNode && !state.localityNodePresent) {
|
|
213
|
+
this.#completeRegionRole(state.resolvedRegion, state.resolvedRegionNode);
|
|
214
|
+
}
|
|
215
|
+
// Admin descendant-consistency (#263): default-ON (#895 settled drift D1; `false` opts out). Re-pick a
|
|
216
|
+
// (region, locality) pair so the locality descends from the region — runs BEFORE postcode-consistency
|
|
217
|
+
// (it resolves the locality the postcode pass may then refine) and before the street tiers (which key
|
|
218
|
+
// off the postcode/street, not the admin coordinate this adjusts). Byte-stable when nothing fell
|
|
219
|
+
// through or the backend lacks `ancestors`.
|
|
220
|
+
if (opts.adminCoherence !== false) {
|
|
221
|
+
await applyAdminCoherence(newRoots, this.#backend);
|
|
222
|
+
// #822 — same joint-consistency family, inverse trigger: an explicit country token whose resolved
|
|
223
|
+
// locality landed in the wrong country (the populous US namesake). Runs after the region pass so the
|
|
224
|
+
// two never contend (region-fallthrough vs resolved-but-foreign are disjoint locality states).
|
|
225
|
+
await applyExplicitCountryCoherence(newRoots, this.#backend);
|
|
226
|
+
// Region-country coherence: a region qualifier the locale-inferred default-country hard filter could not
|
|
227
|
+
// resolve (a foreign subdivision — "Montreal QC" under a US locale). The default filter discarded "QC" and
|
|
228
|
+
// force-matched the locality to the US namesake; this re-resolves the subdivision + its same-named locality
|
|
229
|
+
// under the subdivision's OWN country. Disjoint from the two passes above (unresolved region + resolved
|
|
230
|
+
// locality); evidence-conditional + byte-stable on the domestic path (a US region resolves under `US`).
|
|
231
|
+
await applyRegionCountryCoherence(newRoots, this.#backend, state.defaultCountry);
|
|
232
|
+
}
|
|
233
|
+
// Postcode-consistency (#370 "Change A"): default-ON (promoted 2026-07-04 — the corrected check:
|
|
234
|
+
// FI 231/0, SI 37/6, CZ 47/2, US byte-flat; see the ResolveOpts docstring). After the admin walk
|
|
235
|
+
// (needs both the locality and the postcode resolved) and before the street tiers (which key off
|
|
236
|
+
// the postcode/street, not the locality coordinate this adjusts). `false` opts out, byte-stable.
|
|
237
|
+
if (opts.postcodeConsistency !== false) {
|
|
238
|
+
applyPostcodeConsistency(newRoots, opts.postcodeConsistencyThresholdKm ?? 50);
|
|
239
|
+
}
|
|
240
|
+
// Address-point tier (#476): opt-in street-level exact match. After the admin walk so the
|
|
241
|
+
// tier can never disturb admin attribution — it only ADDS the precise coordinate. Byte-stable
|
|
242
|
+
// when opts.addressPoints is absent.
|
|
243
|
+
if (opts.addressPoints) {
|
|
244
|
+
applyAddressPoint(newRoots, opts.addressPoints, opts.addressPointBboxFallback);
|
|
245
|
+
}
|
|
246
|
+
// Interpolation tier (#483): strictly AFTER the exact-point block so an estimate can never
|
|
247
|
+
// override a real situs point (applyInterpolation also checks on resolution_tier). Opt-in;
|
|
248
|
+
// byte-stable when opts.interpolation is absent.
|
|
249
|
+
if (opts.interpolation) {
|
|
250
|
+
applyInterpolation(newRoots, opts.interpolation, opts.interpolationRadiusCalibration);
|
|
251
|
+
}
|
|
252
|
+
// Span-rescore tier (#370): default-ON (promoted 2026-06-25 — same-harness EU+AU +1pp @25km,
|
|
253
|
+
// zero regressions: CZ 90→95, AT 70→73, PL 88→90, IT/PT/FR/AU flat, no-result 4→3%; fires last
|
|
254
|
+
// so it only runs when every other tier left the tree unresolved, hence inert on the well-resolved
|
|
255
|
+
// US path). Explicit opt-OUT via `spanRescore: false`; byte-stable then.
|
|
256
|
+
if (opts.spanRescore !== false) {
|
|
257
|
+
await applySpanRescore(newRoots, tree.raw, this.#backend, opts);
|
|
258
|
+
}
|
|
259
|
+
// A failed admin walk can leave the exact-point tier without a locality even though span-rescore
|
|
260
|
+
// recovers one immediately afterward (for example, a locality the model tagged as `region`). Give
|
|
261
|
+
// the exact register one bounded retry with that newly established scope. An existing situs hit is
|
|
262
|
+
// returned early by applyAddressPoint, so the normal path performs no duplicate lookup; interpolation
|
|
263
|
+
// remains subordinate because an exact point is allowed to replace its estimate.
|
|
264
|
+
if (opts.addressPoints) {
|
|
265
|
+
applyAddressPoint(newRoots, opts.addressPoints, opts.addressPointBboxFallback);
|
|
266
|
+
}
|
|
267
|
+
// Street-centroid tier (#1042): LAST, after span-rescore, so it can (a) union the span-rescore-recovered
|
|
268
|
+
// country into its FR/national country hints (a placer-misrouted street — "Rue Sainte-Catherine" → IT — leaves
|
|
269
|
+
// admin unresolved, and only span-rescore recovers the FR country signal) and (b) override a coarse recovered
|
|
270
|
+
// locality with the exact street centroid. Applies only when there is no house number + no existing street-level tier, so a
|
|
271
|
+
// rooftop query is untouched; byte-stable when opts.streetCentroids absent.
|
|
272
|
+
if (opts.streetCentroids) {
|
|
273
|
+
applyStreetCentroid(newRoots, tree.raw, opts.streetCentroids, opts.streetCountryHints ?? []);
|
|
274
|
+
}
|
|
275
|
+
return { raw: tree.raw, roots: newRoots };
|
|
276
|
+
}
|
|
277
|
+
/**
|
|
278
|
+
* Record a dropped dual-role locality as a `locality` INTERPRETATION on the resolved region node (#415, generalizes
|
|
279
|
+
* #405's synthesized node). Consults `coincidentLocalitiesFor(regionID)` (O(1) map lookup — no distance math, no
|
|
280
|
+
* backend query), picks the principal city ({@link pickCompletion}: population-primary, distance tiebreak, abstain on
|
|
281
|
+
* a genuine tie), and appends an interpretation to `regionNode.interpretations`. No-op when the backend has no
|
|
282
|
+
* relation, the region isn't a dual-role place, or it abstains. The region node's primary role stays `region`; the
|
|
283
|
+
* locality rides alongside.
|
|
284
|
+
*/
|
|
285
|
+
#completeRegionRole(region, regionNode) {
|
|
286
|
+
if (typeof region.id !== "number" || !this.#backend.coincidentLocalitiesFor)
|
|
287
|
+
return;
|
|
288
|
+
const loc = pickCompletion(this.#backend.coincidentLocalitiesFor(region.id));
|
|
289
|
+
if (!loc)
|
|
290
|
+
return;
|
|
291
|
+
const interpretation = {
|
|
292
|
+
tag: "locality",
|
|
293
|
+
placeID: `wof:${loc.id}`,
|
|
294
|
+
sourceID: `${loc.placetype}:${loc.id}`,
|
|
295
|
+
lat: loc.lat,
|
|
296
|
+
lon: loc.lon,
|
|
297
|
+
confidence: 0,
|
|
298
|
+
metadata: { relationship_type: loc.relationshipType, resolver_completed: true, resolver_name: loc.name },
|
|
299
|
+
};
|
|
300
|
+
regionNode.interpretations = [...(regionNode.interpretations ?? []), interpretation];
|
|
301
|
+
}
|
|
302
|
+
async #walk(node, parentResolved, state) {
|
|
303
|
+
// Always clone — never mutate input nodes.
|
|
304
|
+
const decorated = { ...node, children: [] };
|
|
305
|
+
const placetype = state.placetypeMap[node.tag];
|
|
306
|
+
// Track locality presence for hierarchy completion (#405): completion must NOT fire if the parser
|
|
307
|
+
// already emitted a locality node (even one that failed to resolve) — it only fills a genuine
|
|
308
|
+
// gap. Cheap and always-on; only consulted when hierarchyCompletion is set.
|
|
309
|
+
if (placetype === "locality") {
|
|
310
|
+
state.localityNodePresent = true;
|
|
311
|
+
}
|
|
312
|
+
let resolved = null;
|
|
313
|
+
// Shape-excluded postcode spans (letter-bearing ones keep their tag; #31 Mechanism 1) are
|
|
314
|
+
// stripped of their resolve contribution — the walk does not look them up. Digit-only excluded
|
|
315
|
+
// spans were retagged to `house_number` and flow through their correct sibling placetype.
|
|
316
|
+
if (placetype && state.lookupsRemaining > 0 && node.value.trim().length && !isShapeExcludedPostcode(node)) {
|
|
317
|
+
let picked = await this.#lookupAndPick(node, placetype, parentResolved, state);
|
|
318
|
+
// A compound JP municipality as a scoped pair: the parent fallback is withheld on the tail probe only.
|
|
319
|
+
if (!picked && node.tag === "municipality") {
|
|
320
|
+
picked = await resolveCompoundMunicipality(node.value, parentResolved, () => state.lookupsRemaining > 0, async (value, scope, parentFallback) => {
|
|
321
|
+
const prior = state.parentFallback;
|
|
322
|
+
state.parentFallback = prior && parentFallback;
|
|
323
|
+
try {
|
|
324
|
+
return await this.#lookupAndPick({ ...node, value }, placetype, scope, state);
|
|
325
|
+
}
|
|
326
|
+
finally {
|
|
327
|
+
state.parentFallback = prior;
|
|
328
|
+
}
|
|
329
|
+
});
|
|
330
|
+
}
|
|
331
|
+
if (picked) {
|
|
332
|
+
resolved = picked.top;
|
|
333
|
+
decorateNode(decorated, picked.top, picked.alternatives);
|
|
334
|
+
if (picked.metadata) {
|
|
335
|
+
decorated.metadata = { ...decorated.metadata, ...picked.metadata };
|
|
336
|
+
}
|
|
337
|
+
// #1678 thread 2 — the parse half, resolved from the atlas rather than trained in.
|
|
338
|
+
//
|
|
339
|
+
// The bare-toponym race exists because the model reads a lone country or region name as a
|
|
340
|
+
// `locality`; the race finds the right PLACE and the node keeps the wrong TAG. So
|
|
341
|
+
// `mw geocode 格鲁吉亚` lands on Georgia the country and reports `{"locality": "格鲁吉亚"}`,
|
|
342
|
+
// which is a correct coordinate under a label that will mislead the moment the same toponym
|
|
343
|
+
// appears inside a longer address.
|
|
344
|
+
//
|
|
345
|
+
// The repick metadata already marks exactly these nodes, so the correction is free: retrieval
|
|
346
|
+
// established the placetype, and the tag follows it. Only the race's own picks are retagged —
|
|
347
|
+
// an ordinary locality that resolved to a locality is untouched.
|
|
348
|
+
if (decorated.metadata?.["bare_country_repick"]) {
|
|
349
|
+
decorated.tag = "country";
|
|
350
|
+
}
|
|
351
|
+
else if (decorated.metadata?.["bare_region_repick"]) {
|
|
352
|
+
decorated.tag = "region";
|
|
353
|
+
}
|
|
354
|
+
// Lineage attachment (#404): stamp the resolved place's ancestor chain onto metadata. Opt-in
|
|
355
|
+
// + only when the backend supplies it, so the default stays byte-identical (no extra query).
|
|
356
|
+
if (state.includeAncestors && this.#backend.ancestors) {
|
|
357
|
+
decorated.metadata = { ...decorated.metadata, ancestors: this.#backend.ancestors(picked.top.id) };
|
|
358
|
+
}
|
|
359
|
+
// Capture the first resolved region (place + node) for hierarchy completion — the locality
|
|
360
|
+
// interpretation is pushed onto this node in the post-walk pass.
|
|
361
|
+
if (placetype === "region" && state.resolvedRegion === null) {
|
|
362
|
+
state.resolvedRegion = picked.top;
|
|
363
|
+
state.resolvedRegionNode = decorated;
|
|
364
|
+
}
|
|
365
|
+
}
|
|
366
|
+
}
|
|
367
|
+
const carryParent = resolved ?? parentResolved;
|
|
368
|
+
for (const child of node.children) {
|
|
369
|
+
decorated.children.push(await this.#walk(child, carryParent, state));
|
|
370
|
+
}
|
|
371
|
+
return decorated;
|
|
372
|
+
}
|
|
373
|
+
/**
|
|
374
|
+
* Which admin bands hold a value the probed band did not, keeping the country and dropping the parent.
|
|
375
|
+
*
|
|
376
|
+
* Bands come from `PLACETYPE_SPECIFICITY` rather than a list typed here: that table is already the repo's answer to
|
|
377
|
+
* how coarse a placetype is, and a second hand-kept copy would agree right up until a placetype is added. Probed
|
|
378
|
+
* coarse-to-fine so the report reads down the admin ladder.
|
|
379
|
+
*/
|
|
380
|
+
async #probeOtherBands(query, probed) {
|
|
381
|
+
const found = [];
|
|
382
|
+
for (const band of DIAGNOSTIC_BANDS) {
|
|
383
|
+
if (band === probed)
|
|
384
|
+
continue;
|
|
385
|
+
try {
|
|
386
|
+
const hits = await this.#backend.findPlace({ ...query, placetype: band, parentID: undefined });
|
|
387
|
+
if (hits.length) {
|
|
388
|
+
found.push({ placetype: band, n: hits.length });
|
|
389
|
+
}
|
|
390
|
+
}
|
|
391
|
+
catch {
|
|
392
|
+
// A band the backend cannot answer for is not evidence that the key is absent from it, so it is
|
|
393
|
+
// skipped rather than recorded as an empty result.
|
|
394
|
+
continue;
|
|
395
|
+
}
|
|
396
|
+
}
|
|
397
|
+
return found;
|
|
398
|
+
}
|
|
399
|
+
async #lookupAndPick(node, placetype, parentResolved, state) {
|
|
400
|
+
state.lookupsRemaining--;
|
|
401
|
+
const query = {
|
|
402
|
+
text: node.value,
|
|
403
|
+
placetype,
|
|
404
|
+
limit: state.candidatesPerLookup,
|
|
405
|
+
};
|
|
406
|
+
// Proximity bias (viewport center, user location, …) — a SOFT re-rank the backend folds into
|
|
407
|
+
// its exact-tier prominence; never a filter, so recall is untouched. This is how an ambiguous
|
|
408
|
+
// bare postcode ("48026") follows the map view instead of a global population coin-flip.
|
|
409
|
+
if (state.bias && state.bias.length) {
|
|
410
|
+
query.bias = state.bias;
|
|
411
|
+
}
|
|
412
|
+
// Pass the inherited parent constraint to the backend when available — `parentID` scopes to
|
|
413
|
+
// the resolved parent's descendants. For `country`: a resolved parent's country wins, else
|
|
414
|
+
// fall back to the caller's `defaultCountry`. Without this top-level hint a bare "IL" over a
|
|
415
|
+
// multi-country gazetteer fuzzy-matches a foreign place (e.g. a French region) — see the
|
|
416
|
+
// Direction-C resolver eval.
|
|
417
|
+
if (parentResolved && typeof parentResolved.id === "number") {
|
|
418
|
+
query.parentID = parentResolved.id;
|
|
419
|
+
}
|
|
420
|
+
// #194: a resolved parent's country wins, then the caller's `defaultCountry`, then the confident
|
|
421
|
+
// placer `hardCountry`. All three are a HARD candidate filter. The placer's `hardCountry` is conditional
|
|
422
|
+
// upstream on high confidence (so it only fires when the model is sure), and on a miss the node is
|
|
423
|
+
// left UNRESOLVED rather than re-resolved globally: the off-continent rows are precisely the ones
|
|
424
|
+
// whose locality isn't in the country's gazetteer slice, so a global retry would just re-admit the
|
|
425
|
+
// wrong-continent guess the hard filter exists to drop ("in-region or unresolved"). Measured: a
|
|
426
|
+
// global fallback collapses back to the soft-prior baseline (FI p90 3050, PL p90 1078); pure-hard
|
|
427
|
+
// collapses the tail (FI 18 km, PL p99 8172→494) at a coverage-bounded recall cost.
|
|
428
|
+
// #833 forward linkage: a node's own `country_hint` (an address-system recognizer's derived country —
|
|
429
|
+
// today `recognizeUSRegions` stamping "US" on a recognized closed-set US state) constrains THIS node's
|
|
430
|
+
// lookup when the caller supplied no locale/default country. A caller scope outranks this derived hint:
|
|
431
|
+
// `WA` is both Washington and Western Australia, so en-AU must reach the AU candidate instead of being
|
|
432
|
+
// overwritten by the US-only recognizer. A genuine foreign subdivision under the wrong locale is recovered
|
|
433
|
+
// later by region-country coherence after the scoped lookup abstains.
|
|
434
|
+
const countryHint = node.metadata?.["country_hint"];
|
|
435
|
+
// A locale-INFERRED default country never filters a `country`-placetype lookup: the span names a
|
|
436
|
+
// country outright, and the filter can only admit the scope country itself (bare "Germany" under
|
|
437
|
+
// the en-US default filtered out the DE row; the unresolved span then fell to a US locality whose
|
|
438
|
+
// historical alias is "Germany, Ohio"). An EXPLICIT caller scope stays supreme, matching the #912
|
|
439
|
+
// posture; parent evidence and the confident placer are untouched.
|
|
440
|
+
const defaultCountryForLookup = placetype === "country" && state.defaultCountryIsInferred ? undefined : state.defaultCountry;
|
|
441
|
+
const country = parentResolved?.country ??
|
|
442
|
+
defaultCountryForLookup ??
|
|
443
|
+
(typeof countryHint === "string" ? countryHint : undefined) ??
|
|
444
|
+
state.hardCountry;
|
|
445
|
+
if (country) {
|
|
446
|
+
query.country = country;
|
|
447
|
+
}
|
|
448
|
+
// #1585: the locale hint's country rides on every primary lookup as the TYPO-FUZZY tier's scope.
|
|
449
|
+
// Deliberately set even when `query.country` is (the backend ignores it there — the hard filter
|
|
450
|
+
// is already narrower): the field's contract lives in one place, the backend.
|
|
451
|
+
if (state.fuzzyCountryScope) {
|
|
452
|
+
query.fuzzyCountry = state.fuzzyCountryScope;
|
|
453
|
+
}
|
|
454
|
+
// Admin-containment re-rank (#1717 stage 2): thread the tree's region qualifier onto locality
|
|
455
|
+
// lookups so a capable backend can vouch for (and surface) the candidates that sit UNDER it.
|
|
456
|
+
// Stands down under an EXPLICIT caller country scope (the #912 posture — only a locale-INFERRED
|
|
457
|
+
// scope is bypassable by the address's own evidence); the resolved-parent and placer scopes are
|
|
458
|
+
// left alone, since a resolved parent usually IS the qualifier and the injection dedupes.
|
|
459
|
+
const containmentEligible = state.adminContainmentRerank &&
|
|
460
|
+
placetype === "locality" &&
|
|
461
|
+
state.regionQualifier !== undefined &&
|
|
462
|
+
(!state.defaultCountry || state.defaultCountryIsInferred);
|
|
463
|
+
if (containmentEligible) {
|
|
464
|
+
query.regionQualifier = state.regionQualifier;
|
|
465
|
+
}
|
|
466
|
+
// Coordinate-first: hand the sibling postcode to locality lookups so the backend can inject
|
|
467
|
+
// postcode-proximal candidates the name-match would miss. Only for locality (the placetype both
|
|
468
|
+
// `locality` and `dependent_locality` map to); other placetypes ignore it. The containment flag
|
|
469
|
+
// (#31, Mechanism 2) asks a coordinate-first backend to re-rank the candidates by proximity to
|
|
470
|
+
// the postcode's own centroid — opt-in, OFF by default.
|
|
471
|
+
if (placetype === "locality" && state.postcode) {
|
|
472
|
+
query.postcode = state.postcode;
|
|
473
|
+
if (state.postcodeContainmentCoherence) {
|
|
474
|
+
query.postcodeContainmentCoherence = true;
|
|
475
|
+
}
|
|
476
|
+
}
|
|
477
|
+
// #1721 resolver-interior trace. Stage orders hold the SAME candidate objects across re-ranks
|
|
478
|
+
// (every stage reorders, never clones), which is what lets emit assemble a per-stage rank
|
|
479
|
+
// vector per row. The no-sink walk talks to the frozen no-op recorder — zero per-event branches.
|
|
480
|
+
const rec = state.traceSink ? createNodeTraceRecorder(state.traceSink) : NOOP_TRACE_RECORDER;
|
|
481
|
+
// The query is SNAPSHOT, not bound live. `emit` reads `ctx.query.parentID` at the END of the walk, and the
|
|
482
|
+
// parent-fallback retry `delete`s that key mid-lookup — so binding the object itself lets a later mutation
|
|
483
|
+
// rewrite history. That is how 196 lookups which every one of them carried a parent came out of the
|
|
484
|
+
// constraint census reading `parentID: absent`.
|
|
485
|
+
rec.bind(node, placetype, { ...query }, state.candidatesPerLookup);
|
|
486
|
+
let candidates;
|
|
487
|
+
// #1589: a `postalcode` whose FORMAT implies specific countries, with no surviving country
|
|
488
|
+
// constraint, probes exactly the implied set — most populous hit wins, and an all-miss
|
|
489
|
+
// leaves the candidate set EMPTY rather than falling through to the unconstrained fold:
|
|
490
|
+
// `100 00` space-strips to `10000`, which answers Troyes FR while the CZ rows sit in the
|
|
491
|
+
// artifact under both keyings; a scoped empty must stay empty (the same contract as the
|
|
492
|
+
// fuzzy tier's, #1585). The postcode-prefix prior below still gets its turn on the empty
|
|
493
|
+
// set — its index is country-scoped by construction, so it is not the fold this branch
|
|
494
|
+
// exists to avoid (the B3 tests hold that path).
|
|
495
|
+
if (placetype === "postalcode" && !query.country && state.postcodeFormatCountries?.length) {
|
|
496
|
+
rec.check("postcode_format_probe");
|
|
497
|
+
let best;
|
|
498
|
+
for (const impliedCountry of state.postcodeFormatCountries) {
|
|
499
|
+
try {
|
|
500
|
+
const hits = await this.#backend.findPlace({ ...query, country: impliedCountry });
|
|
501
|
+
const top = hits[0];
|
|
502
|
+
// `score` is the backend's own population-first ranking metric, so comparing the
|
|
503
|
+
// per-country winners by it keeps the cross-country pick population-first too.
|
|
504
|
+
if (top && (!best || top.score > best.score)) {
|
|
505
|
+
best = top;
|
|
506
|
+
}
|
|
507
|
+
}
|
|
508
|
+
catch {
|
|
509
|
+
// A per-country probe failure reads as a miss for that country, never an abort.
|
|
510
|
+
}
|
|
511
|
+
}
|
|
512
|
+
if (best) {
|
|
513
|
+
rec.emit({ id: best.id, name: best.name, source: "postcode_format_probe" });
|
|
514
|
+
return { top: best, alternatives: [] };
|
|
515
|
+
}
|
|
516
|
+
candidates = [];
|
|
517
|
+
}
|
|
518
|
+
else {
|
|
519
|
+
try {
|
|
520
|
+
candidates = await this.#backend.findPlace(query);
|
|
521
|
+
rec.stage("initial", candidates);
|
|
522
|
+
// #1731: the backend's interior region-scope fallback, surfaced as a check — the resolver
|
|
523
|
+
// never sees the scoped probe miss, only the stamp the re-admitted rows carry.
|
|
524
|
+
if (candidates[0]?.regionScopeMiss) {
|
|
525
|
+
rec.check("region_scope_miss");
|
|
526
|
+
}
|
|
527
|
+
// Parent soft-filtering: `parentID` is a HARD descendant filter in the backend, which wrongly
|
|
528
|
+
// zeroes the result when the parent resolved wrong OR the gazetteer hierarchy is incomplete
|
|
529
|
+
// (a real locality whose `ancestors` chain is missing its region). Rather than turn a
|
|
530
|
+
// resolvable node into an unresolved one, retry once WITHOUT the parent constraint — we
|
|
531
|
+
// prefer a parent-scoped hit but never sacrifice recall. The country constraint is kept, so
|
|
532
|
+
// this still can't wander to a foreign place. Same logical resolution → no extra budget.
|
|
533
|
+
if (!candidates.length && state.parentFallback && query.parentID !== undefined) {
|
|
534
|
+
delete query.parentID;
|
|
535
|
+
rec.check("parent_fallback_retry");
|
|
536
|
+
candidates = await this.#backend.findPlace(query);
|
|
537
|
+
rec.stage("parent_fallback", candidates);
|
|
538
|
+
}
|
|
539
|
+
// DIAGNOSTIC ONLY, and after every real attempt: which OTHER bands hold this value. The answer never
|
|
540
|
+
// becomes the pick — a band the model did not ask for is not evidence about what the string means —
|
|
541
|
+
// but it separates the two facts a `null` cannot: a key we hold under another placetype is a
|
|
542
|
+
// reachability failure the tag caused, while a key nowhere is coverage. Off by default; one extra call
|
|
543
|
+
// per band per miss.
|
|
544
|
+
if (!candidates.length && state.diagnoseUnreachable) {
|
|
545
|
+
rec.reachable(await this.#probeOtherBands(query, placetype));
|
|
546
|
+
}
|
|
547
|
+
}
|
|
548
|
+
catch (error) {
|
|
549
|
+
// Defensive: a backend failure should not abort the whole tree walk. Leave the node with
|
|
550
|
+
// its classifier attribution intact.
|
|
551
|
+
//
|
|
552
|
+
// The reason rides the check name. A bare `backend_error` cannot tell a closed database from a
|
|
553
|
+
// finalized statement from a genuine query fault, which is what made three full-board constraint
|
|
554
|
+
// runs unreadable — 64 of 591 rows errored and the census could not say why.
|
|
555
|
+
rec.check(`backend_error: ${error.message}`);
|
|
556
|
+
rec.emit(null);
|
|
557
|
+
return null;
|
|
558
|
+
}
|
|
559
|
+
}
|
|
560
|
+
// Postcode-prefix prior (#31, Mechanism 3): when a `postalcode` node misses the gazetteer, derive
|
|
561
|
+
// the code's prefix and probe the injected PFX1 index (structural — never a model input). A hit
|
|
562
|
+
// resolves the node to a synthetic place (id 0), carrying a coordinate ONLY when the index node
|
|
563
|
+
// does — the ancestry-only tier stays coordinate-free (B3-3's 0% half, meaning-of-zero). The
|
|
564
|
+
// prior's payload is returned as node metadata for #walk to stamp. Opt-in via `postcodePrefixPrior`
|
|
565
|
+
// + `postcodePrefixIndex`; OFF by default (D-rule: the PCN1 posture).
|
|
566
|
+
if (!candidates.length && placetype === "postalcode" && state.postcodePrefixPrior && state.postcodePrefixIndex) {
|
|
567
|
+
const probe = probePostcodePrefix(node.value, state.postcodePrefixIndex, query.country);
|
|
568
|
+
if (probe) {
|
|
569
|
+
const metadata = {
|
|
570
|
+
postcode_prefix: probe.prefix,
|
|
571
|
+
postcode_prefix_ancestors: probe.node.ancestors,
|
|
572
|
+
...(probe.node.radiusP95Km !== undefined ? { postcode_prefix_radius_p95_km: probe.node.radiusP95Km } : {}),
|
|
573
|
+
...(probe.node.lat !== undefined && probe.node.lon !== undefined
|
|
574
|
+
? { coordinate_source: "postcode_prefix" }
|
|
575
|
+
: {}),
|
|
576
|
+
};
|
|
577
|
+
rec.check("postcode_prefix_prior");
|
|
578
|
+
const prefixPlace = postcodePrefixResolvedPlace(probe.prefix, probe.node, state.postcodePrefixIndex);
|
|
579
|
+
rec.emit({ id: prefixPlace.id, name: prefixPlace.name, source: "postcode_prefix" });
|
|
580
|
+
return {
|
|
581
|
+
top: prefixPlace,
|
|
582
|
+
alternatives: [],
|
|
583
|
+
metadata,
|
|
584
|
+
};
|
|
585
|
+
}
|
|
586
|
+
}
|
|
587
|
+
// The bare-toponym country race (fix B of the bare-country class): a lone locality-tagged span
|
|
588
|
+
// also races the `country` placetype, because the parser tags bare country names `locality`
|
|
589
|
+
// about half the time ("Japan", "China") and the locality filter makes the country row
|
|
590
|
+
// unreachable at any rank. Runs ONLY for the tree's single value-bearing node, so every
|
|
591
|
+
// address-shaped input is byte-stable. The locality winner's prominence arbitrates below;
|
|
592
|
+
// with no locality candidates at all, a country hit resolves the span outright.
|
|
593
|
+
const isBareRace = placetype === "locality" && node === state.bareLocalityNode;
|
|
594
|
+
if (isBareRace) {
|
|
595
|
+
rec.check("bare_race");
|
|
596
|
+
}
|
|
597
|
+
const bareCountry = isBareRace ? await bareCountryCandidate(this.#backend, node.value, query.country) : null;
|
|
598
|
+
const bareRegion = isBareRace ? await bareRegionCandidate(this.#backend, node.value, query.country) : null;
|
|
599
|
+
if (!candidates.length) {
|
|
600
|
+
// With no locality candidates at all, the admin namesake with the larger population answers
|
|
601
|
+
// outright (the same precedence the dominance rule below applies).
|
|
602
|
+
const admin = pickLargerAdmin(bareCountry, bareRegion);
|
|
603
|
+
if (admin) {
|
|
604
|
+
rec.check("empty_admin_pick");
|
|
605
|
+
rec.emit({ id: admin.id, name: admin.name, source: "empty_admin" });
|
|
606
|
+
return {
|
|
607
|
+
top: admin,
|
|
608
|
+
alternatives: [],
|
|
609
|
+
metadata: admin === bareRegion ? { bare_region_repick: true } : { bare_country_repick: true },
|
|
610
|
+
};
|
|
611
|
+
}
|
|
612
|
+
rec.emit(null);
|
|
613
|
+
return null;
|
|
614
|
+
}
|
|
615
|
+
// Postcode-anchor re-rank (#369): when a country posterior is supplied (from the address's
|
|
616
|
+
// postcode), boost candidates by `anchorWeight * posterior[candidate.country]` and re-sort, so a
|
|
617
|
+
// postcode that pins the country pulls the right-country place over a higher-BM25 foreign namesake
|
|
618
|
+
// (the "Berlin DE vs Berlin US" class the #59 harness measured). No-op when `anchorPosterior` is
|
|
619
|
+
// undefined (the default) → byte-identical resolution.
|
|
620
|
+
//
|
|
621
|
+
// Applied to BOTH region and locality — the two placetypes that suffer cross-country namesake/
|
|
622
|
+
// abbreviation collisions a country posterior can break. The region case is the one #447's window
|
|
623
|
+
// fix couldn't reach: a bare 2-letter abbreviation is shared across countries ("VT" is
|
|
624
|
+
// both Vermont and Viterbo; "ME" both Maine and Messina), so with no country signal the score
|
|
625
|
+
// picks the wrong one — and because resolveTree resolves region FIRST and inherits its country
|
|
626
|
+
// down, a wrong region poisons the locality too. The postcode posterior breaks the tie at the
|
|
627
|
+
// region, and the right country then flows to the locality. (Country/macroregion/county are
|
|
628
|
+
// excluded: they don't exhibit this collision class and carry country via `parentID` when nested.)
|
|
629
|
+
//
|
|
630
|
+
// Tier-SAFE ordering: the candidate's exact-match flag is the PRIMARY key, so the country pin
|
|
631
|
+
// never crosses the exact/partial boundary. WITHIN a tier, `score + anchorWeight * posterior`
|
|
632
|
+
// applies the (soft) country boost. So a confident US postcode keeps the US EXACT region
|
|
633
|
+
// ("ME" → Maine) ahead of a more-populous US PARTIAL match (Missouri) AND, within the exact
|
|
634
|
+
// tier, ahead of a foreign exact match (Messina IT); a soft posterior still blends with score.
|
|
635
|
+
// (A plain additive re-rank loses the tier — it isn't encoded in `score` — and flips
|
|
636
|
+
// "ME" → Missouri / "PA" → Alabama. Backends that don't set `exactMatch` degrade to additive.)
|
|
637
|
+
const anchorEligible = placetype === "region" || placetype === "locality";
|
|
638
|
+
let ranked = candidates;
|
|
639
|
+
if (state.anchorPosterior && anchorEligible && candidates.length > 1) {
|
|
640
|
+
const post = state.anchorPosterior;
|
|
641
|
+
const w = state.anchorWeight;
|
|
642
|
+
// #928 root cause: this sort's within-tier key was `score + w·posterior` — RAW SCORE order,
|
|
643
|
+
// the exact metric #910 deprecated inside the exact tier as bm25-length-poisoned (a famous
|
|
644
|
+
// place's alias-heavy doc reads ~15 pts WORSE than a tiny namesake's clean one; #905
|
|
645
|
+
// measured it). Before #910 the anchor-off path also sorted by score, so the two paths
|
|
646
|
+
// agreed; after, anchor-ON silently reverted to the poisoned metric — a CORRECT GB@1.00
|
|
647
|
+
// pin flipped "London SE15 1DD" to a US namesake because +w·1.0 can't bridge the bm25 gap.
|
|
648
|
+
// The within-tier key is now the backend's PROMINENCE (population + proximity, #938 units)
|
|
649
|
+
// with the posterior as the additive country pin; score stays the final tiebreak. Backends
|
|
650
|
+
// that don't populate `prominence` degrade to the additive score behavior.
|
|
651
|
+
// oxlint-disable-next-line unicorn/no-array-sort -- sorts a freshly-built array; toSorted would double-allocate on a hot path
|
|
652
|
+
ranked = [...candidates].sort((a, b) => {
|
|
653
|
+
const tier = Number(b.exactMatch ?? false) - Number(a.exactMatch ?? false);
|
|
654
|
+
if (tier !== 0)
|
|
655
|
+
return tier;
|
|
656
|
+
// A candidate with no country gets no posterior mass rather than an index by `undefined`, which reads
|
|
657
|
+
// every unknown-country row as the same key.
|
|
658
|
+
const aKey = (a.prominence ?? a.score) + w * (a.country === undefined ? 0 : (post[a.country] ?? 0));
|
|
659
|
+
const bKey = (b.prominence ?? b.score) + w * (b.country === undefined ? 0 : (post[b.country] ?? 0));
|
|
660
|
+
return bKey - aKey || b.score - a.score;
|
|
661
|
+
});
|
|
662
|
+
rec.stage("anchor", ranked);
|
|
663
|
+
}
|
|
664
|
+
// Locale-country soft prior (#27) — the #912 change's other half, at the tier that decides a bare
|
|
665
|
+
// toponym the model tagged `locality`. `--locale en-GB "Whitby"` answers Whitby, Ontario while
|
|
666
|
+
// `--default-country GB "Whitby"` answers the gold, because the CLI DROPS the locale-inferred
|
|
667
|
+
// country for this shape rather than choosing between "hard filter" and "nothing". This is the
|
|
668
|
+
// third option: an additive bonus inside the exact tier, never a filter.
|
|
669
|
+
//
|
|
670
|
+
// Three stand-downs, in the order they matter. A `defaultCountry` makes the prior a no-op by
|
|
671
|
+
// construction (every candidate is already in it), so we skip the work rather than pretend. An
|
|
672
|
+
// `anchorPosterior` is derived from the address's OWN postcode — evidence, which outranks a guess
|
|
673
|
+
// about where the user is sitting. And an absent prior is the SHIPPED default: `ResolveOpts`
|
|
674
|
+
// documents why (the weight that flips the four bare GB rows and the weight that holds the en-US
|
|
675
|
+
// board are disjoint intervals), so this is inert unless a caller opts in.
|
|
676
|
+
//
|
|
677
|
+
// Runs BEFORE the importance key deliberately, matching span-rescore: fame is the stronger signal
|
|
678
|
+
// wherever it has been measured, and it leaves an unscored candidate exactly where the prior put it.
|
|
679
|
+
if (state.localeCountryPrior && !state.defaultCountry && !state.anchorPosterior && anchorEligible) {
|
|
680
|
+
ranked = rankByCountryPrior(ranked, state.localeCountryPrior, state.localeCountryPriorWeight);
|
|
681
|
+
rec.stage("locale_prior", ranked);
|
|
682
|
+
}
|
|
683
|
+
// Importance-first (#17/#28). Before this key a bare famous name was decided on POPULATION
|
|
684
|
+
// alone, which is measurably the wrong prior for the class: `Whitby` answered Whitby, Ontario
|
|
685
|
+
// (128,377) over Whitby, North Yorkshire (13,130), 5,508 km from where the person meant. Fame is
|
|
686
|
+
// what a bare toponym is asking about, and the candidate build's blended `importance` column
|
|
687
|
+
// measures it. Tier-safe and positive-evidence-only (an UNSCORED candidate keeps the rank
|
|
688
|
+
// population gave it; only the scored ones permute), so it abstains byte-stably on an artifact
|
|
689
|
+
// that predates the column.
|
|
690
|
+
//
|
|
691
|
+
// Skipped outright when an anchor posterior is in force. Fame is the prior of LAST resort: it answers
|
|
692
|
+
// "which one did you probably mean" only when nothing in the query answered it, and a #369 posterior is
|
|
693
|
+
// derived from the address's OWN postcode. Evidence outranks a prior. See `toponym-prior.ts`.
|
|
694
|
+
if (!state.anchorPosterior) {
|
|
695
|
+
ranked = rankByImportance(ranked);
|
|
696
|
+
rec.stage("importance", ranked);
|
|
697
|
+
// #1880 — bounded capital promotion, directly above the fame key it corrects and below the
|
|
698
|
+
// containment partition (the qualifier is the address's own text; evidence outranks a prior).
|
|
699
|
+
// Same stand-down as fame: an anchor posterior is postcode evidence and silences the prior.
|
|
700
|
+
if (state.capitalLevel) {
|
|
701
|
+
ranked = promoteCapitalsWithReceipt(ranked, state.capitalLevel, node);
|
|
702
|
+
rec.stage("capital", ranked);
|
|
703
|
+
}
|
|
704
|
+
}
|
|
705
|
+
// Admin-containment partition (#1717 stage 2): the LAST soft re-rank, after the anchor/fame keys
|
|
706
|
+
// above, because the qualifier is the address's OWN text — evidence, which outranks a prior. The
|
|
707
|
+
// backend already put contained rows first; this second partition is required, not belt-and-
|
|
708
|
+
// braces: `rankByImportance` just re-ordered the exact tier by fame, and Richmond, Virginia
|
|
709
|
+
// outscores Richmond, North Yorkshire on importance — without this the change loses exactly where
|
|
710
|
+
// fame disagrees with the qualifier (the shared-function partition, tier-safe + stable, so it can
|
|
711
|
+
// never promote a contained partial match over an exact one). No stamps → identity → byte-stable
|
|
712
|
+
// on any backend that ignored `regionQualifier`.
|
|
713
|
+
if (containmentEligible) {
|
|
714
|
+
ranked = partitionByContainment(ranked, (c) => c.containedByQualifier === true, (c) => c.exactMatch === true);
|
|
715
|
+
rec.stage("containment", ranked);
|
|
716
|
+
}
|
|
717
|
+
// Exact-type preference (#718): when the placetype-equivalence group let a broader admin tier
|
|
718
|
+
// (`macroregion`/`macrocounty`) into the candidate pool, prefer a candidate of the EXACT
|
|
719
|
+
// requested type over the macro fallback — a real `region` (US state, DE Bundesland, ES
|
|
720
|
+
// provincia) must win over a same-name macroregion namesake, so no real region silently
|
|
721
|
+
// downgrades to a macro. STABLE partition: exact-type candidates keep their (already-ranked)
|
|
722
|
+
// relative order ahead of fallbacks, so the score / anchor re-rank survives WITHIN each tier.
|
|
723
|
+
// No-op for placetypes without a macro fallback (the byte-stable default) and when every
|
|
724
|
+
// candidate is the same tier.
|
|
725
|
+
const hasFallbackCandidate = ranked.some((c) => isPlacetypeFallback(placetype, c.placetype));
|
|
726
|
+
if (hasFallbackCandidate && ranked.length > 1) {
|
|
727
|
+
ranked = [
|
|
728
|
+
...ranked.filter((c) => !isPlacetypeFallback(placetype, c.placetype)),
|
|
729
|
+
...ranked.filter((c) => isPlacetypeFallback(placetype, c.placetype)),
|
|
730
|
+
];
|
|
731
|
+
rec.stage("exact_type", ranked);
|
|
732
|
+
}
|
|
733
|
+
const top = ranked[0];
|
|
734
|
+
if (top.score < state.minWinningScore) {
|
|
735
|
+
rec.check("min_score_reject");
|
|
736
|
+
rec.emit(null);
|
|
737
|
+
return null;
|
|
738
|
+
}
|
|
739
|
+
// The admin side of the bare-toponym race. The COUNTRY row wins on prominence alone —
|
|
740
|
+
// Japan-the-country (pop 126M) over Japan, Pennsylvania (pop 0) — while the REGION row must
|
|
741
|
+
// DOMINATE the locality winner by {@link BARE_REGION_DOMINANCE_LOG10} in log-population:
|
|
742
|
+
// prominence saturates at the backend's populationBoost cap, so the margin is measured on the
|
|
743
|
+
// raw populations, and the margin is what keeps bare "New York" on the city (state 19.6M vs
|
|
744
|
+
// city 8.8M = 0.35, under the threshold) while bare "Georgia" promotes to the 11M state over the
|
|
745
|
+
// Vermont hamlet (margin 3.4). A bare name with no admin namesake never reaches these lines,
|
|
746
|
+
// and the displaced locality stays first among the alternatives either way.
|
|
747
|
+
if (bareCountry && (bareCountry.prominence ?? bareCountry.score) > (top.prominence ?? top.score)) {
|
|
748
|
+
rec.check("bare_country_repick");
|
|
749
|
+
rec.emit({ id: bareCountry.id, name: bareCountry.name, source: "bare_country" });
|
|
750
|
+
return { top: bareCountry, alternatives: ranked, metadata: { bare_country_repick: true } };
|
|
751
|
+
}
|
|
752
|
+
if (bareRegion && logPopulation(bareRegion) >= logPopulation(top) + BARE_REGION_DOMINANCE_LOG10) {
|
|
753
|
+
rec.check("bare_region_repick");
|
|
754
|
+
rec.emit({ id: bareRegion.id, name: bareRegion.name, source: "bare_region" });
|
|
755
|
+
return { top: bareRegion, alternatives: ranked, metadata: { bare_region_repick: true } };
|
|
756
|
+
}
|
|
757
|
+
// Fallback-observability (#718): if the winner is a macro-type AND no exact-type candidate
|
|
758
|
+
// existed for this span, annotate that a broader tier stood in for the true one. Additive —
|
|
759
|
+
// identity/coordinate are unchanged; only `metadata.resolution_quality` is stamped downstream.
|
|
760
|
+
if (isPlacetypeFallback(placetype, top.placetype)) {
|
|
761
|
+
top.resolutionQuality = "fallback";
|
|
762
|
+
rec.check("placetype_fallback");
|
|
763
|
+
}
|
|
764
|
+
rec.emit({ id: top.id, name: top.name, source: "ranked" });
|
|
765
|
+
// The trace stamps (#1717 stage 2 / #1719's rule): an opted-in mechanism that cannot fire — a
|
|
766
|
+
// pre-sidecar artifact, an incapable backend — must say so in the result, not degrade silently.
|
|
767
|
+
// The parse-side census cannot see resolver mechanisms, so these stamps are its census surface.
|
|
768
|
+
// admin_containment asserts a question was asked; variant_alias_exemption (#1893) asserts the
|
|
769
|
+
// winning candidate reached the top BECAUSE the exemption spared it the cross-country penalty —
|
|
770
|
+
// the winner-level firing receipt, same posture as capital_promotion.
|
|
771
|
+
const pickMetadata = {
|
|
772
|
+
...(containmentEligible ? { admin_containment: adminContainmentVerdict(ranked) } : {}),
|
|
773
|
+
...(top.variantAliasExempted === true ? { variant_alias_exemption: true } : {}),
|
|
774
|
+
};
|
|
775
|
+
return {
|
|
776
|
+
top,
|
|
777
|
+
alternatives: ranked.slice(1),
|
|
778
|
+
...(Object.keys(pickMetadata).length ? { metadata: pickMetadata } : {}),
|
|
779
|
+
};
|
|
780
|
+
}
|
|
781
|
+
}
|
|
782
|
+
/**
|
|
783
|
+
* #1880's promotion plus its firing receipt, in one place: when the promotion changes the race's leading candidate, the
|
|
784
|
+
* node is stamped `capital_promotion` with the promoted candidate's country — the same posture as
|
|
785
|
+
* `postcode_country_scope`, a mechanism reporting that it SPOKE apart from whether the outcome moved, so an unchanged
|
|
786
|
+
* verdict downstream can never mean either "harmless" or "never ran". Metadata-only; nothing reads it to rank.
|
|
787
|
+
*/
|
|
788
|
+
function promoteCapitalsWithReceipt(ranked, level, node) {
|
|
789
|
+
const promoted = promoteCapitals(ranked, level);
|
|
790
|
+
if (promoted[0] !== ranked[0]) {
|
|
791
|
+
node.metadata = { ...node.metadata, capital_promotion: promoted[0].country ?? true };
|
|
792
|
+
}
|
|
793
|
+
return promoted;
|
|
794
|
+
}
|
|
795
|
+
//# sourceMappingURL=index.js.map
|