@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
@@ -0,0 +1,178 @@
1
+ /**
2
+ * @copyright Sister Software
3
+ * @license AGPL-3.0
4
+ * @author Teffen Ellis, et al.
5
+ * @file Which resolved admin place answers the query — the one ordering whose postcode rung is not a constant.
6
+ *
7
+ * `postalcode` is the only placetype whose specificity depends on the hit rather than the name. An NL PC6 or a GB unit
8
+ * postcode covers ~8 and ~15 addresses, categorically tighter than any locality centroid; a US ZIP, a French code
9
+ * postal or a German PLZ covers a delivery AREA. `PLACETYPE_SPECIFICITY` answers "which placetype covers less ground"
10
+ * and cannot express that split, so a consumer that sorts by it alone promotes every postcode.
11
+ *
12
+ * Two consumers need the split in two shapes, and both live here so a divergence is a test failure rather than a
13
+ * silent disagreement: result assembly walks a TAG ladder, and the eval harnesses sort resolved nodes by placetype.
14
+ */
15
+
16
+ import { areaPostcodeLeadsLocality, isUnitGradePostcodeHit } from "@mailwoman/codex"
17
+ import type { AddressNode } from "@mailwoman/core/decoder"
18
+ import { PLACETYPE_SPECIFICITY } from "@mailwoman/core/resources/whosonfirst/specificity"
19
+
20
+ /**
21
+ * The admin fallback order when the postcode leads — a unit-grade exact hit, or an address system whose area-grade code
22
+ * is still finer than its locality ({@link areaPostcodeLeadsLocality}).
23
+ */
24
+ export const ADMIN_LADDER_POSTCODE_FIRST: ReadonlyArray<string> = [
25
+ "postcode",
26
+ "locality",
27
+ "dependent_locality",
28
+ "region",
29
+ "country",
30
+ ]
31
+
32
+ /**
33
+ * The admin fallback order everywhere else: the locality tiers lead and the postcode sits between them and `region`.
34
+ *
35
+ * This is the #945 epoch convention, and it is the DEFAULT rather than the universal answer — which address systems
36
+ * leave it is `AREA_POSTCODE_FINER_THAN_LOCALITY`'s question, and that table carries the per-country measurement.
37
+ */
38
+ export const ADMIN_LADDER_LOCALITY_FIRST: ReadonlyArray<string> = [
39
+ "locality",
40
+ "dependent_locality",
41
+ "postcode",
42
+ "region",
43
+ "country",
44
+ ]
45
+
46
+ /**
47
+ * The resolved postcode a ladder decision reads: the PARSED span, the resolver's own hit, and the country the resolver
48
+ * placed it in.
49
+ *
50
+ * The first two are needed together because a full unit shape the resolver answered with a coarser stem is area-grade,
51
+ * whatever the user typed. `country` is separate evidence and answers a different question — not how tight this code
52
+ * is, but whether this address system's codes are tighter than its localities at all.
53
+ */
54
+ export interface ResolvedPostcodeHit {
55
+ value: string
56
+ resolverName: string | undefined
57
+ /**
58
+ * ISO-3166 alpha-2 the RESOLVER placed the postcode in, not a caller's requested scope. Absent when the postcode did
59
+ * not resolve to a country, which reads as the locality-first default.
60
+ */
61
+ country?: string
62
+ }
63
+
64
+ /**
65
+ * Pick the admin fallback order for one resolved tree.
66
+ *
67
+ * Two independent routes to postcode-first: the code itself is unit-grade, or the address system's area-grade codes are
68
+ * finer than its localities. Either one is sufficient and the second is what makes this per-country rather than
69
+ * global.
70
+ */
71
+ export function adminLadderFor(postcode: ResolvedPostcodeHit | undefined): ReadonlyArray<string> {
72
+ if (postcode === undefined) return ADMIN_LADDER_LOCALITY_FIRST
73
+
74
+ const leads =
75
+ isUnitGradePostcodeHit(postcode.value, postcode.resolverName) || areaPostcodeLeadsLocality(postcode.country)
76
+
77
+ return leads ? ADMIN_LADDER_POSTCODE_FIRST : ADMIN_LADDER_LOCALITY_FIRST
78
+ }
79
+
80
+ /**
81
+ * The ladder for a flat list of resolved nodes — the shape result assembly holds.
82
+ *
83
+ * Which node counts, and which of its fields the decision reads, is part of the ordering rather than the caller's
84
+ * business: `country` is the one the RESOLVER placed the code in, never a caller's requested scope, because the ladder
85
+ * is asking which address system this code belongs to and a scope is a filter on the answer rather than evidence about
86
+ * it. Getting that wrong at a call site would be invisible.
87
+ */
88
+ export function adminLadderForNodes(nodes: readonly AddressNode[]): ReadonlyArray<string> {
89
+ const node = nodes.find((n) => n.tag === "postcode" && n.lat != null && n.lon != null)
90
+
91
+ if (!node) return ADMIN_LADDER_LOCALITY_FIRST
92
+
93
+ const country = node.metadata?.["resolver_country"]
94
+
95
+ return adminLadderFor({
96
+ value: node.value,
97
+ resolverName: node.metadata?.["resolver_name"] as string | undefined,
98
+ ...(typeof country === "string" ? { country } : {}),
99
+ })
100
+ }
101
+
102
+ /**
103
+ * Where an AREA-grade postal code sits on `PLACETYPE_SPECIFICITY`: below the whole locality tier, above `county` (2).
104
+ *
105
+ * The tier is `PLACETYPE_FILTER_GROUPS.locality` — `locality` (4), `borough` (5) and `localadmin` (3) — not the
106
+ * `locality` placetype alone, because that is what the resolver's own `locality` tag expands to. New England civil
107
+ * towns are `localadmin` in WOF, so a value between `locality` and `localadmin` would rank a US ZIP above the town it
108
+ * sits in and reproduce the defect on exactly the rows that motivated the group.
109
+ *
110
+ * Deliberately not an integer. The scale's rungs are placetypes and this is not one — it is the position
111
+ * {@link ADMIN_LADDER_LOCALITY_FIRST} puts a postcode in, expressed on the scale the sorting consumers already use.
112
+ */
113
+ export const AREA_GRADE_POSTALCODE_SPECIFICITY = 2.5
114
+
115
+ /**
116
+ * A resolved place, as much of it as an ordering decision reads.
117
+ */
118
+ export interface ResolvedSpecificityInput {
119
+ placetype: string
120
+ /**
121
+ * ISO-3166 alpha-2 the resolver placed this candidate in. Read only for a `postalcode`, where it decides whether the
122
+ * address system's area-grade codes outrank its localities.
123
+ */
124
+ country?: string
125
+ /**
126
+ * The parsed span. Absent for a non-postcode candidate, where nothing conditional applies.
127
+ */
128
+ value?: string
129
+ /**
130
+ * The resolver's own hit name, as `resolver_name` metadata carries it.
131
+ */
132
+ resolverName?: string
133
+ }
134
+
135
+ /**
136
+ * Rank a resolved place for "whose coordinate answers the query" — `PLACETYPE_SPECIFICITY`, except that a `postalcode`
137
+ * is ranked by its hit.
138
+ *
139
+ * An unranked placetype returns `-Infinity` so it wins only when nothing else resolved.
140
+ */
141
+ export function resolvedSpecificity(candidate: ResolvedSpecificityInput): number {
142
+ if (candidate.placetype !== "postalcode") {
143
+ return PLACETYPE_SPECIFICITY[candidate.placetype] ?? Number.NEGATIVE_INFINITY
144
+ }
145
+
146
+ const leads =
147
+ isUnitGradePostcodeHit(candidate.value ?? "", candidate.resolverName) ||
148
+ areaPostcodeLeadsLocality(candidate.country)
149
+
150
+ return leads ? (PLACETYPE_SPECIFICITY["postalcode"] ?? Number.NEGATIVE_INFINITY) : AREA_GRADE_POSTALCODE_SPECIFICITY
151
+ }
152
+
153
+ /**
154
+ * The best of a resolved set under {@link resolvedSpecificity}, or `null` when the set is empty. Ties keep the first,
155
+ * which is document order.
156
+ *
157
+ * `toInput` is explicit rather than structural because each consumer spells the resolver's hit differently — the eval
158
+ * harnesses carry it as `name`, result assembly reads it off `resolver_name` metadata — and a projection at the call
159
+ * site is where that mapping is visible.
160
+ */
161
+ export function mostSpecificResolved<T>(
162
+ candidates: readonly T[],
163
+ toInput: (candidate: T) => ResolvedSpecificityInput
164
+ ): T | null {
165
+ let best: T | null = null
166
+ let bestRank = Number.NEGATIVE_INFINITY
167
+
168
+ for (const candidate of candidates) {
169
+ const rank = resolvedSpecificity(toInput(candidate))
170
+
171
+ if (best === null || rank > bestRank) {
172
+ best = candidate
173
+ bestRank = rank
174
+ }
175
+ }
176
+
177
+ return best
178
+ }
@@ -0,0 +1,88 @@
1
+ /**
2
+ * @copyright Sister Software
3
+ * @license AGPL-3.0
4
+ * @author Teffen Ellis, et al.
5
+ *
6
+ * Which optional {@link ResolverBackend} methods the loaded backend does not implement, and what each absence
7
+ * silently costs.
8
+ *
9
+ * `ancestors` and `coincidentLocalitiesFor` are optional on the backend contract, so a backend that omits them is
10
+ * valid — but the resolver passes that lack through as a guard that simply returns. The option those guards serve
11
+ * (`hierarchyCompletion`) defaults to ON, so a caller who never touched it gets a feature that reports success while
12
+ * doing nothing. That is absence read as a negative answer, and the rule is that a magnitude never carries its own
13
+ * absence: the gap has to be stated somewhere a caller can read it.
14
+ *
15
+ * This module states it. `describeCapabilityGaps` is pure and cheap enough to run at construction; the resolver
16
+ * exposes the result on `Resolver.capabilityGaps` and warns once so the gap appears in a log without a caller having
17
+ * to ask. It changes no resolution behavior — a gap that was silent is now legible, nothing more.
18
+ */
19
+
20
+ import type { BackendCapabilityGap, ResolverBackend } from "@mailwoman/core/resolver"
21
+
22
+ /**
23
+ * The optional backend methods whose absence degrades a passing default, paired with what stops working. A method whose
24
+ * absence is inert (or whose option is opt-in and therefore a deliberate caller choice) does not belong here — the list
25
+ * exists to name silent degradation, not to inventory the interface.
26
+ */
27
+ const CONSEQUENTIAL_CAPABILITIES: ReadonlyArray<Omit<BackendCapabilityGap, "backend">> = [
28
+ {
29
+ capability: "ancestors",
30
+ gates: "hierarchyCompletion",
31
+ defaultOn: true,
32
+ degrades:
33
+ "the containment lineage is never read: a parse that drops the locality of a city-state or dependent locality keeps the gap, and `metadata.ancestors` (the lineage the Nominatim and Photon drop-ins expose) is never populated",
34
+ },
35
+ {
36
+ capability: "coincidentLocalitiesFor",
37
+ gates: "hierarchyCompletion",
38
+ defaultOn: true,
39
+ degrades:
40
+ "the dual-role pass never runs: a region that is also a locality under the same name resolves to one role only",
41
+ },
42
+ ]
43
+
44
+ /**
45
+ * Enumerate the consequential capabilities this backend does not implement. Empty means every default-ON option the
46
+ * resolver offers has the backend support it needs.
47
+ */
48
+ export function describeCapabilityGaps(backend: ResolverBackend): readonly BackendCapabilityGap[] {
49
+ const name = backend.constructor?.name || "backend"
50
+
51
+ return CONSEQUENTIAL_CAPABILITIES.filter((c) => typeof backend[c.capability] !== "function").map(
52
+ (c): BackendCapabilityGap => ({ ...c, backend: name })
53
+ )
54
+ }
55
+
56
+ /**
57
+ * One log line for a backend's whole set of gaps. Deliberately short: what is missing, which option that costs, and
58
+ * where the consequences are written down. The per-gap `degrades` prose stays on the data for a consumer that wants it,
59
+ * because a line long enough to carry it is a line an operator learns to skip.
60
+ */
61
+ export function formatCapabilityGaps(gaps: readonly BackendCapabilityGap[]): string {
62
+ const [first] = gaps
63
+ const names = gaps.map((g) => `${g.capability}()`).join(", ")
64
+ const options = [...new Set(gaps.map((g) => g.gates))].join(", ")
65
+ const posture = gaps.some((g) => g.defaultOn) ? "default-ON" : "opt-in"
66
+
67
+ return `[resolver] ${first?.backend} lacks ${names} — ${options} (${posture}) silently no-ops; see docs/engineering/reference/resolver-backends.mdx`
68
+ }
69
+
70
+ /**
71
+ * Backends already reported, so a process that builds many resolvers over one artifact — the eval harness, the
72
+ * gauntlet, a batch worker — states the gap once rather than once per construction.
73
+ */
74
+ const reported = new Set<string>()
75
+
76
+ /**
77
+ * Report a backend's gaps to stderr the first time this process sees them. The gaps are data on
78
+ * `Resolver.capabilityGaps` regardless; this exists so they also reach an operator who never thought to look. The line
79
+ * disappears on its own once the backend implements the methods, so it cannot become permanent wallpaper.
80
+ */
81
+ export function reportCapabilityGaps(gaps: readonly BackendCapabilityGap[]): void {
82
+ const [first] = gaps
83
+
84
+ if (!first || reported.has(first.backend)) return
85
+ reported.add(first.backend)
86
+
87
+ console.error(formatCapabilityGaps(gaps))
88
+ }
@@ -0,0 +1,129 @@
1
+ /**
2
+ * @copyright Sister Software
3
+ * @license AGPL-3.0
4
+ * @author Teffen Ellis, et al.
5
+ *
6
+ * The bare-toponym ADMIN race — the policy for a query that is one bare name ("Japan", "Georgia").
7
+ * The locality placetype filter makes country/region namesakes unreachable at any rank, so the
8
+ * resolver's lookup runs these side races for the tree's lone locality-tagged span and promotes an
9
+ * admin namesake under the rules each prober documents. Split from `resolve.ts` so the walk file
10
+ * holds the walk and this one holds the race policy.
11
+ */
12
+
13
+ import type { AddressNode, AddressTree, ComponentTag } from "@mailwoman/core/decoder"
14
+ import { loneValueBearingNode } from "@mailwoman/core/decoder"
15
+ import type { PlacetypeMap, ResolvedPlace, ResolverBackend } from "@mailwoman/core/resolver"
16
+
17
+ /**
18
+ * The tree's single value-bearing node when it is locality-tagged, else null — the bare-toponym shape whose
19
+ * country-placetype sibling race `#lookupAndPick` runs. A bare name the parser tagged `locality` can name a country
20
+ * ("Japan", "China" — single country names are out of the parser's training distribution), and the locality placetype
21
+ * filter makes the country row unreachable regardless of how the ranking would order it. Any second value-bearing node
22
+ * makes the input address-shaped and the race stays off; `dependent_locality` maps to the same placetype but is an
23
+ * address-interior tag, so only a literal `locality` qualifies.
24
+ */
25
+ export function loneBareLocalityNode(tree: AddressTree, placetypeMap: PlacetypeMap): AddressNode | null {
26
+ if (placetypeMap["locality" as ComponentTag] !== "locality") return null
27
+ const lone = loneValueBearingNode(tree)
28
+
29
+ return lone?.tag === "locality" ? lone : null
30
+ }
31
+
32
+ /**
33
+ * The log-population dominance a bare REGION namesake must hold over the locality winner before the bare-toponym race
34
+ * promotes it. The value is DECISIVE_MARGIN_LOG10 from the ablation-expectation model (0.5 — below it the top-ranked
35
+ * place is the intended one 52.4% of the time, above it 89.1%); restated here because the resolver package cannot
36
+ * import the eval harness. If that measured value moves, move this with it.
37
+ */
38
+ export const BARE_REGION_DOMINANCE_LOG10 = 0.5
39
+
40
+ /**
41
+ * Log10(population + 1), 0 when the backend carries none — the saturation-free magnitude the bare-region dominance rule
42
+ * compares (prominence caps at the backend's populationBoost and erases exactly the margins this rule needs).
43
+ */
44
+ export function logPopulation(place: ResolvedPlace): number {
45
+ return Math.log10((place.population ?? 0) + 1)
46
+ }
47
+
48
+ /**
49
+ * The larger-population admin namesake of the two side races, or null when neither ran or hit.
50
+ */
51
+ export function pickLargerAdmin(country: ResolvedPlace | null, region: ResolvedPlace | null): ResolvedPlace | null {
52
+ if (!country) return region
53
+
54
+ if (!region) return country
55
+
56
+ return logPopulation(region) > logPopulation(country) ? region : country
57
+ }
58
+
59
+ /**
60
+ * Alias roles the side races refuse to answer through (#1730): a lone bare token that only reaches a place via an
61
+ * ABBREVIATION row ("Tó" folds onto Toledo's "TO") or a translation-gloss row did not name that place — while the
62
+ * role-NULL exonym tier stays open, which is what lets 格鲁吉亚 win the country race through its display-name alias. An
63
+ * artifact without the role column ignores the exclusion and the races behave as before.
64
+ */
65
+ const BARE_RACE_EXCLUDED_NAME_ROLES: readonly string[] = ["abbr", "gloss"]
66
+
67
+ /**
68
+ * The best `country`-placetype row for a bare toponym span, or null. `scopedCountry` is the same hard filter the
69
+ * locality query ran under — an EXPLICIT caller scope therefore bounds this race too (a foreign country row cannot
70
+ * outrank inside an explicit scope), while the bare-locality posture's withheld scope leaves it worldwide. Exact
71
+ * matches only: the fuzzy tier exists for typo recovery on address spans, and a fuzzy country is a guess this race must
72
+ * never promote. Abbreviation/gloss alias rows never enter ({@link BARE_RACE_EXCLUDED_NAME_ROLES}).
73
+ */
74
+ export async function bareCountryCandidate(
75
+ backend: ResolverBackend,
76
+ text: string,
77
+ scopedCountry: string | undefined
78
+ ): Promise<ResolvedPlace | null> {
79
+ try {
80
+ const hits = await backend.findPlace({
81
+ text,
82
+ placetype: "country",
83
+ limit: 1,
84
+ excludeNameRoles: BARE_RACE_EXCLUDED_NAME_ROLES,
85
+ ...(scopedCountry ? { country: scopedCountry } : {}),
86
+ })
87
+
88
+ const top = hits[0]
89
+
90
+ // The placetype check is load-bearing, not paranoia: a backend that ignores the filter
91
+ // (several test stubs, and any future partial implementation) would otherwise hand this
92
+ // race a LOCALITY row wearing a country costume, and the repick would demote the real pick.
93
+ return top && top.placetype === "country" && top.exactMatch !== false ? top : null
94
+ } catch {
95
+ // A failed side race must never abort the primary lookup — the locality answer stands.
96
+ return null
97
+ }
98
+ }
99
+
100
+ /**
101
+ * The best `region`-placetype row for a bare toponym span, or null — the sibling of {@link #bareCountryCandidate} for
102
+ * the US-state class (bare "Georgia"/"Texas" the parser tags `locality`). Same contract: the locality query's own
103
+ * country filter bounds it, exact matches only with abbreviation/gloss rows excluded, and the placetype check guards
104
+ * partial backends. (The `place_abbr`-staged region abbreviations — bare "TX"/"CA" — are role-NULL primaries and stay
105
+ * fully reachable; the exclusion removes only the names-table abbreviation ALIASES like Toledo's "TO".)
106
+ */
107
+ export async function bareRegionCandidate(
108
+ backend: ResolverBackend,
109
+ text: string,
110
+ scopedCountry: string | undefined
111
+ ): Promise<ResolvedPlace | null> {
112
+ try {
113
+ const hits = await backend.findPlace({
114
+ text,
115
+ placetype: "region",
116
+ limit: 1,
117
+ excludeNameRoles: BARE_RACE_EXCLUDED_NAME_ROLES,
118
+ ...(scopedCountry ? { country: scopedCountry } : {}),
119
+ })
120
+
121
+ const top = hits[0]
122
+
123
+ return top && (top.placetype === "region" || top.placetype === "macroregion") && top.exactMatch !== false
124
+ ? top
125
+ : null
126
+ } catch {
127
+ return null
128
+ }
129
+ }
@@ -0,0 +1,127 @@
1
+ /**
2
+ * @copyright Sister Software
3
+ * @license AGPL-3.0
4
+ * @author Teffen Ellis, et al.
5
+ *
6
+ * Node decoration shared by the resolver walk and its post-walk passes — split from `resolve.ts`
7
+ * (the `bare-toponym-race.ts` precedent: the walk file holds the walk) so the coherence passes can
8
+ * live in their own module without an import cycle back into the walk.
9
+ */
10
+
11
+ import type { AddressNode } from "@mailwoman/core/decoder"
12
+ import type { ResolvedPlace } from "@mailwoman/core/resolver"
13
+
14
+ import type { CoordinateOptionalPlace } from "./postcode-prefix.ts"
15
+
16
+ /**
17
+ * A resolved node carries a real coordinate (placeID set + non-zero lat/lon).
18
+ */
19
+ export function isResolvedWithCoord(n: AddressNode): boolean {
20
+ return !!(n.placeID && typeof n.lat === "number" && typeof n.lon === "number" && (n.lat !== 0 || n.lon !== 0))
21
+ }
22
+
23
+ /**
24
+ * Stamp a node with resolver-supplied attribution. Displaces any prior classifier `source` / `sourceID` into
25
+ * `metadata.classifier_source` / `metadata.classifier_source_id` so debugging tools can still see who made the original
26
+ * assertion. Surfaces the runner-up candidates on `alternatives` so callers can disambiguate (Springfield-class
27
+ * failures, [#8 in the failure catalogue]).
28
+ */
29
+ export function decorateNode(
30
+ node: AddressNode,
31
+ resolved: CoordinateOptionalPlace,
32
+ alternatives: ResolvedPlace[]
33
+ ): void {
34
+ if (node.source !== undefined || node.sourceID !== undefined) {
35
+ const meta = { ...node.metadata }
36
+
37
+ if (node.source !== undefined) {
38
+ meta["classifier_source"] = node.source
39
+ }
40
+
41
+ if (node.sourceID !== undefined) {
42
+ meta["classifier_source_id"] = node.sourceID
43
+ }
44
+
45
+ node.metadata = meta
46
+ }
47
+
48
+ node.source = "resolver"
49
+ node.sourceID = `${resolved.placetype}:${resolved.id}`
50
+
51
+ // `0,0` is the gazetteer's UNLOCATED sentinel, not a location in the Gulf of Guinea. Shards carry a lot of it —
52
+ // 48,216 of 142,604 JP postcodes, 86,377 GB, 9,708 intl, 414 US — and stamping it produces a node that answers
53
+ // "yes" to every `lat != null` guard downstream, including the admin ladder's. Absence is the representable form
54
+ // (`AddressNode.lat` is optional and {@link isResolvedWithCoord} already reads the sentinel this way), so the
55
+ // place resolves and identifies itself while stating it cannot say where it is.
56
+ //
57
+ // Both are cleared together rather than left stale: a coordinate from a previously-decorated place beside this
58
+ // one's `placeID` would be a worse answer than none.
59
+ const located = resolved.lat !== undefined && resolved.lon !== undefined && (resolved.lat !== 0 || resolved.lon !== 0)
60
+
61
+ if (located) {
62
+ node.lat = resolved.lat
63
+ node.lon = resolved.lon
64
+ } else {
65
+ delete node.lat
66
+ delete node.lon
67
+ }
68
+
69
+ node.placeID = `wof:${resolved.id}` // v1: only WOF resolvers; the URI scheme stays this simple
70
+ // Record the resolver's ranking score AND the resolved place's CANONICAL name. The name is the
71
+ // gazetteer's truth for the place we picked — distinct from `node.value` (the raw input span). It
72
+ // lets consumers display the canonical name and lets the end-to-end eval check the resolver chose
73
+ // the right PLACE (gazetteer-name vs ground-truth) rather than merely echoing the parser's text.
74
+ node.metadata = { ...node.metadata, resolver_score: resolved.score, resolver_name: resolved.name }
75
+
76
+ // The winner's PROMINENCE, when the backend computed one. `alternatives` below are full `ResolvedPlace`s and
77
+ // already carry theirs; without this stamp the WINNER's is the one value in the ranked list that gets dropped,
78
+ // which makes a top-1-vs-top-2 margin uncomputable from the tree — and that margin is what
79
+ // `mailwoman/query-intent.ts` reads to decide whether a bare-toponym answer was a clear win. Additive metadata
80
+ // only; nothing in the resolve reads it back.
81
+ if (resolved.prominence !== undefined) {
82
+ node.metadata["resolver_prominence"] = resolved.prominence
83
+ }
84
+
85
+ // The resolved place's ISO-3166 alpha-2 country (from the gazetteer/candidate row), when known. #1014: lets a
86
+ // forward consumer fill country/countrycode without an ancestry walk — the candidate backend carries this even
87
+ // though it has no `ancestors()` table.
88
+ if (resolved.country) {
89
+ node.metadata["resolver_country"] = resolved.country
90
+ }
91
+
92
+ // The score-channel carries (ROAD_TO_V9 §2 + #28). Written ONLY when the backend actually has a
93
+ // value: an absent score means "unmeasured" or "pre-split gazetteer", and a `resolver_*: 0` on the
94
+ // node would assert a measurement nobody made. Nothing in the resolve path reads these keys back —
95
+ // they exist for annotation / API surfaces downstream. `resolver_importance` is the blended #28
96
+ // prior (the value the ranking consulted); `resolver_encyclopedic` is the strict channel, reserved
97
+ // until a strict-channel source ships.
98
+ if (resolved.referential !== undefined) {
99
+ node.metadata["resolver_referential"] = resolved.referential
100
+ }
101
+
102
+ if (resolved.encyclopedic !== undefined) {
103
+ node.metadata["resolver_encyclopedic"] = resolved.encyclopedic
104
+ }
105
+
106
+ if (resolved.importance !== undefined) {
107
+ node.metadata["resolver_importance"] = resolved.importance
108
+ }
109
+
110
+ // The postcode/locality conflict flag (the falsehood differentiator): the postcode pointed to a
111
+ // geographically different place than the parsed city name. Surface it so callers can warn rather
112
+ // than silently trust the resolved point.
113
+ if (resolved.mismatch) {
114
+ node.metadata["postcode_city_mismatch"] = true
115
+ }
116
+
117
+ // Fallback-observability (#718): a broader admin tier (macroregion/macrocounty) stood in for the
118
+ // true region/county because no exact-type candidate existed. Additive annotation only — the
119
+ // resolved coordinate/identity above is untouched; this just lets a consumer / QA pass see it.
120
+ if (resolved.resolutionQuality) {
121
+ node.metadata["resolution_quality"] = resolved.resolutionQuality
122
+ }
123
+
124
+ if (alternatives.length) {
125
+ node.alternatives = alternatives
126
+ }
127
+ }
package/fold-name.ts CHANGED
@@ -3,17 +3,33 @@
3
3
  * @license AGPL-3.0
