@mailwoman/resolver 10.0.0 → 10.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (134) hide show
  1. package/README.md +9 -7
  2. package/lib/admin/coherence-passes.ts +31 -172
  3. package/lib/admin/containment.ts +15 -33
  4. package/lib/admin/jp-municipality.ts +21 -14
  5. package/lib/admin/winner.ts +37 -69
  6. package/lib/backend-capabilities.ts +28 -27
  7. package/lib/bare-toponym-race.ts +69 -37
  8. package/lib/decorate-node.ts +25 -49
  9. package/lib/fold-name.ts +5 -18
  10. package/lib/index.ts +5 -9
  11. package/lib/plausibility.ts +41 -68
  12. package/lib/postcode/country-coherence.ts +92 -296
  13. package/lib/postcode/prefix.ts +24 -86
  14. package/lib/postcode/shape-coherence.ts +26 -116
  15. package/lib/remote-resolver.ts +38 -33
  16. package/lib/rerank.ts +41 -54
  17. package/lib/resolve/passes.ts +188 -177
  18. package/lib/resolve.ts +744 -0
  19. package/lib/span-rescore.ts +219 -175
  20. package/lib/street/evidence.ts +65 -73
  21. package/lib/street/tier.ts +51 -194
  22. package/lib/toponym-prior.ts +54 -180
  23. package/out/admin/coherence-passes.d.ts +18 -69
  24. package/out/admin/coherence-passes.d.ts.map +1 -1
  25. package/out/admin/coherence-passes.js +24 -166
  26. package/out/admin/coherence-passes.js.map +1 -1
  27. package/out/admin/containment.d.ts +13 -31
  28. package/out/admin/containment.d.ts.map +1 -1
  29. package/out/admin/containment.js +13 -31
  30. package/out/admin/containment.js.map +1 -1
  31. package/out/admin/jp-municipality.d.ts +21 -14
  32. package/out/admin/jp-municipality.d.ts.map +1 -1
  33. package/out/admin/jp-municipality.js +18 -12
  34. package/out/admin/jp-municipality.js.map +1 -1
  35. package/out/admin/winner.d.ts +32 -64
  36. package/out/admin/winner.d.ts.map +1 -1
  37. package/out/admin/winner.js +23 -56
  38. package/out/admin/winner.js.map +1 -1
  39. package/out/{admin/index.d.ts → admin.d.ts} +1 -1
  40. package/out/admin.d.ts.map +1 -0
  41. package/out/{admin/index.js → admin.js} +1 -1
  42. package/out/admin.js.map +1 -0
  43. package/out/backend-capabilities.d.ts +19 -20
  44. package/out/backend-capabilities.d.ts.map +1 -1
  45. package/out/backend-capabilities.js +28 -26
  46. package/out/backend-capabilities.js.map +1 -1
  47. package/out/bare-toponym-race.d.ts +54 -27
  48. package/out/bare-toponym-race.d.ts.map +1 -1
  49. package/out/bare-toponym-race.js +69 -37
  50. package/out/bare-toponym-race.js.map +1 -1
  51. package/out/decorate-node.d.ts +6 -8
  52. package/out/decorate-node.d.ts.map +1 -1
  53. package/out/decorate-node.js +25 -49
  54. package/out/decorate-node.js.map +1 -1
  55. package/out/fold-name.d.ts +5 -18
  56. package/out/fold-name.d.ts.map +1 -1
  57. package/out/fold-name.js +5 -18
  58. package/out/fold-name.js.map +1 -1
  59. package/out/index.d.ts +5 -6
  60. package/out/index.d.ts.map +1 -1
  61. package/out/index.js +5 -8
  62. package/out/index.js.map +1 -1
  63. package/out/plausibility.d.ts +30 -60
  64. package/out/plausibility.d.ts.map +1 -1
  65. package/out/plausibility.js +19 -52
  66. package/out/plausibility.js.map +1 -1
  67. package/out/postcode/country-coherence.d.ts +53 -167
  68. package/out/postcode/country-coherence.d.ts.map +1 -1
  69. package/out/postcode/country-coherence.js +42 -259
  70. package/out/postcode/country-coherence.js.map +1 -1
  71. package/out/postcode/prefix.d.ts +18 -69
  72. package/out/postcode/prefix.d.ts.map +1 -1
  73. package/out/postcode/prefix.js +11 -78
  74. package/out/postcode/prefix.js.map +1 -1
  75. package/out/postcode/shape-coherence.d.ts +18 -85
  76. package/out/postcode/shape-coherence.d.ts.map +1 -1
  77. package/out/postcode/shape-coherence.js +11 -107
  78. package/out/postcode/shape-coherence.js.map +1 -1
  79. package/out/{postcode/index.d.ts → postcode.d.ts} +1 -1
  80. package/out/postcode.d.ts.map +1 -0
  81. package/out/{postcode/index.js → postcode.js} +1 -1
  82. package/out/postcode.js.map +1 -0
  83. package/out/remote-resolver.d.ts +32 -31
  84. package/out/remote-resolver.d.ts.map +1 -1
  85. package/out/remote-resolver.js +12 -20
  86. package/out/remote-resolver.js.map +1 -1
  87. package/out/rerank.d.ts +32 -46
  88. package/out/rerank.d.ts.map +1 -1
  89. package/out/rerank.js +16 -41
  90. package/out/rerank.js.map +1 -1
  91. package/out/resolve/passes.d.ts +108 -95
  92. package/out/resolve/passes.d.ts.map +1 -1
  93. package/out/resolve/passes.js +67 -126
  94. package/out/resolve/passes.js.map +1 -1
  95. package/out/resolve.d.ts +15 -0
  96. package/out/resolve.d.ts.map +1 -0
  97. package/out/resolve.js +557 -0
  98. package/out/resolve.js.map +1 -0
  99. package/out/span-rescore.d.ts +56 -65
  100. package/out/span-rescore.d.ts.map +1 -1
  101. package/out/span-rescore.js +134 -132
  102. package/out/span-rescore.js.map +1 -1
  103. package/out/street/evidence.d.ts +56 -61
  104. package/out/street/evidence.d.ts.map +1 -1
  105. package/out/street/evidence.js +22 -46
  106. package/out/street/evidence.js.map +1 -1
  107. package/out/street/tier.d.ts +18 -30
  108. package/out/street/tier.d.ts.map +1 -1
  109. package/out/street/tier.js +43 -191
  110. package/out/street/tier.js.map +1 -1
  111. package/out/{street/index.d.ts → street.d.ts} +1 -1
  112. package/out/street.d.ts.map +1 -0
  113. package/out/{street/index.js → street.js} +1 -1
  114. package/out/street.js.map +1 -0
  115. package/out/toponym-prior.d.ts +22 -110
  116. package/out/toponym-prior.d.ts.map +1 -1
  117. package/out/toponym-prior.js +41 -170
  118. package/out/toponym-prior.js.map +1 -1
  119. package/package.json +44 -147
  120. package/lib/resolve/index.ts +0 -989
  121. package/out/admin/index.d.ts.map +0 -1
  122. package/out/admin/index.js.map +0 -1
  123. package/out/postcode/index.d.ts.map +0 -1
  124. package/out/postcode/index.js.map +0 -1
  125. package/out/resolve/index.d.ts +0 -20
  126. package/out/resolve/index.d.ts.map +0 -1
  127. package/out/resolve/index.js +0 -808
  128. package/out/resolve/index.js.map +0 -1
  129. package/out/street/index.d.ts.map +0 -1
  130. package/out/street/index.js.map +0 -1
  131. package/vitest.config.ts +0 -38
  132. /package/lib/{admin/index.ts → admin.ts} +0 -0
  133. /package/lib/{postcode/index.ts → postcode.ts} +0 -0
  134. /package/lib/{street/index.ts → street.ts} +0 -0
