@mailwoman/resolver 9.0.0 → 9.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 (79) hide show
  1. package/README.md +89 -0
  2. package/admin-coherence-passes.ts +435 -0
  3. package/admin-containment.ts +101 -0
  4. package/admin-winner.ts +178 -0
  5. package/backend-capabilities.ts +88 -0
  6. package/bare-toponym-race.ts +129 -0
  7. package/decorate-node.ts +127 -0
  8. package/fold-name.ts +19 -3
  9. package/index.ts +14 -0
  10. package/out/admin-coherence-passes.d.ts +70 -0
  11. package/out/admin-coherence-passes.d.ts.map +1 -0
  12. package/out/admin-coherence-passes.js +327 -0
  13. package/out/admin-coherence-passes.js.map +1 -0
  14. package/out/admin-containment.d.ts +48 -0
  15. package/out/admin-containment.d.ts.map +1 -0
  16. package/out/admin-containment.js +82 -0
  17. package/out/admin-containment.js.map +1 -0
  18. package/out/admin-winner.d.ts +109 -0
  19. package/out/admin-winner.d.ts.map +1 -0
  20. package/out/admin-winner.js +119 -0
  21. package/out/admin-winner.js.map +1 -0
  22. package/out/backend-capabilities.d.ts +37 -0
  23. package/out/backend-capabilities.d.ts.map +1 -0
  24. package/out/backend-capabilities.js +75 -0
  25. package/out/backend-capabilities.js.map +1 -0
  26. package/out/bare-toponym-race.d.ts +55 -0
  27. package/out/bare-toponym-race.d.ts.map +1 -0
  28. package/out/bare-toponym-race.js +110 -0
  29. package/out/bare-toponym-race.js.map +1 -0
  30. package/out/decorate-node.d.ts +24 -0
  31. package/out/decorate-node.d.ts.map +1 -0
  32. package/out/decorate-node.js +103 -0
  33. package/out/decorate-node.js.map +1 -0
  34. package/out/fold-name.d.ts +18 -3
  35. package/out/fold-name.d.ts.map +1 -1
  36. package/out/fold-name.js +19 -3
  37. package/out/fold-name.js.map +1 -1
  38. package/out/index.d.ts +4 -1
  39. package/out/index.d.ts.map +1 -1
  40. package/out/index.js +3 -1
  41. package/out/index.js.map +1 -1
  42. package/out/postcode-country-coherence.d.ts +91 -14
  43. package/out/postcode-country-coherence.d.ts.map +1 -1
  44. package/out/postcode-country-coherence.js +279 -42
  45. package/out/postcode-country-coherence.js.map +1 -1
  46. package/out/postcode-prefix.d.ts +101 -0
  47. package/out/postcode-prefix.d.ts.map +1 -0
  48. package/out/postcode-prefix.js +125 -0
  49. package/out/postcode-prefix.js.map +1 -0
  50. package/out/postcode-shape-coherence.d.ts +113 -0
  51. package/out/postcode-shape-coherence.d.ts.map +1 -0
  52. package/out/postcode-shape-coherence.js +193 -0
  53. package/out/postcode-shape-coherence.js.map +1 -0
  54. package/out/resolve.d.ts +1 -1
  55. package/out/resolve.d.ts.map +1 -1
  56. package/out/resolve.js +592 -410
  57. package/out/resolve.js.map +1 -1
  58. package/out/span-rescore.d.ts +28 -0
  59. package/out/span-rescore.d.ts.map +1 -1
  60. package/out/span-rescore.js +151 -17
  61. package/out/span-rescore.js.map +1 -1
  62. package/out/street-evidence.js +1 -1
  63. package/out/street-evidence.js.map +1 -1
  64. package/out/street-tier.d.ts.map +1 -1
  65. package/out/street-tier.js +28 -5
  66. package/out/street-tier.js.map +1 -1
  67. package/out/toponym-prior.d.ts +139 -0
  68. package/out/toponym-prior.d.ts.map +1 -0
  69. package/out/toponym-prior.js +308 -0
  70. package/out/toponym-prior.js.map +1 -0
  71. package/package.json +98 -7
  72. package/postcode-country-coherence.ts +355 -50
  73. package/postcode-prefix.ts +166 -0
  74. package/postcode-shape-coherence.ts +248 -0
  75. package/resolve.ts +809 -527
  76. package/span-rescore.ts +206 -19
  77. package/street-evidence.ts +1 -1
  78. package/street-tier.ts +31 -5
  79. package/toponym-prior.ts +367 -0
