@mailwoman/resolver 9.1.0 → 9.3.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 (142) hide show
  1. package/README.md +89 -0
  2. package/lib/admin/coherence-passes.ts +435 -0
  3. package/lib/admin/containment.ts +92 -0
  4. package/lib/admin/index.ts +10 -0
  5. package/lib/admin/jp-municipality.ts +97 -0
  6. package/lib/admin/winner.ts +189 -0
  7. package/lib/backend-capabilities.ts +88 -0
  8. package/lib/bare-toponym-race.ts +129 -0
  9. package/lib/decorate-node.ts +127 -0
  10. package/lib/fold-name.ts +36 -0
  11. package/{index.ts → lib/index.ts} +27 -18
  12. package/{plausibility.ts → lib/plausibility.ts} +5 -4
  13. package/{postcode-country-coherence.ts → lib/postcode/country-coherence.ts} +173 -86
  14. package/lib/postcode/index.ts +9 -0
  15. package/{postcode-prefix.ts → lib/postcode/prefix.ts} +7 -6
  16. package/{postcode-shape-coherence.ts → lib/postcode/shape-coherence.ts} +10 -24
  17. package/{remote-resolver.ts → lib/remote-resolver.ts} +13 -4
  18. package/{rerank.ts → lib/rerank.ts} +2 -2
  19. package/lib/resolve/index.ts +982 -0
  20. package/lib/resolve/passes.ts +544 -0
  21. package/{span-rescore.ts → lib/span-rescore.ts} +114 -99
  22. package/{street-evidence.ts → lib/street/evidence.ts} +40 -7
  23. package/lib/street/index.ts +8 -0
  24. package/{street-tier.ts → lib/street/tier.ts} +138 -99
  25. package/{toponym-prior.ts → lib/toponym-prior.ts} +97 -8
  26. package/out/admin/coherence-passes.d.ts +70 -0
  27. package/out/admin/coherence-passes.d.ts.map +1 -0
  28. package/out/admin/coherence-passes.js +327 -0
  29. package/out/admin/coherence-passes.js.map +1 -0
  30. package/out/admin/containment.d.ts +48 -0
  31. package/out/admin/containment.d.ts.map +1 -0
  32. package/out/admin/containment.js +76 -0
  33. package/out/admin/containment.js.map +1 -0
  34. package/out/admin/index.d.ts +10 -0
  35. package/out/admin/index.d.ts.map +1 -0
  36. package/out/admin/index.js +10 -0
  37. package/out/admin/index.js.map +1 -0
  38. package/out/admin/jp-municipality.d.ts +50 -0
  39. package/out/admin/jp-municipality.d.ts.map +1 -0
  40. package/out/admin/jp-municipality.js +54 -0
  41. package/out/admin/jp-municipality.js.map +1 -0
  42. package/out/admin/winner.d.ts +114 -0
  43. package/out/admin/winner.d.ts.map +1 -0
  44. package/out/admin/winner.js +130 -0
  45. package/out/admin/winner.js.map +1 -0
  46. package/out/backend-capabilities.d.ts +37 -0
  47. package/out/backend-capabilities.d.ts.map +1 -0
  48. package/out/backend-capabilities.js +75 -0
  49. package/out/backend-capabilities.js.map +1 -0
  50. package/out/bare-toponym-race.d.ts +55 -0
  51. package/out/bare-toponym-race.d.ts.map +1 -0
  52. package/out/bare-toponym-race.js +110 -0
  53. package/out/bare-toponym-race.js.map +1 -0
  54. package/out/decorate-node.d.ts +24 -0
  55. package/out/decorate-node.d.ts.map +1 -0
  56. package/out/decorate-node.js +103 -0
  57. package/out/decorate-node.js.map +1 -0
  58. package/out/fold-name.d.ts +18 -3
  59. package/out/fold-name.d.ts.map +1 -1
  60. package/out/fold-name.js +19 -3
  61. package/out/fold-name.js.map +1 -1
  62. package/out/index.d.ts +15 -12
  63. package/out/index.d.ts.map +1 -1
  64. package/out/index.js +9 -7
  65. package/out/index.js.map +1 -1
  66. package/out/plausibility.d.ts +5 -4
  67. package/out/plausibility.d.ts.map +1 -1
  68. package/out/plausibility.js +5 -4
  69. package/out/plausibility.js.map +1 -1
  70. package/out/{postcode-country-coherence.d.ts → postcode/country-coherence.d.ts} +46 -25
  71. package/out/postcode/country-coherence.d.ts.map +1 -0
  72. package/out/{postcode-country-coherence.js → postcode/country-coherence.js} +157 -77
  73. package/out/postcode/country-coherence.js.map +1 -0
  74. package/out/postcode/index.d.ts +9 -0
  75. package/out/postcode/index.d.ts.map +1 -0
  76. package/out/postcode/index.js +9 -0
  77. package/out/postcode/index.js.map +1 -0
  78. package/out/{postcode-prefix.d.ts → postcode/prefix.d.ts} +4 -4
  79. package/out/postcode/prefix.d.ts.map +1 -0
  80. package/out/{postcode-prefix.js → postcode/prefix.js} +7 -6
  81. package/out/postcode/prefix.js.map +1 -0
  82. package/out/{postcode-shape-coherence.d.ts → postcode/shape-coherence.d.ts} +3 -3
  83. package/out/postcode/shape-coherence.d.ts.map +1 -0
  84. package/out/{postcode-shape-coherence.js → postcode/shape-coherence.js} +11 -20
  85. package/out/postcode/shape-coherence.js.map +1 -0
  86. package/out/remote-resolver.d.ts +18 -3
  87. package/out/remote-resolver.d.ts.map +1 -1
  88. package/out/remote-resolver.js +2 -2
  89. package/out/remote-resolver.js.map +1 -1
  90. package/out/rerank.d.ts +1 -1
  91. package/out/rerank.d.ts.map +1 -1
  92. package/out/rerank.js +2 -2
  93. package/out/rerank.js.map +1 -1
  94. package/out/{resolve.d.ts → resolve/index.d.ts} +2 -2
  95. package/out/resolve/index.d.ts.map +1 -0
  96. package/out/resolve/index.js +795 -0
  97. package/out/resolve/index.js.map +1 -0
  98. package/out/resolve/passes.d.ts +218 -0
  99. package/out/resolve/passes.d.ts.map +1 -0
  100. package/out/resolve/passes.js +333 -0
  101. package/out/resolve/passes.js.map +1 -0
  102. package/out/span-rescore.d.ts +16 -16
  103. package/out/span-rescore.d.ts.map +1 -1
  104. package/out/span-rescore.js +87 -71
  105. package/out/span-rescore.js.map +1 -1
  106. package/out/{street-evidence.d.ts → street/evidence.d.ts} +18 -3
  107. package/out/street/evidence.d.ts.map +1 -0
  108. package/out/{street-evidence.js → street/evidence.js} +23 -7
  109. package/out/street/evidence.js.map +1 -0
  110. package/out/street/index.d.ts +8 -0
  111. package/out/street/index.d.ts.map +1 -0
  112. package/out/street/index.js +8 -0
  113. package/out/street/index.js.map +1 -0
  114. package/out/{street-tier.d.ts → street/tier.d.ts} +14 -3
  115. package/out/street/tier.d.ts.map +1 -0
  116. package/out/{street-tier.js → street/tier.js} +127 -90
  117. package/out/street/tier.js.map +1 -0
  118. package/out/toponym-prior.d.ts +43 -19
  119. package/out/toponym-prior.d.ts.map +1 -1
  120. package/out/toponym-prior.js +76 -8
  121. package/out/toponym-prior.js.map +1 -1
  122. package/package.json +167 -19
  123. package/vitest.config.ts +5 -6
  124. package/fold-name.ts +0 -20
  125. package/out/postcode-country-coherence.d.ts.map +0 -1
  126. package/out/postcode-country-coherence.js.map +0 -1
  127. package/out/postcode-prefix.d.ts.map +0 -1
  128. package/out/postcode-prefix.js.map +0 -1
  129. package/out/postcode-shape-coherence.d.ts.map +0 -1
  130. package/out/postcode-shape-coherence.js.map +0 -1
  131. package/out/resolve.d.ts.map +0 -1
  132. package/out/resolve.js +0 -1049
  133. package/out/resolve.js.map +0 -1
  134. package/out/street-evidence.d.ts.map +0 -1
  135. package/out/street-evidence.js.map +0 -1
  136. package/out/street-tier.d.ts.map +0 -1
  137. package/out/street-tier.js.map +0 -1
  138. package/out/vitest.config.d.ts +0 -16
  139. package/out/vitest.config.d.ts.map +0 -1
  140. package/out/vitest.config.js +0 -36
  141. package/out/vitest.config.js.map +0 -1
  142. package/resolve.ts +0 -1369
