@mailwoman/resolver 10.0.0 → 10.1.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 +19 -160
  3. package/lib/admin/containment.ts +12 -30
  4. package/lib/admin/jp-municipality.ts +20 -13
  5. package/lib/admin/winner.ts +30 -62
  6. package/lib/backend-capabilities.ts +25 -24
  7. package/lib/bare-toponym-race.ts +69 -37
  8. package/lib/decorate-node.ts +17 -41
  9. package/lib/fold-name.ts +5 -18
  10. package/lib/index.ts +5 -9
  11. package/lib/plausibility.ts +35 -62
  12. package/lib/postcode/country-coherence.ts +64 -284
  13. package/lib/postcode/prefix.ts +20 -84
  14. package/lib/postcode/shape-coherence.ts +23 -113
  15. package/lib/remote-resolver.ts +32 -29
  16. package/lib/rerank.ts +34 -50
  17. package/lib/resolve/passes.ts +144 -147
  18. package/lib/resolve.ts +726 -0
  19. package/lib/span-rescore.ts +215 -172
  20. package/lib/street/evidence.ts +65 -73
  21. package/lib/street/tier.ts +33 -175
  22. package/lib/toponym-prior.ts +53 -179
  23. package/out/admin/coherence-passes.d.ts +17 -68
  24. package/out/admin/coherence-passes.d.ts.map +1 -1
  25. package/out/admin/coherence-passes.js +18 -160
  26. package/out/admin/coherence-passes.js.map +1 -1
  27. package/out/admin/containment.d.ts +11 -29
  28. package/out/admin/containment.d.ts.map +1 -1
  29. package/out/admin/containment.js +12 -30
  30. package/out/admin/containment.js.map +1 -1
  31. package/out/admin/jp-municipality.d.ts +20 -13
  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 +30 -62
  36. package/out/admin/winner.d.ts.map +1 -1
  37. package/out/admin/winner.js +18 -51
  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 +18 -19
  44. package/out/backend-capabilities.d.ts.map +1 -1
  45. package/out/backend-capabilities.js +25 -24
  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 +17 -41
  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 +27 -57
  64. package/out/plausibility.d.ts.map +1 -1
  65. package/out/plausibility.js +16 -49
  66. package/out/plausibility.js.map +1 -1
  67. package/out/postcode/country-coherence.d.ts +48 -162
  68. package/out/postcode/country-coherence.d.ts.map +1 -1
  69. package/out/postcode/country-coherence.js +19 -252
  70. package/out/postcode/country-coherence.js.map +1 -1
  71. package/out/postcode/prefix.d.ts +17 -68
  72. package/out/postcode/prefix.d.ts.map +1 -1
  73. package/out/postcode/prefix.js +8 -77
  74. package/out/postcode/prefix.js.map +1 -1
  75. package/out/postcode/shape-coherence.d.ts +17 -84
  76. package/out/postcode/shape-coherence.d.ts.map +1 -1
  77. package/out/postcode/shape-coherence.js +9 -105
  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 +27 -28
  84. package/out/remote-resolver.d.ts.map +1 -1
  85. package/out/remote-resolver.js +9 -19
  86. package/out/remote-resolver.js.map +1 -1
  87. package/out/rerank.d.ts +28 -45
  88. package/out/rerank.d.ts.map +1 -1
  89. package/out/rerank.js +13 -38
  90. package/out/rerank.js.map +1 -1
  91. package/out/resolve/passes.d.ts +95 -85
  92. package/out/resolve/passes.d.ts.map +1 -1
  93. package/out/resolve/passes.js +40 -105
  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 +543 -0
  98. package/out/resolve.js.map +1 -0
  99. package/out/span-rescore.d.ts +51 -64
  100. package/out/span-rescore.d.ts.map +1 -1
  101. package/out/span-rescore.js +132 -130
  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 +17 -29
  108. package/out/street/tier.d.ts.map +1 -1
  109. package/out/street/tier.js +27 -175
  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 +21 -109
  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,9 +2,6 @@
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"
@@ -28,32 +25,17 @@ import type { CoordinateOptionalPlace } from "#postcode/prefix"
28
25
  import { isShapeExcludedPostcode } from "#postcode/shape-coherence"
