@mailwoman/resolver 11.2.0 → 11.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (62) hide show
  1. package/lib/admin/coherence-passes.ts +1 -1
  2. package/lib/admin/county-designator.ts +1 -1
  3. package/lib/admin/former-division.ts +116 -0
  4. package/lib/bare-toponym-race.ts +1 -1
  5. package/lib/decorate-node.ts +102 -2
  6. package/lib/postcode/prefix.ts +7 -16
  7. package/lib/remote-resolver.ts +1 -1
  8. package/lib/resolve/parent-place.ts +109 -0
  9. package/lib/resolve/passes.ts +62 -11
  10. package/lib/resolve/sibling-locality.ts +150 -0
  11. package/lib/resolve.ts +255 -42
  12. package/lib/scope-retrieval.ts +91 -0
  13. package/lib/span-rescore.ts +65 -14
  14. package/lib/toponym-prior.ts +57 -6
  15. package/out/admin/coherence-passes.js +1 -1
  16. package/out/admin/coherence-passes.js.map +1 -1
  17. package/out/admin/county-designator.js +1 -1
  18. package/out/admin/former-division.d.ts +47 -0
  19. package/out/admin/former-division.d.ts.map +1 -0
  20. package/out/admin/former-division.js +74 -0
  21. package/out/admin/former-division.js.map +1 -0
  22. package/out/bare-toponym-race.d.ts +1 -1
  23. package/out/bare-toponym-race.d.ts.map +1 -1
  24. package/out/decorate-node.d.ts +22 -3
  25. package/out/decorate-node.d.ts.map +1 -1
  26. package/out/decorate-node.js +84 -1
  27. package/out/decorate-node.js.map +1 -1
  28. package/out/postcode/prefix.d.ts +4 -2
  29. package/out/postcode/prefix.d.ts.map +1 -1
  30. package/out/postcode/prefix.js +7 -13
  31. package/out/postcode/prefix.js.map +1 -1
  32. package/out/remote-resolver.d.ts.map +1 -1
  33. package/out/remote-resolver.js +1 -1
  34. package/out/remote-resolver.js.map +1 -1
  35. package/out/resolve/parent-place.d.ts +34 -0
  36. package/out/resolve/parent-place.d.ts.map +1 -0
  37. package/out/resolve/parent-place.js +76 -0
  38. package/out/resolve/parent-place.js.map +1 -0
  39. package/out/resolve/passes.d.ts +39 -8
  40. package/out/resolve/passes.d.ts.map +1 -1
  41. package/out/resolve/passes.js +17 -6
  42. package/out/resolve/passes.js.map +1 -1
  43. package/out/resolve/sibling-locality.d.ts +34 -0
  44. package/out/resolve/sibling-locality.d.ts.map +1 -0
  45. package/out/resolve/sibling-locality.js +95 -0
  46. package/out/resolve/sibling-locality.js.map +1 -0
  47. package/out/resolve.d.ts.map +1 -1
  48. package/out/resolve.js +177 -39
  49. package/out/resolve.js.map +1 -1
  50. package/out/scope-retrieval.d.ts +44 -0
  51. package/out/scope-retrieval.d.ts.map +1 -0
  52. package/out/scope-retrieval.js +52 -0
  53. package/out/scope-retrieval.js.map +1 -0
  54. package/out/span-rescore.d.ts +15 -1
  55. package/out/span-rescore.d.ts.map +1 -1
  56. package/out/span-rescore.js +36 -9
  57. package/out/span-rescore.js.map +1 -1
  58. package/out/toponym-prior.d.ts +15 -0
  59. package/out/toponym-prior.d.ts.map +1 -1
  60. package/out/toponym-prior.js +37 -6
  61. package/out/toponym-prior.js.map +1 -1
  62. package/package.json +9 -9