4
4
  * @author Teffen Ellis, et al.
5
5
  *
6
- * One shared name fold, used by the resolver's commune reconciliation and by the street tier's
7
- * locality comparison. Its own module because both would otherwise import each other for it.
6
+ * One shared name fold, used by the resolver's commune reconciliation, by the street tier's
7
+ * locality comparison and by span-rescore's key guards. Its own module because those would
8
+ * otherwise import each other for it.
9
+ *
10
+ * `@mailwoman/codex`'s `foldName` (`packages/codex/normalize.ts`) is a near twin and is also
11
+ * correct; it differs in collapsing every non-alphanumeric RUN, whitespace included. The two are
12
+ * equivalent on the inputs either sees today. They are kept apart because this one answers to a
13
+ * comparison contract the resolver owns, not because the codex copy is wrong.
8
14
  */
9
15
 
10
16
  /**
11
- * Case/diacritic-insensitive fold for commune-name comparison (#1058) — mirrors span-rescore's `norm`.
17
+ * Case/diacritic-insensitive fold for commune-name comparison (#1058).
18
+ *
19
+ * Marks are DELETED, never spaced. `[^a-z0-9 ]` alone maps the combining cedilla that NFD has just produced to a SPACE,
20
+ * so `Besançon` keys as `besanc on` and matches nothing it should. The gazetteer side of the same comparison deletes
21
+ * them — 0 of 32,539 distinct `locality_base` keys in `street-centroids-fr.db` carry a mark — so spacing puts the two
22
+ * halves of one comparison on different keys. Order is load-bearing: after the class filter the strip is a no-op.
23
+ *
24
+ * Not fixed here, and worth knowing before trusting the fold on a non-Latin-1 name: a letter with no decomposition is
25
+ * DROPPED rather than folded (`Łódź` → `odz`, `Đà Nẵng` → `a nang`). That needs a transliteration table, not a regex,
26
+ * and it is shared with every other fold in the repo.
12
27
  */