@@ -2,15 +2,14 @@
2
2
  * @copyright Sister Software
3
3
  * @license AGPL-3.0
4
4
  * @author Teffen Ellis, et al.
5
- * @file The resolver walk's per-node machinery: the trace recorder and its diagnostic bands, the walk's
6
- * `ResolutionState`, and the span-rescore / postcode-recovery / postcode-consistency passes the walk applies.
7
- * Split from `resolve.ts`, which owns `WOFResolver` — the walk itself over what this module provides.
8
5
  */
9
6
 
10
7
  import type { PlacetypeMap } from "@mailwoman/codex/placetype-map"
11
8
  import { walkNodes, type AddressNode } from "@mailwoman/core/decoder"
12
9
  import {
13
10
  type CoincidentLocality,
11
+ type DefaultCountry,
12
+ EMPTY_PLACE_FIELDS,
14
13
  compareReferential,
15
14
  type ResolveCandidateTrace,
16
15
  type ResolveNodeTrace,
@@ -19,6 +18,7 @@ import {
19
18
  type ResolvedPlace,
20
19
  type ResolveOpts,
21
20
  type ResolverBackend,
21
+ type ResolveSwitches,
22
22
  } from "@mailwoman/core/resolver"
23
23
  import { PLACETYPE_SPECIFICITY } from "@mailwoman/core/resources/whosonfirst/specificity"
24
24
  import { haversineKm } from "@mailwoman/spatial"
@@ -28,42 +28,32 @@ import type { CoordinateOptionalPlace } from "#postcode/prefix"
28
28
  import { isShapeExcludedPostcode } from "#postcode/shape-coherence"
29
29
  import { findRescoreCandidate, hasResolvedPlace, postcodeCodeSubset } from "#span-rescore"
30
30
 
31
- /**
32
- * Cap on candidates recorded per {@link ResolveNodeTrace} — the trace is a record, not a dump. The count past the cap is
33
- * reported in `candidatesTruncated`, so absence of a row is never silent.
34
- */
35
31
  const TRACE_CANDIDATE_CAP = 10
36
32
 
37
- /**
38
- * The fine end of the probe window: `microhood` and no finer.
39
- *
40
- * Everything above it — `postalcode`, `venue`, `campus`, `building`, `address` — is excluded because a mislabeled ADMIN
41
- * span lands on another admin band, and probing every venue in a country per miss buys a long tail of coincidental name
42
- * matches for a diagnostic that is meant to be read.
43
- */
44
33
  const FINEST_DIAGNOSTIC_BAND = PLACETYPE_SPECIFICITY["microhood"]!
45
34
 
35
+ const COARSEST_DIAGNOSTIC_BAND = PLACETYPE_SPECIFICITY["country"]!
36
+
46
37
  /**
47
- * The coarse end of the probe window. `country` and no coarser: a name matching at `continent` or `planet` says nothing
48
- * about a mislabeled admin span, and the walk resolves the country from its own node anyway.
38
+ * {@link ResolveOpts} with every {@link ResolveSwitches} key resolved against its default.
49
39
  */
50
- const COARSEST_DIAGNOSTIC_BAND = PLACETYPE_SPECIFICITY["country"]!
40
+ export type ResolvedOpts = ResolveOpts & ResolveSwitches
51
41
 
52
42
  /**
53
- * The admin bands `ResolveOpts.diagnoseUnreachable` re-probes, coarse to fine.
43
+ * The admin placetypes from country to microhood that `ResolveOpts.diagnoseUnreachable`
44
+ * re-probes, coarse to fine.
54
45
  *
55
- * Derived from `PLACETYPE_SPECIFICITY` rather than typed out, so a placetype added there is probed here without anyone
56
- * remembering to.
46
+ * The list derives from `PLACETYPE_SPECIFICITY`, so a new placetype in that range is probed automatically.
57
47
  */
58
48
  export const DIAGNOSTIC_BANDS: readonly string[] = Object.entries(PLACETYPE_SPECIFICITY)
59
- .filter(([, rank]) => rank !== undefined && rank <= FINEST_DIAGNOSTIC_BAND && rank >= COARSEST_DIAGNOSTIC_BAND)
49
+ .filter(([, rank]) => rank != null && rank <= FINEST_DIAGNOSTIC_BAND && rank >= COARSEST_DIAGNOSTIC_BAND)
60
50
  .toSorted((a, b) => (a[1] as number) - (b[1] as number))
61
51
  .map(([placetype]) => placetype)
62
52
 
63
53
  /**
64
- * Per-lookup trace bookkeeping (#1721). `#lookupAndPick` talks to ONE of these unconditionally — a real recorder when
65
- * `ResolveOpts.traceSink` is set, the frozen {@link NOOP_TRACE_RECORDER} otherwise — so the hot path carries no
66
- * per-event branches and the no-sink walk costs a handful of empty calls per node.
54
+ * Collects the trace for one placetype lookup and emits it as a `ResolveNodeTrace`;
55
+ * the walk always calls one and uses {@link NOOP_TRACE_RECORDER} when no trace
56
+ * sink is set, so the hot path has no per-event branches.
67
57
  */
68
58
  export interface NodeTraceRecorder {
69
59
  bind(
@@ -72,8 +62,8 @@ export interface NodeTraceRecorder {
72
62
  query: {
73
63
  country?: string
74
64
  parentID?: string | number
75
- postcode?: string
76
- regionQualifier?: string
65
+ postcode?: string | null
66
+ regionQualifier?: string | null
77
67
  limit?: number
78
68
  },
79
69
  defaultLimit: number
@@ -85,7 +75,7 @@ export interface NodeTraceRecorder {
85
75
  }
86
76
 
87
77
  /**
88
- * A recorder that records nothing — the walk's default when no trace was requested.
78
+ * A {@link NodeTraceRecorder} that records no events, for walks without a trace sink.
89
79
  */
90
80
  export const NOOP_TRACE_RECORDER: NodeTraceRecorder = Object.freeze({
91
81
  bind() {},
@@ -95,11 +85,15 @@ export const NOOP_TRACE_RECORDER: NodeTraceRecorder = Object.freeze({
95
85
  emit() {},
96
86
  })
97
87
 
88
+ /**
89
+ * Creates a {@link NodeTraceRecorder} that sends one `ResolveNodeTrace` to `sink` on `emit`,
90
+ * listing at most ten candidates from the last stage with each candidate's rank in every stage.
91
+ */
98
92
  export function createNodeTraceRecorder(sink: (record: ResolveNodeTrace) => void): NodeTraceRecorder {
99
93
  const checks: string[] = []
100
94
  const stageOrders: Array<[string, readonly ResolvedPlace[]]> = []
101
95
 
102
- let reachableIn: ResolveNodeTrace["reachableIn"]
96
+ let reachableIn: ResolveNodeTrace["reachableIn"] = null
103
97
 
104
98
  let ctx: {
105
99
  node: AddressNode
@@ -147,11 +141,11 @@ export function createNodeTraceRecorder(sink: (record: ResolveNodeTrace) => void
147
141
  country: c.country,
148
142
  placetype: c.placetype,
149
143
  score: c.score,
150
- ...(c.prominence !== undefined ? { prominence: c.prominence } : {}),
151
- ...(c.importance !== undefined ? { importance: c.importance } : {}),
152
- ...(c.population !== undefined ? { population: c.population } : {}),
153
- ...(c.exactMatch !== undefined ? { exactMatch: c.exactMatch } : {}),
154
- ...(c.containedByQualifier !== undefined ? { containedByQualifier: c.containedByQualifier } : {}),
144
+ prominence: c.prominence ?? null,
145
+ importance: c.importance ?? null,
146
+ population: c.population ?? null,
147
+ exactMatch: c.exactMatch ?? null,
148
+ containedByQualifier: c.containedByQualifier ?? null,
155
149
  ranks: rankMap.get(c) ?? {},
156
150
  }))
157
151
 
@@ -160,14 +154,14 @@ export function createNodeTraceRecorder(sink: (record: ResolveNodeTrace) => void
160
154
  value: ctx.node.value,
161
155
  placetype: ctx.placetype,
162
156
  query: {
163
- ...(ctx.query.country ? { country: ctx.query.country } : {}),
164
- ...(ctx.query.parentID !== undefined ? { parentID: ctx.query.parentID } : {}),
165
- ...(ctx.query.postcode ? { postcode: ctx.query.postcode } : {}),
166
- ...(ctx.query.regionQualifier ? { regionQualifier: ctx.query.regionQualifier } : {}),
157
+ country: ctx.query.country || null,
158
+ parentID: ctx.query.parentID ?? null,
159
+ postcode: ctx.query.postcode || null,
160
+ regionQualifier: ctx.query.regionQualifier || null,
167
161
  limit: ctx.query.limit ?? ctx.defaultLimit,
168
162
  },
169
163
  checks,
170
- ...(reachableIn ? { reachableIn } : {}),
164
+ reachableIn,
171
165
  candidates: rows,
172
166
  candidatesTruncated: Math.max(0, finalOrder.length - TRACE_CANDIDATE_CAP),
173
167
  picked,
@@ -176,138 +170,181 @@ export function createNodeTraceRecorder(sink: (record: ResolveNodeTrace) => void
176
170
  }
177
171
  }
178
172
 
173
+ /**
174
+ * The options and mutable state that one `resolveTree` call passes through its tree walk.
175
+ */
179
176
  export interface ResolutionState {
180
177
  lookupsRemaining: number
181
178
  placetypeMap: PlacetypeMap
182
179
  minWinningScore: number
180
+
181
+ /**
182
+ * The count of lookups rejected by {@link ResolutionState.minWinningScore}.
183
+ *
184
+ * A nonzero count skips the span-rescore pass.
185
+ * That pass would otherwise treat the refused node as unresolved and repeat the rejected lookup.
186
+ */
187
+ minScoreRefusals: number
183
188
  candidatesPerLookup: number
184
- defaultCountry?: string
185
189
  /**
186
- * Whether {@link defaultCountry} came from the locale rather than the caller. Consulted only by `country`-placetype
187
- * lookups, which skip an inferred scope — see `ResolveOpts.defaultCountryIsInferred`.
190
+ * The default country scope, or null for none.
191
+ *
192
+ * `country` lookups ignore an inferred default.
188
193
  */
189
- defaultCountryIsInferred: boolean
194
+ defaultCountry: DefaultCountry | null
195
+
190
196
  /**
191
- * The tree's single value-bearing node when it is locality-tagged (the bare-toponym shape), else null. Checks the
192
- * country-placetype sibling race in `#lookupAndPick` — a bare name can be a country the parser tagged `locality`
193
- * ("Japan", "China"), and the locality placetype filter makes the country row unreachable no matter how it ranks.
197
+ * The tree's only value-bearing node when it maps to `locality`, or null otherwise.
198
+ *
199
+ * Its lookup also probes countries and regions of the same name, because the locality
200
+ * placetype filter cannot reach a country that the parser tagged as a locality.
194
201
  */
195
202
  bareLocalityNode: AddressNode | null
196
203
  parentFallback: boolean
204
+
197
205
  /**
198
- * The address's postcode string, extracted once up front, passed to locality lookups so a coordinate-first backend
199
- * can inject postcode-proximal locality candidates.
206
+ * The tree's first postcode value.
207
+ *
208
+ * Locality lookups send it to the backend.
209
+ * The backend can then favor nearby candidates.
200
210
  */
201
- postcode?: string
211
+ postcode?: string | null
212
+
202
213
  /**
203
- * Postcode-containment coherence (#31, Mechanism 2) — forwarded to locality lookups so a coordinate-first backend can
204
- * re-rank name candidates by proximity to the postcode's own centroid. Opt-in; OFF by default.
214
+ * Whether locality lookups ask the backend to re-rank candidates by distance to the postcode centroid.
205
215
  */
206
216
  postcodeContainmentCoherence: boolean
217
+
207
218
  /**
208
- * Postcode-prefix prior (#31, Mechanism 3) — on a `postalcode` miss, derive the code's prefix and probe
209
- * `postcodePrefixIndex`. Opt-in; OFF by default.
219
+ * Whether a `postalcode` lookup that misses falls back to {@link ResolutionState.postcodePrefixIndex}.
210
220
  */
211
221
  postcodePrefixPrior: boolean
222
+
212
223
  /**
213
- * #1589 — the countries the parsed postcode's FORMAT implies (the #928 singles plus the shared `NNN NN` family). When
214
- * set AND no country constraint survives, the `postalcode` lookup probes exactly these countries and abstains if all
215
- * miss — never falling through to an unconstrained probe, whose space-stripped fold collides across systems (`100 00`
216
- * folded to `10000` answers Troyes FR while Prague sits in the artifact under both keyings).
224
+ * The countries implied by the postcode's format.
225
+ *
226
+ * A `postalcode` lookup without a country scope probes only these countries
227
+ * and abstains if all of them miss.
228
+ * An unscoped probe of a space-stripped code can match another country's postcode system.
217
229
  */
218
230
  postcodeFormatCountries?: readonly string[]
231
+
219
232
  /**
220
- * #1585 — the locale hint's country, forwarded to the backend as `fuzzyCountry` on every primary lookup. Scopes the
221
- * typo-fuzzy tier only; exact matches stay worldwide. See `ResolveOpts.fuzzyCountryScope`.
233
+ * The locale hint's country, sent as `fuzzyCountry` on every lookup.
234
+ * It scopes only the typo-fuzzy tier.
222
235
  */
223
236
  fuzzyCountryScope?: string
237
+
224
238
  /**
225
- * The injected PFX1 index (structural — `PostcodePrefixIndexLike`, core/resolver/types.ts). Absent = the prior cannot
226
- * fire.
239
+ * The postcode prefix index that {@link ResolutionState.postcodePrefixPrior} requires.
227
240
  */
228
241
  postcodePrefixIndex?: PostcodePrefixIndexLike
242
+
229
243
  /**
230
- * Proximity-bias points (viewport, user location) — forwarded to every primary lookup.
244
+ * Proximity-bias points, such as a viewport or user location, that every
245
+ * lookup uses to reorder candidates.
231
246
  */
232
247
  bias?: Array<{ lat: number; lon: number; weight?: number }>
248
+
233
249
  /**
234
- * Postcode-anchor country posterior (#369). Undefined = no re-rank (byte-stable default).
250
+ * The postcode anchor's posterior over countries, used to re-rank region and locality candidates.
251
+ *
252
+ * When set, it also replaces the importance re-rank and capital promotion.
235
253
  */
236
254
  anchorPosterior?: Record<string, number>
255
+
237
256
  /**
238
- * Weight on the posterior in the locality re-rank. Only used when `anchorPosterior` is set.
257
+ * The weight on {@link ResolutionState.anchorPosterior} in the re-rank key.
239
258
  */
240
259
  anchorWeight: number
260
+
241
261
  /**
242
- * #1721 resolver-interior trace sink. Undefined (the default) = zero bookkeeping, byte-identical walk.
262
+ * The callback that receives one trace record per lookup.
263
+ * The walk records no events when it is absent.
243
264
  */
244
265
  traceSink?: (record: ResolveNodeTrace) => void
266
+
245
267
  /**
246
- * Re-probe a resolved-nothing lookup across the other admin bands and record which hold it. Diagnostic only — never
247
- * reaches the pick. See `ResolveOpts.diagnoseUnreachable`.
268
+ * Whether an empty lookup re-probes the other admin bands and traces which ones hold the value.
269
+ *
270
+ * It is set only when a trace sink exists.
271
+ * It never affects the pick.
248
272
  */
249
273
  diagnoseUnreachable?: boolean
274
+
250
275
  /**
251
- * #27 locale-country SOFT prior for the bare-toponym admin walk. Undefined = no prior (the shipped default) →
252
- * byte-stable. See `ResolveOpts.localeCountryPrior` for the calibration and why it ships opt-in.
276
+ * The locale country used as a soft prior on region and locality candidates
277
+ * when no default country or anchor posterior applies.
253
278
  */
254
279
  localeCountryPrior?: string
280
+
255
281
  /**
256
- * Weight of that prior in log10-population units. Only consulted when `localeCountryPrior` is set.
282
+ * The weight of {@link ResolutionState.localeCountryPrior}, in log10-population units.
257
283
  */
258
284
  localeCountryPriorWeight: number
285
+
259
286
  /**
260
- * #1880 capital status per candidate, from `ResolveOpts.capitalLevel`. Undefined → no promotion, byte-stable.
287
+ * Returns a candidate's capital level for bounded capital promotion.
288
+ * Capital promotion is off when it is absent.
261
289
  */
262
- capitalLevel?: (place: { name: string; country?: string; lat: number; lon: number }) => number
290
+ capitalLevel?: (place: { name: string; country: string | null; lat: number; lon: number }) => number
291
+
263
292
  /**
264
- * #743/#194 confident-placer country as a HARD filter (empty→unresolved, no global retry). Off = undefined.
293
+ * The country scope applied to a lookup when no parent, default country, or node hint supplies one.
265
294
  */
266
295
  hardCountry?: string
296
+
267
297
  /**
268
- * Dual-role hierarchy completion (#405). Off by default → byte-stable.
298
+ * Whether a resolved region gains its coincident locality of the same name as an
299
+ * interpretation when the tree has no locality node.
269
300
  */
270
301
  hierarchyCompletion: boolean
302
+
271
303
  /**
272
- * Attach ancestor lineage to each resolved node (#404). Off by default → byte-stable.
304
+ * Whether each resolved node gets its ancestor lineage in metadata, when the backend supports it.
273
305
  */
274
306
  includeAncestors: boolean
307
+
275
308
  /**
276
- * Admin-containment re-rank (#1717 stage 2). Off by default → byte-stable. See `ResolveOpts.adminContainmentRerank`.
309
+ * Whether locality candidates contained by {@link ResolutionState.regionQualifier}
310
+ * are ordered ahead of the rest.
277
311
  */
278
312
  adminContainmentRerank: boolean
313
+
279
314
  /**
280
- * The tree's first parsed region-tagged span, extracted once up front (the `postcode` pattern above — region and
281
- * locality are siblings, so the top-down walk wouldn't otherwise let the locality lookup see it). Only consulted when
282
- * {@link adminContainmentRerank} is on.
315
+ * The tree's first region value.
316
+ *
317
+ * The region and locality nodes are siblings, so the walk would not otherwise
318
+ * pass the region to the locality lookup.
319
+ * It applies only with {@link ResolutionState.adminContainmentRerank}
320
+ * and no caller-supplied default country.
283
321
  */
284
- regionQualifier?: string
322
+ regionQualifier?: string | null
323
+
285
324
  /**
286
- * Set while resolving when ANY tree node maps to the `locality` placetype (resolved or not) — the completion only
287
- * fires when the parser emitted no locality at all, never to override one.
325
+ * Whether any node maps to the `locality` placetype.
326
+ * Hierarchy completion runs only when this is false.
288
327
  */
289
328
  localityNodePresent: boolean
329
+
290
330
  /**
291
- * The first region that resolved (its place — for the coincident-roles lookup).
331
+ * The first resolved region place, used to look up its coincident locality.
292
332
  */
293
333
  resolvedRegion: CoordinateOptionalPlace | null
334
+
294
335
  /**
295
- * The decorated region NODE that produced {@link resolvedRegion} — completion pushes the locality interpretation onto
296
- * it in place (no synthesized sibling).
336
+ * The decorated node for {@link ResolutionState.resolvedRegion}.
337
+ *
338
+ * Hierarchy completion adds the locality interpretation to it in place.
297
339
  */
298
340
  resolvedRegionNode: AddressNode | null
299
341
  }
300
342
 
301
343
  /**
302
- * Pick the completion locality when an admin maps to several coincident same-name candidates (#405). REFERENTIAL
303
- * likelihood is the PRIMARY signal — the principal city is the populous one, and it can sit FARTHER from the admin
304
- * centroid than a tiny same-name hamlet (the Niigata case from #403). Nearest centroid breaks a referential tie; a
305
- * genuine tie (same population AND distance) ABSTAINS rather than guess.
344
+ * Picks the completion locality among coincident candidates of the same name.
306
345
  *
307
- * ROAD_TO_V9 §2: `compareReferential` is referential DESC with raw population as its own tiebreak, which is the SAME
308
- * ORDER as the plain `b.population - a.population` it replaced — referential is strictly increasing in population below
309
- * saturation and constant above it. The abstention check below still reads raw population, deliberately: two megacities
310
- * that saturate to the same referential score are not tied, and abstaining there would be a new behavior.
346
+ * It prefers the most populous candidate, then the nearest candidate.
347
+ * It returns `null` on an exact tie.
311
348
  */
312
349
  export function pickCompletion(candidates: readonly CoincidentLocality[]): CoincidentLocality | null {
313
350
  if (!candidates.length) return null
@@ -316,7 +353,7 @@ export function pickCompletion(candidates: readonly CoincidentLocality[]): Coinc
316
353
 
317
354
  const ranked = [...candidates]
318
355
  .map((c) => ({ c, referential: referentialFromPopulation(c.population), population: c.population }))
319
- // oxlint-disable-next-line unicorn/no-array-sort -- sorts a freshly-built array; toSorted would double-allocate on a hot path
356
+ // oxlint-disable-next-line unicorn/no-array-sort -- sorts a freshly-built array. toSorted would double-allocate on a hot path
320
357
  .sort((a, b) => compareReferential(a, b) || a.c.distanceKm - b.c.distanceKm)
321
358
  .map((x) => x.c)
322
359
 
@@ -328,61 +365,50 @@ export function pickCompletion(candidates: readonly CoincidentLocality[]): Coinc
328
365
  }
329
366
 
330
367
  /**
331
- * Find the first postcode value anywhere in the tree (a one-shot pre-scan; postcode and locality are siblings, so the
332
- * top-down walk wouldn't otherwise let the locality lookup see it).
368
+ * Returns the first postcode value anywhere in the tree, skipping shape-excluded postcodes.
369
+ * a locality lookup uses it because the postcode node is usually a sibling.
333
370
  */
334
- export function firstPostcodeValue(roots: readonly AddressNode[]): string | undefined {
371
+ export function firstPostcodeValue(roots: readonly AddressNode[]): string | null {
335
372
  for (const n of walkNodes(roots)) {
336
- // #31 Mechanism 1: a shape-excluded span keeps its tag but contributes nothing — its code
337
- // must never become the address's postcode (it would poison the country-scope pass's anchor).
338
- if (n.tag === "postcode" && !isShapeExcludedPostcode(n) && n.value.trim().length) return n.value.trim()
373
+ if (n.tag === "postcode" && !isShapeExcludedPostcode(n) && n.value.trim()) return n.value.trim()
339
374
  }
340
375
 
341
- return undefined
376
+ return null
342
377
  }
343
378
 
344
379
  /**
345
- * Span-rescore tier (#370): opt-in last-resort locality recovery. Runs ONLY when the tree resolved NOTHING (the #685
346
- * brake — never disturb a working coordinate). Enumerates raw-token spans, exact- matches the same-country gazetteer
347
- * (longest-wins + postcode-consistency check; see `span-rescore.ts`), and on a hit INJECTS a resolved `locality` node
348
- * decorated exactly like a normally-resolved one. Default-ON (#370, promoted 2026-06-25); byte-stable opt-out via
349
- * `opts.spanRescore: false`. Async (it queries the backend), so it's awaited.
380
+ * Recovers a locality from raw-text spans when the tree resolved no place,
381
+ * appending a resolved `locality` node on a hit.
382
+ *
383
+ * When no span matches, it tries the postcode node's code part.
350
384
  */
351
385
  export async function applySpanRescore(
352
386
  roots: AddressNode[],
353
387
  raw: string,
354
388
  backend: ResolverBackend,
355
- opts: ResolveOpts
389
+ opts: ResolvedOpts
356
390
  ): Promise<void> {
357
- if (hasResolvedPlace(roots)) return // already resolved — never second-guess a working coordinate
358
- // Default-ON since 2026-06-25, so this runs on every unresolved tree — a backend hiccup here must
359
- // degrade to no-rescore, never crash the resolve (the same fall-through the main walk gives).
391
+ if (hasResolvedPlace(roots, opts.spanRescoreWeakResolution ?? false)) return
392
+
360
393
  let hit
361
394
 
362
395
  try {
363
396
  hit = await findRescoreCandidate(raw, roots, backend, {
364
- country: opts.defaultCountry,
397
+ country: opts.defaultCountry?.country,
365
398
  postcode: firstPostcodeValue(roots),
366
399
  thresholdKm: opts.spanRescoreThresholdKm,
367
- // Default-ON (promoted 2026-07-03); explicit `false` opts out — the spanRescore idiom.
368
- postalCompoundRecovery: opts.postalCompoundRecovery !== false,
400
+
401
+ postalCompoundRecovery: opts.postalCompoundRecovery,
402
+ spanRescoreRequireContextRemainder: opts.spanRescoreRequireContextRemainder,
369
403
  })
370
404
  } catch {
371
405
  return
372
406
  }
373
407
 
374
- // #942 postal-compound recovery, part 2: when NO city span matched, decorate the FAILED postcode
375
- // node from its code-shaped token subset ("1382 Kožljek" → the bare "1382" row) — a postcode-tier
376
- // coordinate FLOOR, strictly subordinate to a recovered locality. Only-on-miss matters: a GeoNames
377
- // medoid postcode centroid is COARSER than the exact village centroid, and consumers that rank
378
- // postcode above locality (the eval harness does) would otherwise trade a 0.2 km village pin for a
379
- // 5 km area centroid. Same unresolved tree, so the #685 brake semantics hold.
380
- if (!hit && opts.postalCompoundRecovery !== false) {
408
+ if (!hit && opts.postalCompoundRecovery) {
381
409
  try {
382
- await recoverPostcodeNode(roots, backend, opts.defaultCountry, opts.traceSink)
383
- } catch {
384
- // degrade to no-recovery, never crash the resolve
385
- }
410
+ await recoverPostcodeNode(roots, backend, opts.defaultCountry?.country ?? null, opts.traceSink)
411
+ } catch {}
386
412
  }
387
413
 
388
414
  if (!hit) return
@@ -392,31 +418,20 @@ export async function applySpanRescore(
392
418
  value: hit.text,
393
419
  start: hit.start,
394
420
  end: hit.end,
395
- // No model confidence for a post-hoc recovery; a mid-tier value marks it as recovered, not asserted.
421
+
396
422
  confidence: 0.5,
397
423
  children: [],
398
424
  }
399
425
 
400
- // #1537: the same-span namesake runner-ups, not an empty list. A name the model reads as a `street`
401
- // ("Springfield", "Berlin", "Moscow") never reaches the admin walk, so this tier is the ONLY thing that
402
- // resolves it — and decorating with `[]` meant the geocode path's `candidates` held one entry and the
403
- // dominance margin `declared_ambiguity` reads was uncomputable for exactly the famous-homonym class.
404
- // The winner is unchanged (see findRescoreCandidate); this is additive.
405
426
  decorateNode(node, hit.place, hit.alternatives)
406
- // `rescore_postcode_verified` carries the check's precision signal as an EXPLICIT handle — NOT folded into the
407
- // calibrated `confidence`, which would break the isotonic guarantee (a true calibrated 0.83 must not
408
- // be confused with a rescore plug-in estimate; DeepSeek 2026-06-23). true = postcode check fired
409
- // (high-precision); false = unrestricted (no postcode→point coverage for this country, ~83%-precision).
427
+
410
428
  node.metadata = { ...node.metadata, span_rescore: true, rescore_postcode_verified: hit.postcodeVerified }
411
429
  roots.push(node)
412
430
 
413
- // #1721 follow-up: this tier answers OFF the walk, and it used to answer off the record too — the famous-name
414
- // class ("Frankfurt") returned a coordinate beside an empty resolver trace, blinding every retrieval account.
415
- // One record per rescue keeps the trace's promise: no resolved coordinate without a lookup record.
416
431
  if (opts.traceSink) {
417
432
  const rec = createNodeTraceRecorder(opts.traceSink)
418
433
 
419
- rec.bind(node, "locality", opts.defaultCountry ? { country: opts.defaultCountry } : {}, 1)
434
+ rec.bind(node, "locality", opts.defaultCountry ? { country: opts.defaultCountry.country } : {}, 1)
420
435
  rec.check("span_rescore")
421
436
  rec.check(hit.postcodeVerified ? "rescore_postcode_verified" : "rescore_postcode_unverified")
422
437
  rec.stage("rescore", [hit.place, ...hit.alternatives])
@@ -424,16 +439,10 @@ export async function applySpanRescore(
424
439
  }
425
440
  }
426
441
 
427
- /**
428
- * #942: find the first confident-but-UNRESOLVED postcode node whose value is a polluted compound ("1382 Kožljek"),
429
- * resolve its code-shaped token subset as a `postalcode`, and decorate the node from that hit
430
- * (`postal_compound_recovered` metadata marks the provenance). No-op when every postcode node resolved, the value has
431
- * no digit-bearing tokens, or the subset equals the full value (then the walk already tried it).
432
- */
433
442
  async function recoverPostcodeNode(
434
443
  roots: AddressNode[],
435
444
  backend: ResolverBackend,
436
- country: string | undefined,
445
+ country: string | null,
437
446
  traceSink?: (record: ResolveNodeTrace) => void
438
447
  ): Promise<void> {
439
448
  for (const n of walkNodes(roots)) {
@@ -441,14 +450,20 @@ async function recoverPostcodeNode(
441
450
  const code = postcodeCodeSubset(n.value)
442
451
 
443
452
  if (!code || code === n.value.trim()) continue
444
- const hits = await backend.findPlace({ text: code, placetype: "postalcode", country, limit: 1 })
453
+
454
+ const hits = await backend.findPlace({
455
+ text: code,
456
+ placetype: "postalcode",
457
+ ...(country ? { country } : {}),
458
+ limit: 1,
459
+ })
460
+
445
461
  const top = hits.find((h) => h.lat !== 0 || h.lon !== 0)
446
462
 
447
463
  if (top) {
448
464
  decorateNode(n, top, [])
449
465
  n.metadata = { ...n.metadata, postal_compound_recovered: true }
450
466
 
451
- // The same off-the-record hole the span-rescore record closes (#1721 follow-up).
452
467
  if (traceSink) {
453
468
  const rec = createNodeTraceRecorder(traceSink)
454
469
 
@@ -459,37 +474,30 @@ async function recoverPostcodeNode(
459
474
  }
460
475
  }
461
476
 
462
- return // first postcode node only — one recovery per tree
477
+ return
463
478
  }
464
479
  }
465
480
  }
466
481
 
467
482
  /**
468
- * Postcode-disambiguated locality selection (#370 "Change A"). The single biggest miss on the EU/AU panel is a
469
- * same-named town resolved to the WRONG instance — "06260 Saint-Pierre" lands 617 km off — while the postcode that
470
- * would disambiguate it (06260 → Alpes-Maritimes) sits resolved in the same tree, discarded because the
471
- * coordinate-picker prefers the (wrong) locality node and never cross- checks it. This post-walk pass closes that loop,
472
- * backend-agnostically and with no extra query:
473
- *
474
- * 1. Find the resolved postcode's coordinate (the trustworthy anchor — a postcode is unambiguous within a country in a way
475
- * a town name is not).
476
- * 2. For each resolved locality node farther than `thresholdKm` from it: re-pick the same-named candidate from the node's
477
- * already-captured `alternatives` that is NEAREST the postcode and within the radius. This keeps locality
478
- * granularity at the CORRECT instance.
479
- * 3. If no alternative reconciles, the locality instance is unreliable — fall its coordinate back to the postcode point
480
- * (right area, the safe answer) and flag `postcode_city_mismatch`.
481
- *
482
- * Only fires where the postcode resolved to a point, so it composes with postcode coverage (#193) — add a country's
483
- * postcodes and this immediately disambiguates its same-named towns. **Default-ON** since the #370 operator promotion
484
- * (2026-07-04, commit `0010bb8c`) — `opts.postcodeConsistency: false` opts out, and the pass is byte-stable on every
485
- * tree with no resolved postcode point (the `!anchor` early return below).
483
+ * The farthest distance, in kilometers, that {@link applyPostcodeConsistency}
484
+ * moves a locality onto its postcode's point.
485
+ */
486
+ export const DEFAULT_POSTCODE_MAX_MOVE_KM = 300
487
+
488
+ /**
489
+ * Reconciles each resolved locality that lies farther than `thresholdKm` from the tree's
490
+ * resolved postcode point, re-picking the nearest alternative within the threshold and otherwise
491
+ * moving the coordinate there, but skipping the move when the distance exceeds `maxMoveKm`.
486
492
  */
487
- export function applyPostcodeConsistency(roots: readonly AddressNode[], thresholdKm: number): void {
488
- // The resolved postcode anchor (first one with a real coordinate).
493
+ export function applyPostcodeConsistency(
494
+ roots: readonly AddressNode[],
495
+ thresholdKm: number,
496
+ maxMoveKm = DEFAULT_POSTCODE_MAX_MOVE_KM
497
+ ): void {
489
498
  let anchor: { lat: number; lon: number } | null = null
490
499
 
491
500
  for (const n of walkNodes(roots)) {
492
- // #31 Mechanism 1: a shape-excluded span never anchors the consistency re-pick either.
493
501
  if (n.tag === "postcode" && !isShapeExcludedPostcode(n) && isResolvedWithCoord(n)) {
494
502
  anchor = { lat: n.lat!, lon: n.lon! }
495
503
 
@@ -497,29 +505,27 @@ export function applyPostcodeConsistency(roots: readonly AddressNode[], threshol
497
505
  }
498
506
  }
499
507
 
500
- // No postcode→point — nothing to disambiguate against (the check cannot fire).
501
508
  if (!anchor) return
502
509
 
503
510
  for (const node of walkNodes(roots)) {
504
511
  if ((node.tag !== "locality" && node.tag !== "dependent_locality") || !isResolvedWithCoord(node)) continue
505
512
 
506
- if (haversineKm(anchor.lat, anchor.lon, node.lat!, node.lon!) <= thresholdKm) continue // already consistent
513
+ const gapKm = haversineKm(anchor.lat, anchor.lon, node.lat!, node.lon!)
507
514
 
508
- // Re-pick: the same-named candidate nearest the postcode, within the radius. `alternatives` is
509
- // typed `unknown[]` on the node (decoder/types.ts can't import resolver types) — they ARE the
510
- // `ResolvedPlace` runner-ups decorateNode attached, so the cast is sound.
511
- const alts = (node.alternatives as ResolvedPlace[] | undefined) ?? []
515
+ if (gapKm <= thresholdKm) continue
516
+
517
+ const alts = (node.alternatives as ResolvedPlace[] | null) ?? []
512
518
 
513
519
  const reconciling = alts
514
520
  .filter((a) => a.lat !== 0 || a.lon !== 0)
515
521
  .map((a) => ({ a, d: haversineKm(anchor!.lat, anchor!.lon, a.lat, a.lon) }))
516
522
  .filter((x) => x.d <= thresholdKm)
517
- // oxlint-disable-next-line unicorn/no-array-sort -- sorts a freshly-built array; toSorted would double-allocate on a hot path
523
+ // oxlint-disable-next-line unicorn/no-array-sort -- sorts a freshly-built array. toSorted would double-allocate on a hot path
518
524
  .sort((x, y) => x.d - y.d)[0]
519
525
 
520
526
  if (reconciling) {
521
- // Swap to the consistent instance; the displaced winner becomes an alternative.
522
527
  const displaced: ResolvedPlace = {
528
+ ...EMPTY_PLACE_FIELDS,
523
529
  id: 0,
524
530
  name: String(node.metadata?.["resolver_name"] ?? node.value),
525
531
  placetype: "locality",
@@ -536,7 +542,12 @@ export function applyPostcodeConsistency(roots: readonly AddressNode[], threshol
536
542
  continue
537
543
  }
538
544
 
539
- // No same-named instance near the postcode → the town is unreliable; trust the postcode's area.
545
+ if (gapKm > maxMoveKm) {
546
+ node.metadata = { ...node.metadata, postcode_city_mismatch: true, postcode_move_refused_km: gapKm }
547
+
548
+ continue
549
+ }
550
+
540
551
  node.lat = anchor.lat
541
552
  node.lon = anchor.lon
542
553
  node.metadata = { ...node.metadata, postcode_city_mismatch: true, coordinate_source: "postcode_fallback" }