@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
package/README.md CHANGED
@@ -26,9 +26,11 @@ const decorated = await resolver.resolveTree(tree)
26
26
 
27
27
  ## Backend-agnostic on purpose
28
28
 
29
- `createWOFResolver` takes a `ResolverBackend` — a structural interface, not a class. `@mailwoman/resolver-wof-sqlite` implements it over `node:sqlite`, `@mailwoman/resolver-wof-wasm` over `@sqlite.org/sqlite-wasm` in a browser, and `RemoteResolver` over HTTP. Nothing here imports any of them.
29
+ `createWOFResolver` takes a `ResolverBackend` — a structural interface rather than a class. `@mailwoman/resolver-wof-sqlite` implements it over `node:sqlite`, `@mailwoman/resolver-wof-wasm` over `@sqlite.org/sqlite-wasm` in a browser, and `RemoteResolver` over HTTP. This package imports none of them.
30
30
 
31
- Backends differ in what they can answer, and that is visible rather than silent: `describeCapabilityGaps(backend)` reports which optional methods are missing, so a default-on feature that no-ops without logging on your backend says so instead of looking like a bad result.
31
+ Backends differ in what they can answer. `describeCapabilityGaps(backend)` reports missing optional
32
+ methods. A default-on feature that no-ops without logging on your backend reports that condition instead
33
+ of looking like a bad result.
32
34
 
33
35
  ## Absence is a value
34
36
 
@@ -36,7 +38,7 @@ Two rules run through this package, and both exist because their opposites shipp
36
38
 
37
39
  **A coordinate the gazetteer cannot supply is absent, never `0,0`.** `0,0` is the unlocated sentinel in every WOF-lineage database, and those databases carry a great deal of it — 48,216 of 142,604 Japanese postcodes, 86,377 GB, 414 US. `decorateNode` leaves `lat`/`lon` unset for such a row, so the place still resolves and identifies itself while stating that it cannot say where it is. A consumer's `lat != null` check then means what it looks like it means.
38
40
 
39
- **A missing answer is not a wrong answer.** An unresolvable span is returned as parsed. Nothing here invents a centroid to fill a hole.
41
+ **A missing answer is not a wrong answer.** An unresolvable span is returned as parsed. The resolver invents no centroid to fill a hole.
40
42
 
41
43
  ## Which resolved place answers the query
42
44
 