@@ -0,0 +1,34 @@
1
+ /**
2
+ * Sibling-locality containment: when a tree holds two resolved `locality` spans
3
+ * and the gazetteer places a candidate of one inside the other's place, the inner
4
+ * span resolves inside the outer place as a dependent locality.
5
+ *
6
+ * `Kensington, London` can decode as two localities.
7
+ * Resolved apart, `Kensington` takes the largest namesake, Kensington, California, beside London.
8
+ *
9
+ * The gazetteer's containment decides which span is inner, so `London, Kensington` reads the same.
10
+ */
11
+ import { type AddressNode } from "@mailwoman/core/decoder";
12
+ import type { ResolveNodeTrace, ResolverBackend } from "@mailwoman/core/resolver";
13
+ /**
14
+ * The metadata stamp naming the outer place a sibling span resolved inside.
15
+ */
16
+ export declare const SIBLING_LOCALITY_CONTAINMENT = "sibling_locality_containment";
17
+ interface SiblingLocalityOptions {
18
+ /**
19
+ * The resolver placetype a `locality` span looks up.
20
+ */
21
+ placetype: string;
22
+ limit: number;
23
+ traceSink: ((record: ResolveNodeTrace) => void) | null;
24
+ }
25
+ /**
26
+ * Resolves each inner `locality` span inside its sibling's place and retags it `dependent_locality`.
27
+ *
28
+ * A pair is read in both orders.
29
+ * A pair whose spans each hold a candidate inside the other, or that resolved
30
+ * to one place, is left as it was.
31
+ */
32
+ export declare function applySiblingLocalityContainment(roots: readonly AddressNode[], backend: ResolverBackend, opts: SiblingLocalityOptions): Promise<void>;
33
+ export {};
34
+ //# sourceMappingURL=sibling-locality.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"sibling-locality.d.ts","sourceRoot":"","sources":["../../lib/resolve/sibling-locality.ts"],"names":[],"mappings":"AAGA;;;;;;;;;GASG;AAEH,OAAO,EAAgB,KAAK,WAAW,EAAE,MAAM,yBAAyB,CAAA;AACxE,OAAO,KAAK,EAAiB,gBAAgB,EAAE,eAAe,EAAE,MAAM,0BAA0B,CAAA;AAOhG;;GAEG;AACH,eAAO,MAAM,4BAA4B,iCAAiC,CAAA;AAO1E,UAAU,sBAAsB;IAC/B;;OAEG;IACH,SAAS,EAAE,MAAM,CAAA;IACjB,KAAK,EAAE,MAAM,CAAA;IACb,SAAS,EAAE,CAAC,CAAC,MAAM,EAAE,gBAAgB,KAAK,IAAI,CAAC,GAAG,IAAI,CAAA;CACtD;AAgDD;;;;;;GAMG;AACH,wBAAsB,+BAA+B,CACpD,KAAK,EAAE,SAAS,WAAW,EAAE,EAC7B,OAAO,EAAE,eAAe,EACxB,IAAI,EAAE,sBAAsB,GAC1B,OAAO,CAAC,IAAI,CAAC,CAmDf"}
@@ -0,0 +1,95 @@
1
+ // SPDX-FileCopyrightText: Teffen Ellis and Mailwoman contributors
2
+ // SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-Commercial
3
+ /**
4
+ * Sibling-locality containment: when a tree holds two resolved `locality` spans
5
+ * and the gazetteer places a candidate of one inside the other's place, the inner
6
+ * span resolves inside the outer place as a dependent locality.
7
+ *
8
+ * `Kensington, London` can decode as two localities.
9
+ * Resolved apart, `Kensington` takes the largest namesake, Kensington, California, beside London.
10
+ *
11
+ * The gazetteer's containment decides which span is inner, so `London, Kensington` reads the same.
12
+ */
13
+ import { collectNodes } from "@mailwoman/core/decoder";
14
+ import { adminContainmentVerdict, partitionByContainment } from "#admin/containment";
15
+ import { decorateNode } from "#decorate-node";
16
+ import { createNodeTraceRecorder } from "#resolve/passes";
17
+ import { rankByImportance } from "#toponym-prior";
18
+ /**
19
+ * The metadata stamp naming the outer place a sibling span resolved inside.
20
+ */
21
+ export const SIBLING_LOCALITY_CONTAINMENT = "sibling_locality_containment";
22
+ /**
23
+ * The most locality spans the pass pairs, because each ordered pair costs one lookup.
24
+ */
25
+ const MAX_SIBLING_LOCALITIES = 3;
26
+ function wofID(node) {
27
+ const id = node.placeID?.startsWith("wof:") ? Number(node.placeID.slice(4)) : Number.NaN;
28
+ return Number.isInteger(id) && id > 0 ? id : null;
29
+ }
30
+ /**
31
+ * The inner span's candidates looked up with the outer place as the containment qualifier,
32
+ * contained first, or null when none lies inside the outer place.
33
+ */
34
+ async function readContainment(inner, outer, outerID, backend, opts) {
35
+ const country = outer.metadata?.["resolver_country"];
36
+ const hits = await backend.findPlace({
37
+ text: inner.value,
38
+ placetype: opts.placetype,
39
+ parentQualifierID: outerID,
40
+ ...(typeof country === "string" && country ? { country } : {}),
41
+ limit: opts.limit,
42
+ });
43
+ const inside = (c) => c.containedByQualifier === true && Number(c.id) !== outerID;
44
+ if (!hits.some(inside))
45
+ return null;
46
+ const ranked = partitionByContainment(rankByImportance(hits), inside, (c) => c.exactMatch === true);
47
+ return { inner, outer, outerID, ranked };
48
+ }
49
+ /**
50
+ * Resolves each inner `locality` span inside its sibling's place and retags it `dependent_locality`.
51
+ *
52
+ * A pair is read in both orders.
53
+ * A pair whose spans each hold a candidate inside the other, or that resolved
54
+ * to one place, is left as it was.
55
+ */
56
+ export async function applySiblingLocalityContainment(roots, backend, opts) {
57
+ const localities = collectNodes(roots, (n) => n.tag === "locality" && wofID(n) != null).slice(0, MAX_SIBLING_LOCALITIES);
58
+ if (localities.length < 2)
59
+ return;
60
+ const retagged = new Set();
61
+ for (const [i, a] of localities.entries()) {
62
+ for (const b of localities.slice(i + 1)) {
63
+ if (retagged.has(a) || retagged.has(b))
64
+ continue;
65
+ const aID = wofID(a);
66
+ const bID = wofID(b);
67
+ if (aID === bID)
68
+ continue;
69
+ const aInB = await readContainment(a, b, bID, backend, opts);
70
+ const bInA = await readContainment(b, a, aID, backend, opts);
71
+ // The gazetteer must order the pair one way only.
72
+ const reading = aInB && !bInA ? aInB : bInA && !aInB ? bInA : null;
73
+ if (!reading)
74
+ continue;
75
+ const [top, ...alternatives] = reading.ranked;
76
+ decorateNode(reading.inner, top, alternatives);
77
+ reading.inner.tag = "dependent_locality";
78
+ reading.inner.metadata = {
79
+ ...reading.inner.metadata,
80
+ admin_containment: adminContainmentVerdict(reading.ranked),
81
+ contained_by_parent: true,
82
+ [SIBLING_LOCALITY_CONTAINMENT]: `wof:${reading.outerID}`,
83
+ };
84
+ retagged.add(reading.inner);
85
+ if (opts.traceSink) {
86
+ const rec = createNodeTraceRecorder(opts.traceSink);
87
+ rec.bind(reading.inner, opts.placetype, { parentQualifierID: reading.outerID, limit: opts.limit }, opts.limit);
88
+ rec.check(SIBLING_LOCALITY_CONTAINMENT);
89
+ rec.stage("sibling_containment", reading.ranked);
90
+ rec.emit({ id: top.id, name: top.name, source: "sibling_locality_containment" });
91
+ }
92
+ }
93
+ }
94
+ }
95
+ //# sourceMappingURL=sibling-locality.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"sibling-locality.js","sourceRoot":"","sources":["../../lib/resolve/sibling-locality.ts"],"names":[],"mappings":"AAAA,kEAAkE;AAClE,kEAAkE;AAElE;;;;;;;;;GASG;AAEH,OAAO,EAAE,YAAY,EAAoB,MAAM,yBAAyB,CAAA;AAGxE,OAAO,EAAE,uBAAuB,EAAE,sBAAsB,EAAE,MAAM,oBAAoB,CAAA;AACpF,OAAO,EAAE,YAAY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AE,IAAI,CAAC,KAAK,CAAC,CAAA;gBAC9G,GAAG,CAAC,KAAK,CAAC,4BAA4B,CAAC,CAAA;gBACvC,GAAG,CAAC,KAAK,CAAC,qBAAqB,EAAE,OAAO,CAAC,MAAM,CAAC,CAAA;gBAChD,GAAG,CAAC,IAAI,CAAC,EAAE,EAAE,EAAE,GAAI,CAAC,EAAE,EAAE,IAAI,EAAE,GAAI,CAAC,IAAI,EAAE,MAAM,EAAE,8BAA8B,EAAE,CAAC,CAAA;YACnF,CAAC;QACF,CAAC;IACF,CAAC;AACF,CAAC"}
@@ -1 +1 @@
1
- {"version":3,"file":"resolve.d.ts","sourceRoot":"","sources":["../lib/resolve.ts"],"names":[],"mappings":"AAaA,OAAO,EAKN,KAAK,QAAQ,EACb,KAAK,eAAe,EAEpB,MAAM,0BAA0B,CAAA;AA2DjC;;GAEG;AACH,OAAO,EAAE,4BAA4B,EAAE,MAAM,iBAAiB,CAAA;AAE9D,wBAAgB,iBAAiB,CAAC,OAAO,EAAE,eAAe,GAAG,QAAQ,CAEpE"}
1
+ {"version":3,"file":"resolve.d.ts","sourceRoot":"","sources":["../lib/resolve.ts"],"names":[],"mappings":"AAaA,OAAO,EAON,KAAK,QAAQ,EACb,KAAK,eAAe,EAEpB,MAAM,0BAA0B,CAAA;AA0EjC;;GAEG;AACH,OAAO,EAAE,4BAA4B,EAAE,MAAM,iBAAiB,CAAA;AAE9D,wBAAgB,iBAAiB,CAAC,OAAO,EAAE,eAAe,GAAG,QAAQ,CAEpE"}
package/out/resolve.js CHANGED
@@ -1,13 +1,15 @@
1
1
  // SPDX-FileCopyrightText: Teffen Ellis and Mailwoman contributors