@@ -13,11 +13,10 @@
13
13
  */
14
14
 
15
15
  import { isStreetDirectionalToken } from "@mailwoman/codex/us"
16
- import type { AddressNode } from "@mailwoman/core/decoder"
16
+ import { collectNodes, walkNodes, type AddressNode } from "@mailwoman/core/decoder"
17
17
  import type { AddressPointLookup, InterpolationLookup, StreetCentroidLookup } from "@mailwoman/core/resolver"
18
- import { haversineKm } from "@mailwoman/spatial"
19
18
 
20
- import { foldName } from "./fold-name.ts"
19
+ import { foldName } from "#fold-name"
21
20
 
22
21
  /**
23
22
  * Street-name component tags that, with the street node itself, reconstruct the full street string.
@@ -27,27 +26,16 @@ const STREET_NAME_TAGS = new Set(["street", "street_prefix", "street_prefix_part
27
26
  /**
28
27
  * Reassemble the full street string from the street node's subtree (#483 coverage fix). The parser nests the
29
28
  * directional/suffix as `street_prefix`/`street_suffix` CHILDREN of `street` (containment.ts), so `street.value` alone
30
- * is the bare base name ("Sheldon" for "East Sheldon Rd") — which misses the coordinate shards keyed on the FULL
29
+ * is the bare base name ("Sheldon" for "East Sheldon Rd") — which misses the coordinate extracts keyed on the FULL
31
30
  * normalized name. Collect street + its prefix/particle/suffix descendants (NOT house_number/unit, which also nest
32
31
  * under street), order by span offset, and join.
33
32
  */