29
26
  import { findRescoreCandidate, hasResolvedPlace, postcodeCodeSubset } from "#span-rescore"
30
27
 
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
28
  const TRACE_CANDIDATE_CAP = 10
36
29
 
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
30
  const FINEST_DIAGNOSTIC_BAND = PLACETYPE_SPECIFICITY["microhood"]!
45
31
 
46
- /**
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.
49
- */
50
32
  const COARSEST_DIAGNOSTIC_BAND = PLACETYPE_SPECIFICITY["country"]!
51
33
 
52
34
  /**
53
- * The admin bands `ResolveOpts.diagnoseUnreachable` re-probes, coarse to fine.
35
+ * The admin placetypes from country to microhood that `ResolveOpts.diagnoseUnreachable`
36
+ * re-probes, coarse to fine.
54
37
  *
55
- * Derived from `PLACETYPE_SPECIFICITY` rather than typed out, so a placetype added there is probed here without anyone
56
- * remembering to.
38
+ * The list derives from `PLACETYPE_SPECIFICITY`, so a new placetype in that range is probed automatically.
57
39
  */
58
40
  export const DIAGNOSTIC_BANDS: readonly string[] = Object.entries(PLACETYPE_SPECIFICITY)
59
41
  .filter(([, rank]) => rank !== undefined && rank <= FINEST_DIAGNOSTIC_BAND && rank >= COARSEST_DIAGNOSTIC_BAND)