2
2
  // SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-Commercial
3
3
  import { matchCountry, matchSubdivision } from "@mailwoman/codex/country";
4
- import { DEFAULT_PLACETYPE_MAP, isPlacetypeFallback } from "@mailwoman/codex/placetype-map";
4
+ import { DEFAULT_PLACETYPE_MAP, isPlacetypeFallback } from "@mailwoman/codex/labels/placetype-map";
5
5
  import { collectNodes, isShapeExcludedPostcode } from "@mailwoman/core/decoder";
6
- import { resolveSwitches, } from "@mailwoman/core/resolver";
6
+ import { hardCountryOf, ScopeStrength, resolveSwitches, } from "@mailwoman/core/resolver";
7
+ import { isPresent } from "@mailwoman/core/values/objects";
7
8
  import { countriesFromPostcodeFormat } from "@mailwoman/postcode/postcode-format";
8
9
  import { applyAdminCoherence, applyExplicitCountryCoherence, applyParentFallbackContradiction, applyRegionCountryCoherence, } from "#admin/coherence-passes";
9
10
  import { adminContainmentVerdict, firstRegionQualifier, partitionByContainment } from "#admin/containment";
10
11
  import { COUNTY_DESIGNATOR_FALLBACK, countyFromDesignatedLocality } from "#admin/county-designator";