34
33
  function assembleStreetValue(streetNode: AddressNode, directionalUnit?: AddressNode): string {
35
- const parts: AddressNode[] = []
36
- const stack = [streetNode]
37
-
38
- while (stack.length) {
39
- const n = stack.pop()!
40
-
41
- if (STREET_NAME_TAGS.has(n.tag) && n.value.trim()) {
42
- parts.push(n)
43
- }
44
-
45
- stack.push(...n.children)
46
- }
34
+ const parts = collectNodes([streetNode], (n) => STREET_NAME_TAGS.has(n.tag) && n.value.trim().length > 0)
47
35
 
48
36
  // #718 admin-tail: a directional quadrant the model mis-tagged `unit` ("1532 Taylor Street NE" →
49
37
  // [unit] "NE") folds back into the street key by span order, so the situs/interp lookup matches the
50
- // shard's "taylor street northeast" (the lookup normalizer expands the abbreviation). Lookup-key
38
+ // extract's "taylor street northeast" (the lookup normalizer expands the abbreviation). Lookup-key
51
39
  // only — the parse output and admin resolution are untouched. Byte-stable when absent (undefined).
52
40
  if (directionalUnit && directionalUnit.value.trim()) {
53
41
  parts.push(directionalUnit)
@@ -62,7 +50,7 @@ function assembleStreetValue(streetNode: AddressNode, directionalUnit?: AddressN
62
50
  * Directional quadrant values the model sometimes emits as a `unit` node instead of inside the street subtree (#718
63
51
  * admin-tail diagnostic: ~19% of the admin-fallback tail, 83% of DC). Folded into the street lookup key by
64
52
  * {@link assembleStreetValue}; the situs/interp lookup normalizer expands the abbreviation ("ne" → "northeast") so the
65
- * shard's full street name matches.
53
+ * extract's full street name matches.
66
54
  */
67
55
  // The 8 USPS cardinals/intercardinals (abbrev or name) — @codex/us owns the canonical table (#215).
68
56
  const isDirectionalUnit = (value: string): boolean => isStreetDirectionalToken(value.replaceAll(".", ""))
@@ -80,47 +68,69 @@ const isDirectionalUnit = (value: string): boolean => isStreetDirectionalToken(v
80
68
  */
81
69
  const LOCALITY_BBOX_RADIUS_DEG = 0.25
82
70
 
83
- export function applyAddressPoint(roots: AddressNode[], lookup: AddressPointLookup, bboxFallback?: boolean): void {
84
- let street: AddressNode | undefined
85
- let houseNumber: AddressNode | undefined
86
- let directionalUnit: AddressNode | undefined
87
- let localityNode: AddressNode | undefined
88
- let locality: string | undefined
89
- let postcode: string | undefined
90
- const stack = [...roots]
91
-
92
- while (stack.length) {
93
- const n = stack.pop()!
94
-
95
- if (n.tag === "street" && !street) {
96
- street = n
71
+ /**
72
+ * Every `(street, house_number)` pair the tree offers, nearest pair first: the house number whose span sits closest to
73
+ * the street's, a number BEFORE the street winning a tie. A venue-led string parses more than one of each — `Bar 1802,
74
+ * 22 Rue Pascal, 75005 Paris, France` carries two house numbers and one street, and `22` is the one written beside `Rue
75
+ * Pascal`. The tiers probe the pairs in this order and stop at the first register hit, and the pair that hit is what
76
+ * the result names; a walk that took "the first node of each tag" paired whatever the traversal met first.
77
+ */
78
+ export function streetNumberPairs(
79
+ roots: readonly AddressNode[]
80
+ ): Array<{ street: AddressNode; houseNumber: AddressNode }> {
81
+ const streets: AddressNode[] = []
82
+ const numbers: AddressNode[] = []
83
+
84
+ for (const node of walkNodes(roots)) {
85
+ if (node.tag === "street") {
86
+ streets.push(node)
97
87
  }
98
88
 
99
- if (n.tag === "house_number" && !houseNumber) {
100
- houseNumber = n
89
+ if (node.tag === "house_number") {
90
+ numbers.push(node)
101
91
  }
92
+ }
102
93
 
103
- if (n.tag === "unit" && !directionalUnit && isDirectionalUnit(n.value)) {
104
- directionalUnit = n
105
- }
94
+ const pairs = streets.flatMap((street) => numbers.map((houseNumber) => ({ street, houseNumber })))
106
95
 
107
- if (n.tag === "locality" && !localityNode && n.value.trim()) {
108
- localityNode = n
109
- locality = n.value.trim()
110
- }
96
+ return pairs.toSorted((a, b) => pairGap(a) - pairGap(b))
97
+ }
111
98
 
112
- if (n.tag === "postcode" && !postcode && n.value.trim()) {
113
- postcode = n.value.trim()
114
- }
99
+ /**
100
+ * Characters between a house number and its street; a number after the street costs one extra so the tie goes to the
101
+ * number written before it, the order every Latin-script address system this resolver serves writes.
102
+ */
103
+ function pairGap(pair: { street: AddressNode; houseNumber: AddressNode }): number {
104
+ const { street, houseNumber } = pair
105
+
106
+ if (houseNumber.end <= street.start) return street.start - houseNumber.end
107
+
108
+ return houseNumber.start - street.end + 1
109
+ }
115
110
 
116
- stack.push(...n.children)
111
+ /**
112
+ * The first node of `tag` in document order whose value is non-blank, when the tree carries one.
113
+ */
114
+ function firstOfTag(roots: readonly AddressNode[], tag: AddressNode["tag"]): AddressNode | undefined {
115
+ for (const node of walkNodes(roots)) {
116
+ if (node.tag === tag && node.value.trim()) return node
117
117
  }
118
118
 
119
- if (!street || !houseNumber) return
119
+ return undefined
120
+ }
121
+
122
+ export function applyAddressPoint(roots: AddressNode[], lookup: AddressPointLookup, bboxFallback?: boolean): void {
123
+ const pairs = streetNumberPairs(roots)
124
+ const directionalUnit = [...walkNodes(roots)].find((n) => n.tag === "unit" && isDirectionalUnit(n.value))
125
+ const localityNode = firstOfTag(roots, "locality")
126
+ const locality = localityNode?.value.trim()
127
+ const postcode = firstOfTag(roots, "postcode")?.value.trim()
128
+
129
+ if (!pairs.length) return
120
130
 
121
- if (street.metadata?.["resolution_tier"] === "address_point") return
131
+ if (pairs.some((pair) => pair.street.metadata?.["resolution_tier"] === "address_point")) return
122
132
 
123
- // #247 OSM bbox fall-through: when enabled (an OSM shard is wired) and the locality resolved to a
133
+ // #247 OSM bbox fall-through: when enabled (an OSM extract is wired) and the locality resolved to a
124
134
  // coordinate, scope a final `(street, number)` probe by the locality's box — recovering OSM points that
125
135
  // carry no postcode/locality tag of their own. US situs never enables it, so its probes are byte-identical.
126
136
  let bbox: { minLat: number; maxLat: number; minLon: number; maxLon: number } | undefined
@@ -134,26 +144,51 @@ export function applyAddressPoint(roots: AddressNode[], lookup: AddressPointLook
134
144
  }
135
145
  }
136
146
 
137
- const hit = lookup.find({
138
- street: assembleStreetValue(street, directionalUnit),
139
- number: houseNumber.value,
140
- postcode,
141
- locality,
142
- bbox,
143
- })
147
+ let street: AddressNode | undefined
148
+ let houseNumber: AddressNode | undefined
149
+ let hit: ReturnType<AddressPointLookup["find"]> | undefined
150
+
151
+ for (const pair of pairs) {
152
+ hit = lookup.find({
153
+ street: assembleStreetValue(pair.street, directionalUnit),
154
+ number: pair.houseNumber.value,
155
+ postcode,
156
+ locality,
157
+ bbox,
158
+ })
159
+
160
+ if (hit) {
161
+ street = pair.street
162
+ houseNumber = pair.houseNumber
163
+
164
+ break
165
+ }
166
+ }
167
+
168
+ if (!hit || !street || !houseNumber) return
144
169
 
145
- if (!hit) return
170
+ // The number the register answered for is the one the result names (tree-shape.ts `slotNodes` reads the stamp).
171
+ houseNumber.metadata = { ...houseNumber.metadata, resolution_tier: "address_point" }
146
172
 
147
173
  street.metadata = {
148
174
  ...street.metadata,
149
- address_point: { lat: hit.lat, lon: hit.lon, source: hit.source, release: hit.release },
175
+ address_point: {
176
+ lat: hit.lat,
177
+ lon: hit.lon,
178
+ source: hit.source,
179
+ release: hit.release,
180
+ // The register row's OWN scope tags, when carried — a rooftop consumer can decorate the
181
+ // commune/postcode the register attests even when the query never named them.
182
+ ...(hit.localityNorm ? { locality_norm: hit.localityNorm } : {}),
183
+ ...(hit.postcode ? { postcode: hit.postcode } : {}),
184
+ },
150
185
  resolution_tier: "address_point",
151
186
  }
152
187
  }
153
188
 
154
189
  /**
155
190
  * House-number interpolation tier (#483): the third rung, consulted ONLY when the exact address-point tier
156
- * ({@link applyAddressPoint}) did NOT already stamp the street node (`resolution_tier === "address_point"`). That gate
191
+ * ({@link applyAddressPoint}) did NOT already stamp the street node (`resolution_tier === "address_point"`). That check
157
192
  * IS the "after the exact-point fall-through" — an estimate never overwrites a real situs point. Postcode-scoped (no
158
193
  * locality — the interpolators abstain statewide without a postcode). Stamps a DISTINCT metadata key
159
194
  * (`interpolated_point`, never `address_point`). Additive only — admin resolution is untouched.
@@ -163,45 +198,50 @@ export function applyInterpolation(
163
198
  lookup: InterpolationLookup,
164
199
  radiusCalibration?: number
165
200
  ): void {
166
- let street: AddressNode | undefined
167
- let houseNumber: AddressNode | undefined
168
- let directionalUnit: AddressNode | undefined
169
- let postcode: string | undefined
170
- const stack = [...roots]
201
+ const pairs = streetNumberPairs(roots)
202
+ const directionalUnit = [...walkNodes(roots)].find((n) => n.tag === "unit" && isDirectionalUnit(n.value))
203
+ const postcode = firstOfTag(roots, "postcode")?.value.trim()
204
+ // The resolved locality's coordinate — the `near` tie-breaker the interpolator may consult when the query carries
205
+ // no postcode and the covering ranges span several ZIPs (the borough-namesake class). Only a RESOLVED locality
206
+ // qualifies; an unresolved one contributes nothing.
207
+ const resolvedLocality = [...walkNodes(roots)].find((n) => n.tag === "locality" && n.lat != null && n.lon != null)
171
208
 
172
- while (stack.length) {
173
- const n = stack.pop()!
209
+ const localityCoord = resolvedLocality ? { lat: resolvedLocality.lat!, lon: resolvedLocality.lon! } : undefined
174
210
 
175
- if (n.tag === "street" && !street) {
176
- street = n
177
- }
211
+ if (!pairs.length) return
178
212
 
179
- if (n.tag === "house_number" && !houseNumber) {
180
- houseNumber = n
181
- }
213
+ // The fall-through check: an exact situs point already won — never override it with an estimate.
214
+ if (pairs.some((pair) => pair.street.metadata?.["resolution_tier"] === "address_point")) return
182
215
 
183
- if (n.tag === "unit" && !directionalUnit && isDirectionalUnit(n.value)) {
184
- directionalUnit = n
185
- }
216
+ const near = postcode ? undefined : localityCoord
186
217
 
187
- if (n.tag === "postcode" && !postcode && n.value.trim()) {
188
- postcode = n.value.trim()
189
- }
218
+ let street: AddressNode | undefined
219
+ let houseNumber: AddressNode | undefined
220
+ let hit: ReturnType<InterpolationLookup["find"]> | undefined
190
221
 
191
- stack.push(...n.children)
192
- }
222
+ for (const pair of pairs) {
223
+ hit = lookup.find({
224
+ street: assembleStreetValue(pair.street, directionalUnit),
225
+ number: pair.houseNumber.value,
226
+ postcode,
227
+ ...(near ? { near } : {}),
228
+ })
229
+
230
+ if (hit) {
231
+ street = pair.street
232
+ houseNumber = pair.houseNumber
193
233
 
194
- if (!street || !houseNumber) return
234
+ break
235
+ }
236
+ }
195
237
 
196
- // The fall-through gate: an exact situs point already won — never override it with an estimate.
197
- if (street.metadata?.["resolution_tier"] === "address_point") return
198
- const hit = lookup.find({ street: assembleStreetValue(street, directionalUnit), number: houseNumber.value, postcode })
238
+ if (!hit || !street || !houseNumber) return
199
239
 
200
- if (!hit) return
240
+ houseNumber.metadata = { ...houseNumber.metadata, resolution_tier: "interpolated" }
201
241
  // Conformal-calibrated radius (#374): the raw half-segment heuristic underestimates the true spread
202
- // (~72% coverage on Travis); ×1.70 → a 90% bound. The ARTIFACT's own multiplier (read from the shard's
242
+ // (~72% coverage on Travis); ×1.70 → a 90% bound. The ARTIFACT's own multiplier (read from the extract's
203
243
  // `interp_calibration` metadata table at open time — `lookup.radiusCalibration`) is the default; an
204
- // explicit caller factor is the @internal instrument override. Neither present (shards predating the
244
+ // explicit caller factor is the @internal instrument override. Neither present (extracts predating the
205
245
  // metadata table, no caller factor) keeps the raw value, byte-stable. Preserve the raw radius for
206
246
  // transparency.
207
247
  const factor = radiusCalibration ?? lookup.radiusCalibration
@@ -224,7 +264,7 @@ export function applyInterpolation(
224
264
  * a place name ("Place Bellecour", "Cours de l'Intendance", "Quai des Bateliers"). Used by the #1042 street-centroid
225
265
  * tier to recognize a thoroughfare that the model mis-parsed as a `locality` (the FR no-street class, #901).
226
266
  * Deliberately generous — a false positive simply misses the exact street-centroid lookup and no-ops; the lookup is the
227
- * real gate.
267
+ * real check.
228
268
  */
229
269
  const FR_VOIE_TYPES: ReadonlySet<string> = new Set([
230
270
  "rue",
@@ -278,7 +318,9 @@ const FR_VOIE_TYPES: ReadonlySet<string> = new Set([
278
318
  ])
279
319
 
280
320
  /**
281
- * Fold to lower-case, diacritic-stripped, punctuation-free tokens — mirrors `street-normalize.ts`'s `fold`.
321
+ * Fold to lower-case, diacritic-stripped, punctuation-free tokens — a deliberate local copy of
322
+ * `@mailwoman/resolver-wof-sqlite/street-normalize`'s `fold`: `@mailwoman/resolver` does not depend on that package, so
323
+ * the two are kept in step by hand.
282
324
  */
283
325
  function foldVoieTokens(s: string): string[] {
284
326
  return s
@@ -288,7 +330,7 @@ function foldVoieTokens(s: string): string[] {
288
330
  .replaceAll(/[.,'’]/g, "")
289
331
  .replaceAll("-", " ")
290
332
  .split(/\s+/)
291
- .filter(Boolean)
333
+ .filter((token) => token.length > 0)
292
334
  }
293
335
 
294
336
  /**
@@ -333,13 +375,12 @@ export function applyStreetCentroid(
333
375
  let streetNode: AddressNode | undefined
334
376
  let houseNumber = false
335
377
  let postcode: string | undefined
336
- const adminValues: string[] = [] // region / locality values, in tree order (thoroughfare and commune both hide here)
337
- const resolvedCountries: string[] = [] // countries the tree actually resolved to — a post-resolution country hint
338
- const stack = [...roots]
339
-
340
- while (stack.length) {
341
- const n = stack.pop()!
378
+ // Region / locality values in document order (thoroughfare and commune both hide here), and the countries the tree
379
+ // resolved to — a post-resolution country hint.
380
+ const adminValues: string[] = []
381
+ const resolvedCountries: string[] = []
342
382
 
383
+ for (const n of walkNodes(roots)) {
343
384
  if (n.tag === "house_number") {
344
385
  houseNumber = true
345
386
  }
@@ -366,13 +407,11 @@ export function applyStreetCentroid(
366
407
  if (rc && !resolvedCountries.includes(rc)) {
367
408
  resolvedCountries.push(rc)
368
409
  }
369
-
370
- stack.push(...n.children)
371
410
  }
372
411
 
373
412
  if (houseNumber) return // street-only tier — a numbered address is the rooftop tiers' job
374
413
 
375
- // Candidate countries: pre-resolution hints (defaultCountry + ungated placer) then the resolved countries. BAN is
414
+ // Candidate countries: pre-resolution hints (defaultCountry + unrestricted placer) then the resolved countries. BAN is
376
415
  // FR-only, so a non-FR candidate simply yields no lookup; the exact (street, base-commune) match is the real filter.
377
416
  const countries: string[] = []
378
417
 
@@ -391,7 +430,7 @@ export function applyStreetCentroid(
391
430
  const rawSegments = raw
392
431
  .split(",")
393
432
  .map((s) => s.trim())
394
- .filter(Boolean)
433
+ .filter((segment) => segment.length > 0)
395
434
 
396
435
  const CAP = 5
397
436
 
@@ -32,7 +32,7 @@
32
32
  * {@link rankByCountryPrior} covers the other half of the class — the query where a country IS
33
33
  * known, but only because a locale said so. See `span-rescore.ts` for where that one applies.
34
34
  *
35
- * Both obey the same three house rules, and neither is a gate:
35
+ * Both obey the same three house rules, and neither is a check:
36
36
  *
37
37
  * 1. **Tier-safe.** `exactMatch` stays the primary key. A soft prior re-orders WITHIN a tier; it never
38
38
  * promotes a partial match over an exact one.
@@ -41,7 +41,10 @@
41
41
  * rank population gave it while the scored rows reorder among themselves. On a candidate.db built
42
42
  * before the #28 `importance` column, nothing is scored, so {@link rankByImportance} is
43
43
  * byte-stable by construction.
44
- * 3. **Stable.** Equal keys keep their incoming order, so the backend's own ranking survives underneath.
44
+ * 3. **Stable.** Equal keys keep their incoming order, so the backend's own ranking survives underneath. That order
45
+ * carries decisions only the backend can make — the candidate backend's seat tiebreak
46
+ * (`resolver-wof-sqlite/primary-preference.ts`) reaches an end-to-end answer solely through this stability
47
+ * (#1729), so equal-key stability here is required, not cosmetic.
45
48
  */
46
49
 
47
50
  import type { ResolvedPlace } from "@mailwoman/core/resolver"
@@ -76,7 +79,7 @@ export const DEFAULT_COUNTRY_PRIOR_WEIGHT = 2
76
79
  * policy (ROAD_TO_V9) says: within a country the geocoder ranks referentially; the blended prior's job is the
77
80
  * cross-country question — which country's bearer a bare query meant.
78
81
  */
79
- export const SAME_COUNTRY_IMPORTANCE_TIE_BAND = 0.02
82
+ const SAME_COUNTRY_IMPORTANCE_TIE_BAND = 0.02
80
83
 
81
84
  /**
82
85
  * The fields a ranking key reads. Structural rather than `ResolvedPlace` so the backend's own `PlaceCandidate` (a
@@ -97,7 +100,7 @@ function rankWithinTier<T extends Rankable>(candidates: readonly T[], compare: (
97
100
 
98
101
  for (const c of candidates) {
99
102
  // `exactMatch` is TRI-STATE: true / false / undefined (a backend path that stamps no flag —
100
- // e.g. WOFSqlitePlaceLookup's postcode-area neighbours from #fetchLocalitiesByID). Only a
103
+ // e.g. WOFSQLitePlaceLookup's postcode-area neighbours from #fetchLocalitiesByID). Only a
101
104
  // stated TRUE earns the exact tier; undefined must not outrank a real fuzzy name match
102
105
  // (the 2026-08-10 de.native_locality incident: 75 Saxon towns lost to nameless neighbours).
103
106
  ;(c.exactMatch === true ? exact : rest).push(c)
@@ -223,10 +226,10 @@ function orderMeasuredByImportance<T extends Rankable>(rows: readonly T[]): T[]
223
226
  * fewer than two candidates are scored.
224
227
  *
225
228
  * The producer is the candidate build's `importance` column (#28) — the BLENDED prior (the concordance's
226
- * encyclopedia-derived channel where a concordance matched, a population-derived proxy elsewhere; see
227
- * `candidate-schema.ts` → `CandidateTable.importance` for why the strict channel is deliberately NOT what lands there).
228
- * On an artifact predating the column, `importance` is `undefined` on every candidate the backend produces and the
229
- * abstention below keeps the ranking byte-stable.
229
+ * encyclopedia-derived channel clamped around a population-derived base — `place-importance-schema.ts`'s
230
+ * `blendImportance`; see `candidate-schema.ts` → `CandidateTable.importance` for why the strict channel is deliberately
231
+ * NOT what lands there). On an artifact predating the column, `importance` is `undefined` on every candidate the
232
+ * backend produces and the abstention below keeps the ranking byte-stable.
230
233
  *
231
234
  * Flip decisions, ratified 2026-08-11: bare `Moscow`→Москва, `Manchester`→GB, `Fulda`→DE, `Cambridge`→GB are ACCEPTED
232
235
  * behavior — all cross-country contests, where this prior answers the question population cannot. Bare `Springfield`
@@ -276,3 +279,89 @@ export function rankByCountryPrior<T extends Rankable>(
276
279
 
277
280
  return rankWithinTier(candidates, (a, b) => key(b) - key(a))
278
281
  }
282
+
283
+ /**
284
+ * Capital status of a resolved candidate, answered by the caller's reference (#1880 —
285
+ * `@mailwoman/resolver-wof-sqlite/capitals` is the shipped implementation): 2 for a national capital, 1 for an admin-1
286
+ * seat, 0 for neither. The resolver stays backend-agnostic — it never loads the reference, it only consumes the
287
+ * verdict.
288
+ */
289
+ export type CapitalLevelFn = (place: Pick<ResolvedPlace, "name" | "country" | "lat" | "lon">) => number
290
+
291
+ /**
292
+ * The level a candidate must hold to be PROMOTED: national capitals only. Admin-1 seats stay un-promoted, and that
293
+ * scope is forced by decided rows, not caution — a seat margin of even 1 log10 unit flips bare `Springfield` to
294
+ * Springfield, Illinois against the ratified 2026-08-11 referential decision
295
+ * ({@link SAME_COUNTRY_IMPORTANCE_TIE_BAND}), and sends bare `Hamilton` to the Waikato seat (Hamilton NZ, 2.8x smaller
296
+ * than Hamilton, Ontario), both measured on the shipped `candidate.db`. The reference still records seats; no consumer
297
+ * promotes on them.
298
+ */
299
+ const PROMOTABLE_CAPITAL_LEVEL = 2
300
+
301
+ /**
302
+ * Margin a national capital may give away, in log10-population units: a namesake must be more than 10^2 = 100x more
303
+ * populous to hold the lead. Bare "San José" reaches the Costa Rican capital (342,188) over San Jose, California
304
+ * (969,655 — 2.8x); bare "Hamilton" stays on Hamilton, Ontario (519,949) over Bermuda's 902-person capital (576x).
305
+ */
306
+ export const NATIONAL_CAPITAL_MARGIN_LOG10 = 2
307
+
308
+ /**
309
+ * Bounded capital promotion (#1880) — the third soft key for the bare-toponym class, applied AFTER
310
+ * {@link rankByImportance} because the fame prior is what decides this class and a capital signal parked below the
311
+ * deciding stage measurably never reaches an answer (the iteration-1 board run: the candidate-order bonus reordered
312
+ * `findPlace` on every target row and moved 0 of the 12).
313
+ *
314
+ * The rule: within the exact tier, take the first NATIONAL-capital row and walk it upward past each row it is within
315
+ * {@link NATIONAL_CAPITAL_MARGIN_LOG10} of, stopping at the first row over the margin or at another national capital.
316
+ * Same three house rules as the other keys — tier-safe (never crosses the exact/partial boundary.
317
+ *
318
+ * A capital that only PARTIALLY matched the query — Saint George's, Grenada for the abbreviated "St. George's" — stays
319
+ * behind every exact match, because crossing that line is how iteration 1 answered bare "Djibouti" with the capital
320
+ * city instead of the country), positive evidence only (no capital in the list → identity, and the margin reads the
321
+ * same `prominence ?? score` size every other key does), and stable (non-promoted rows keep their order).
322
+ *
323
+ * The margin deliberately re-uses log10-population units rather than the importance scale: the ratified importance flip
324
+ * decisions (Whitby/Windsor/Springfield) sit on gaps of 0.004–0.02, while the capital contests this key exists for sit
325
+ * on gaps of 0.21–0.24 — an importance-scale bonus big enough to win them would dwarf every ratified decision on the
326
+ * same scale.
327
+ */
328
+ export function promoteCapitals<T extends Rankable & Pick<ResolvedPlace, "name" | "country" | "lat" | "lon">>(
329
+ candidates: readonly T[],
330
+ level: CapitalLevelFn | undefined
331
+ ): T[] {
332
+ if (!level || candidates.length < 2) return [...candidates]
333
+
334
+ const exact: T[] = []
335
+ const rest: T[] = []
336
+
337
+ for (const c of candidates) {
338
+ // Tri-state exactMatch, same reading as rankWithinTier: only a stated TRUE earns the tier.
339
+ ;(c.exactMatch === true ? exact : rest).push(c)
340
+ }
341
+
342
+ const tier = exact.length ? exact : rest
343
+ const best = tier.findIndex((c) => level(c) >= PROMOTABLE_CAPITAL_LEVEL)
344
+
345
+ if (best <= 0) return [...candidates]
346
+
347
+ let target = best
348
+
349
+ while (target > 0) {
350
+ const above = tier[target - 1]!
351
+
352
+ if (level(above) >= PROMOTABLE_CAPITAL_LEVEL) break
353
+
354
+ if (size(tier[best]!) + NATIONAL_CAPITAL_MARGIN_LOG10 < size(above)) break
355
+
356
+ target--
357
+ }
358
+
359
+ if (target === best) return [...candidates]
360
+
361
+ const reordered = [...tier]
362
+ const [capital] = reordered.splice(best, 1)
363
+
364
+ reordered.splice(target, 0, capital!)
365
+
366
+ return exact.length ? [...reordered, ...rest] : reordered
367
+ }
@@ -0,0 +1,70 @@
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
+ import type { AddressNode } from "@mailwoman/core/decoder";
12
+ import type { ResolverBackend } from "@mailwoman/core/resolver";
13
+ /**
14
+ * Admin descendant-consistency (#263) — the joint-consistency resolve, scoped to the admin assignment. The greedy walk
15
+ * resolves a region on its own (name + population), so "ME" picks Messina (IT) over Maine, then scopes "Portland" to
16
+ * Messina's descendants, finds nothing, and the result falls back to the region centroid (Sicily). The region's
17
+ * same-named runner-ups (Maine, Missouri, …) were already captured as `alternatives`; this pass asks the question the
18
+ * greedy order skipped — _which "ME" has a "Portland" under it?_ — and re-picks the (region, locality) pair where a
19
+ * same-named locality descends from a same-named region candidate. Geography decides; no country prior, no list.
20
+ *
21
+ * Fires ONLY for a resolved region whose child locality fell through (the unresolved-locality signal), so a
22
+ * well-resolved tree ("Springfield, IL" → Illinois, Springfield) is byte-identical. Costs one unscoped locality lookup
23
+ * per triggering pair. Needs {@link ResolverBackend.ancestors}; no-op without it. See `ResolveOpts.adminCoherence`.
24
+ */
25
+ export declare function applyAdminCoherence(roots: readonly AddressNode[], backend: ResolverBackend): Promise<void>;
26
+ /**
27
+ * Explicit-country coherence (#822) — the joint-consistency resolve keyed on the query's own EXPLICIT country token.
28
+ * The greedy walk resolves a locality on name + population alone, so "Vienna, Austria" picks the populous US namesake
29
+ * (Vienna WV) and IGNORES the "Austria" the address named. This pass asks the question the greedy order skipped —
30
+ * _which "Vienna" is in the country the address names?_ — and re-picks the locality to the same-named place under that
31
+ * country. The country code comes from the parser's OWN `country` emission via codex's ISO-3166 table (a name→code
32
+ * normalization of a token the model already classified, NOT a routing prior or safelist); the gazetteer's `country`
33
+ * column does the geographic confirmation. No pin, no list; generalizes to every country.
34
+ *
35
+ * Disjoint from {@link applyAdminCoherence} by the region guard: that pass owns the case where a REGION scopes the
36
+ * locality; this one fires only when the explicit country is the locality's nearest admin context (no region between),
37
+ * and then regardless of the locality's resolution state — so it covers both the resolved-but-foreign locality (Sydney
38
+ * → the greedy AU pick was wrong) and the unresolved locality the span-rescore tier would otherwise back-fill with the
39
+ * US namesake (Vienna → Vienna WV). Byte-stable when the locality already resolved in-country (the id guard) or the
40
+ * named country holds no same-named locality (the fail-safe — what also protects "Turkey, TX": no country token ⇒ no
41
+ * trigger; and an in-country lookup that finds nothing keeps the greedy result). Costs one country-scoped locality
42
+ * lookup per triggering pair. See `ResolveOpts.adminCoherence`.
43
+ */
44
+ export declare function applyExplicitCountryCoherence(roots: readonly AddressNode[], backend: ResolverBackend): Promise<void>;
45
+ /**
46
+ * Region-country coherence — the joint-consistency resolve keyed on a REGION token the locale-inferred default-country
47
+ * filter could not resolve. Companion to {@link applyExplicitCountryCoherence} (which keys on an explicit COUNTRY token)
48
+ * and disjoint from {@link applyAdminCoherence} (which needs a region that DID resolve): this pass owns the mirror case,
49
+ * where the region qualifier is a foreign subdivision the default-country hard filter (`spr.country = ?`) discarded.
50
+ *
51
+ * "Montreal QC" under a US locale: the walk applies `defaultCountry="US"` as a hard candidate filter to every admin
52
+ * lookup, so the region "QC" (a Canadian subdivision) resolves to nothing and is dropped — the one signal that would
53
+ * redirect the country to CA — and the locality "Montreal" is force-matched to the populous US namesake (Montreal, WI).
54
+ * The greedy order threw away the evidence that could correct it.
55
+ *
56
+ * The fix expands the region token to its country via codex's ISO-3166-2 subdivision table (`matchSubdivision`: "QC" →
57
+ * `{ name: "Quebec", country: "CA" }`, handling the FTS index's missing "QC" alt-name code-side), then asks the two
58
+ * questions the greedy walk skipped: does that subdivision genuinely resolve UNDER its own country, and is there a
59
+ * same-named locality under it? Only when BOTH hold does it swap the region and locality to the in-country pair.
60
+ * Geography confirms; the subdivision table is a soft name→country prior, not a routing decision.
61
+ *
62
+ * Evidence-conditional to stay byte-stable on the domestic path. It fires ONLY when (a) a default country is in force,
63
+ * (b) the region node is UNRESOLVED (the default-country filter came up empty — a US region resolves fine under `US`,
64
+ * so a well-formed US query never trips this), (c) the token is a subdivision of a DIFFERENT country than the default,
65
+ * and (d) both the foreign region and a same-named foreign locality resolve. "Springfield, IL" / "Portland, ME": the
66
+ * region resolves under `US`, so check (b) fails and the tree is untouched. Costs one region + one locality lookup per
67
+ * triggering pair. See `ResolveOpts.adminCoherence`.
68
+ */
69
+ export declare function applyRegionCountryCoherence(roots: readonly AddressNode[], backend: ResolverBackend, defaultCountry: string | undefined): Promise<void>;
70
+ //# sourceMappingURL=coherence-passes.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"coherence-passes.d.ts","sourceRoot":"","sources":["../../lib/admin/coherence-passes.ts"],"names":[],"mappings":"AAAA;;;;;;;;;GASG;AAGH,OAAO,KAAK,EAAE,WAAW,EAAE,MAAM,yBAAyB,CAAA;AAC1D,OAAO,KAAK,EAAiB,eAAe,EAAE,MAAM,0BAA0B,CAAA;AAI9E;;;;;;;;;;;GAWG;AACH,wBAAsB,mBAAmB,CAAC,KAAK,EAAE,SAAS,WAAW,EAAE,EAAE,OAAO,EAAE,eAAe,GAAG,OAAO,CAAC,IAAI,CAAC,CAqBhH;AAoKD;;;;;;;;;;;;;;;;;GAiBG;AACH,wBAAsB,6BAA6B,CAClD,KAAK,EAAE,SAAS,WAAW,EAAE,EAC7B,OAAO,EAAE,eAAe,GACtB,OAAO,CAAC,IAAI,CAAC,CA2Bf;AA2CD;;;;;;;;;;;;;;;;;;;;;;;GAuBG;AACH,wBAAsB,2BAA2B,CAChD,KAAK,EAAE,SAAS,WAAW,EAAE,EAC7B,OAAO,EAAE,eAAe,EACxB,cAAc,EAAE,MAAM,GAAG,SAAS,GAChC,OAAO,CAAC,IAAI,CAAC,CA8Bf"}