package/README.md ADDED
@@ -0,0 +1,89 @@
1
+ # @mailwoman/resolver
2
+
3
+ Walk a parsed `AddressTree` and decide, for each span, which real place it names — then hand back the tree with coordinates, attribution and ancestry stamped on it.
4
+
5
+ This is the half of [mailwoman](https://www.npmjs.com/package/mailwoman) that turns _"the model thinks this run of characters is a locality"_ into _"this is Springfield, Illinois, at 39.7973/-89.6455, and here is why."_ It owns the ranking, the coherence passes and the ordering rules; it owns no data. The gazetteer lives behind a `ResolverBackend` you supply.
6
+
7
+ ## Installation
8
+
9
+ ```bash
10
+ npm install @mailwoman/resolver
11
+ ```
12
+
13
+ ## Quick start
14
+
15
+ ```ts
16
+ import { createWOFResolver } from "@mailwoman/resolver"
17
+ import { WOFSQLitePlaceLookup } from "@mailwoman/resolver-wof-sqlite"
18
+
19
+ const backend = new WOFSQLitePlaceLookup({ databasePath: "/path/to/admin.db" })
20
+ const resolver = createWOFResolver(backend)
21
+
22
+ const decorated = await resolver.resolveTree(tree)
23
+ ```
24
+
25
+ `resolveTree` returns a new tree. Nodes that resolved carry `lat`/`lon`, a `placeID`, and `resolver_*` metadata; nodes that did not are returned untouched.
26
+
27
+ ## Backend-agnostic on purpose
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.
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 quietly no-ops on your backend says so instead of looking like a bad result.
32
+
33
+ ## Absence is a value
34
+
35
+ Two rules run through this package, and both exist because their opposites shipped bugs.
36
+
37
+ **A coordinate the gazetteer cannot supply is absent, never `0,0`.** `0,0` is the unlocated sentinel in every WOF-lineage shard, and the shards 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
+
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.
40
+
41
+ ## Which resolved place answers the query
42
+
43
+ `admin-winner.ts` owns one ordering, and it is the only one whose rungs are not fixed.
44
+
45
+ `PLACETYPE_SPECIFICITY` ranks placetypes by how much ground they cover, which is the right question for most of them and the wrong one for `postalcode`. A GB unit postcode covers ~15 addresses and is tighter than any locality centroid; a French _code postal_ often spans several communes and is coarser than the one you want. One number cannot be both.
46
+
47
+ So the rank of a resolved postcode is computed, from two independent routes:
48
+
49
+ ```ts
50
+ import { adminLadderForNodes, resolvedSpecificity } from "@mailwoman/resolver"
51
+
52
+ // Result assembly walks a tag ladder…
53
+ const ladder = adminLadderForNodes(nodes)
54
+
55
+ // …and a harness sorting resolved nodes by placetype asks the same question this way.
56
+ const rank = resolvedSpecificity({ placetype: "postalcode", value: "N7 0BT", resolverName: "n70bt" })
57
+ ```
58
+
59
+ 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
+
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.
62
+
63
+ 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
+
65
+ ## Coherence passes
66
+
67
+ Ranking a span in isolation gets Portland, Maine to Messina, Italy. These run over the whole tree:
68
+
69
+ | Pass | Question |
70
+ | ---------------------------- | ------------------------------------------------------------------------------ |
71
+ | `admin-coherence-passes` | Do the resolved places actually contain one another? |
72
+ | `postcode-country-coherence` | Does the postcode's shape agree with the country the rest of the tree implies? |
73
+ | `postcode-shape-coherence` | Is this span a postcode at all, in any system the query could be in? |
74
+ | `admin-containment` | Split candidates by whether they sit inside an established parent. |
75
+ | `span-rescore` | A resolved neighbour is evidence about an unresolved span. |
76
+ | `street-evidence` | A commune-scoped street hit is evidence of that street's locality. |
77
+ | `plausibility` | Is this answer outside the country it claims? |
78
+
79
+ ## Subpath exports
80
+
81
+ Import the barrel for the whole surface, or a subpath to take one piece without the rest:
82
+
83
+ `./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
+
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.
86
+
87
+ ## License
88
+
89
+ AGPL-3.0 — see the [repository](https://github.com/sister-software/mailwoman).
@@ -0,0 +1,435 @@
1
+ /**
2
+ * @copyright Sister Software
3
+ * @license AGPL-3.0
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
+ */
11
+
12
+ import { matchCountry, matchSubdivision } from "@mailwoman/codex/country"
13
+ import type { AddressNode } from "@mailwoman/core/decoder"
14
+ import type { ResolvedPlace, ResolverBackend } from "@mailwoman/core/resolver"
15
+
16
+ import { decorateNode, isResolvedWithCoord } from "./decorate-node.ts"
17
+
18
+ /**
19
+ * Admin descendant-consistency (#263) — the joint-consistency resolve, scoped to the admin assignment. The greedy walk
20
+ * resolves a region on its own (name + population), so "ME" picks Messina (IT) over Maine, then scopes "Portland" to
21
+ * Messina's descendants, finds nothing, and the result falls back to the region centroid (Sicily). The region's
22
+ * same-named runner-ups (Maine, Missouri, …) were already captured as `alternatives`; this pass asks the question the
23
+ * greedy order skipped — _which "ME" has a "Portland" under it?_ — and re-picks the (region, locality) pair where a
24
+ * same-named locality descends from a same-named region candidate. Geography decides; no country prior, no list.
25
+ *
26
+ * Fires ONLY for a resolved region whose child locality fell through (the unresolved-locality signal), so a
27
+ * well-resolved tree ("Springfield, IL" → Illinois, Springfield) is byte-identical. Costs one unscoped locality lookup
28
+ * per triggering pair. Needs {@link ResolverBackend.ancestors}; no-op without it. See `ResolveOpts.adminCoherence`.
29
+ */
30
+ export async function applyAdminCoherence(roots: readonly AddressNode[], backend: ResolverBackend): Promise<void> {
31
+ const visit = async (node: AddressNode, regionAncestor: AddressNode | null): Promise<void> => {
32
+ const regionHere = node.tag === "region" && isResolvedWithCoord(node) ? node : regionAncestor
33
+
34
+ if (
35
+ regionHere &&
36
+ (node.tag === "locality" || node.tag === "dependent_locality") &&
37
+ !isResolvedWithCoord(node) &&
38
+ node.value.trim().length
39
+ ) {
40
+ await reconcileAdminPair(regionHere, node, backend)
41
+ }
42
+
43
+ for (const child of node.children) {
44
+ await visit(child, regionHere)
45
+ }
46
+ }
47
+
48
+ for (const root of roots) {
49
+ await visit(root, null)
50
+ }
51
+ }
52
+
53
+ /**
54
+ * Re-pick a (region, locality) pair so the locality descends from the region. `alternatives` on the node are the
55
+ * `ResolvedPlace` runner-ups `decorateNode` attached (typed `unknown[]` in the decoder, which can't import resolver
56
+ * types — the cast is sound). Picks the FIRST same-named locality (already score-ordered) that descends from a
57
+ * same-named region candidate, then swaps both nodes. Leaves both untouched when no consistent pair exists (a genuinely
58
+ * un-gazetteered locality — "Portland, VT" with no Portland in Vermont — stays as the region centroid, not a foreign
59
+ * namesake).
60
+ */
61
+ async function reconcileAdminPair(
62
+ regionNode: AddressNode,
63
+ localityNode: AddressNode,
64
+ backend: ResolverBackend
65
+ ): Promise<void> {
66
+ // EXACT region matches only: the alternatives for a 2-letter token are loose ("ME" also surfaces
67
+ // Missouri/Michigan/Mississippi as fuzzy M-state runner-ups). Restricting to exact name/alias matches
68
+ // (Maine/Messina/Medway for "ME") keeps the join honest. `exactMatch` is stamped by exactMatchTiering.
69
+ const regionCands = ((regionNode.alternatives as ResolvedPlace[] | undefined) ?? []).filter((r) => r.exactMatch)
70
+
71
+ // For each exact region candidate, ask the gazetteer directly: is there a same-named locality UNDER it?
72
+ // The `parentID` scope is the descendant test (over the #832-repaired ancestors table), and it finds the
73
+ // instance regardless of its global population rank — "Springfield, ME" reaches the small Springfield in
74
+ // Maine that an unscoped top-N window would drop. First region with an exact-named descendant wins; the
75
+ // region candidates are score-ordered, so a tie breaks toward the more prominent place.
76
+ for (const region of regionCands) {
77
+ const scoped = await backend.findPlace({
78
+ text: localityNode.value,
79
+ placetype: "locality",
80
+ parentID: region.id,
81
+ limit: 3,
82
+ })
83
+
84
+ const lc = scoped.find((l) => l.exactMatch && !(l.lat === 0 && l.lon === 0))
85
+
86
+ if (lc) {
87
+ decorateNode(
88
+ regionNode,
89
+ region,
90
+ regionCands.filter((r) => r !== region)
91
+ )
92
+
93
+ regionNode.metadata = { ...regionNode.metadata, admin_coherence_repicked: true }
94
+
95
+ decorateNode(
96
+ localityNode,
97
+ lc,
98
+ scoped.filter((l) => l !== lc)
99
+ )
100
+
101
+ localityNode.metadata = { ...localityNode.metadata, admin_coherence_repicked: true }
102
+
103
+ return
104
+ }
105
+ }
106
+
107
+ // #267 follow-up: the token may name a COUNTRY whose namesake is a more-populous foreign region — "Tbilisi,
108
+ // Georgia" parses region("Georgia") → the US state, but Tbilisi descends from Georgia the COUNTRY. When no
109
+ // region candidate holds the locality, try same-named country candidates: a foreign capital under its
110
+ // country out-votes the state namesake. Needs the country + the locality's ancestry in the gazetteer (the
111
+ // #267 admin fold). The re-picked region node then carries the country place; the locality coordinate wins.
112
+ const countryCands = (await backend.findPlace({ text: regionNode.value, placetype: "country", limit: 3 })).filter(
113
+ (c) => c.exactMatch
114
+ )
115
+
116
+ for (const country of countryCands) {
117
+ const scoped = await backend.findPlace({
118
+ text: localityNode.value,
119
+ placetype: "locality",
120
+ parentID: country.id,
121
+ limit: 3,
122
+ })
123
+
124
+ const lc = scoped.find((l) => l.exactMatch && !(l.lat === 0 && l.lon === 0))
125
+
126
+ if (lc) {
127
+ decorateNode(regionNode, country, regionCands)
128
+ regionNode.metadata = { ...regionNode.metadata, admin_coherence_repicked: true }
129
+
130
+ decorateNode(
131
+ localityNode,
132
+ lc,
133
+ scoped.filter((l) => l !== lc)
134
+ )
135
+
136
+ localityNode.metadata = { ...localityNode.metadata, admin_coherence_repicked: true }
137
+
138
+ return
139
+ }
140
+ }
141
+
142
+ // #1023: the admin gazetteer may carry NO `country`-placetype node for the token AND the same-named
143
+ // foreign locality may be ORPHANED (parent_id = -1) — the 2026-07-07 rebuild flattened Georgia's admin
144
+ // hierarchy to localities-only, so the country-node lookup above finds nothing and the `parentID`
145
+ // descendant test can never reach Tbilisi. Fall back to matchCountry: normalize the token to an
146
+ // ISO-3166 alpha-2 and scope the locality by the gazetteer's `country` COLUMN (set even on an orphaned
147
+ // row). Same primitive reconcileExplicitCountry (#822) uses, so the region-parsed namesake path
148
+ // ("Tbilisi, Georgia") converges with the country-parsed one ("Vienna, Austria"). matchCountry returns
149
+ // null for a US state name/abbrev ("Illinois" / "ME" / "IL"), so a real US (region, locality) pair
150
+ // never reaches here — this stays inert on the domestic path.
151
+ const mc = matchCountry(regionNode.value)
152
+
153
+ if (mc) {
154
+ const scoped = await backend.findPlace({
155
+ text: localityNode.value,
156
+ placetype: "locality",
157
+ country: mc.iso2,
158
+ limit: 3,
159
+ })
160
+
161
+ const lc = scoped.find((l) => l.exactMatch && !(l.lat === 0 && l.lon === 0))
162
+
163
+ if (lc) {
164
+ decorateNode(
165
+ localityNode,
166
+ lc,
167
+ scoped.filter((l) => l !== lc)
168
+ )
169
+
170
+ localityNode.metadata = { ...localityNode.metadata, admin_coherence_repicked: true }
171
+ // The token named a foreign country the admin gazetteer has no node for, but the greedy walk had
172
+ // already decorated the region node with the US-state namesake. Revert that stale decoration so the
173
+ // node stops asserting the wrong-country coordinate + `resolver_country` (which would otherwise leak
174
+ // into the result's `countryCode`); the re-picked locality carries the winning coordinate, and the
175
+ // region node falls back to the parsed "Georgia" token, unresolved (the admin DB has nothing truer).
176
+ revertResolverDecoration(regionNode)
177
+ }
178
+ }
179
+ }
180
+
181
+ /**
182
+ * Undo a resolver decoration on a node: restore the classifier attribution {@link decorateNode} displaced into
183
+ * `metadata.classifier_source(_id)` and drop the resolver-supplied coordinate/identity/alternatives. Used by the #1023
184
+ * country fall-through when the region token turns out to name a foreign country the admin gazetteer holds no node for
185
+ * — the greedy walk had bound it to the US-state namesake, and that stale claim must not survive the locality re-pick.
186
+ */
187
+ function revertResolverDecoration(node: AddressNode): void {
188
+ const meta = { ...node.metadata }
189
+ const priorSource = meta["classifier_source"]
190
+ const priorSourceID = meta["classifier_source_id"]
191
+ node.source = typeof priorSource === "string" ? priorSource : undefined
192
+ node.sourceID = typeof priorSourceID === "string" ? priorSourceID : undefined
193
+
194
+ for (const key of [
195
+ "classifier_source",
196
+ "classifier_source_id",
197
+ "resolver_score",
198
+ "resolver_prominence",
199
+ "resolver_name",
200
+ "resolver_country",
201
+ "resolution_quality",
202
+ "postcode_city_mismatch",
203
+ ]) {
204
+ // oxlint-disable-next-line typescript/no-dynamic-delete -- removing one key from a plain record; the object is not on a hot path
205
+ delete meta[key]
206
+ }
207
+
208
+ node.metadata = meta
209
+ node.lat = undefined
210
+ node.lon = undefined
211
+ node.placeID = undefined
212
+ node.alternatives = undefined
213
+ }
214
+
215
+ /**
216
+ * Explicit-country coherence (#822) — the joint-consistency resolve keyed on the query's own EXPLICIT country token.
217
+ * The greedy walk resolves a locality on name + population alone, so "Vienna, Austria" picks the populous US namesake
218
+ * (Vienna WV) and IGNORES the "Austria" the address named. This pass asks the question the greedy order skipped —
219
+ * _which "Vienna" is in the country the address names?_ — and re-picks the locality to the same-named place under that
220
+ * country. The country code comes from the parser's OWN `country` emission via codex's ISO-3166 table (a name→code
221
+ * normalization of a token the model already classified, NOT a routing prior or safelist); the gazetteer's `country`
222
+ * column does the geographic confirmation. No pin, no list; generalizes to every country.
223
+ *
224
+ * Disjoint from {@link applyAdminCoherence} by the region guard: that pass owns the case where a REGION scopes the
225
+ * locality; this one fires only when the explicit country is the locality's nearest admin context (no region between),
226
+ * and then regardless of the locality's resolution state — so it covers both the resolved-but-foreign locality (Sydney
227
+ * → the greedy AU pick was wrong) and the unresolved locality the span-rescore tier would otherwise back-fill with the
228
+ * US namesake (Vienna → Vienna WV). Byte-stable when the locality already resolved in-country (the id guard) or the
229
+ * named country holds no same-named locality (the fail-safe — what also protects "Turkey, TX": no country token ⇒ no
230
+ * trigger; and an in-country lookup that finds nothing keeps the greedy result). Costs one country-scoped locality
231
+ * lookup per triggering pair. See `ResolveOpts.adminCoherence`.
232
+ */
233
+ export async function applyExplicitCountryCoherence(
234
+ roots: readonly AddressNode[],
235
+ backend: ResolverBackend
236
+ ): Promise<void> {
237
+ const visit = async (node: AddressNode, countryToken: AddressNode | null, regionAbove: boolean): Promise<void> => {
238
+ const countryHere = node.tag === "country" && node.value.trim().length ? node : countryToken
239
+
240
+ // A region suppresses the country re-pick only when it RESOLVED: the suppression's rationale is
241
+ // that applyAdminCoherence + the region's `parentID` scope already disambiguate the locality
242
+ // ("Springfield, IL" must not re-pick to the most populous US Springfield), and an UNRESOLVED
243
+ // region disambiguates nothing — 'NIC-38' (an ISO-3166-2 code the gazetteer holds no node for)
244
+ // silently swallowed the explicit 'Nicaragua', and El Sauce resolved a US namesake. This pass
245
+ // runs post-walk, so resolution state is known.
246
+ const regionHere = regionAbove || ((node.tag === "region" || node.tag === "subregion") && isResolvedWithCoord(node))
247
+
248
+ // Fire only when the explicit country is the locality's NEAREST RESOLVED admin context.
249
+ // Fires regardless of the locality's resolution state, so it PRE-EMPTS the span-rescore tier
250
+ // (which would otherwise back-fill the unresolved locality with the US namesake).
251
+ if (countryHere && !regionHere && (node.tag === "locality" || node.tag === "dependent_locality")) {
252
+ await reconcileExplicitCountry(countryHere, node, backend)
253
+ }
254
+
255
+ for (const child of node.children) {
256
+ await visit(child, countryHere, regionHere)
257
+ }
258
+ }
259
+
260
+ for (const root of roots) {
261
+ await visit(root, null, false)
262
+ }
263
+ }
264
+
265
+ /**
266
+ * Re-pick a resolved locality to its same-named place UNDER the explicitly-named country. `matchCountry` turns the
267
+ * country token into an ISO-3166 alpha-2 (returns null for an unrecognized token → no-op); the backend then surfaces
268
+ * the in-country namesake the population-first unscoped window buried. Leaves the node untouched when the country is
269
+ * unrecognized, the named country has no exact same-named locality (the fail-safe), or the locality already resolved to
270
+ * that place (the id guard → byte-stable). The country node itself stays as the parser emitted it — the named
271
+ * well-covered countries carry no `country`-placetype row in the admin gazetteer, so there is nothing to decorate it
272
+ * with; the locality coordinate is what the re-pick fixes.
273
+ */
274
+ async function reconcileExplicitCountry(
275
+ countryNode: AddressNode,
276
+ localityNode: AddressNode,
277
+ backend: ResolverBackend
278
+ ): Promise<void> {
279
+ const mc = matchCountry(countryNode.value)
280
+
281
+ if (!mc) return
282
+
283
+ const scoped = await backend.findPlace({
284
+ text: localityNode.value,
285
+ placetype: "locality",
286
+ country: mc.iso2,
287
+ limit: 3,
288
+ })
289
+
290
+ const lc = scoped.find((l) => l.exactMatch && !(l.lat === 0 && l.lon === 0))
291
+
292
+ if (!lc) return
293
+
294
+ // Already the in-country place? (placeID encodes the WOF id.) Then the greedy walk was right — byte-stable.
295
+ if (localityNode.placeID === `wof:${lc.id}`) return
296
+
297
+ decorateNode(
298
+ localityNode,
299
+ lc,
300
+ scoped.filter((l) => l !== lc)
301
+ )
302
+
303
+ localityNode.metadata = { ...localityNode.metadata, explicit_country_repicked: true }
304
+ }
305
+
306
+ /**
307
+ * Region-country coherence — the joint-consistency resolve keyed on a REGION token the locale-inferred default-country
308
+ * filter could not resolve. Companion to {@link applyExplicitCountryCoherence} (which keys on an explicit COUNTRY token)
309
+ * and disjoint from {@link applyAdminCoherence} (which needs a region that DID resolve): this pass owns the mirror case,
310
+ * where the region qualifier is a foreign subdivision the default-country hard filter (`spr.country = ?`) discarded.
311
+ *
312
+ * "Montreal QC" under a US locale: the walk applies `defaultCountry="US"` as a hard candidate filter to every admin
313
+ * lookup, so the region "QC" (a Canadian subdivision) resolves to nothing and is dropped — the one signal that would
314
+ * redirect the country to CA — and the locality "Montreal" is force-matched to the populous US namesake (Montreal, WI).
315
+ * The greedy order threw away the evidence that could correct it.
316
+ *
317
+ * The fix expands the region token to its country via codex's ISO-3166-2 subdivision table (`matchSubdivision`: "QC" →
318
+ * `{ name: "Quebec", country: "CA" }`, handling the FTS index's missing "QC" alt-name code-side), then asks the two
319
+ * questions the greedy walk skipped: does that subdivision genuinely resolve UNDER its own country, and is there a
320
+ * same-named locality under it? Only when BOTH hold does it swap the region and locality to the in-country pair.
321
+ * Geography confirms; the subdivision table is a soft name→country prior, not a routing decision.
322
+ *
323
+ * Evidence-gated to stay byte-stable on the domestic path. It fires ONLY when (a) a default country is in force, (b)
324
+ * the region node is UNRESOLVED (the default-country filter came up empty — a US region resolves fine under `US`, so a
325
+ * well-formed US query never trips this), (c) the token is a subdivision of a DIFFERENT country than the default, and
326
+ * (d) both the foreign region and a same-named foreign locality resolve. "Springfield, IL" / "Portland, ME": the region
327
+ * resolves under `US`, so gate (b) fails and the tree is untouched. Costs one region + one locality lookup per
328
+ * triggering pair. See `ResolveOpts.adminCoherence`.
329
+ */
330
+ export async function applyRegionCountryCoherence(
331
+ roots: readonly AddressNode[],
332
+ backend: ResolverBackend,
333
+ defaultCountry: string | undefined
334
+ ): Promise<void> {
335
+ // No default country → no hard country filter was applied, so no region qualifier was discarded by one. The bug
336
+ // this pass corrects is specific to the locale-inferred default country; without it, there is nothing to rescue.
337
+ if (!defaultCountry) return
338
+
339
+ const visit = async (node: AddressNode, regionAncestor: AddressNode | null): Promise<void> => {
340
+ // Track the nearest region ancestor regardless of its resolution state (the trigger is an UNRESOLVED region).
341
+ const regionHere = node.tag === "region" || node.tag === "subregion" ? node : regionAncestor
342
+
343
+ // Fire for an UNRESOLVED region (the default-country filter came up empty) whose companion locality node
344
+ // exists — regardless of the locality's resolution state, so it covers both the resolved-but-foreign namesake
345
+ // (Montreal → the greedy US pick, Montreal WI) and the unresolved locality the span-rescore tier would
346
+ // otherwise back-fill with a US namesake. The in-country lookups below are the evidence gate.
347
+ if (
348
+ regionHere &&
349
+ !isResolvedWithCoord(regionHere) &&
350
+ (node.tag === "locality" || node.tag === "dependent_locality") &&
351
+ node.value.trim().length
352
+ ) {
353
+ await reconcileRegionCountry(regionHere, node, backend, defaultCountry)
354
+ }
355
+
356
+ for (const child of node.children) {
357
+ await visit(child, regionHere)
358
+ }
359
+ }
360
+
361
+ for (const root of roots) {
362
+ await visit(root, null)
363
+ }
364
+ }
365
+
366
+ /**
367
+ * Re-pick an (unresolved region, resolved-but-foreign-namesake locality) pair to the in-country instance the
368
+ * default-country filter hid. `matchSubdivision` turns the region token into `{ name, country }` (null for anything
369
+ * that isn't a US state or CA province → no-op); the region's full name then resolves it under that country (expanding
370
+ * the abbreviation the gazetteer FTS index lacks), and the locality is re-scoped to the same country. Leaves both nodes
371
+ * untouched unless every gate holds — the subdivision names a different country than the default, the region resolves
372
+ * under it, and a same-named locality exists there — so the domestic path stays byte-identical.
373
+ */
374
+ async function reconcileRegionCountry(
375
+ regionNode: AddressNode,
376
+ localityNode: AddressNode,
377
+ backend: ResolverBackend,
378
+ defaultCountry: string
379
+ ): Promise<void> {
380
+ const sub = matchSubdivision(regionNode.value)
381
+
382
+ if (!sub) return
383
+
384
+ // The subdivision must belong to a DIFFERENT country than the locale default. A US-state token under a US default
385
+ // (sub.country === defaultCountry) never reaches the swap — the pass is inert on the domestic path.
386
+ if (sub.country.toUpperCase() === defaultCountry.toUpperCase()) return
387
+
388
+ // The locality already resolved in the subdivision's country? Then the greedy walk was already right — byte-stable.
389
+ const localityCountry = (localityNode.metadata?.["resolver_country"] as string | undefined)?.toUpperCase()
390
+
391
+ if (localityCountry === sub.country.toUpperCase()) return
392
+
393
+ // Confirm the subdivision genuinely resolves under its own country, by its full name (expands "QC" → "Quebec", the
394
+ // form the FTS index carries). No resolvable region → no evidence the token is a real foreign subdivision; abstain.
395
+ const regionScoped = await backend.findPlace({
396
+ text: sub.name,
397
+ placetype: "region",
398
+ country: sub.country,
399
+ limit: 3,
400
+ })
401
+
402
+ const rc = regionScoped.find((r) => r.exactMatch && !(r.lat === 0 && r.lon === 0))
403
+
404
+ if (!rc) return
405
+
406
+ // Is there a same-named locality under that country? (the descendant test, by country column — the same primitive
407
+ // reconcileExplicitCountry uses.) No in-country namesake → keep the greedy result (fail-safe).
408
+ const scoped = await backend.findPlace({
409
+ text: localityNode.value,
410
+ placetype: "locality",
411
+ country: sub.country,
412
+ limit: 3,
413
+ })
414
+
415
+ const lc = scoped.find((l) => l.exactMatch && !(l.lat === 0 && l.lon === 0))
416
+
417
+ if (!lc) return
418
+
419
+ // Adopt the in-country pair: the region gets the foreign subdivision, the locality its same-named foreign instance.
420
+ decorateNode(
421
+ regionNode,
422
+ rc,
423
+ regionScoped.filter((r) => r !== rc)
424
+ )
425
+
426
+ regionNode.metadata = { ...regionNode.metadata, region_country_repicked: true }
427
+
428
+ decorateNode(
429
+ localityNode,
430
+ lc,
431
+ scoped.filter((l) => l !== lc)
432
+ )
433
+
434
+ localityNode.metadata = { ...localityNode.metadata, region_country_repicked: true }
435
+ }
@@ -0,0 +1,101 @@
1
+ /**
2
+ * @copyright Sister Software
3
+ * @license AGPL-3.0
4
+ * @author Teffen Ellis, et al.
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 lever loses exactly where fame
13
+ * disagrees with the qualifier). Two call sites, one function, one ordering.
14
+ */
15
+
16
+ import type { AddressNode } from "@mailwoman/core/decoder"
17
+
18
+ /**
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 lever'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.
24
+ */
25
+ export function firstRegionQualifier(roots: readonly AddressNode[]): string | undefined {
26
+ const stack = [...roots]
27
+
28
+ while (stack.length) {
29
+ const n = stack.pop()!
30
+
31
+ if (n.tag === "region" && n.value.trim().length) return n.value.trim()
32
+ stack.push(...n.children)
33
+ }
34
+
35
+ return undefined
36
+ }
37
+
38
+ /**
39
+ * Stable, TIER-SAFE partition: within each match tier, candidates the containment source vouched for (`isContained`)
40
+ * move ahead of the rest, and BOTH groups keep their incoming relative order — the same house rules every soft ranking
41
+ * key here obeys (`toponym-prior.ts`): tier-safe (a contained partial match never outranks an exact one — `isExact`
42
+ * splits the population exactly as `rankWithinTier`'s tri-state rule does, only a stated exact tier earns the front),
43
+ * positive-evidence-only (only a stated `true` moves a row; `false` and "never evaluated" both hold their incoming
44
+ * rank, so an incapable backend is a no-op by construction), and stable (the backend's own ordering survives within
45
+ * each (tier, containment) cell).
46
+ *
47
+ * Implemented with the slot idiom (`reorderMeasured`'s mechanics): each tier's members permute only among the positions
48
+ * that tier already occupies, so a tier-interleaved list — the walk's no-importance path never regrouped tiers — cannot
49
+ * have a rest-tier row promoted across an exact-tier boundary by this partition.
50
+ */
51
+ export function partitionByContainment<T>(
52
+ rows: readonly T[],
53
+ isContained: (row: T) => boolean,
54
+ isExact: (row: T) => boolean
55
+ ): T[] {
56
+ const out = [...rows]
57
+
58
+ for (const wantExact of [true, false]) {
59
+ const slots: number[] = []
60
+
61
+ for (const [index, row] of out.entries()) {
62
+ if (isExact(row) === wantExact) {
63
+ slots.push(index)
64
+ }
65
+ }
66
+
67
+ if (slots.length < 2) continue
68
+
69
+ const members = slots.map((slot) => out[slot]!)
70
+ const reordered = [...members.filter((row) => isContained(row)), ...members.filter((row) => !isContained(row))]
71
+
72
+ for (const [k, slot] of slots.entries()) {
73
+ out[slot] = reordered[k]!
74
+ }
75
+ }
76
+
77
+ return out
78
+ }
79
+
80
+ /**
81
+ * The trace verdict for one locality pick under the lever — stamped as `metadata.admin_containment` so an inert
82
+ * mechanism is visible in the result rather than silently dead (#1719's rule). Derived from the candidates'
83
+ * `containedByQualifier` stamps: any `true` → `"contained"`; stamps present but none true → `"no_contained_candidate"`;
84
+ * no stamps at all → `"unavailable"` (the backend or artifact cannot answer — a pre-sidecar candidate.db, the FTS or
85
+ * browser backend, or a qualifier the probe never ran for).
86
+ */
87
+ export function adminContainmentVerdict(
88
+ candidates: ReadonlyArray<{ containedByQualifier?: boolean | undefined }>
89
+ ): "contained" | "no_contained_candidate" | "unavailable" {
90
+ let evaluated = false
91
+
92
+ for (const candidate of candidates) {
93
+ if (candidate.containedByQualifier === true) return "contained"
94
+
95
+ if (candidate.containedByQualifier !== undefined) {
96
+ evaluated = true
97
+ }
98
+ }
99
+
100
+ return evaluated ? "no_contained_candidate" : "unavailable"
101
+ }