12
+ import { acceptFormerDivisions, FORMER_DIVISION_TAGS } from "#admin/former-division";
11
13
  import { resolveCompoundMunicipality } from "#admin/jp-municipality";
12
14
  import { BARE_REGION_DOMINANCE_LOG10, bareCountryCandidate, bareRegionCandidate, emptyLocalityPick, logPopulation, loneBareLocalityNode, } from "#bare-toponym-race";
13
15
  import { decorateNode } from "#decorate-node";
@@ -16,9 +18,12 @@ import { postcodePrefixResolvedPlace, probePostcodePrefix } from "#postcode/pref
16
18
  import { applyPostcodeShapeCoherence } from "#postcode/shape-coherence";
17
19
  import { applyCountryCode, readRegionCodeAsCountry } from "#resolve/country-code";
18
20
  import { applyLandmark } from "#resolve/landmark";
21
+ import { agreesWithParent, applyCallerParentQualifier, applyParentPlaceCountry, readParentPlace, } from "#resolve/parent-place";
19
22
  import { applyPostcodeConsistency, applyRooftopConsistency, applySpanRescore, createNodeTraceRecorder, DIAGNOSTIC_BANDS, firstPostcodeValue, NOOP_TRACE_RECORDER, } from "#resolve/passes";
20
23
  import { applyCountryAsRegion, applyLocalityAsRegion, applyRegionCity, applyStreetAsTown, applyVenueAsTown, } from "#resolve/region-city";
24
+ import { applySiblingLocalityContainment } from "#resolve/sibling-locality";
21
25
  import { applyWholeInputPlace } from "#resolve/whole-input";
26
+ import { placesOutsideCountryScope, promoteSoftCountry, retrieveWithSoftCountry, softScopeRetrieves, } from "#scope-retrieval";
22
27
  import { applyAddressPoint, applyInterpolation, applyStreetCentroid } from "#street/tier";
23
28
  import { DEFAULT_COUNTRY_PRIOR_WEIGHT, promoteCapitals, rankByCountryPrior, rankByImportance, } from "#toponym-prior";
