@mailwoman/resolver 9.4.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 +21 -161
  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 +73 -39
  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 +37 -63
  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 +145 -148
  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 +18 -69
  24. package/out/admin/coherence-passes.d.ts.map +1 -1
  25. package/out/admin/coherence-passes.js +19 -161
  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 +56 -28
  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 +29 -58
  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 +97 -86
  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 -995
  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 -807
  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,29 +2,17 @@
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"
8
+ import { PLACETYPE_FILTER_GROUPS } from "@mailwoman/codex/placetype-map"
13
9
  import type { AddressNode } from "@mailwoman/core/decoder"
14
- import { PLACETYPE_FILTER_GROUPS, type ResolvedPlace, type ResolverBackend } from "@mailwoman/core/resolver"
10
+ import type { ResolvedPlace, ResolverBackend } from "@mailwoman/core/resolver"
15
11
 
16
12
  import { decorateNode, isResolvedWithCoord } from "#decorate-node"
17
13
 
18
- /**
19
- * The region-band placetypes a lineage names a region by — `region` and its macro widening, the same set the lookup
20
- * filter admits for a `region` request.
21
- */
22
14
  const REGION_LINEAGE_PLACETYPES: ReadonlySet<string> = new Set(PLACETYPE_FILTER_GROUPS["region"] ?? ["region"])
23
15
 