@@ -61,9 +43,9 @@ export const DIAGNOSTIC_BANDS: readonly string[] = Object.entries(PLACETYPE_SPEC
61
43
  .map(([placetype]) => placetype)
62
44
 
63
45
  /**
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.
46
+ * Collects the trace for one placetype lookup and emits it as a `ResolveNodeTrace`;
47
+ * the walk always calls one and uses {@link NOOP_TRACE_RECORDER} when no trace
48
+ * sink is set, so the hot path has no per-event branches.
67
49
  */
68
50
  export interface NodeTraceRecorder {
69
51
  bind(
@@ -85,7 +67,7 @@ export interface NodeTraceRecorder {
85
67
  }
86
68
 
87
69
  /**
88
- * A recorder that records nothing — the walk's default when no trace was requested.
70
+ * A {@link NodeTraceRecorder} that records no events, for walks without a trace sink.
89
71
  */
90
72
  export const NOOP_TRACE_RECORDER: NodeTraceRecorder = Object.freeze({
91
73
  bind() {},
@@ -95,6 +77,10 @@ export const NOOP_TRACE_RECORDER: NodeTraceRecorder = Object.freeze({
95
77
  emit() {},
96
78
  })
97
79
 
80
+ /**
81
+ * Creates a {@link NodeTraceRecorder} that sends one `ResolveNodeTrace` to `sink` on `emit`,
82
+ * listing at most ten candidates from the last stage with each candidate's rank in every stage.
83
+ */
98
84
  export function createNodeTraceRecorder(sink: (record: ResolveNodeTrace) => void): NodeTraceRecorder {
99
85
  const checks: string[] = []
100
86
  const stageOrders: Array<[string, readonly ResolvedPlace[]]> = []
@@ -176,138 +162,183 @@ export function createNodeTraceRecorder(sink: (record: ResolveNodeTrace) => void
176
162
  }
177
163
  }
178
164
 
165
+ /**
166
+ * The options and mutable state that one `resolveTree` call passes through its tree walk.
167
+ */
179
168
  export interface ResolutionState {
180
169
  lookupsRemaining: number
181
170
  placetypeMap: PlacetypeMap
182
171
  minWinningScore: number
172
+
173
+ /**
174
+ * The count of lookups rejected by {@link ResolutionState.minWinningScore}.
175
+ *
176
+ * A nonzero count skips the span-rescore pass.
177
+ * That pass would otherwise treat the refused node as unresolved and repeat the rejected lookup.
178
+ */
179
+ minScoreRefusals: number
183
180
  candidatesPerLookup: number
184
181
  defaultCountry?: string
182
+
185
183
  /**
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`.
184
+ * Whether {@link ResolutionState.defaultCountry} came from the locale instead of the caller.
185
+ *
186
+ * `country` lookups ignore an inferred default.
188
187
  */
189
188
  defaultCountryIsInferred: boolean
189
+
190
190
  /**
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.
191
+ * The tree's only value-bearing node when it maps to `locality`, or null otherwise.
192
+ *
193
+ * Its lookup also probes countries and regions of the same name, because the locality
194
+ * placetype filter cannot reach a country that the parser tagged as a locality.
194
195
  */
195
196
  bareLocalityNode: AddressNode | null
196
197
  parentFallback: boolean
198
+
197
199
  /**
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.
200
+ * The tree's first postcode value.
201
+ *
202
+ * Locality lookups send it to the backend.
203
+ * The backend can then favor nearby candidates.
200
204
  */
201
205
  postcode?: string
206
+
202
207
  /**
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.
208
+ * Whether locality lookups ask the backend to re-rank candidates by distance to the postcode centroid.
205
209
  */
206
210
  postcodeContainmentCoherence: boolean
211
+
207
212
  /**
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.
213
+ * Whether a `postalcode` lookup that misses falls back to {@link ResolutionState.postcodePrefixIndex}.
210
214
  */
211
215
  postcodePrefixPrior: boolean
216
+
212
217
  /**
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).
218
+ * The countries implied by the postcode's format.
219
+ *
220
+ * A `postalcode` lookup without a country scope probes only these countries
221
+ * and abstains if all of them miss.
222
+ * An unscoped probe of a space-stripped code can match another country's postcode system.
217
223
  */
218
224
  postcodeFormatCountries?: readonly string[]
225
+
219
226
  /**
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`.
227
+ * The locale hint's country, sent as `fuzzyCountry` on every lookup.
228
+ * It scopes only the typo-fuzzy tier.
222
229
  */
223
230
  fuzzyCountryScope?: string
231
+
224
232
  /**
225
- * The injected PFX1 index (structural — `PostcodePrefixIndexLike`, core/resolver/types.ts). Absent = the prior cannot
226
- * fire.
233
+ * The postcode prefix index that {@link ResolutionState.postcodePrefixPrior} requires.
227
234
  */
228
235
  postcodePrefixIndex?: PostcodePrefixIndexLike
236
+
229
237
  /**
230
- * Proximity-bias points (viewport, user location) — forwarded to every primary lookup.
238
+ * Proximity-bias points, such as a viewport or user location, that every
239
+ * lookup uses to reorder candidates.
231
240
  */
232
241
  bias?: Array<{ lat: number; lon: number; weight?: number }>
242
+
233
243
  /**
234
- * Postcode-anchor country posterior (#369). Undefined = no re-rank (byte-stable default).
244
+ * The postcode anchor's posterior over countries, used to re-rank region and locality candidates.
245
+ *
246
+ * When set, it also replaces the importance re-rank and capital promotion.
235
247
  */
236
248
  anchorPosterior?: Record<string, number>
249
+
237
250
  /**
238
- * Weight on the posterior in the locality re-rank. Only used when `anchorPosterior` is set.
251
+ * The weight on {@link ResolutionState.anchorPosterior} in the re-rank key.
239
252
  */
240
253
  anchorWeight: number
254
+
241
255
  /**
242
- * #1721 resolver-interior trace sink. Undefined (the default) = zero bookkeeping, byte-identical walk.
256
+ * The callback that receives one trace record per lookup.
257
+ * The walk records no events when it is absent.
243
258
  */
244
259
  traceSink?: (record: ResolveNodeTrace) => void
260
+
245
261
  /**
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`.
262
+ * Whether an empty lookup re-probes the other admin bands and traces which ones hold the value.
263
+ *
264
+ * It is set only when a trace sink exists.
265
+ * It never affects the pick.
248
266
  */
249
267
  diagnoseUnreachable?: boolean
268
+
250
269
  /**
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.
270
+ * The locale country used as a soft prior on region and locality candidates
271
+ * when no default country or anchor posterior applies.
253
272
  */
254
273
  localeCountryPrior?: string
274
+
255
275
  /**
256
- * Weight of that prior in log10-population units. Only consulted when `localeCountryPrior` is set.
276
+ * The weight of {@link ResolutionState.localeCountryPrior}, in log10-population units.
257
277
  */
258
278
  localeCountryPriorWeight: number
279
+
259
280
  /**
260
- * #1880 capital status per candidate, from `ResolveOpts.capitalLevel`. Undefined → no promotion, byte-stable.
281
+ * Returns a candidate's capital level for bounded capital promotion.
282
+ * Capital promotion is off when it is absent.
261
283
  */
262
284
  capitalLevel?: (place: { name: string; country?: string; lat: number; lon: number }) => number
285
+
263
286
  /**
264
- * #743/#194 confident-placer country as a HARD filter (empty→unresolved, no global retry). Off = undefined.
287
+ * The country scope applied to a lookup when no parent, default country, or node hint supplies one.
265
288
  */
266
289
  hardCountry?: string
290
+
267
291
  /**
268
- * Dual-role hierarchy completion (#405). Off by default → byte-stable.
292
+ * Whether a resolved region gains its coincident locality of the same name as an
293
+ * interpretation when the tree has no locality node.
269
294
  */
270
295
  hierarchyCompletion: boolean
296
+
271
297
  /**
272
- * Attach ancestor lineage to each resolved node (#404). Off by default → byte-stable.
298
+ * Whether each resolved node gets its ancestor lineage in metadata, when the backend supports it.
273
299
  */
274
300
  includeAncestors: boolean
301
+
275
302
  /**
276
- * Admin-containment re-rank (#1717 stage 2). Off by default → byte-stable. See `ResolveOpts.adminContainmentRerank`.
303
+ * Whether locality candidates contained by {@link ResolutionState.regionQualifier}
304
+ * are ordered ahead of the rest.
277
305
  */
278
306
  adminContainmentRerank: boolean
307
+
279
308
  /**
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.
309
+ * The tree's first region value.
310
+ *
311
+ * The region and locality nodes are siblings, so the walk would not otherwise
312
+ * pass the region to the locality lookup.
313
+ * It applies only with {@link ResolutionState.adminContainmentRerank}
314
+ * and no caller-supplied default country.
283
315
  */
284
316
  regionQualifier?: string
317
+
285
318
  /**
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.
319
+ * Whether any node maps to the `locality` placetype.
320
+ * Hierarchy completion runs only when this is false.
288
321
  */
289
322
  localityNodePresent: boolean
323
+
290
324
  /**
291
- * The first region that resolved (its place — for the coincident-roles lookup).
325
+ * The first resolved region place, used to look up its coincident locality.
292
326
  */
293
327
  resolvedRegion: CoordinateOptionalPlace | null
328
+
294
329
  /**
295
- * The decorated region NODE that produced {@link resolvedRegion} — completion pushes the locality interpretation onto
296
- * it in place (no synthesized sibling).
330
+ * The decorated node for {@link ResolutionState.resolvedRegion}.
331
+ *
332
+ * Hierarchy completion adds the locality interpretation to it in place.
297
333
  */
298
334
  resolvedRegionNode: AddressNode | null
299
335
  }
300
336
 
301
337
  /**
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.
338
+ * Picks the completion locality among coincident candidates of the same name.
306
339
  *
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.
340
+ * It prefers the most populous candidate, then the nearest candidate.
341
+ * It returns `null` on an exact tie.
311
342
  */
312
343
  export function pickCompletion(candidates: readonly CoincidentLocality[]): CoincidentLocality | null {
313
344
  if (!candidates.length) return null
@@ -316,7 +347,7 @@ export function pickCompletion(candidates: readonly CoincidentLocality[]): Coinc
316
347
 
317
348
  const ranked = [...candidates]
318
349
  .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
350
+ // oxlint-disable-next-line unicorn/no-array-sort -- sorts a freshly-built array. toSorted would double-allocate on a hot path
320
351
  .sort((a, b) => compareReferential(a, b) || a.c.distanceKm - b.c.distanceKm)
321
352
  .map((x) => x.c)
322
353
 
@@ -328,13 +359,11 @@ export function pickCompletion(candidates: readonly CoincidentLocality[]): Coinc
328
359
  }
329
360
 
330
361
  /**
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).
362
+ * Returns the first postcode value anywhere in the tree, skipping shape-excluded postcodes.
363
+ * a locality lookup uses it because the postcode node is usually a sibling.
333
364
  */
334
365
  export function firstPostcodeValue(roots: readonly AddressNode[]): string | undefined {
335
366
  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
367
  if (n.tag === "postcode" && !isShapeExcludedPostcode(n) && n.value.trim().length) return n.value.trim()
339
368
  }
340
369
 
@@ -342,11 +371,10 @@ export function firstPostcodeValue(roots: readonly AddressNode[]): string | unde
342
371
  }
343
372
 
344
373
  /**
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.
374
+ * Recovers a locality from raw-text spans when the tree resolved no place,
375
+ * appending a resolved `locality` node on a hit.
376
+ *
377
+ * When no span matches, it tries the postcode node's code part.
350
378
  */
351
379
  export async function applySpanRescore(
352
380
  roots: AddressNode[],
@@ -354,9 +382,8 @@ export async function applySpanRescore(
354
382
  backend: ResolverBackend,
355
383
  opts: ResolveOpts
356
384
  ): 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).
385
+ if (hasResolvedPlace(roots, opts.spanRescoreWeakResolution ?? false)) return
386
+
360
387
  let hit
361
388
 
362
389
  try {
@@ -364,25 +391,18 @@ export async function applySpanRescore(
364
391
  country: opts.defaultCountry,
365
392
  postcode: firstPostcodeValue(roots),
366
393
  thresholdKm: opts.spanRescoreThresholdKm,
367
- // Default-ON (promoted 2026-07-03); explicit `false` opts out — the spanRescore idiom.
394
+
368
395
  postalCompoundRecovery: opts.postalCompoundRecovery !== false,
396
+ spanRescoreRequireContextRemainder: opts.spanRescoreRequireContextRemainder,
369
397
  })
370
398
  } catch {
371
399
  return
372
400
  }
373
401
 
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
402
  if (!hit && opts.postalCompoundRecovery !== false) {
381
403
  try {
382
404
  await recoverPostcodeNode(roots, backend, opts.defaultCountry, opts.traceSink)
383
- } catch {
384
- // degrade to no-recovery, never crash the resolve
385
- }
405
+ } catch {}
386
406
  }
387
407
 
388
408
  if (!hit) return
@@ -392,27 +412,16 @@ export async function applySpanRescore(
392
412
  value: hit.text,
393
413
  start: hit.start,
394
414
  end: hit.end,
395
- // No model confidence for a post-hoc recovery; a mid-tier value marks it as recovered, not asserted.
415
+
396
416
  confidence: 0.5,
397
417
  children: [],
398
418
  }
399
419
 
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
420
  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).
421
+
410
422
  node.metadata = { ...node.metadata, span_rescore: true, rescore_postcode_verified: hit.postcodeVerified }
411
423
  roots.push(node)
412
424
 
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
425
  if (opts.traceSink) {
417
426
  const rec = createNodeTraceRecorder(opts.traceSink)
418
427
 
@@ -424,12 +433,6 @@ export async function applySpanRescore(
424
433
  }
425
434
  }
426
435
 
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
436
  async function recoverPostcodeNode(
434
437
  roots: AddressNode[],
435
438
  backend: ResolverBackend,
@@ -448,7 +451,6 @@ async function recoverPostcodeNode(
448
451
  decorateNode(n, top, [])
449
452
  n.metadata = { ...n.metadata, postal_compound_recovered: true }
450
453
 
451
- // The same off-the-record hole the span-rescore record closes (#1721 follow-up).
452
454
  if (traceSink) {
453
455
  const rec = createNodeTraceRecorder(traceSink)
454
456
 
@@ -459,37 +461,30 @@ async function recoverPostcodeNode(
459
461
  }
460
462
  }
461
463
 
462
- return // first postcode node only — one recovery per tree
464
+ return
463
465
  }
464
466
  }
465
467
  }
