@mailwoman/resolver 8.1.0 → 8.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.
package/street-tier.ts ADDED
@@ -0,0 +1,498 @@
1
+ /**
2
+ * @copyright Sister Software
3
+ * @license AGPL-3.0
4
+ * @author Teffen Ellis, et al.
5
+ *
6
+ * The street-level coordinate tiers, in cascade order: exact address point (#476), house-number
7
+ * interpolation (#483), then the street-centroid fallback. Each answers WHERE, never WHICH PLACE —
8
+ * they stamp a coordinate onto the STREET node's metadata and never touch admin resolution.
9
+ *
10
+ * Split out of `resolve.ts` so the resolver file holds the walk and the admin-coherence passes, and
11
+ * this one holds the tiers. The FR voie-type folding lives here because only the street-centroid
12
+ * tier consults it.
13
+ */
14
+
15
+ import { isStreetDirectionalToken } from "@mailwoman/codex/us"
16
+ import type { AddressNode } from "@mailwoman/core/decoder"
17
+ import type { AddressPointLookup, InterpolationLookup, StreetCentroidLookup } from "@mailwoman/core/resolver"
18
+ import { haversineKm } from "@mailwoman/spatial"
19
+
20
+ import { foldName } from "./fold-name.ts"
21
+
22
+ /**
23
+ * Street-name component tags that, with the street node itself, reconstruct the full street string.
24
+ */
25
+ const STREET_NAME_TAGS = new Set(["street", "street_prefix", "street_prefix_particle", "street_suffix"])
26
+
27
+ /**
28
+ * Reassemble the full street string from the street node's subtree (#483 coverage fix). The parser nests the
29
+ * 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
31
+ * normalized name. Collect street + its prefix/particle/suffix descendants (NOT house_number/unit, which also nest
32
+ * under street), order by span offset, and join.
33
+ */
34
+ 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
+ }
47
+
48
+ // #718 admin-tail: a directional quadrant the model mis-tagged `unit` ("1532 Taylor Street NE" →
49
+ // [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
51
+ // only — the parse output and admin resolution are untouched. Byte-stable when absent (undefined).
52
+ if (directionalUnit && directionalUnit.value.trim()) {
53
+ parts.push(directionalUnit)
54
+ }
55
+
56
+ parts.sort((a, b) => a.start - b.start)
57
+
58
+ return parts.map((n) => n.value.trim()).join(" ")
59
+ }
60
+
61
+ /**
62
+ * Directional quadrant values the model sometimes emits as a `unit` node instead of inside the street subtree (#718
63
+ * admin-tail diagnostic: ~19% of the admin-fallback tail, 83% of DC). Folded into the street lookup key by
64
+ * {@link assembleStreetValue}; the situs/interp lookup normalizer expands the abbreviation ("ne" → "northeast") so the
65
+ * shard's full street name matches.
66
+ */
67
+ // The 8 USPS cardinals/intercardinals (abbrev or name) — @codex/us owns the canonical table (#215).
68
+ const isDirectionalUnit = (value: string): boolean => isStreetDirectionalToken(value.replaceAll(".", ""))
69
+
70
+ /**
71
+ * Address-point tier (#476): find `street` + `house_number` in the tree (first occurrence, depth-first), scope by the
72
+ * tree's postcode/locality values, and on an exact hit stamp the point onto the STREET node's metadata. Additive only —
73
+ * admin resolution is never altered.
74
+ */
75
+ /**
76
+ * Half-width (degrees) of the bbox derived from a resolved locality centroid for the #247 OSM bbox fall-through. ~0.25°
77
+ * ≈ 28 km N–S — generous enough for a large metro whose centroid sits off the queried point, while the EXACT `(street,
78
+ * number)` match keeps a cross-commune collision rare. The proper fix is per-point scope backfill (the OSM association
79
+ * / point-in-polygon pass, #250); this is the coverage stopgap until then.
80
+ */
81
+ const LOCALITY_BBOX_RADIUS_DEG = 0.25
82
+
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
97
+ }
98
+
99
+ if (n.tag === "house_number" && !houseNumber) {
100
+ houseNumber = n
101
+ }
102
+
103
+ if (n.tag === "unit" && !directionalUnit && isDirectionalUnit(n.value)) {
104
+ directionalUnit = n
105
+ }
106
+
107
+ if (n.tag === "locality" && !localityNode && n.value.trim()) {
108
+ localityNode = n
109
+ locality = n.value.trim()
110
+ }
111
+
112
+ if (n.tag === "postcode" && !postcode && n.value.trim()) {
113
+ postcode = n.value.trim()
114
+ }
115
+
116
+ stack.push(...n.children)
117
+ }
118
+
119
+ if (!street || !houseNumber) return
120
+
121
+ // #247 OSM bbox fall-through: when enabled (an OSM shard is wired) and the locality resolved to a
122
+ // coordinate, scope a final `(street, number)` probe by the locality's box — recovering OSM points that
123
+ // carry no postcode/locality tag of their own. US situs never enables it, so its probes are byte-identical.
124
+ let bbox: { minLat: number; maxLat: number; minLon: number; maxLon: number } | undefined
125
+
126
+ if (bboxFallback && localityNode?.lat != null && localityNode.lon != null) {
127
+ bbox = {
128
+ minLat: localityNode.lat - LOCALITY_BBOX_RADIUS_DEG,
129
+ maxLat: localityNode.lat + LOCALITY_BBOX_RADIUS_DEG,
130
+ minLon: localityNode.lon - LOCALITY_BBOX_RADIUS_DEG,
131
+ maxLon: localityNode.lon + LOCALITY_BBOX_RADIUS_DEG,
132
+ }
133
+ }
134
+
135
+ const hit = lookup.find({
136
+ street: assembleStreetValue(street, directionalUnit),
137
+ number: houseNumber.value,
138
+ postcode,
139
+ locality,
140
+ bbox,
141
+ })
142
+
143
+ if (!hit) return
144
+
145
+ street.metadata = {
146
+ ...street.metadata,
147
+ address_point: { lat: hit.lat, lon: hit.lon, source: hit.source, release: hit.release },
148
+ resolution_tier: "address_point",
149
+ }
150
+ }
151
+
152
+ /**
153
+ * House-number interpolation tier (#483): the third rung, consulted ONLY when the exact address-point tier
154
+ * ({@link applyAddressPoint}) did NOT already stamp the street node (`resolution_tier === "address_point"`). That gate
155
+ * IS the "after the exact-point fall-through" — an estimate never overwrites a real situs point. Postcode-scoped (no
156
+ * locality — the interpolators abstain statewide without a postcode). Stamps a DISTINCT metadata key
157
+ * (`interpolated_point`, never `address_point`). Additive only — admin resolution is untouched.
158
+ */
159
+ export function applyInterpolation(
160
+ roots: AddressNode[],
161
+ lookup: InterpolationLookup,
162
+ radiusCalibration?: number
163
+ ): void {
164
+ let street: AddressNode | undefined
165
+ let houseNumber: AddressNode | undefined
166
+ let directionalUnit: AddressNode | undefined
167
+ let postcode: string | undefined
168
+ const stack = [...roots]
169
+
170
+ while (stack.length) {
171
+ const n = stack.pop()!
172
+
173
+ if (n.tag === "street" && !street) {
174
+ street = n
175
+ }
176
+
177
+ if (n.tag === "house_number" && !houseNumber) {
178
+ houseNumber = n
179
+ }
180
+
181
+ if (n.tag === "unit" && !directionalUnit && isDirectionalUnit(n.value)) {
182
+ directionalUnit = n
183
+ }
184
+
185
+ if (n.tag === "postcode" && !postcode && n.value.trim()) {
186
+ postcode = n.value.trim()
187
+ }
188
+
189
+ stack.push(...n.children)
190
+ }
191
+
192
+ if (!street || !houseNumber) return
193
+
194
+ // The fall-through gate: an exact situs point already won — never override it with an estimate.
195
+ if (street.metadata?.["resolution_tier"] === "address_point") return
196
+ const hit = lookup.find({ street: assembleStreetValue(street, directionalUnit), number: houseNumber.value, postcode })
197
+
198
+ if (!hit) return
199
+ // Conformal-calibrated radius (#374): the raw half-segment heuristic underestimates the true spread
200
+ // (~72% coverage on Travis); ×1.70 → a 90% bound. The ARTIFACT's own multiplier (read from the shard's
201
+ // `interp_calibration` metadata table at open time — `lookup.radiusCalibration`) is the default; an
202
+ // explicit caller factor is the @internal instrument override. Neither present (shards predating the
203
+ // metadata table, no caller factor) keeps the raw value, byte-stable. Preserve the raw radius for
204
+ // transparency.
205
+ const factor = radiusCalibration ?? lookup.radiusCalibration
206
+ const calibrated = factor ? Math.round(hit.uncertaintyM * factor) : hit.uncertaintyM
207
+
208
+ street.metadata = {
209
+ ...street.metadata,
210
+ interpolated_point: { lat: hit.lat, lon: hit.lon, source: hit.source, release: hit.release },
211
+ resolution_tier: "interpolated",
212
+ uncertainty_m: calibrated,
213
+ ...(factor ? { uncertainty_raw_m: hit.uncertaintyM, uncertainty_calibration: factor } : {}),
214
+ interpolation_method: hit.method,
215
+ ...(hit.parityMatched !== undefined ? { parity_matched: hit.parityMatched } : {}),
216
+ ...(hit.bracket !== undefined ? { interpolation_bracket: hit.bracket } : {}),
217
+ }
218
+ }
219
+
220
+ /**
221
+ * French thoroughfare (voie) type tokens — the leading word that marks a street-only span as a THOROUGHFARE rather than
222
+ * a place name ("Place Bellecour", "Cours de l'Intendance", "Quai des Bateliers"). Used by the #1042 street-centroid
223
+ * tier to recognize a thoroughfare that the model mis-parsed as a `locality` (the FR no-street class, #901).
224
+ * Deliberately generous — a false positive simply misses the exact street-centroid lookup and no-ops; the lookup is the
225
+ * real gate.
226
+ */
227
+ const FR_VOIE_TYPES: ReadonlySet<string> = new Set([
228
+ "rue",
229
+ "ruelle",
230
+ "venelle",
231
+ "avenue",
232
+ "av",
233
+ "ave",
234
+ "boulevard",
235
+ "bd",
236
+ "bld",
237
+ "bvd",
238
+ "boul",
239
+ "place",
240
+ "pl",
241
+ "cours",
242
+ "quai",
243
+ "impasse",
244
+ "imp",
245
+ "allee",
246
+ "all",
247
+ "chemin",
248
+ "ch",
249
+ "che",
250
+ "passage",
251
+ "pas",
252
+ "square",
253
+ "sq",
254
+ "faubourg",
255
+ "fg",
256
+ "fbg",
257
+ "route",
258
+ "rte",
259
+ "esplanade",
260
+ "promenade",
261
+ "sentier",
262
+ "sente",
263
+ "villa",
264
+ "cite",
265
+ "hameau",
266
+ "montee",
267
+ "chaussee",
268
+ "traverse",
269
+ "mail",
270
+ "clos",
271
+ "voie",
272
+ "quartier",
273
+ "lotissement",
274
+ "residence",
275
+ "rond",
276
+ ])
277
+
278
+ /**
279
+ * Fold to lower-case, diacritic-stripped, punctuation-free tokens — mirrors `street-normalize.ts`'s `fold`.
280
+ */
281
+ function foldVoieTokens(s: string): string[] {
282
+ return s
283
+ .normalize("NFKD")
284
+ .replaceAll(/[̀-ͯ]/g, "")
285
+ .toLowerCase()
286
+ .replaceAll(/[.,'’]/g, "")
287
+ .replaceAll("-", " ")
288
+ .split(/\s+/)
289
+ .filter(Boolean)
290
+ }
291
+
292
+ /**
293
+ * Does a string START with a French thoroughfare type token ("Rue …", "Place …")?
294
+ */
295
+ function isVoieShaped(s: string): boolean {
296
+ const first = foldVoieTokens(s)[0]
297
+
298
+ return first !== undefined && FR_VOIE_TYPES.has(first)
299
+ }
300
+
301
+ /**
302
+ * Push `v` (trimmed, non-empty, deduped, capped) onto `list`.
303
+ */
304
+ function pushCandidate(list: string[], v: string | undefined, cap: number): void {
305
+ const t = v?.trim()
306
+
307
+ if (t && list.length < cap && !list.includes(t)) {
308
+ list.push(t)
309
+ }
310
+ }
311
+
312
+ /**
313
+ * Street-centroid tier (#1042): the street-level rung BELOW the exact/interpolation tiers and ABOVE admin-centroid
314
+ * resolution. For a STREET-ONLY query (a thoroughfare with NO house number), stamp the street's centroid onto a
315
+ * `street` node so a consumer gets a street-level coordinate instead of the commune centroid (or a wrong namesake).
316
+ *
317
+ * The FR no-street class mis-parses the thoroughfare — "Place Bellecour, Lyon" parses `region=Lyon`, `locality="Place
318
+ * Bellecour"`; "Avenue des Champs-Élysées" truncates — so this recovers the thoroughfare + commune RAW-TEXT-first (the
319
+ * same substrate as span-rescore), preferring parsed nodes and falling back to the comma-split raw query. A
320
+ * thoroughfare is recognized by its leading voie type ({@link isVoieShaped}); the commune is any non-voie span. Every
321
+ * (thoroughfare, commune) pair is probed against the exact street-centroid lookup, first hit wins — a false candidate
322
+ * simply misses. Additive only: fires ONLY when no house number is present (rooftop tiers untouched) and no
323
+ * street-level coordinate already resolved, and never alters admin resolution.
324
+ */
325
+ export function applyStreetCentroid(
326
+ roots: AddressNode[],
327
+ raw: string,
328
+ provider: (country: string) => StreetCentroidLookup | undefined,
329
+ hints: readonly string[]
330
+ ): void {
331
+ let streetNode: AddressNode | undefined
332
+ let houseNumber = false
333
+ let postcode: string | undefined
334
+ const adminValues: string[] = [] // region / locality values, in tree order (thoroughfare and commune both hide here)
335
+ const resolvedCountries: string[] = [] // countries the tree actually resolved to — a post-resolution country hint
336
+ const stack = [...roots]
337
+
338
+ while (stack.length) {
339
+ const n = stack.pop()!
340
+
341
+ if (n.tag === "house_number") {
342
+ houseNumber = true
343
+ }
344
+
345
+ if (n.tag === "street" && !streetNode) {
346
+ streetNode = n
347
+ }
348
+
349
+ // Never shadow a real street-level coordinate the exact/interp tiers already stamped.
350
+ if (n.metadata?.["resolution_tier"] === "address_point" || n.metadata?.["resolution_tier"] === "interpolated") {
351
+ return
352
+ }
353
+
354
+ if (!postcode && n.tag === "postcode" && n.value.trim()) {
355
+ postcode = n.value.trim()
356
+ }
357
+
358
+ if ((n.tag === "region" || n.tag === "locality" || n.tag === "dependent_locality") && n.value.trim()) {
359
+ adminValues.push(n.value.trim())
360
+ }
361
+
362
+ const rc = (n.metadata?.["resolver_country"] as string | undefined)?.trim().toLowerCase()
363
+
364
+ if (rc && !resolvedCountries.includes(rc)) {
365
+ resolvedCountries.push(rc)
366
+ }
367
+
368
+ stack.push(...n.children)
369
+ }
370
+
371
+ if (houseNumber) return // street-only tier — a numbered address is the rooftop tiers' job
372
+
373
+ // Candidate countries: pre-resolution hints (defaultCountry + ungated placer) then the resolved countries. BAN is
374
+ // FR-only, so a non-FR candidate simply yields no lookup; the exact (street, base-commune) match is the real filter.
375
+ const countries: string[] = []
376
+
377
+ for (const c of [...hints, ...resolvedCountries]) {
378
+ const cc = c?.trim().toLowerCase()
379
+
380
+ if (cc && !countries.includes(cc)) {
381
+ countries.push(cc)
382
+ }
383
+ }
384
+
385
+ const lookups = countries.map((c) => provider(c)).filter((l): l is StreetCentroidLookup => l != null)
386
+
387
+ if (!lookups.length) return
388
+
389
+ const rawSegments = raw
390
+ .split(",")
391
+ .map((s) => s.trim())
392
+ .filter(Boolean)
393
+
394
+ const CAP = 5
395
+
396
+ // Thoroughfare candidates (parsed-first, then raw): the assembled street node, any voie-shaped parsed value, any
397
+ // voie-shaped raw comma-segment. The parse often truncates these (Champs-Élysées → "Avenue des Champs"), so the raw
398
+ // segment is the recovery — a candidate that misses just advances to the next.
399
+ const thoroughfares: string[] = []
400
+
401
+ if (streetNode) {
402
+ pushCandidate(thoroughfares, assembleStreetValue(streetNode), CAP)
403
+ }
404
+
405
+ for (const v of adminValues) {
406
+ if (isVoieShaped(v)) {
407
+ pushCandidate(thoroughfares, v, CAP)
408
+ }
409
+ }
410
+
411
+ for (const s of rawSegments) {
412
+ if (isVoieShaped(s)) {
413
+ pushCandidate(thoroughfares, s, CAP)
414
+ }
415
+ }
416
+
417
+ if (!thoroughfares.length) return
418
+
419
+ // Commune candidates: non-voie parsed admin values, then non-voie raw segments (a truncated/garbled parse loses the
420
+ // commune — "Rue de la République, Marseille" parses `locality="e"` — so the raw "Marseille" is the recovery).
421
+ const communes: string[] = []
422
+
423
+ for (const v of adminValues) {
424
+ if (!isVoieShaped(v)) {
425
+ pushCandidate(communes, v, CAP)
426
+ }
427
+ }
428
+
429
+ for (const s of rawSegments) {
430
+ if (!isVoieShaped(s) && !thoroughfares.includes(s)) {
431
+ pushCandidate(communes, s, CAP)
432
+ }
433
+ }
434
+
435
+ for (const lookup of lookups) {
436
+ for (const street of thoroughfares) {
437
+ let hit = postcode ? lookup.find({ street, postcode }) : null
438
+ let matchedCommune: string | undefined
439
+
440
+ for (let i = 0; !hit && i < communes.length; i++) {
441
+ hit = lookup.find({ street, locality: communes[i]! })
442
+
443
+ if (hit) {
444
+ matchedCommune = communes[i]
445
+ }
446
+ }
447
+
448
+ if (!hit) continue
449
+
450
+ const target =
451
+ streetNode ??
452
+ (() => {
453
+ const injected: AddressNode = {
454
+ tag: "street",
455
+ value: street,
456
+ start: 0,
457
+ end: 0,
458
+ confidence: 0.5,
459
+ children: [],
460
+ }
461
+
462
+ roots.push(injected)
463
+
464
+ return injected
465
+ })()
466
+
467
+ target.metadata = {
468
+ ...target.metadata,
469
+ street_centroid: { lat: hit.lat, lon: hit.lon, source: hit.source, release: hit.release },
470
+ resolution_tier: "street",
471
+ uncertainty_m: hit.uncertaintyM,
472
+ }
473
+
474
+ // #1058: a commune-scoped hit is REGISTER evidence of the street's locality — record it for
475
+ // the geocode layer's locality/city decoration, and drop any span-rescored locality that
476
+ // contradicts it. Span-rescore injects SPECULATIVELY (a low-confidence street prefix like
477
+ // "Rue" exact-matches the commune Rue in Somme); the register's exact (street, commune)
478
+ // match is strictly stronger, so the injected token-of-the-street must not survive as the
479
+ // result's city.
480
+ if (matchedCommune) {
481
+ target.metadata = { ...target.metadata, street_locality: matchedCommune }
482
+
483
+ for (let i = roots.length - 1; i >= 0; i--) {
484
+ const n = roots[i]!
485
+
486
+ if (n.tag !== "locality" || n.metadata?.["span_rescore"] !== true) continue
487
+ const names = [n.value, (n.metadata?.["resolver_name"] as string | undefined) ?? ""]
488
+
489
+ if (!names.some((name) => foldName(name) === foldName(matchedCommune))) {
490
+ roots.splice(i, 1)
491
+ }
492
+ }
493
+ }
494
+
495
+ return
496
+ }
497
+ }
498
+ }