13
28
  export function foldName(s: string): string {
14
29
  return s
15
30
  .toLowerCase()
16
31
  .normalize("NFD")
32
+ .replaceAll(/\p{M}/gu, "")
17
33
  .replaceAll(/[^a-z0-9 ]/g, " ")
18
34
  .replaceAll(/\s+/g, " ")
19
35
  .trim()
package/index.ts CHANGED
@@ -43,6 +43,7 @@ export type {
43
43
  export {
44
44
  findPostcodeCountryScope,
45
45
  firstLocalityValue,
46
+ localityValuesInDocumentOrder,
46
47
  POSTCODE_COUNTRY_COHERENCE_GATE_KM,
47
48
  stampPostcodeCountryScope,
48
49
  } from "./postcode-country-coherence.ts"
@@ -50,6 +51,19 @@ export {
50
51
  export type { PostcodeCountryScope, PostcodeCountryScopeOpts } from "./postcode-country-coherence.ts"
51
52
  export { findRescoreCandidate, hasResolvedPlace } from "./span-rescore.ts"
52
53
  export type { RescoreCandidate, SpanRescoreOptions } from "./span-rescore.ts"
54
+ export { adminContainmentVerdict, partitionByContainment } from "./admin-containment.ts"
55
+
56
+ export {
57
+ ADMIN_LADDER_LOCALITY_FIRST,
58
+ ADMIN_LADDER_POSTCODE_FIRST,
59
+ adminLadderFor,
60
+ adminLadderForNodes,
61
+ AREA_GRADE_POSTALCODE_SPECIFICITY,
62
+ mostSpecificResolved,
63
+ resolvedSpecificity,
64
+ } from "./admin-winner.ts"
65
+
66
+ export type { ResolvedPostcodeHit, ResolvedSpecificityInput } from "./admin-winner.ts"
53
67
 
54
68
  // The type contract + placetype helpers live in core (pure types, keep core a leaf). Re-export so
55
69
  // consumers get the whole surface from `@mailwoman/resolver`.
@@ -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-gated to stay byte-stable on the domestic path. It fires ONLY when (a) a default country is in force, (b)
63
+ * the region node is UNRESOLVED (the default-country filter came up empty — a US region resolves fine under `US`, so a
64
+ * well-formed US query never trips this), (c) the token is a subdivision of a DIFFERENT country than the default, and
65
+ * (d) both the foreign region and a same-named foreign locality resolve. "Springfield, IL" / "Portland, ME": the region
66
+ * resolves under `US`, so gate (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=admin-coherence-passes.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"admin-coherence-passes.d.ts","sourceRoot":"","sources":["../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"}