466
468
 
467
469
  /**
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).
470
+ * The farthest distance, in kilometers, that {@link applyPostcodeConsistency}
471
+ * moves a locality onto its postcode's point.
472
+ */
473
+ export const DEFAULT_POSTCODE_MAX_MOVE_KM = 300
474
+
475
+ /**
476
+ * Reconciles each resolved locality that lies farther than `thresholdKm` from the tree's
477
+ * resolved postcode point, re-picking the nearest alternative within the threshold and otherwise
478
+ * moving the coordinate there, but skipping the move when the distance exceeds `maxMoveKm`.
486
479
  */
487
- export function applyPostcodeConsistency(roots: readonly AddressNode[], thresholdKm: number): void {
488
- // The resolved postcode anchor (first one with a real coordinate).
480
+ export function applyPostcodeConsistency(
481
+ roots: readonly AddressNode[],
482
+ thresholdKm: number,
483
+ maxMoveKm = DEFAULT_POSTCODE_MAX_MOVE_KM
484
+ ): void {
489
485
  let anchor: { lat: number; lon: number } | null = null
490
486
 
491
487
  for (const n of walkNodes(roots)) {
492
- // #31 Mechanism 1: a shape-excluded span never anchors the consistency re-pick either.
493
488
  if (n.tag === "postcode" && !isShapeExcludedPostcode(n) && isResolvedWithCoord(n)) {
494
489
  anchor = { lat: n.lat!, lon: n.lon! }
495
490
 
@@ -497,28 +492,25 @@ export function applyPostcodeConsistency(roots: readonly AddressNode[], threshol
497
492
  }
498
493
  }
499
494
 
500
- // No postcode→point — nothing to disambiguate against (the check cannot fire).
501
495
  if (!anchor) return
502
496
 
503
497
  for (const node of walkNodes(roots)) {
504
498
  if ((node.tag !== "locality" && node.tag !== "dependent_locality") || !isResolvedWithCoord(node)) continue
505
499
 
506
- if (haversineKm(anchor.lat, anchor.lon, node.lat!, node.lon!) <= thresholdKm) continue // already consistent
500
+ const gapKm = haversineKm(anchor.lat, anchor.lon, node.lat!, node.lon!)
501
+
502
+ if (gapKm <= thresholdKm) continue
507
503
 
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
504
  const alts = (node.alternatives as ResolvedPlace[] | undefined) ?? []
512
505
 
513
506
  const reconciling = alts
514
507
  .filter((a) => a.lat !== 0 || a.lon !== 0)
515
508
  .map((a) => ({ a, d: haversineKm(anchor!.lat, anchor!.lon, a.lat, a.lon) }))
516
509
  .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
510
+ // oxlint-disable-next-line unicorn/no-array-sort -- sorts a freshly-built array. toSorted would double-allocate on a hot path
518
511
  .sort((x, y) => x.d - y.d)[0]
519
512
 
520
513
  if (reconciling) {
521
- // Swap to the consistent instance; the displaced winner becomes an alternative.
522
514
  const displaced: ResolvedPlace = {
523
515
  id: 0,
524
516
  name: String(node.metadata?.["resolver_name"] ?? node.value),
@@ -536,7 +528,12 @@ export function applyPostcodeConsistency(roots: readonly AddressNode[], threshol
536
528
  continue
537
529
  }
538
530
 
539
- // No same-named instance near the postcode → the town is unreliable; trust the postcode's area.
531
+ if (gapKm > maxMoveKm) {
532
+ node.metadata = { ...node.metadata, postcode_city_mismatch: true, postcode_move_refused_km: gapKm }
533
+
534
+ continue
535
+ }
536
+
540
537
  node.lat = anchor.lat
541
538
  node.lon = anchor.lon
542
539
  node.metadata = { ...node.metadata, postcode_city_mismatch: true, coordinate_source: "postcode_fallback" }