@@ -58,13 +60,13 @@ const rank = resolvedSpecificity({ placetype: "postalcode", value: "N7 0BT", res
58
60
 
59
61
  Either an **exact hit on a unit-grade code** (`@mailwoman/codex`'s `UNIT_GRADE_POSTCODE` — NL PC6, GB unit, CA urban LDU) or an **address system whose area-grade codes are finer than its localities** (`AREA_POSTCODE_FINER_THAN_LOCALITY` — Germany, where a Gemeinde can be the size of Berlin) puts the postcode ahead of the locality. Everything else follows the locality.
60
62
 
61
- The two shapes live in one module deliberately. They express one claim and are consumed by different callers, and when they were separate the eval harnesses each froze one arm of the conditional as a constant — every grader correct on half the data and wrong on the other half, unconditionally, for as long as nobody compared them. `test/unit/admin-winner.test.ts` asserts they agree on every arm; mutating either side fails it.
63
+ The two shapes live in one module deliberately. They express one claim and are consumed by different callers, and when they were separate the eval harnesses each froze one arm of the conditional as a constant — every grader correct on half the data and wrong on the other half, unconditionally, for as long as nobody compared them. `lib/admin/winner.test.ts` asserts they agree on every arm; mutating either side fails it.
62
64
 
63
65
  Membership in those tiers is earned by measurement, never by shape alone. Canada is the worked example: its urban LDU measures 78 m against rooftop truth and joined the tier, while its rural codes measure 2.08 km and did not — and Canada Post already marks the difference with a `0` in the second character, so the code says which before any lookup runs.
64
66
 
65
67
  ## Coherence passes
66
68
 
67
- Ranking a span in isolation gets Portland, Maine to Messina, Italy. These run over the whole tree:
69
+ A span ranked in isolation gets Portland, Maine to Messina, Italy. These checks run over the whole tree:
68
70
 
69
71
  | Pass | Question |
70
72
  | ---------------------------- | ------------------------------------------------------------------------------ |
@@ -72,7 +74,7 @@ Ranking a span in isolation gets Portland, Maine to Messina, Italy. These run ov
72
74
  | `postcode-country-coherence` | Does the postcode's shape agree with the country the rest of the tree implies? |
73
75
  | `postcode-shape-coherence` | Is this span a postcode at all, in any system the query could be in? |
74
76
  | `admin-containment` | Split candidates by whether they sit inside an established parent. |
75
- | `span-rescore` | A resolved neighbour is evidence about an unresolved span. |
77
+ | `span-rescore` | A resolved neighbor is evidence about an unresolved span. |
76
78
  | `street-evidence` | A commune-scoped street hit is evidence of that street's locality. |
77
79
  | `plausibility` | Is this answer outside the country it claims? |
78
80
 
@@ -82,7 +84,7 @@ Import the barrel for the whole surface, or a subpath to take one piece without
82
84
 
83
85
  `./resolve` · `./admin-winner` · `./decorate-node` · `./plausibility` · `./postcode-prefix` · `./postcode-country-coherence` · `./postcode-shape-coherence` · `./admin-containment` · `./span-rescore` · `./street-evidence` · `./toponym-prior` · `./rerank` · `./remote-resolver` · `./backend-capabilities`
84
86
 
85
- The type contract (`ResolverBackend`, `ResolveOpts`, `ResolvedPlace`) lives in `@mailwoman/core/resolver` so that `core` stays a leaf, and is re-exported here — `@mailwoman/resolver` is the complete surface.
87
+ The type interface (`ResolverBackend`, `ResolveOpts`, `ResolvedPlace`) lives in `@mailwoman/core/resolver` so that `core` stays a leaf, and is re-exported here — `@mailwoman/resolver` is the complete surface.
86
88
 
87
89
  ## License
88
90
 
@@ -2,11 +2,6 @@
2
2
  * @copyright Sister Software
3
3
  * @license AGPL-3.0
4
4
  * @author Teffen Ellis, et al.
5
- *
6
- * The three post-walk admin coherence passes (#263 / #822 / the region-country pass) — split from
7
- * `resolve.ts` on the `bare-toponym-race.ts` precedent: the walk file holds the walk, this one
8
- * holds the joint-consistency re-picks that run after it. Each pass's contract, triggers, and
9
- * byte-stability guarantees are documented on the pass itself; `resolveTree` sequences them.
10
5
  */
11
6
 
12
7
  import { matchCountry, matchSubdivision } from "@mailwoman/codex/country"
@@ -16,46 +11,24 @@ import type { ResolvedPlace, ResolverBackend } from "@mailwoman/core/resolver"
16
11
 
17
12
  import { decorateNode, isResolvedWithCoord } from "#decorate-node"
18
13
 
19
- /**
20
- * The region-band placetypes a lineage names a region by — `region` and its macro widening, the same set the lookup
21
- * filter admits for a `region` request.
22
- */
23
14
  const REGION_LINEAGE_PLACETYPES: ReadonlySet<string> = new Set(PLACETYPE_FILTER_GROUPS["region"] ?? ["region"])
24
15
 
25
- /**
26
- * The numeric or string id behind a node's `placeID` (`wof:85679553` → `85679553`), or undefined when the node resolved
27
- * to no place.
28
- */
29
- function placeIDValue(node: AddressNode): string | undefined {
16
+ function placeIDValue(node: AddressNode): string | null {
30
17
  const match = /^[a-z]+:(.+)$/u.exec(node.placeID ?? "")
31
18
 
32
- return match?.[1]
19
+ return match?.[1] ?? null
33
20
  }
34
21
 
35
22
  /**
36
- * Refuse a pick admitted from outside its parent's scope whose own lineage names a DIFFERENT region than the one the
37
- * walk resolved above it.
23
+ * Un-resolves a parent-fallback pick whose stamped ancestors name a region other than
24
+ * the resolved region above it, marking it `parent_fallback_refused`.
38
25
  *
39
- * The walk scopes a child lookup to its resolved parent. When that scoped probe misses, two widenings exist so an
40
- * incomplete hierarchy (a real place whose ancestor chain lacks its region) still resolves: the resolver's retry
41
- * without the parent, and the candidate backend's interior region-scope fallback (#1731), which re-admits rows from
42
- * outside the region and stamps them `regionScopeMiss`. Both also admit a namesake under another region: `臺南市北區`
43
- * resolved 臺南市 (Tainan City), found no 北區 under it — the candidate table carries no Han key for Tainan's — and the
44
- * widening answered Hsinchu's 北區, 214 km away, which the coherence report then marked `region: contradicted` while the
45
- * point stood. Of the 289 held-out Taiwanese 鄉鎮市區, 21 resolved this way at 15.6–238 km when the register was read as
46
- * bare `縣市鄉鎮市區` lines.
47
- *
48
- * The two cases a widening conflates are told apart by the pick's stamped ancestors: an incomplete chain names NO
49
- * region and is kept, the case the widenings exist for; a chain that names a region other than the resolved parent is a
50
- * different place and is un-resolved here, so the admin ladder answers the parent's own point rather than a namesake
51
- * elsewhere. Only widened picks are examined (`metadata.parent_fallback`, stamped by the walk for either mechanism),
52
- * and only when the parent region resolved to a place identity; no-op without the ancestor sidecar, since a chain that
53
- * cannot be read is not a contradiction. The classifier attribution stays on the node; `parent_fallback_refused`
54
- * records what happened.
26
+ * A pick whose ancestor chain names no region is kept, because the fallback
27
+ * exists for places with incomplete hierarchies.
55
28
  */
56
29
  export function applyParentFallbackContradiction(roots: readonly AddressNode[]): void {
57
30
  const visit = (node: AddressNode, regionAncestor: AddressNode | null): void => {
58
- const regionHere = node.tag === "region" && placeIDValue(node) !== undefined ? node : regionAncestor
31
+ const regionHere = node.tag === "region" && placeIDValue(node) ? node : regionAncestor
59
32
 
60
33
  if (regionHere && node !== regionHere && node.metadata?.["parent_fallback"] === true) {
61
34
  const regionID = placeIDValue(regionHere)
@@ -66,7 +39,7 @@ export function applyParentFallbackContradiction(roots: readonly AddressNode[]):
66
39
 
67
40
  const regions = (ancestors ?? []).filter((a) => REGION_LINEAGE_PLACETYPES.has(a.placetype))
68
41
 
69
- if (regionID !== undefined && regions.length && !regions.some((a) => String(a.id) === regionID)) {
42
+ if (regionID && regions.length && !regions.some((a) => String(a.id) === regionID)) {
70
43
  delete node.lat
71
44
  delete node.lon
72
45
  delete node.placeID
@@ -95,16 +68,12 @@ export function applyParentFallbackContradiction(roots: readonly AddressNode[]):
95
68
  }
96
69
 
97
70
  /**
98
- * Admin descendant-consistency (#263) — the joint-consistency resolve, scoped to the admin assignment. The greedy walk
99
- * resolves a region on its own (name + population), so "ME" picks Messina (IT) over Maine, then scopes "Portland" to
100
- * Messina's descendants, finds nothing, and the result falls back to the region centroid (Sicily). The region's
101
- * same-named runner-ups (Maine, Missouri, …) were already captured as `alternatives`; this pass asks the question the
102
- * greedy order skipped — _which "ME" has a "Portland" under it?_ — and re-picks the (region, locality) pair where a
103
- * same-named locality descends from a same-named region candidate. Geography decides; no country prior, no list.
71
+ * Re-picks a resolved region and its unresolved child locality as a pair, choosing the
72
+ * region candidate that actually contains a locality with the same name.
104
73
  *
105
- * Fires ONLY for a resolved region whose child locality fell through (the unresolved-locality signal), so a
106
- * well-resolved tree ("Springfield, IL" → Illinois, Springfield) is byte-identical. Costs one unscoped locality lookup
107
- * per triggering pair. Needs {@link ResolverBackend.ancestors}; no-op without it. See `ResolveOpts.adminCoherence`.
74
+ * This recovers cases such as "Portland, ME" where the region was picked in isolation
75
+ * before the locality was known.
76
+ * It leaves trees with a resolved locality untouched.
108
77
  */
109
78
  export async function applyAdminCoherence(roots: readonly AddressNode[], backend: ResolverBackend): Promise<void> {
110
79
  const visit = async (node: AddressNode, regionAncestor: AddressNode | null): Promise<void> => {
@@ -114,7 +83,7 @@ export async function applyAdminCoherence(roots: readonly AddressNode[], backend
114
83
  regionHere &&
115
84
  (node.tag === "locality" || node.tag === "dependent_locality") &&
116
85
  !isResolvedWithCoord(node) &&
117
- node.value.trim().length
86
+ node.value.trim()
118
87
  ) {
119
88
  await reconcileAdminPair(regionHere, node, backend)
120
89
  }
@@ -129,29 +98,13 @@ export async function applyAdminCoherence(roots: readonly AddressNode[], backend
129
98
  }
130
99
  }
131
100
 
132
- /**
133
- * Re-pick a (region, locality) pair so the locality descends from the region. `alternatives` on the node are the
134
- * `ResolvedPlace` runner-ups `decorateNode` attached (typed `unknown[]` in the decoder, which can't import resolver
135
- * types — the cast is sound). Picks the FIRST same-named locality (already score-ordered) that descends from a
136
- * same-named region candidate, then swaps both nodes. Leaves both untouched when no consistent pair exists (a genuinely
137
- * un-gazetteered locality — "Portland, VT" with no Portland in Vermont — stays as the region centroid, not a foreign
138
- * namesake).
139
- */
140
101
  async function reconcileAdminPair(
141
102
  regionNode: AddressNode,
142
103
  localityNode: AddressNode,
143
104
  backend: ResolverBackend
144
105
  ): Promise<void> {
145
- // EXACT region matches only: the alternatives for a 2-letter token are loose ("ME" also surfaces
146
- // Missouri/Michigan/Mississippi as fuzzy M-state runner-ups). Restricting to exact name/alias matches
147
- // (Maine/Messina/Medway for "ME") keeps the join honest. `exactMatch` is stamped by exactMatchTiering.
148
- const regionCands = ((regionNode.alternatives as ResolvedPlace[] | undefined) ?? []).filter((r) => r.exactMatch)
149
-
150
- // For each exact region candidate, ask the gazetteer directly: is there a same-named locality UNDER it?
151
- // The `parentID` scope is the descendant test (over the #832-repaired ancestors table), and it finds the
152
- // instance regardless of its global population rank — "Springfield, ME" reaches the small Springfield in
153
- // Maine that an unscoped top-N window would drop. First region with an exact-named descendant wins; the
154
- // region candidates are score-ordered, so a tie breaks toward the more prominent place.
106
+ const regionCands = ((regionNode.alternatives as ResolvedPlace[] | null) ?? []).filter((r) => r.exactMatch)
107
+
155
108
  for (const region of regionCands) {
156
109
  const scoped = await backend.findPlace({
157
110
  text: localityNode.value,
@@ -183,11 +136,6 @@ async function reconcileAdminPair(
183
136
  }
184
137
  }
185
138
 
186
- // #267 follow-up: the token may name a COUNTRY whose namesake is a more-populous foreign region — "Tbilisi,
187
- // Georgia" parses region("Georgia") → the US state, but Tbilisi descends from Georgia the COUNTRY. When no
188
- // region candidate holds the locality, try same-named country candidates: a foreign capital under its
189
- // country out-votes the state namesake. Needs the country + the locality's ancestry in the gazetteer (the
190
- // #267 admin fold). The re-picked region node then carries the country place; the locality coordinate wins.
191
139
  const countryCands = (await backend.findPlace({ text: regionNode.value, placetype: "country", limit: 3 })).filter(
192
140
  (c) => c.exactMatch
193
141
  )
@@ -218,15 +166,6 @@ async function reconcileAdminPair(
218
166
  }
219
167
  }
220
168
 
221
- // #1023: the admin gazetteer may carry NO `country`-placetype node for the token AND the same-named
222
- // foreign locality may be ORPHANED (parent_id = -1) — the 2026-07-07 rebuild flattened Georgia's admin
223
- // hierarchy to localities-only, so the country-node lookup above finds nothing and the `parentID`
224
- // descendant test can never reach Tbilisi. Fall back to matchCountry: normalize the token to an
225
- // ISO-3166 alpha-2 and scope the locality by the gazetteer's `country` COLUMN (set even on an orphaned
226
- // row). Same primitive reconcileExplicitCountry (#822) uses, so the region-parsed namesake path
227
- // ("Tbilisi, Georgia") converges with the country-parsed one ("Vienna, Austria"). matchCountry returns
228
- // null for a US state name/abbrev ("Illinois" / "ME" / "IL"), so a real US (region, locality) pair
229
- // never reaches here — this stays inert on the domestic path.
230
169
  const mc = matchCountry(regionNode.value)
231
170
 
232
171
  if (mc) {
@@ -247,22 +186,12 @@ async function reconcileAdminPair(
247
186
  )
248
187
 
249
188
  localityNode.metadata = { ...localityNode.metadata, admin_coherence_repicked: true }
250
- // The token named a foreign country the admin gazetteer has no node for, but the greedy walk had
251
- // already decorated the region node with the US-state namesake. Revert that stale decoration so the
252
- // node stops asserting the wrong-country coordinate + `resolver_country` (which would otherwise leak
253
- // into the result's `countryCode`); the re-picked locality carries the winning coordinate, and the
254
- // region node falls back to the parsed "Georgia" token, unresolved (the admin DB has nothing truer).
189
+
255
190
  revertResolverDecoration(regionNode)
256
191
  }
257
192
  }
258
193
  }
259
194
 
260
- /**
261
- * Undo a resolver decoration on a node: restore the classifier attribution {@link decorateNode} displaced into
262
- * `metadata.classifier_source(_id)` and drop the resolver-supplied coordinate/identity/alternatives. Used by the #1023
263
- * country fall-through when the region token turns out to name a foreign country the admin gazetteer holds no node for
264
- * — the greedy walk had bound it to the US-state namesake, and that stale claim must not survive the locality re-pick.
265
- */
266
195
  function revertResolverDecoration(node: AddressNode): void {
267
196
  const meta = { ...node.metadata }
268
197
  const priorSource = meta["classifier_source"]
@@ -280,7 +209,7 @@ function revertResolverDecoration(node: AddressNode): void {
280
209
  "resolution_quality",
281
210
  "postcode_city_mismatch",
282
211
  ]) {
283
- // oxlint-disable-next-line typescript/no-dynamic-delete -- removing one key from a plain record; the object is not on a hot path
212
+ // oxlint-disable-next-line typescript/no-dynamic-delete -- removing one key from a plain record. the object is not on a hot path
284
213
  delete meta[key]
285
214
  }
286
215
 
@@ -292,41 +221,21 @@ function revertResolverDecoration(node: AddressNode): void {
292
221
  }
293
222
 
294
223
  /**
295
- * Explicit-country coherence (#822) — the joint-consistency resolve keyed on the query's own EXPLICIT country token.
296
- * The greedy walk resolves a locality on name + population alone, so "Vienna, Austria" picks the populous US namesake
297
- * (Vienna WV) and IGNORES the "Austria" the address named. This pass asks the question the greedy order skipped —
298
- * _which "Vienna" is in the country the address names?_ — and re-picks the locality to the same-named place under that
299
- * country. The country code comes from the parser's OWN `country` emission via codex's ISO-3166 table (a name→code
300
- * normalization of a token the model already classified, NOT a routing prior or safelist); the gazetteer's `country`
301
- * column does the geographic confirmation. No pin, no list; generalizes to every country.
224
+ * Re-picks a locality to the place with the same name inside the country specified in
225
+ * the address, when that country is the locality's nearest admin context.
302
226
  *
303
- * Disjoint from {@link applyAdminCoherence} by the region guard: that pass owns the case where a REGION scopes the
304
- * locality; this one fires only when the explicit country is the locality's nearest admin context (no region between),
305
- * and then regardless of the locality's resolution state — so it covers both the resolved-but-foreign locality (Sydney
306
- * → the greedy AU pick was wrong) and the unresolved locality the span-rescore tier would otherwise back-fill with the
307
- * US namesake (Vienna → Vienna WV). Byte-stable when the locality already resolved in-country (the id guard) or the
308
- * named country holds no same-named locality (the fail-safe — what also protects "Turkey, TX": no country token ⇒ no
309
- * trigger; and an in-country lookup that finds nothing keeps the greedy result). Costs one country-scoped locality
310
- * lookup per triggering pair. See `ResolveOpts.adminCoherence`.
227
+ * It leaves the locality unchanged when it already resolved to that place or
228
+ * when that country has no locality with the same name.
311
229
  */
312
230
  export async function applyExplicitCountryCoherence(
313
231
  roots: readonly AddressNode[],
314
232
  backend: ResolverBackend
315
233
  ): Promise<void> {
316
234
  const visit = async (node: AddressNode, countryToken: AddressNode | null, regionAbove: boolean): Promise<void> => {
317
- const countryHere = node.tag === "country" && node.value.trim().length ? node : countryToken
318
-
319
- // A region suppresses the country re-pick only when it RESOLVED: the suppression's rationale is
320
- // that applyAdminCoherence + the region's `parentID` scope already disambiguate the locality
321
- // ("Springfield, IL" must not re-pick to the most populous US Springfield), and an UNRESOLVED
322
- // region disambiguates nothing — 'NIC-38' (an ISO-3166-2 code the gazetteer holds no node for)
323
- // silently swallowed the explicit 'Nicaragua', and El Sauce resolved a US namesake. This pass
324
- // runs post-walk, so resolution state is known.
235
+ const countryHere = node.tag === "country" && node.value.trim() ? node : countryToken
236
+
325
237
  const regionHere = regionAbove || ((node.tag === "region" || node.tag === "subregion") && isResolvedWithCoord(node))
326
238
 
327
- // Fire only when the explicit country is the locality's NEAREST RESOLVED admin context.
328
- // Fires regardless of the locality's resolution state, so it PRE-EMPTS the span-rescore tier
329
- // (which would otherwise back-fill the unresolved locality with the US namesake).
330
239
  if (countryHere && !regionHere && (node.tag === "locality" || node.tag === "dependent_locality")) {
331
240
  await reconcileExplicitCountry(countryHere, node, backend)
332
241
  }
@@ -341,15 +250,6 @@ export async function applyExplicitCountryCoherence(
341
250
  }
342
251
  }
343
252
 
344
- /**
345
- * Re-pick a resolved locality to its same-named place UNDER the explicitly-named country. `matchCountry` turns the
346
- * country token into an ISO-3166 alpha-2 (returns null for an unrecognized token → no-op); the backend then surfaces
347
- * the in-country namesake the population-first unscoped window buried. Leaves the node untouched when the country is
348
- * unrecognized, the named country has no exact same-named locality (the fail-safe), or the locality already resolved to
349
- * that place (the id guard → byte-stable). The country node itself stays as the parser emitted it — the named
350
- * well-covered countries carry no `country`-placetype row in the admin gazetteer, so there is nothing to decorate it
351
- * with; the locality coordinate is what the re-pick fixes.
352
- */
353
253
  async function reconcileExplicitCountry(
354
254
  countryNode: AddressNode,
355
255
  localityNode: AddressNode,
@@ -370,7 +270,6 @@ async function reconcileExplicitCountry(
370
270
 
371
271
  if (!lc) return
372
272
 
373
- // Already the in-country place? (placeID encodes the WOF id.) Then the greedy walk was right — byte-stable.
374
273
  if (localityNode.placeID === `wof:${lc.id}`) return
375
274
 
376
275
  decorateNode(
@@ -383,51 +282,27 @@ async function reconcileExplicitCountry(
383
282
  }
384
283
 
385
284
  /**
386
- * Region-country coherence — the joint-consistency resolve keyed on a REGION token the locale-inferred default-country
387
- * filter could not resolve. Companion to {@link applyExplicitCountryCoherence} (which keys on an explicit COUNTRY token)
388
- * and disjoint from {@link applyAdminCoherence} (which needs a region that DID resolve): this pass owns the mirror case,
389
- * where the region qualifier is a foreign subdivision the default-country hard filter (`spr.country = ?`) discarded.
285
+ * Re-picks the region and locality into a foreign country when the region token is that
286
+ * country's subdivision and the default-country filter left it unresolved.
390
287
  *
391
- * "Montreal QC" under a US locale: the walk applies `defaultCountry="US"` as a hard candidate filter to every admin
392
- * lookup, so the region "QC" (a Canadian subdivision) resolves to nothing and is dropped — the one signal that would
393
- * redirect the country to CA — and the locality "Montreal" is force-matched to the populous US namesake (Montreal, WI).
394
- * The greedy order threw away the evidence that could correct it.
395
- *
396
- * The fix expands the region token to its country via codex's ISO-3166-2 subdivision table (`matchSubdivision`: "QC" →
397
- * `{ name: "Quebec", country: "CA" }`, handling the FTS index's missing "QC" alt-name code-side), then asks the two
398
- * questions the greedy walk skipped: does that subdivision genuinely resolve UNDER its own country, and is there a
399
- * same-named locality under it? Only when BOTH hold does it swap the region and locality to the in-country pair.
400
- * Geography confirms; the subdivision table is a soft name→country prior, not a routing decision.
401
- *
402
- * Evidence-conditional to stay byte-stable on the domestic path. It fires ONLY when (a) a default country is in force,
403
- * (b) the region node is UNRESOLVED (the default-country filter came up empty — a US region resolves fine under `US`,
404
- * so a well-formed US query never trips this), (c) the token is a subdivision of a DIFFERENT country than the default,
405
- * and (d) both the foreign region and a same-named foreign locality resolve. "Springfield, IL" / "Portland, ME": the
406
- * region resolves under `US`, so check (b) fails and the tree is untouched. Costs one region + one locality lookup per
407
- * triggering pair. See `ResolveOpts.adminCoherence`.
288
+ * Both the foreign region and a locality with the same name under that country must resolve,
289
+ * so domestic queries whose region resolves are never changed.
408
290
  */
409
291
  export async function applyRegionCountryCoherence(
410
292
  roots: readonly AddressNode[],
411
293
  backend: ResolverBackend,
412
- defaultCountry: string | undefined
294
+ defaultCountry: string | null
413
295
  ): Promise<void> {
414
- // No default country → no hard country filter was applied, so no region qualifier was discarded by one. The bug
415
- // this pass corrects is specific to the locale-inferred default country; without it, there is nothing to rescue.
416
296
  if (!defaultCountry) return
417
297
 
418
298
  const visit = async (node: AddressNode, regionAncestor: AddressNode | null): Promise<void> => {
419
- // Track the nearest region ancestor regardless of its resolution state (the trigger is an UNRESOLVED region).
420
299
  const regionHere = node.tag === "region" || node.tag === "subregion" ? node : regionAncestor
421
300
 
422
- // Fire for an UNRESOLVED region (the default-country filter came up empty) whose companion locality node
423
- // exists — regardless of the locality's resolution state, so it covers both the resolved-but-foreign namesake
424
- // (Montreal → the greedy US pick, Montreal WI) and the unresolved locality the span-rescore tier would
425
- // otherwise back-fill with a US namesake. The in-country lookups below are the evidence check.
426
301
  if (
427
302
  regionHere &&
428
303
  !isResolvedWithCoord(regionHere) &&
429
304
  (node.tag === "locality" || node.tag === "dependent_locality") &&
430
- node.value.trim().length
305
+ node.value.trim()
431
306
  ) {
432
307
  await reconcileRegionCountry(regionHere, node, backend, defaultCountry)
433
308
  }
@@ -442,14 +317,6 @@ export async function applyRegionCountryCoherence(
442
317
  }
443
318
  }
444
319
 
445
- /**
446
- * Re-pick an (unresolved region, resolved-but-foreign-namesake locality) pair to the in-country instance the
447
- * default-country filter hid. `matchSubdivision` turns the region token into `{ name, country }` (null for anything
448
- * that isn't a US state or CA province → no-op); the region's full name then resolves it under that country (expanding
449
- * the abbreviation the gazetteer FTS index lacks), and the locality is re-scoped to the same country. Leaves both nodes
450
- * untouched unless every check holds — the subdivision names a different country than the default, the region resolves
451
- * under it, and a same-named locality exists there — so the domestic path stays byte-identical.
452
- */
453
320
  async function reconcileRegionCountry(
454
321
  regionNode: AddressNode,
455
322
  localityNode: AddressNode,
@@ -460,17 +327,12 @@ async function reconcileRegionCountry(
460
327
 
461
328
  if (!sub) return
462
329
 
463
- // The subdivision must belong to a DIFFERENT country than the locale default. A US-state token under a US default
464
- // (sub.country === defaultCountry) never reaches the swap — the pass is inert on the domestic path.
465
330
  if (sub.country.toUpperCase() === defaultCountry.toUpperCase()) return
466
331
 
467
- // The locality already resolved in the subdivision's country? Then the greedy walk was already right — byte-stable.
468
- const localityCountry = (localityNode.metadata?.["resolver_country"] as string | undefined)?.toUpperCase()
332
+ const localityCountry = (localityNode.metadata?.["resolver_country"] as string | null)?.toUpperCase()
469
333
 
470
334
  if (localityCountry === sub.country.toUpperCase()) return
471
335
 
472
- // Confirm the subdivision genuinely resolves under its own country, by its full name (expands "QC" → "Quebec", the
473
- // form the FTS index carries). No resolvable region → no evidence the token is a real foreign subdivision; abstain.
474
336
  const regionScoped = await backend.findPlace({
475
337
  text: sub.name,
476
338
  placetype: "region",
@@ -482,8 +344,6 @@ async function reconcileRegionCountry(
482
344
 
483
345
  if (!rc) return
484
346
 
485
- // Is there a same-named locality under that country? (the descendant test, by country column — the same primitive
486
- // reconcileExplicitCountry uses.) No in-country namesake → keep the greedy result (fail-safe).
487
347
  const scoped = await backend.findPlace({
488
348
  text: localityNode.value,
489
349
  placetype: "locality",
@@ -495,7 +355,6 @@ async function reconcileRegionCountry(
495
355
 
496
356
  if (!lc) return
497
357
 
498
- // Adopt the in-country pair: the region gets the foreign subdivision, the locality its same-named foreign instance.
499
358
  decorateNode(
500
359
  regionNode,
501
360
  rc,
@@ -3,41 +3,25 @@
3
3
  * @license AGPL-3.0
4
4
  * @author Teffen Ellis, et al.
5
5
  *
6
- * The admin-containment partition (#1717 stage 2) — the ONE ordering function both deciding sites
7
- * call, per the #861 rule (shared constants prove nothing; the #861 parity contract diverged at
8
- * exactly the points a constant cannot express). The candidate backend partitions its row set
9
- * before the limit window (so a contained candidate can reach the walk at all), and the resolver
10
- * walk partitions AGAIN after its fame/anchor re-ranks (so `rankByImportance` cannot hand the top
11
- * slot back to a more-famous uncontained namesake — Richmond VA outscores Richmond, North
12
- * Yorkshire on importance, and without the second partition the change loses exactly where fame
13
- * disagrees with the qualifier). Two call sites, one function, one ordering.
6
+ * Both decision sites call this ordering function.
7
+ * The candidate backend partitions rows before the limit window. The resolver walk partitions again after fame and anchor re-ranking.
14
8
  */
15
9
 
16
10
  import { firstNodeWhere, type AddressNode } from "@mailwoman/core/decoder"
17
11
 
18
12
  /**
19
- * Find the first non-empty region-tagged span anywhere in a tree — the qualifier the walk threads onto locality
20
- * lookups. Deliberately the same node the admin-coherence VERDICTS read (the first `region` node), so the change's
21
- * firing population and the flag's `contradicted` population are the same rows. A `region` slot can hold a country name
22
- * the parser mislabeled ("Moscow, Russia" parses region="Russia") — the backend's qualifier probe answers that too,
23
- * because containment is containment whatever tier the container sits at.
13
+ * Find the first non-empty region-tagged span anywhere in a tree — the qualifier the
14
+ * walk threads onto locality lookups, deliberately the same node the admin-coherence
15
+ * verdicts read so the two populations coincide.
24
16
  */
25
- export function firstRegionQualifier(roots: readonly AddressNode[]): string | undefined {
26
- return firstNodeWhere(roots, (n) => n.tag === "region" && n.value.trim().length > 0)?.value.trim()
17
+ export function firstRegionQualifier(roots: readonly AddressNode[]): string | null {
18
+ return firstNodeWhere(roots, (n) => n.tag === "region" && n.value.trim())?.value.trim() ?? null
27
19
  }
28
20
 
29
21
  /**
30
- * Stable, TIER-SAFE partition: within each match tier, candidates the containment source vouched for (`isContained`)
31
- * move ahead of the rest, and BOTH groups keep their incoming relative order — the same house rules every soft ranking
32
- * key here obeys (`toponym-prior.ts`): tier-safe (a contained partial match never outranks an exact one — `isExact`
33
- * splits the population exactly as `rankWithinTier`'s tri-state rule does, only a stated exact tier earns the front),
34
- * positive-evidence-only (only a stated `true` moves a row; `false` and "never evaluated" both hold their incoming
35
- * rank, so an incapable backend is a no-op by construction), and stable (the backend's own ordering survives within
36
- * each (tier, containment) cell).
37
- *
38
- * Implemented with the slot idiom (`reorderMeasured`'s mechanics): each tier's members permute only among the positions
39
- * that tier already occupies, so a tier-interleaved list — the walk's no-importance path never regrouped tiers — cannot
40
- * have a rest-tier row promoted across an exact-tier boundary by this partition.
22
+ * Stable, tier-safe, positive-evidence-only partition: within each match tier,
23
+ * candidates vouched for by the containment source (`isContained`) move ahead of the others.
24
+ * Both groups keep their incoming relative order.
41
25
  */
42
26
  export function partitionByContainment<T>(
43
27
  rows: readonly T[],
@@ -69,21 +53,19 @@ export function partitionByContainment<T>(
69
53
  }
70
54
 
71
55
  /**
72
- * The trace verdict for one locality pick under the change — stamped as `metadata.admin_containment` so an inert
73
- * mechanism is visible in the result rather than silently dead (#1719's rule). Derived from the candidates'
74
- * `containedByQualifier` stamps: any `true` → `"contained"`; stamps present but none true → `"no_contained_candidate"`;
75
- * no stamps at all → `"unavailable"` (the backend or artifact cannot answer — a pre-sidecar candidate.db, the FTS or
76
- * browser backend, or a qualifier the probe never ran for).
56
+ * The trace verdict for one locality pick, stamped as `metadata.admin_containment`:
57
+ * any `true` → `"contained"`; stamps present but none true → `"no_contained_candidate"`;
58
+ * no stamps at all → `"unavailable"`.
77
59
  */
78
60
  export function adminContainmentVerdict(
79
- candidates: ReadonlyArray<{ containedByQualifier?: boolean | undefined }>
61
+ candidates: ReadonlyArray<{ containedByQualifier?: boolean | null }>
80
62
  ): "contained" | "no_contained_candidate" | "unavailable" {
81
63
  let evaluated = false
82
64
 
83
65
  for (const candidate of candidates) {
84
66
  if (candidate.containedByQualifier === true) return "contained"
85
67
 
86
- if (candidate.containedByQualifier !== undefined) {
68
+ if (candidate.containedByQualifier != null) {
87
69
  evaluated = true
88
70
  }
89
71
  }
@@ -4,12 +4,14 @@
4
4
  * @author Teffen Ellis, et al.
5
5
  * @file A compound Japanese municipality split into the two units the gazetteer keys separately.
6
6
  *
7
- * The JP model tags `神戸市西区` (city + ward) and `猿島郡五霞町` (county + town) as ONE `municipality` span, which is
8
- * the postal form, and WOF keys the city, the ward and the town — never the compound. Probed whole, the span misses
9
- * and the coordinate falls to the prefecture centroid (25–52 km on the JP board). Probed as its trailing unit
10
- * UNSCOPED it does worse: a bare `西区` resolves a namesake ward in another city (Kobe's answered Fukuoka's, 407 km;
11
- * 251 of 300 rows against 271 whole). The split is therefore consumed by the resolver walk as a SCOPED pair: the
12
- * head resolves first, the tail probes as its child, and a namesake outside the head is not admissible.
7
+ * The JP model tags `神戸市西区` (city plus ward) and `猿島郡五霞町` (county plus town) as one
8
+ * `municipality` span. This matches the postal form. WOF keys the city, ward and town separately.
9
+ * A whole-span probe misses, so the coordinate falls to the prefecture centroid. The JP board records
10
+ * errors of 25–52 km. An unscoped probe of the trailing unit performs worse. A bare `西区` resolves to a
11
+ * namesake ward in another city. In the test, Kobe's query resolves to Fukuoka, 407 km away.
12
+ * The split scores 251 of 300 rows, compared with 271 for the whole-span probe. The resolver uses the
13
+ * head and tail as a scoped pair. It resolves the head first, then probes the tail as its child.
14
+ * Candidate matching stays within the head scope.
13
15
  */
14
16
 
15
17
  export interface CompoundMunicipality {
@@ -48,7 +50,8 @@ export function compoundMunicipality(value: string): CompoundMunicipality | null
48
50
  }
49
51
 
50
52
  /**
51
- * One probe of the gazetteer as the walk makes it: `value` under `scope`, with the parent fallback allowed or withheld.
53
+ * One probe of the gazetteer as the walk makes it: `value` under `scope`,
54
+ * with the parent fallback allowed or withheld.
52
55
  */
53
56
  export type CompoundMunicipalityProbe<Place, Pick extends { top: Place; metadata?: Record<string, unknown> }> = (
54
57
  value: string,
@@ -65,15 +68,19 @@ function stamp<Pick extends { metadata?: Record<string, unknown> }>(
65
68
  }
66
69
 
67
70
  /**
68
- * A compound municipality probed as a SCOPED pair after the whole span missed: the head under the node's own parent
69
- * with the walk's ordinary fallback, then the tail as the head's child with the parent fallback WITHHELD, so a namesake
70
- * ward or town outside the head is never admissible — including one the backend re-admits through its own region-scope
71
- * fallback (`regionScopeMiss`). A county head usually has no key; the tail then probes under the parent the walk
72
- * already holds. Answers the tail when it hits, else the head, else null. Two probes at most, each drawn from the
73
- * caller's budget (`hasBudget`).
71
+ * A compound municipality probed as a scoped pair after the whole span missed: the head under the
72
+ * node's own parent with the walk's ordinary fallback, then the tail as the head's child with
73
+ * the parent fallback withheld, so a namesake ward or town outside the head is never admissible,
74
+ * including one the backend re-admits through its own region-scope fallback (`regionScopeMiss`).
75
+ *
76
+ * A county head usually has no key.
77
+ * The tail then probes under the parent the walk already holds.
78
+ * Answers the tail when it hits, else the head, else null.
79
+ *
80
+ * Two probes at most, each drawn from the caller's budget (`hasBudget`).
74
81
  */
75
82
  export async function resolveCompoundMunicipality<
76
- Place extends { regionScopeMiss?: boolean },
83
+ Place extends { regionScopeMiss?: boolean | null },
77
84
  Pick extends { top: Place; metadata?: Record<string, unknown> },
78
85
  >(
79
86
  value: string,