24
29
  /**
@@ -89,7 +94,12 @@ class WOFResolver {
89
94
  minWinningScore: opts.minWinningScore ?? 0,
90
95
  minScoreRefusals: 0,
91
96
  candidatesPerLookup: opts.candidatesPerLookup ?? 5,
92
- defaultCountry: opts.defaultCountry ?? null,
97
+ // One scope value: a hard scope filters, and a soft one ranks.
98
+ defaultCountry: hardCountryOf(opts.defaultCountry) ? opts.defaultCountry : null,
99
+ softCountry: opts.defaultCountry?.strength === ScopeStrength.Soft ? opts.defaultCountry : null,
100
+ softCountryWeight: opts.softCountryWeight ?? DEFAULT_COUNTRY_PRIOR_WEIGHT,
101
+ scopeCountryRetrieval: opts.scopeCountryRetrieval,
102
+ parentPlace: opts.parentPlace ? readParentPlace(this.#backend, opts.parentPlace) : null,
93
103
  bareLocalityNode: loneBareLocalityNode(tree, opts.placetypeMap ?? DEFAULT_PLACETYPE_MAP),
94
104
  parentFallback: opts.parentFallback,
95
105
  // Only enable unreachable diagnostics when a trace sink exists.
@@ -106,8 +116,6 @@ class WOFResolver {
106
116
  bias: opts.bias,
107
117
  anchorPosterior: opts.anchorPosterior,
108
118
  anchorWeight: opts.anchorWeight ?? 2,
109
- localeCountryPrior: opts.localeCountryPrior,
110
- localeCountryPriorWeight: opts.localeCountryPriorWeight ?? DEFAULT_COUNTRY_PRIOR_WEIGHT,
111
119
  capitalLevel: opts.capitalLevel,
112
120
  hardCountry: opts.hardCountry,
113
121
  includeAncestors: opts.includeAncestors,
@@ -115,9 +123,13 @@ class WOFResolver {
115
123
  adminContainmentRerank: opts.adminContainmentRerank,
116
124
  dependentLocalityContainment: opts.dependentLocalityContainment,
117
125
  countyDesignatorFallback: opts.countyDesignatorFallback,
126
+ ...(opts.formerDivisions && opts.formerDivisionLookup
127
+ ? { formerDivisionLookup: opts.formerDivisionLookup, pendingFormerDivisions: new Map() }
128
+ : {}),
118
129
  regionQualifier: firstRegionQualifier(tree.roots),
119
130
  ...(opts.traceSink ? { traceSink: opts.traceSink } : {}),
120
131
  };
132
+ applyParentPlaceCountry(state);
121
133
  // Optional pre-walk postcode-country coherence pass.
122
134
  // This is the only pass allowed to override `defaultCountry`.
123
135
  let postcodeScope = null;
@@ -151,6 +163,13 @@ class WOFResolver {
151
163
  }
152
164
  // A later pass that gives one of these nodes a different place removes the walk's ancestors with the old place.
153
165
  const walkedWithAncestors = collectNodes(newRoots, (n) => n.metadata?.["ancestors"] != null);
166
+ if (opts.siblingLocalityContainment) {
167
+ await applySiblingLocalityContainment(newRoots, this.#backend, {
168
+ placetype: state.placetypeMap.locality ?? "locality",
169
+ limit: state.candidatesPerLookup,
170
+ traceSink: state.traceSink ?? null,
171
+ });
172
+ }
154
173
  // Stamp metadata for postcode-country override.
155
174
  if (postcodeScope) {
156
175
  stampPostcodeCountryScope(newRoots, postcodeScope);
@@ -207,7 +226,9 @@ class WOFResolver {
207
226
  // Span-rescore fallback tier (default on).
208
227
  // Skip when a min-score refusal already occurred.
209
228
  if (opts.spanRescore && state.minScoreRefusals === 0) {
210
- await applySpanRescore(newRoots, tree.raw, this.#backend, opts);
229
+ await applySpanRescore(newRoots, tree.raw, this.#backend,
230
+ // A hard parent's country filters the probes as a caller's default country does.
231
+ state.parentPlace && state.defaultCountry ? { ...opts, defaultCountry: state.defaultCountry } : opts, !state.defaultCountry && softScopeRetrieves(state) ? state.softCountry.country : null);
211
232
  }
212
233
  // OpenStreetMap places answer after span rescore, so a town that holds the whole name keeps it.
213
234
  if (opts.osmPlaces) {
@@ -225,6 +246,10 @@ class WOFResolver {
225
246
  if (opts.streetCentroids) {
226
247
  applyStreetCentroid(newRoots, tree.raw, opts.streetCentroids, opts.streetCountryHints ?? []);
227
248
  }
249
+ // A value no current division answered is accepted when a former division of that name covered the settlement.
250
+ if (state.pendingFormerDivisions?.size && this.#backend.ancestors) {
251
+ acceptFormerDivisions(newRoots, state.pendingFormerDivisions, this.#backend.ancestors.bind(this.#backend));
252
+ }
228
253
  // The walk's ancestors are read again for the place that replaced its pick.
229
254
  if (this.#backend.ancestors) {
230
255
  for (const node of walkedWithAncestors) {
@@ -260,7 +285,7 @@ class WOFResolver {
260
285
  }
261
286
  if (picked) {
262
287
  resolved = picked.top;
263
- decorateNode(decorated, picked.top, picked.alternatives);
288
+ decorateNode(decorated, picked.top, picked.alternatives, picked.considered);
264
289
  if (picked.metadata) {
265
290
  decorated.metadata = { ...decorated.metadata, ...picked.metadata };
266
291
  }
@@ -279,6 +304,14 @@ class WOFResolver {
279
304
  decorated.metadata = { ...decorated.metadata, ancestors: this.#backend.ancestors(picked.top.id) };
280
305
  }
281
306
  }
307
+ else if (state.formerDivisionLookup && FORMER_DIVISION_TAGS.has(node.tag)) {
308
+ // No current division answered, so the value may name a former one, checked after the walk.
309
+ const country = parentResolved?.country ?? state.defaultCountry?.country ?? null;
310
+ const matches = state.formerDivisionLookup.divisionsNamed(node.value, country);
311
+ if (matches.length) {
312
+ state.pendingFormerDivisions.set(decorated, matches);
313
+ }
314
+ }
282
315
  }
283
316
  const carryParent = resolved ?? parentResolved;
284
317
  for (const child of node.children) {
@@ -313,6 +346,58 @@ class WOFResolver {
313
346
  }
314
347
  return found;
315
348
  }
349
+ /**
350
+ * A soft scope's own rows merged into an unscoped lookup's candidates, under scope retrieval.
351
+ *
352
+ * It returns `candidates` unchanged without a soft country, when the lookup already
353
+ * has a country, or when the soft scope ranks only.
354
+ */
355
+ async #withSoftCountryRows(query, candidates, softCountry, state, rec) {
356
+ if (!softCountry || query.country || !softScopeRetrieves(state))
357
+ return candidates;
358
+ rec.check("soft_country_retrieval");
359
+ const merged = await retrieveWithSoftCountry(this.#backend, query, candidates, softCountry);
360
+ rec.stage("soft_country", merged);
361
+ return merged;
362
+ }
363
+ /**
364
+ * A hard caller parent's split of the ranked candidates into those its lineage agrees with
365
+ * and the excluded rest, each marked `outsideScope`.
366
+ *
367
+ * Without a hard parent or an ancestors lookup, every candidate is kept.
368
+ */
369
+ #applyHardParent(ranked, qualifierIsParent, state, rec) {
370
+ const parent = state.parentPlace;
371
+ if (parent?.scope.strength !== ScopeStrength.Hard || !this.#backend.ancestors)
372
+ return { kept: ranked, excluded: [] };
373
+ const ancestors = this.#backend.ancestors.bind(this.#backend);
374
+ const agrees = (c) => agreesWithParent(c, parent, ancestors, qualifierIsParent);
375
+ const kept = ranked.filter(agrees);
376
+ rec.stage("parent_scope", kept);
377
+ return {
378
+ kept,
379
+ excluded: ranked.filter((c) => !agrees(c)).map((c) => ({ ...c, outsideScope: true })),
380
+ };
381
+ }
382
+ /**
383
+ * The same-name places outside a hard default country, for the node's
384
+ * `considered` list, under scope retrieval.
385
+ *
386
+ * The probe changes no pick, so a backend error is traced and answers no places.
387
+ */
388
+ async #placesOutsideScope(query, state, rec) {
389
+ if (!state.scopeCountryRetrieval || !query.country)
390
+ return [];
391
+ try {
392
+ const outside = await placesOutsideCountryScope(this.#backend, query, query.country);
393
+ rec.check(`outside_scope: ${outside.length}`);
394
+ return outside;
395
+ }
396
+ catch (error) {
397
+ rec.check(`outside_scope_error: ${error.message}`);
398
+ return [];
399
+ }
400
+ }
316
401
  /**
317
402
  * The county of a designated `locality` value's name in its region, when the locality
318
403
  * lookup found no locality known to be inside that region.
@@ -380,6 +465,7 @@ class WOFResolver {
380
465
  query.bias = state.bias;
381
466
  }
382
467
  const parentContainment = applyParentScope(query, node, parentResolved, state);
468
+ const callerParentQualifies = applyCallerParentQualifier(query, state);
383
469
  // Country scope precedence: parent -> default -> node hint -> hard country.
384
470
  const countryHint = node.metadata?.["country_hint"];
385
471
  // Do not apply inferred default-country filtering to country lookups.
@@ -399,7 +485,9 @@ class WOFResolver {
399
485
  const containmentEligible = state.adminContainmentRerank &&
400
486
  placetype === "locality" &&
401
487
  state.regionQualifier != null &&
402
- !isCallerScope(state.defaultCountry);
488
+ !isCallerScope(state.defaultCountry) &&
489
+ // The backend reads one qualifier, and the caller's parent outranks the parsed region.
490
+ !state.parentPlace;
403
491
  if (containmentEligible) {
404
492
  query.regionQualifier = state.regionQualifier;
405
493
  }
@@ -415,14 +503,24 @@ class WOFResolver {
415
503
  // Bind a snapshot so later query mutations do not affect trace history.
416
504
  rec.bind(node, placetype, { ...query }, state.candidatesPerLookup);
417
505
  let candidates;
506
+ // The anchor posterior and both country scopes act on region and locality lookups only.
507
+ const anchorEligible = placetype === "region" || placetype === "locality";
508
+ // A soft scope ranks a lookup no hard country, tree parent or anchor posterior already scopes.
509
+ const softCountry = anchorEligible && !state.defaultCountry && !state.anchorPosterior ? (state.softCountry?.country ?? null) : null;
510
+ // The places a hard scope excluded, reported on `considered`.
511
+ let outsideScope = [];
418
512
  // For unconstrained postalcodes, probe format-implied countries only.
419
513
  if (placetype === "postalcode" && !query.country && state.postcodeFormatCountries?.length) {
420
514
  rec.check("postcode_format_probe");
421
515
  let best = null;
516
+ const countryWinners = [];
422
517
  for (const impliedCountry of state.postcodeFormatCountries) {
423
518
  try {
424
519
  const hits = await this.#backend.findPlace({ ...query, country: impliedCountry });
425
520
  const top = hits[0];
521
+ if (top) {
522
+ countryWinners.push(top);
523
+ }
426
524
  // Keep the best per-country winner by score.
427
525
  if (top && (!best || top.score > best.score)) {
428
526
  best = top;
@@ -434,7 +532,7 @@ class WOFResolver {
434
532
  }
435
533
  if (best) {
436
534
  rec.emit({ id: best.id, name: best.name, source: "postcode_format_probe" });
437
- return { top: best, alternatives: [] };
535
+ return { top: best, alternatives: [], considered: countryWinners.filter((c) => c !== best) };
438
536
  }
439
537
  candidates = [];
440
538
  }
@@ -453,6 +551,10 @@ class WOFResolver {
453
551
  candidates = await this.#backend.findPlace(query);
454
552
  rec.stage("parent_fallback", candidates);
455
553
  }
554
+ candidates = await this.#withSoftCountryRows(query, candidates, softCountry, state, rec);
555
+ // Only a lookup the default country filtered reports the same-name places outside it.
556
+ const filteredByDefault = anchorEligible && !parentResolved && query.country != null && query.country === defaultCountryForLookup;
557
+ outsideScope = filteredByDefault ? await this.#placesOutsideScope(query, state, rec) : [];
456
558
  // Optional diagnostics: record other bands that can resolve this value.
457
559
  if (!candidates.length && state.diagnoseUnreachable) {
458
560
  rec.reachable(await this.#probeOtherBands(query, placetype));
@@ -477,6 +579,8 @@ class WOFResolver {
477
579
  }
478
580
  const bareCountry = isBareRace ? await bareCountryCandidate(this.#backend, node.value, query.country) : null;
479
581
  const bareRegion = isBareRace ? await bareRegionCandidate(this.#backend, node.value, query.country) : null;
582
+ // The race probes a pick passes over, kept for the geocode result's candidate list.
583
+ const raceLosers = (picked) => [bareCountry, bareRegion].filter(isPresent).filter((probe) => probe !== picked);
480
584
  if (!candidates.length) {
481
585
  // With no locality candidates, a bare name takes an admin or sub-locality namesake.
482
586
  const pick = isBareRace
@@ -485,40 +589,21 @@ class WOFResolver {
485
589
  if (pick) {
486
590
  rec.check(pick.check);
487
591
  rec.emit({ id: pick.place.id, name: pick.place.name, source: pick.source });
488
- return { top: pick.place, alternatives: [], metadata: pick.metadata };
592
+ return {
593
+ top: pick.place,
594
+ alternatives: [],
595
+ considered: [...raceLosers(pick.place), ...outsideScope],
596
+ metadata: pick.metadata,
597
+ };
489
598
  }
490
599
  rec.emit(null);
491
600
  return null;
492
601
  }
493
- // Optional anchor-based rerank using postcode country posterior.
494
- // Applied to region/locality and kept tier-safe by exact-match first.
495
- const anchorEligible = placetype === "region" || placetype === "locality";
496
- let ranked = candidates;
497
- if (state.anchorPosterior && anchorEligible && candidates.length > 1) {
498
- ranked = rankByAnchorPosterior(candidates, state.anchorPosterior, state.anchorWeight);
499
- rec.stage("anchor", ranked);
500
- ranked = rankWithinPosteriorCountry(ranked, state.capitalLevel, node);
501
- rec.stage("importance", ranked);
502
- }
503
- // Optional locale-country soft prior adds to candidate scores while retaining every candidate.
504
- // Disabled when default country or anchor posterior is present.
505
- if (state.localeCountryPrior && !state.defaultCountry && !state.anchorPosterior && anchorEligible) {
506
- ranked = rankByCountryPrior(ranked, state.localeCountryPrior, state.localeCountryPriorWeight);
507
- rec.stage("locale_prior", ranked);
508
- }
509
- // Importance-first rerank (the posterior branch above runs its own, within the winning country).
510
- if (!state.anchorPosterior) {
511
- ranked = rankByImportance(ranked);
512
- rec.stage("importance", ranked);
513
- // Optional bounded capital promotion.
514
- if (state.capitalLevel) {
515
- ranked = promoteCapitalsWithReceipt(ranked, state.capitalLevel, node);
516
- rec.stage("capital", ranked);
517
- }
518
- }
602
+ const softPromotion = rankByPriors(candidates, anchorEligible, softCountry, node, state, rec);
603
+ let ranked = softPromotion.ranked;
519
604
  // Final containment partition.
520
605
  // It reads the address's own qualifier and preserves the exact-match tier.
521
- const qualifierPartition = containmentEligible || parentContainment;
606
+ const qualifierPartition = containmentEligible || parentContainment || callerParentQualifies;
522
607
  if (qualifierPartition) {
523
608
  ranked = partitionByContainment(ranked, (c) => c.containedByQualifier === true, (c) => c.exactMatch === true);
524
609
  rec.stage("containment", ranked);
@@ -532,6 +617,14 @@ class WOFResolver {
532
617
  ];
533
618
  rec.stage("exact_type", ranked);
534
619
  }
620
+ const parentScoped = this.#applyHardParent(ranked, callerParentQualifies, state, rec);
621
+ ranked = parentScoped.kept;
622
+ outsideScope = [...parentScoped.excluded, ...outsideScope];
623
+ if (!ranked.length) {
624
+ rec.check("parent_scope_excluded_all");
625
+ rec.emit(null);
626
+ return null;
627
+ }
535
628
  const top = ranked[0];
536
629
  if (top.score < state.minWinningScore) {
537
630
  state.minScoreRefusals++;
@@ -543,12 +636,22 @@ class WOFResolver {
543
636
  if (bareCountry && (bareCountry.prominence ?? bareCountry.score) > (top.prominence ?? top.score)) {
544
637
  rec.check("bare_country_repick");
545
638
  rec.emit({ id: bareCountry.id, name: bareCountry.name, source: "bare_country" });
546
- return { top: bareCountry, alternatives: ranked, metadata: { bare_country_repick: true } };
639
+ return {
640
+ top: bareCountry,
641
+ alternatives: ranked,
642
+ considered: [...raceLosers(bareCountry), ...outsideScope],
643
+ metadata: { bare_country_repick: true },
644
+ };
547
645
  }
548
646
  if (bareRegion && logPopulation(bareRegion) >= logPopulation(top) + BARE_REGION_DOMINANCE_LOG10) {
549
647
  rec.check("bare_region_repick");
550
648
  rec.emit({ id: bareRegion.id, name: bareRegion.name, source: "bare_region" });
551
- return { top: bareRegion, alternatives: ranked, metadata: { bare_region_repick: true } };
649
+ return {
650
+ top: bareRegion,
651
+ alternatives: ranked,
652
+ considered: [...raceLosers(bareRegion), ...outsideScope],
653
+ metadata: { bare_region_repick: true },
654
+ };
552
655
  }
553
656
  // Stamp fallback quality when a macro-type winner stands in.
554
657
  if (isPlacetypeFallback(placetype, top.placetype)) {
@@ -560,6 +663,8 @@ class WOFResolver {
560
663
  const pickMetadata = {
561
664
  ...containmentStamps(qualifierPartition, parentContainment, ranked, top),
562
665
  ...(top.variantAliasExempted === true ? { variant_alias_exemption: true } : {}),
666
+ // The soft scope's promotion moved this place ahead of a larger namesake.
667
+ ...(top === softPromotion.promoted ? { soft_country_promotion: softCountry } : {}),
563
668
  // Mark picks admitted outside resolved parent scope.
564
669
  ...((parentResolved && typeof parentResolved.id === "number" && query.parentID == null) ||
565
670
  top.regionScopeMiss === true
@@ -569,6 +674,7 @@ class WOFResolver {
569
674
  return {
570
675
  top,
571
676
  alternatives: ranked.slice(1),
677
+ considered: [...raceLosers(null), ...outsideScope],
572
678
  ...(Object.keys(pickMetadata).length ? { metadata: pickMetadata } : {}),
573
679
  };
574
680
  }
@@ -608,6 +714,38 @@ function containmentStamps(qualifierPartition, parentContainment, ranked, top) {
608
714
  ...(parentContainment && top.containedByQualifier === true ? { contained_by_parent: true } : {}),
609
715
  };
610
716
  }
717
+ /**
718
+ * Ranks a lookup's candidates by its priors in order: the postcode anchor posterior,
719
+ * the ranking-only soft scope, importance with capital promotion, then the retrieval soft scope.
720
+ *
721
+ * `promoted` is the place the retrieval soft scope moved to the lead, or null.
722
+ */
723
+ function rankByPriors(candidates, anchorEligible, softCountry, node, state, rec) {
724
+ let ranked = candidates;
725
+ // Optional anchor-based rerank using postcode country posterior, kept tier-safe by exact-match first.
726
+ if (state.anchorPosterior && anchorEligible && candidates.length > 1) {
727
+ ranked = rankByAnchorPosterior(candidates, state.anchorPosterior, state.anchorWeight);
728
+ rec.stage("anchor", ranked);
729
+ ranked = rankWithinPosteriorCountry(ranked, state.capitalLevel, node);
730
+ rec.stage("importance", ranked);
731
+ }
732
+ // Without scope retrieval, the soft scope adds to candidate scores ahead of the importance rerank.
733
+ if (softCountry && !softScopeRetrieves(state)) {
734
+ ranked = rankByCountryPrior(ranked, softCountry, state.softCountryWeight);
735
+ rec.stage("locale_prior", ranked);
736
+ }
737
+ // Importance-first rerank (the posterior branch above runs its own, within the winning country).
738
+ if (!state.anchorPosterior) {
739
+ ranked = rankByImportance(ranked);
740
+ rec.stage("importance", ranked);
741
+ // Optional bounded capital promotion.
742
+ if (state.capitalLevel) {
743
+ ranked = promoteCapitalsWithReceipt(ranked, state.capitalLevel, node);
744
+ rec.stage("capital", ranked);
745
+ }
746
+ }
747
+ return promoteSoftCountry(ranked, softCountry, state, rec);
748
+ }
611
749
  /**
612
750
  * Sorts candidates by the postcode country posterior, exact matches first.
613
751
  *