24
- /**
25
- * The numeric or string id behind a node's `placeID` (`wof:85679553` → `85679553`), or undefined when the node resolved
26
- * to no place.
27
- */
28
16
  function placeIDValue(node: AddressNode): string | undefined {
29
17
  const match = /^[a-z]+:(.+)$/u.exec(node.placeID ?? "")
30
18
 
@@ -32,25 +20,11 @@ function placeIDValue(node: AddressNode): string | undefined {
32
20
  }
33
21
 
34
22
  /**
35
- * Refuse a pick admitted from outside its parent's scope whose own lineage names a DIFFERENT region than the one the
36
- * 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`.
37
25
  *
38
- * The walk scopes a child lookup to its resolved parent. When that scoped probe misses, two widenings exist so an
39
- * incomplete hierarchy (a real place whose ancestor chain lacks its region) still resolves: the resolver's retry
40
- * without the parent, and the candidate backend's interior region-scope fallback (#1731), which re-admits rows from
41
- * outside the region and stamps them `regionScopeMiss`. Both also admit a namesake under another region: `臺南市北區`
42
- * resolved 臺南市 (Tainan City), found no 北區 under it — the candidate table carries no Han key for Tainan's — and the
43
- * widening answered Hsinchu's 北區, 214 km away, which the coherence report then marked `region: contradicted` while the
44
- * point stood. Of the 289 held-out Taiwanese 鄉鎮市區, 21 resolved this way at 15.6–238 km when the register was read as
45
- * bare `縣市鄉鎮市區` lines.
46
- *
47
- * The two cases a widening conflates are told apart by the pick's stamped ancestors: an incomplete chain names NO
48
- * region and is kept, the case the widenings exist for; a chain that names a region other than the resolved parent is a
49
- * different place and is un-resolved here, so the admin ladder answers the parent's own point rather than a namesake
50
- * elsewhere. Only widened picks are examined (`metadata.parent_fallback`, stamped by the walk for either mechanism),
51
- * and only when the parent region resolved to a place identity; no-op without the ancestor sidecar, since a chain that
52
- * cannot be read is not a contradiction. The classifier attribution stays on the node; `parent_fallback_refused`
53
- * records what happened.
26
+ * A pick whose ancestor chain names no region is kept, because the fallback
27
+ * exists for places with incomplete hierarchies.
54
28
  */
55
29
  export function applyParentFallbackContradiction(roots: readonly AddressNode[]): void {
56
30
  const visit = (node: AddressNode, regionAncestor: AddressNode | null): void => {
@@ -94,16 +68,12 @@ export function applyParentFallbackContradiction(roots: readonly AddressNode[]):
94
68
  }
95
69
 
96
70
  /**
97
- * Admin descendant-consistency (#263) — the joint-consistency resolve, scoped to the admin assignment. The greedy walk
98
- * resolves a region on its own (name + population), so "ME" picks Messina (IT) over Maine, then scopes "Portland" to
99
- * Messina's descendants, finds nothing, and the result falls back to the region centroid (Sicily). The region's
100
- * same-named runner-ups (Maine, Missouri, …) were already captured as `alternatives`; this pass asks the question the
101
- * greedy order skipped — _which "ME" has a "Portland" under it?_ — and re-picks the (region, locality) pair where a
102
- * 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.
103
73
  *
104
- * Fires ONLY for a resolved region whose child locality fell through (the unresolved-locality signal), so a
105
- * well-resolved tree ("Springfield, IL" → Illinois, Springfield) is byte-identical. Costs one unscoped locality lookup
106
- * 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.
107
77
  */
108
78
  export async function applyAdminCoherence(roots: readonly AddressNode[], backend: ResolverBackend): Promise<void> {
109
79
  const visit = async (node: AddressNode, regionAncestor: AddressNode | null): Promise<void> => {
@@ -128,29 +98,13 @@ export async function applyAdminCoherence(roots: readonly AddressNode[], backend
128
98
  }
129
99
  }
130
100
 
131
- /**
132
- * Re-pick a (region, locality) pair so the locality descends from the region. `alternatives` on the node are the
133
- * `ResolvedPlace` runner-ups `decorateNode` attached (typed `unknown[]` in the decoder, which can't import resolver
134
- * types — the cast is sound). Picks the FIRST same-named locality (already score-ordered) that descends from a
135
- * same-named region candidate, then swaps both nodes. Leaves both untouched when no consistent pair exists (a genuinely
136
- * un-gazetteered locality — "Portland, VT" with no Portland in Vermont — stays as the region centroid, not a foreign
137
- * namesake).
138
- */
139
101
  async function reconcileAdminPair(
140
102
  regionNode: AddressNode,
141
103
  localityNode: AddressNode,
142
104
  backend: ResolverBackend
143
105
  ): Promise<void> {
144
- // EXACT region matches only: the alternatives for a 2-letter token are loose ("ME" also surfaces
145
- // Missouri/Michigan/Mississippi as fuzzy M-state runner-ups). Restricting to exact name/alias matches
146
- // (Maine/Messina/Medway for "ME") keeps the join honest. `exactMatch` is stamped by exactMatchTiering.
147
106
  const regionCands = ((regionNode.alternatives as ResolvedPlace[] | undefined) ?? []).filter((r) => r.exactMatch)
148
107
 
149
- // For each exact region candidate, ask the gazetteer directly: is there a same-named locality UNDER it?
150
- // The `parentID` scope is the descendant test (over the #832-repaired ancestors table), and it finds the
151
- // instance regardless of its global population rank — "Springfield, ME" reaches the small Springfield in
152
- // Maine that an unscoped top-N window would drop. First region with an exact-named descendant wins; the
153
- // region candidates are score-ordered, so a tie breaks toward the more prominent place.
154
108
  for (const region of regionCands) {
155
109
  const scoped = await backend.findPlace({
156
110
  text: localityNode.value,
@@ -182,11 +136,6 @@ async function reconcileAdminPair(
182
136
  }
183
137
  }
184
138
 
185
- // #267 follow-up: the token may name a COUNTRY whose namesake is a more-populous foreign region — "Tbilisi,
186
- // Georgia" parses region("Georgia") → the US state, but Tbilisi descends from Georgia the COUNTRY. When no
187
- // region candidate holds the locality, try same-named country candidates: a foreign capital under its
188
- // country out-votes the state namesake. Needs the country + the locality's ancestry in the gazetteer (the
189
- // #267 admin fold). The re-picked region node then carries the country place; the locality coordinate wins.
190
139
  const countryCands = (await backend.findPlace({ text: regionNode.value, placetype: "country", limit: 3 })).filter(
191
140
  (c) => c.exactMatch
192
141
  )
@@ -217,15 +166,6 @@ async function reconcileAdminPair(
217
166
  }
218
167
  }
219
168
 
220
- // #1023: the admin gazetteer may carry NO `country`-placetype node for the token AND the same-named
221
- // foreign locality may be ORPHANED (parent_id = -1) — the 2026-07-07 rebuild flattened Georgia's admin
222
- // hierarchy to localities-only, so the country-node lookup above finds nothing and the `parentID`
223
- // descendant test can never reach Tbilisi. Fall back to matchCountry: normalize the token to an
224
- // ISO-3166 alpha-2 and scope the locality by the gazetteer's `country` COLUMN (set even on an orphaned
225
- // row). Same primitive reconcileExplicitCountry (#822) uses, so the region-parsed namesake path
226
- // ("Tbilisi, Georgia") converges with the country-parsed one ("Vienna, Austria"). matchCountry returns
227
- // null for a US state name/abbrev ("Illinois" / "ME" / "IL"), so a real US (region, locality) pair
228
- // never reaches here — this stays inert on the domestic path.
229
169
  const mc = matchCountry(regionNode.value)
230
170
 
231
171
  if (mc) {
@@ -246,22 +186,12 @@ async function reconcileAdminPair(
246
186
  )
247
187
 
248
188
  localityNode.metadata = { ...localityNode.metadata, admin_coherence_repicked: true }
249
- // The token named a foreign country the admin gazetteer has no node for, but the greedy walk had
250
- // already decorated the region node with the US-state namesake. Revert that stale decoration so the
251
- // node stops asserting the wrong-country coordinate + `resolver_country` (which would otherwise leak
252
- // into the result's `countryCode`); the re-picked locality carries the winning coordinate, and the
253
- // region node falls back to the parsed "Georgia" token, unresolved (the admin DB has nothing truer).
189
+
254
190
  revertResolverDecoration(regionNode)
255
191
  }
256
192
  }
257
193
  }
258
194
 
259
- /**
260
- * Undo a resolver decoration on a node: restore the classifier attribution {@link decorateNode} displaced into
261
- * `metadata.classifier_source(_id)` and drop the resolver-supplied coordinate/identity/alternatives. Used by the #1023
262
- * country fall-through when the region token turns out to name a foreign country the admin gazetteer holds no node for
263
- * — the greedy walk had bound it to the US-state namesake, and that stale claim must not survive the locality re-pick.
264
- */
265
195
  function revertResolverDecoration(node: AddressNode): void {
266
196
  const meta = { ...node.metadata }
267
197
  const priorSource = meta["classifier_source"]
@@ -279,7 +209,7 @@ function revertResolverDecoration(node: AddressNode): void {
279
209
  "resolution_quality",
280
210
  "postcode_city_mismatch",
281
211
  ]) {
282
- // 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
283
213
  delete meta[key]
284
214
  }
285
215
 
@@ -291,22 +221,11 @@ function revertResolverDecoration(node: AddressNode): void {
291
221
  }
292
222
 
293
223
  /**
294
- * Explicit-country coherence (#822) — the joint-consistency resolve keyed on the query's own EXPLICIT country token.
295
- * The greedy walk resolves a locality on name + population alone, so "Vienna, Austria" picks the populous US namesake
296
- * (Vienna WV) and IGNORES the "Austria" the address named. This pass asks the question the greedy order skipped —
297
- * _which "Vienna" is in the country the address names?_ — and re-picks the locality to the same-named place under that
298
- * country. The country code comes from the parser's OWN `country` emission via codex's ISO-3166 table (a name→code
299
- * normalization of a token the model already classified, NOT a routing prior or safelist); the gazetteer's `country`
300
- * 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.
301
226
  *
302
- * Disjoint from {@link applyAdminCoherence} by the region guard: that pass owns the case where a REGION scopes the
303
- * locality; this one fires only when the explicit country is the locality's nearest admin context (no region between),
304
- * and then regardless of the locality's resolution state — so it covers both the resolved-but-foreign locality (Sydney
305
- * → the greedy AU pick was wrong) and the unresolved locality the span-rescore tier would otherwise back-fill with the
306
- * US namesake (Vienna → Vienna WV). Byte-stable when the locality already resolved in-country (the id guard) or the
307
- * named country holds no same-named locality (the fail-safe — what also protects "Turkey, TX": no country token ⇒ no
308
- * trigger; and an in-country lookup that finds nothing keeps the greedy result). Costs one country-scoped locality
309
- * 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.
310
229
  */
311
230
  export async function applyExplicitCountryCoherence(
312
231
  roots: readonly AddressNode[],
@@ -315,17 +234,8 @@ export async function applyExplicitCountryCoherence(
315
234
  const visit = async (node: AddressNode, countryToken: AddressNode | null, regionAbove: boolean): Promise<void> => {
316
235
  const countryHere = node.tag === "country" && node.value.trim().length ? node : countryToken
317
236
 
318
- // A region suppresses the country re-pick only when it RESOLVED: the suppression's rationale is
319
- // that applyAdminCoherence + the region's `parentID` scope already disambiguate the locality
320
- // ("Springfield, IL" must not re-pick to the most populous US Springfield), and an UNRESOLVED
321
- // region disambiguates nothing — 'NIC-38' (an ISO-3166-2 code the gazetteer holds no node for)
322
- // silently swallowed the explicit 'Nicaragua', and El Sauce resolved a US namesake. This pass
323
- // runs post-walk, so resolution state is known.
324
237
  const regionHere = regionAbove || ((node.tag === "region" || node.tag === "subregion") && isResolvedWithCoord(node))
325
238
 
326
- // Fire only when the explicit country is the locality's NEAREST RESOLVED admin context.
327
- // Fires regardless of the locality's resolution state, so it PRE-EMPTS the span-rescore tier
328
- // (which would otherwise back-fill the unresolved locality with the US namesake).
329
239
  if (countryHere && !regionHere && (node.tag === "locality" || node.tag === "dependent_locality")) {
330
240
  await reconcileExplicitCountry(countryHere, node, backend)
331
241
  }
@@ -340,15 +250,6 @@ export async function applyExplicitCountryCoherence(
340
250
  }
341
251
  }
342
252
 
343
- /**
344
- * Re-pick a resolved locality to its same-named place UNDER the explicitly-named country. `matchCountry` turns the
345
- * country token into an ISO-3166 alpha-2 (returns null for an unrecognized token → no-op); the backend then surfaces
346
- * the in-country namesake the population-first unscoped window buried. Leaves the node untouched when the country is
347
- * unrecognized, the named country has no exact same-named locality (the fail-safe), or the locality already resolved to
348
- * that place (the id guard → byte-stable). The country node itself stays as the parser emitted it — the named
349
- * well-covered countries carry no `country`-placetype row in the admin gazetteer, so there is nothing to decorate it
350
- * with; the locality coordinate is what the re-pick fixes.
351
- */
352
253
  async function reconcileExplicitCountry(
353
254
  countryNode: AddressNode,
354
255
  localityNode: AddressNode,
@@ -369,7 +270,6 @@ async function reconcileExplicitCountry(
369
270
 
370
271
  if (!lc) return
371
272
 
372
- // Already the in-country place? (placeID encodes the WOF id.) Then the greedy walk was right — byte-stable.
373
273
  if (localityNode.placeID === `wof:${lc.id}`) return
374
274
 
375
275
  decorateNode(
@@ -382,46 +282,22 @@ async function reconcileExplicitCountry(
382
282
  }
383
283
 
384
284
  /**
385
- * Region-country coherence — the joint-consistency resolve keyed on a REGION token the locale-inferred default-country
386
- * filter could not resolve. Companion to {@link applyExplicitCountryCoherence} (which keys on an explicit COUNTRY token)
387
- * and disjoint from {@link applyAdminCoherence} (which needs a region that DID resolve): this pass owns the mirror case,
388
- * 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.
389
287
  *
390
- * "Montreal QC" under a US locale: the walk applies `defaultCountry="US"` as a hard candidate filter to every admin
391
- * lookup, so the region "QC" (a Canadian subdivision) resolves to nothing and is dropped — the one signal that would
392
- * redirect the country to CA — and the locality "Montreal" is force-matched to the populous US namesake (Montreal, WI).
393
- * The greedy order threw away the evidence that could correct it.
394
- *
395
- * The fix expands the region token to its country via codex's ISO-3166-2 subdivision table (`matchSubdivision`: "QC" →
396
- * `{ name: "Quebec", country: "CA" }`, handling the FTS index's missing "QC" alt-name code-side), then asks the two
397
- * questions the greedy walk skipped: does that subdivision genuinely resolve UNDER its own country, and is there a
398
- * same-named locality under it? Only when BOTH hold does it swap the region and locality to the in-country pair.
399
- * Geography confirms; the subdivision table is a soft name→country prior, not a routing decision.
400
- *
401
- * Evidence-conditional to stay byte-stable on the domestic path. It fires ONLY when (a) a default country is in force,
402
- * (b) the region node is UNRESOLVED (the default-country filter came up empty — a US region resolves fine under `US`,
403
- * so a well-formed US query never trips this), (c) the token is a subdivision of a DIFFERENT country than the default,
404
- * and (d) both the foreign region and a same-named foreign locality resolve. "Springfield, IL" / "Portland, ME": the
405
- * region resolves under `US`, so check (b) fails and the tree is untouched. Costs one region + one locality lookup per
406
- * 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.
407
290
  */
408
291
  export async function applyRegionCountryCoherence(
409
292
  roots: readonly AddressNode[],
410
293
  backend: ResolverBackend,
411
294
  defaultCountry: string | undefined
412
295
  ): Promise<void> {
413
- // No default country → no hard country filter was applied, so no region qualifier was discarded by one. The bug
414
- // this pass corrects is specific to the locale-inferred default country; without it, there is nothing to rescue.
415
296
  if (!defaultCountry) return
416
297
 
417
298
  const visit = async (node: AddressNode, regionAncestor: AddressNode | null): Promise<void> => {
418
- // Track the nearest region ancestor regardless of its resolution state (the trigger is an UNRESOLVED region).
419
299
  const regionHere = node.tag === "region" || node.tag === "subregion" ? node : regionAncestor
420
300
 
421
- // Fire for an UNRESOLVED region (the default-country filter came up empty) whose companion locality node
422
- // exists — regardless of the locality's resolution state, so it covers both the resolved-but-foreign namesake
423
- // (Montreal → the greedy US pick, Montreal WI) and the unresolved locality the span-rescore tier would
424
- // otherwise back-fill with a US namesake. The in-country lookups below are the evidence check.
425
301
  if (
426
302
  regionHere &&
427
303
  !isResolvedWithCoord(regionHere) &&
@@ -441,14 +317,6 @@ export async function applyRegionCountryCoherence(
441
317
  }
442
318
  }
443
319
 
444
- /**
445
- * Re-pick an (unresolved region, resolved-but-foreign-namesake locality) pair to the in-country instance the
446
- * default-country filter hid. `matchSubdivision` turns the region token into `{ name, country }` (null for anything
447
- * that isn't a US state or CA province → no-op); the region's full name then resolves it under that country (expanding
448
- * the abbreviation the gazetteer FTS index lacks), and the locality is re-scoped to the same country. Leaves both nodes
449
- * untouched unless every check holds — the subdivision names a different country than the default, the region resolves
450
- * under it, and a same-named locality exists there — so the domestic path stays byte-identical.
451
- */
452
320
  async function reconcileRegionCountry(
453
321
  regionNode: AddressNode,
454
322
  localityNode: AddressNode,
@@ -459,17 +327,12 @@ async function reconcileRegionCountry(
459
327
 
460
328
  if (!sub) return
461
329
 
462
- // The subdivision must belong to a DIFFERENT country than the locale default. A US-state token under a US default
463
- // (sub.country === defaultCountry) never reaches the swap — the pass is inert on the domestic path.
464
330
  if (sub.country.toUpperCase() === defaultCountry.toUpperCase()) return
465
331
 
466
- // The locality already resolved in the subdivision's country? Then the greedy walk was already right — byte-stable.
467
332
  const localityCountry = (localityNode.metadata?.["resolver_country"] as string | undefined)?.toUpperCase()
468
333
 
469
334
  if (localityCountry === sub.country.toUpperCase()) return
470
335
 
471
- // Confirm the subdivision genuinely resolves under its own country, by its full name (expands "QC" → "Quebec", the
472
- // form the FTS index carries). No resolvable region → no evidence the token is a real foreign subdivision; abstain.
473
336
  const regionScoped = await backend.findPlace({
474
337
  text: sub.name,
475
338
  placetype: "region",
@@ -481,8 +344,6 @@ async function reconcileRegionCountry(
481
344
 
482
345
  if (!rc) return
483
346
 
484
- // Is there a same-named locality under that country? (the descendant test, by country column — the same primitive
485
- // reconcileExplicitCountry uses.) No in-country namesake → keep the greedy result (fail-safe).
486
347
  const scoped = await backend.findPlace({
487
348
  text: localityNode.value,
488
349
  placetype: "locality",
@@ -494,7 +355,6 @@ async function reconcileRegionCountry(
494
355
 
495
356
  if (!lc) return
496
357
 
497
- // Adopt the in-country pair: the region gets the foreign subdivision, the locality its same-named foreign instance.
498
358
  decorateNode(
499
359
  regionNode,
500
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
17
  export function firstRegionQualifier(roots: readonly AddressNode[]): string | undefined {
26
- return firstNodeWhere(roots, (n) => n.tag === "region" && n.value.trim().length > 0)?.value.trim()
18
+ return firstNodeWhere(roots, (n) => n.tag === "region" && n.value.trim())?.value.trim()
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,11 +53,9 @@ 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
61
  candidates: ReadonlyArray<{ containedByQualifier?: boolean | undefined }>
@@ -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,12 +68,16 @@ 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
83
  Place extends { regionScopeMiss?: boolean },