@mailwoman/core 7.1.0 → 7.2.1

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 (149) hide show
  1. package/api/APIClient.ts +175 -0
  2. package/api/headless.ts +23 -0
  3. package/api/index.ts +11 -0
  4. package/api/responses.ts +135 -0
  5. package/coarse-placer/coarse-placer.ts +300 -0
  6. package/coarse-placer/featurize.ts +171 -0
  7. package/coarse-placer/tools/build-dataset.ts +223 -0
  8. package/coarse-placer/tools/build-outlier-exposure.ts +172 -0
  9. package/coarse-placer/tools/build-outlier-latin.ts +200 -0
  10. package/coarse-placer/tools/build-outlier-oa.ts +231 -0
  11. package/coarse-placer/tools/eval-latin-offmap.ts +140 -0
  12. package/coarse-placer/tools/eval-openset.ts +519 -0
  13. package/coarse-placer/tools/eval-quant-compare.ts +151 -0
  14. package/coarse-placer/tools/eval.ts +187 -0
  15. package/coarse-placer/tools/fnv-hash.ts +24 -0
  16. package/coarse-placer/tools/index.ts +23 -0
  17. package/coarse-placer/tools/probe-frontier.ts +216 -0
  18. package/coarse-placer/tools/quantize.ts +116 -0
  19. package/coarse-placer/tools/train.ts +244 -0
  20. package/collections.ts +134 -0
  21. package/db/schema.ts +21 -0
  22. package/decoder/build-tree.ts +228 -0
  23. package/decoder/calibration.ts +101 -0
  24. package/decoder/containment.ts +87 -0
  25. package/decoder/index.ts +17 -0
  26. package/decoder/proposals-to-tree.ts +83 -0
  27. package/decoder/resolve-proposal-overlaps.ts +79 -0
  28. package/decoder/serialize-json.ts +70 -0
  29. package/decoder/serialize-tuples.ts +61 -0
  30. package/decoder/serialize-xml.ts +209 -0
  31. package/decoder/types.ts +159 -0
  32. package/decoder/unknown-spans.ts +103 -0
  33. package/decoder/validate-tree.ts +100 -0
  34. package/env/index.ts +42 -0
  35. package/env/load.ts +14 -0
  36. package/env/paths.ts +40 -0
  37. package/env/schema.ts +125 -0
  38. package/errors/index.ts +9 -0
  39. package/errors/schema.ts +155 -0
  40. package/fs/node.ts +38 -0
  41. package/identifiers.ts +58 -0
  42. package/index.ts +13 -0
  43. package/kysley/adapter.ts +29 -0
  44. package/kysley/client.ts +30 -0
  45. package/kysley/dialect-config.ts +30 -0
  46. package/kysley/dialect.ts +67 -0
  47. package/kysley/driver.ts +175 -0
  48. package/layers/index.ts +12 -0
  49. package/layers/manifest.ts +154 -0
  50. package/layers/schema.ts +105 -0
  51. package/lifecycle/ServiceSymbol.ts +95 -0
  52. package/lifecycle/index.ts +11 -0
  53. package/lifecycle/lru-cache.ts +44 -0
  54. package/lifecycle/services.ts +322 -0
  55. package/locale/index.ts +9 -0
  56. package/locale/locale.ts +49 -0
  57. package/locale/profiles/en-us.ts +69 -0
  58. package/locale/profiles/fr-fr.ts +75 -0
  59. package/locale/profiles/index.ts +9 -0
  60. package/locale/profiles/ja-jp.ts +33 -0
  61. package/locale/registry.ts +68 -0
  62. package/logging/index.ts +8 -0
  63. package/logging/shared.ts +145 -0
  64. package/logging/utils.ts +46 -0
  65. package/objects.ts +211 -0
  66. package/out/layers/index.d.ts +12 -0
  67. package/out/layers/index.d.ts.map +1 -0
  68. package/out/layers/index.js +12 -0
  69. package/out/layers/index.js.map +1 -0
  70. package/out/layers/manifest.d.ts +64 -0
  71. package/out/layers/manifest.d.ts.map +1 -0
  72. package/out/layers/manifest.js +102 -0
  73. package/out/layers/manifest.js.map +1 -0
  74. package/out/layers/schema.d.ts +72 -0
  75. package/out/layers/schema.d.ts.map +1 -0
  76. package/out/layers/schema.js +61 -0
  77. package/out/layers/schema.js.map +1 -0
  78. package/out/pipeline/index.d.ts +1 -1
  79. package/out/pipeline/index.d.ts.map +1 -1
  80. package/out/pipeline/runtime-pipeline.d.ts.map +1 -1
  81. package/out/pipeline/runtime-pipeline.js +27 -0
  82. package/out/pipeline/runtime-pipeline.js.map +1 -1
  83. package/out/pipeline/types.d.ts +74 -4
  84. package/out/pipeline/types.d.ts.map +1 -1
  85. package/out/pipeline/types.js.map +1 -1
  86. package/package.json +21 -21
  87. package/pipeline/index.ts +46 -0
  88. package/pipeline/reconcile-lookups.ts +108 -0
  89. package/pipeline/reconcile.ts +542 -0
  90. package/pipeline/runtime-pipeline.ts +732 -0
  91. package/pipeline/span-logit-aggregation.ts +151 -0
  92. package/pipeline/span-proposer.ts +587 -0
  93. package/pipeline/types.ts +348 -0
  94. package/policy/defaults.ts +35 -0
  95. package/policy/index.ts +10 -0
  96. package/policy/policy.ts +60 -0
  97. package/policy/proposal-collection.ts +64 -0
  98. package/policy/registry.ts +149 -0
  99. package/resolver/index.ts +29 -0
  100. package/resolver/types.ts +584 -0
  101. package/resources/LocaleIndex.ts +124 -0
  102. package/resources/ResourceMapCache.ts +126 -0
  103. package/resources/collections.ts +93 -0
  104. package/resources/debugging.ts +19 -0
  105. package/resources/git.ts +54 -0
  106. package/resources/index.ts +17 -0
  107. package/resources/languages/index.ts +49 -0
  108. package/resources/languages/types.gen.ts +1368 -0
  109. package/resources/libaddressinput.ts +105 -0
  110. package/resources/libpostal.ts +182 -0
  111. package/resources/locale.ts +23 -0
  112. package/resources/set.ts +179 -0
  113. package/resources/whosonfirst/DataSourceCache.ts +72 -0
  114. package/resources/whosonfirst/PlacetypeDataSource.ts +199 -0
  115. package/resources/whosonfirst/index.ts +10 -0
  116. package/resources/whosonfirst/loader.ts +157 -0
  117. package/resources/whosonfirst/placetypes/Placetype.ts +438 -0
  118. package/resources/whosonfirst/placetypes/admin.ts +173 -0
  119. package/resources/whosonfirst/placetypes/definition.ts +135 -0
  120. package/resources/whosonfirst/placetypes/graph.ts +0 -0
  121. package/resources/whosonfirst/placetypes/index.ts +12 -0
  122. package/resources/whosonfirst/placetypes/mermaid.ts +168 -0
  123. package/resources/whosonfirst/placetypes/tree.ts +46 -0
  124. package/routing/index.ts +208 -0
  125. package/scripting/index.ts +40 -0
  126. package/scripting/utils/index.ts +106 -0
  127. package/tokenization/Graph.ts +50 -0
  128. package/tokenization/Span.ts +297 -0
  129. package/tokenization/index.ts +9 -0
  130. package/tokenization/normalizer.ts +123 -0
  131. package/tools/download-libpostal-resources.ts +98 -0
  132. package/tools/download-ssl-address.ts +99 -0
  133. package/tools/generate-language-types.ts +194 -0
  134. package/tools/index.ts +13 -0
  135. package/types/Classification.ts +211 -0
  136. package/types/classifier.ts +133 -0
  137. package/types/component.ts +75 -0
  138. package/types/index.ts +10 -0
  139. package/types/mapping.ts +81 -0
  140. package/utils/data-root.ts +56 -0
  141. package/utils/hash.ts +27 -0
  142. package/utils/index.ts +14 -0
  143. package/utils/jsonl.ts +43 -0
  144. package/utils/python-json.ts +105 -0
  145. package/utils/python-random.ts +90 -0
  146. package/utils/repo.ts +118 -0
  147. package/utils/sealed-db.ts +85 -0
  148. package/utils/stats.ts +32 -0
  149. package/vitest.config.ts +53 -0
@@ -0,0 +1,29 @@
1
+ /**
2
+ * @copyright Sister Software
3
+ * @license AGPL-3.0
4
+ * @author Teffen Ellis, et al.
5
+ *
6
+ * The resolver TYPE CONTRACT — `ResolverBackend`, `Resolver`, `ResolveOpts`, `ResolvedPlace`, the
7
+ * lookup interfaces, the placetype map. Pure types + tiny helpers; NO implementation, so `core`
8
+ * stays a dependency-free leaf and `core/pipeline` can compose the resolver structurally without
9
+ * a cycle. The IMPLEMENTATION (`createWOFResolver`, `RemoteResolver`, span-rescore) lives in
10
+ * `@mailwoman/resolver` (#215), which depends on this + `@mailwoman/spatial` +
11
+ * `@mailwoman/codex`.
12
+ */
13
+
14
+ export { DEFAULT_PLACETYPE_MAP, PLACETYPE_FILTER_GROUPS, expandPlacetypeFilter, isPlacetypeFallback } from "./types.ts"
15
+ export type {
16
+ AddressPointHit,
17
+ AddressPointLookup,
18
+ Ancestor,
19
+ CoincidentLocality,
20
+ InterpolatedPointHit,
21
+ InterpolationLookup,
22
+ PlacetypeMap,
23
+ ResolveOpts,
24
+ ResolvedPlace,
25
+ Resolver,
26
+ ResolverBackend,
27
+ StreetCentroidHit,
28
+ StreetCentroidLookup,
29
+ } from "./types.ts"
@@ -0,0 +1,584 @@
1
+ /**
2
+ * @copyright Sister Software
3
+ * @license AGPL-3.0
4
+ * @author Teffen Ellis, et al.
5
+ *
6
+ * Resolver interface for Phase 4.3 — wires the address-component decoder to a place-id / coordinate
7
+ * lookup backend.
8
+ *
9
+ * The interface is deliberately decoupled from any specific resolver implementation. The first
10
+ * shipped impl is `@mailwoman/core/resolver-wof-sqlite`, but the same contract supports a future
11
+ * `RemoteResolver` adapter (Phase 4.4 — Pelias / BAN / Nominatim) without a public-API break.
12
+ *
13
+ * See `docs/plan/phases/PHASE_4_3_resolver_integration.md` for the design intent.
14
+ */
15
+
16
+ import type { AddressTree, ComponentTag } from "../decoder/types.ts"
17
+
18
+ /**
19
+ * One candidate place returned by a resolver. Mirrors the shape used by `@mailwoman/core/resolver-wof-sqlite`'s
20
+ * `PlaceCandidate` — kept structurally compatible so a callsite holding a `PlaceCandidate` can be passed where a
21
+ * `ResolvedPlace` is expected.
22
+ */
23
+ export interface ResolvedPlace {
24
+ /** Resolver-specific place identifier (e.g. WOF id). */
25
+ id: number | string
26
+ /** Canonical name of the place as the resolver knows it. */
27
+ name: string
28
+ /** Resolver's placetype taxonomy label (e.g. WOF's `country` / `region` / `locality`). */
29
+ placetype: string
30
+ /** ISO 3166-1 alpha-2 country code, if known. */
31
+ country: string
32
+ /** Centroid latitude in WGS-84 decimal degrees. */
33
+ lat: number
34
+ /** Centroid longitude in WGS-84 decimal degrees. */
35
+ lon: number
36
+ /** Parent place id within the resolver's hierarchy, if any. */
37
+ parent_id?: number | string
38
+ /**
39
+ * Resolver-defined ranking score. Higher = better fit for the query. Scale is implementation- defined; callers should
40
+ * treat as ordinal.
41
+ */
42
+ score: number
43
+ /**
44
+ * The candidate's PROMINENCE (see the glossary): how important this place is when breaking ties among equally-good
45
+ * text matches. Computed by the backend as the population term (log-scaled, capped at `populationBoost`, default 4.0)
46
+ * plus the best proximity-bias term (distance-decayed, capped at `biasBoost`, default 4.0). Domain [0,
47
+ * populationBoost + biasBoost] — typically [0, 8]; HIGHER = more prominent = ranked EARLIER within an exact-match
48
+ * tier. Exists because raw bm25 `score` is length-poisoned for famous places (a capital's alias-heavy index entry
49
+ * reads ~15 pts worse than a tiny namesake's clean one), so within-tier ordering keys on this instead; the #369
50
+ * anchor re-rank adds `anchorWeight × posterior[country]` on top. Optional — backends that don't compute it degrade
51
+ * to score-based ordering.
52
+ */
53
+ prominence?: number
54
+ /**
55
+ * Set by the backend when this candidate is an EXACT name/alias match for the query (vs a partial token match). The
56
+ * postcode-anchor re-rank (#369) uses it as the PRIMARY key so a country posterior can pin the country WITHOUT
57
+ * crossing the exact-match tier: "ME" under a confident US posterior stays Maine (US exact) rather than promoting the
58
+ * more-populous Missouri (US partial), and still beats Messina (IT exact) on the posterior WITHIN the exact tier.
59
+ * Absent → treated as non-exact (backends that don't tier omit it; the re-rank degrades to a plain score+posterior).
60
+ */
61
+ exactMatch?: boolean
62
+ /**
63
+ * Set when the resolver detected that the address's postcode and its parsed locality name point to geographically
64
+ * different places (a transposed / wrong-for-the-city postcode). Surfaced onto the resolved node's metadata as
65
+ * `postcode_city_mismatch` so callers can lower confidence or flag the conflict instead of silently mislocating.
66
+ */
67
+ mismatch?: boolean
68
+ /**
69
+ * Fallback-observability marker (#718). Set to `"fallback"` by the resolver when this span resolved to a
70
+ * placetype-EQUIVALENCE-GROUP member (a macro-type — `macroregion`/`macrocounty`) because no candidate of the EXACT
71
+ * requested placetype (`region`/`county`) existed. It does NOT change the resolved identity or coordinate — it only
72
+ * annotates that a broader admin tier stood in for the true one, so a downstream consumer / QA pass can see a
73
+ * macroregion was used in lieu of a region. Surfaced onto the resolved node's metadata as `resolution_quality`.
74
+ * Absent when the exact placetype matched (the normal case).
75
+ */
76
+ resolutionQuality?: "fallback"
77
+ }
78
+
79
+ /**
80
+ * Pull-based contract for a single resolver query. The resolver knows nothing about `AddressTree` — it just answers
81
+ * "what place is named X, optionally constrained by Y?"
82
+ *
83
+ * Structurally compatible with `PlaceLookup` from `@mailwoman/core/resolver-wof-sqlite` so the latter satisfies this
84
+ * interface without an adapter shim.
85
+ */
86
+ export interface ResolverBackend {
87
+ findPlace(query: {
88
+ text: string
89
+ placetype?: string | string[]
90
+ country?: string
91
+ parentID?: number | string
92
+ /**
93
+ * Sibling postcode string, when the address carries one. A coordinate-first backend uses it to inject
94
+ * postcode-proximal locality candidates (the postcode→locality table) and soft-score them against the parsed name —
95
+ * recovering localities the name-match alone misses. Backends without postcode support ignore it.
96
+ */
97
+ postcode?: string
98
+ /** Proximity-bias points — a SOFT prominence re-rank; backends without support ignore it. */
99
+ bias?: Array<{ lat: number; lon: number; weight?: number }>
100
+ limit?: number
101
+ }): Promise<ResolvedPlace[]>
102
+ /**
103
+ * The dual-role locality (or localities) coincident with an admin place id, from the precomputed coincident-roles
104
+ * relation (#403). Drives {@link ResolveOpts.hierarchyCompletion}: when the parse drops the locality of a city-state /
105
+ * capital-seat region, the resolver completes it from here instead of re-querying. OPTIONAL — backends without the
106
+ * relation omit it, and completion no-ops. Synchronous: it's an in-memory map lookup once the relation is loaded.
107
+ */
108
+ coincidentLocalitiesFor?(adminID: number | string): CoincidentLocality[]
109
+ /**
110
+ * The ancestor lineage of a resolved place — its containment chain (county → region → country), nearest-first. Backs
111
+ * {@link ResolveOpts.includeAncestors} (#404): the Pelias/Nominatim "always-attach-the-hierarchy" enrichment. OPTIONAL
112
+ * — backends without it omit it, and the attachment is skipped. Synchronous: a memoized read of the gazetteer's
113
+ * `ancestors` table.
114
+ */
115
+ ancestors?(id: number | string): Ancestor[]
116
+ }
117
+
118
+ /** One link in a resolved place's containment lineage ({@link ResolverBackend.ancestors}, #404). */
119
+ export interface Ancestor {
120
+ id: number | string
121
+ placetype: string
122
+ name: string
123
+ }
124
+
125
+ /**
126
+ * A dual-role locality returned by {@link ResolverBackend.coincidentLocalitiesFor} — a resolved place (so it can
127
+ * decorate a node directly) plus the relation metadata the completion step disambiguates on.
128
+ */
129
+ export interface CoincidentLocality extends ResolvedPlace {
130
+ /**
131
+ * `city-state` / `capital-seat` / `consolidated-county` — surfaced as `metadata.relationship_type`.
132
+ */
133
+ relationshipType: string
134
+ /** Locality population (0 when unknown) — the PRIMARY disambiguator when an admin has several. */
135
+ population: number
136
+ /** Centroid distance (km) admin↔locality from the relation — the population tiebreak. */
137
+ distanceKm: number
138
+ }
139
+
140
+ /**
141
+ * Options for `resolveTree`. All optional with sensible defaults.
142
+ */
143
+ /**
144
+ * One exact address-point hit (#476): a real situs coordinate for `(street, number)` within a postcode/locality scope —
145
+ * the street-level tier in front of admin-centroid resolution.
146
+ */
147
+ export interface AddressPointHit {
148
+ lat: number
149
+ lon: number
150
+ /** Provenance, e.g. `"overture:NAD"`. */
151
+ source: string
152
+ /** Pinned data release the point came from, e.g. `"2026-05-20.0"`. */
153
+ release: string
154
+ }
155
+
156
+ /**
157
+ * Street-level exact-point lookup (#476). Implementations own their normalization — both the shard build and this
158
+ * lookup must apply the SAME normalizer (see `resolver-wof-sqlite/street-normalize.ts`). Core depends only on this
159
+ * contract.
160
+ */
161
+ export interface AddressPointLookup {
162
+ find(query: {
163
+ street: string
164
+ number: string
165
+ postcode?: string
166
+ locality?: string
167
+ /**
168
+ * Optional bbox scope (`minLat`/`maxLat`/`minLon`/`maxLon`), tried AFTER postcode/locality. For shards whose points
169
+ * carry no postcode/locality of their own (OSM addr nodes often don't) but DO carry a coordinate — the resolved
170
+ * locality's bounding box scopes the `(street, number)` probe instead. US situs never passes it (byte-stable).
171
+ */
172
+ bbox?: { minLat: number; maxLat: number; minLon: number; maxLon: number }
173
+ }): AddressPointHit | null
174
+ }
175
+
176
+ /**
177
+ * One interpolated coordinate estimate (#483) — NEVER an exact situs point (`uncertaintyM` prices the estimate
178
+ * honestly). Structural mirror of `InterpolatedHit` in `resolver-wof-sqlite/interpolation.ts`; keep this a SUBSET of
179
+ * that shape so the concrete `StreetInterpolator`/`AddressPointInterpolator` satisfy {@link InterpolationLookup} with no
180
+ * adapter (the {@link AddressPointHit} precedent).
181
+ */
182
+ export interface InterpolatedPointHit {
183
+ lat: number
184
+ lon: number
185
+ interpolated: true
186
+ /**
187
+ * `address_point` = bracketed between real neighbor points; `tiger_range` = linear within a segment range.
188
+ */
189
+ method: "address_point" | "tiger_range"
190
+ /** False when only the opposite side's range contained the number (right block, wrong side). */
191
+ parityMatched?: boolean
192
+ /** `both` = neighbors bracketed it; `single` = one-sided extrapolation (larger uncertainty). */
193
+ bracket?: "both" | "single"
194
+ /** Honest uncertainty radius in METERS (half the matched segment length). */
195
+ uncertaintyM: number
196
+ source: string
197
+ release: string
198
+ }
199
+
200
+ /**
201
+ * House-number interpolation lookup (#483). Like {@link AddressPointLookup}, implementations own their normalization
202
+ * (the shared `resolver-wof-sqlite/street-normalize.ts`); core depends only on this contract. Postcode-scoped (no
203
+ * locality field) — the tier abstains statewide without a postcode.
204
+ */
205
+ export interface InterpolationLookup {
206
+ find(query: { street: string; number: string; postcode?: string }): InterpolatedPointHit | null
207
+ }
208
+
209
+ /**
210
+ * One street-CENTROID hit (#1042) — the street-level tier BELOW the exact address-point tier and ABOVE admin-centroid
211
+ * resolution. A street's centroid + an honest extent-derived radius, for a street-only query (no house number) that an
212
+ * address-point tier cannot serve by definition. Derived from a national register's rooftop points
213
+ * (`street-centroids-<cc>.db`, a `GROUP BY street` roll-up). `uncertaintyM` prices the coarseness (half the street's
214
+ * bbox diagonal) so a consumer never mistakes it for a rooftop.
215
+ */
216
+ export interface StreetCentroidHit {
217
+ lat: number
218
+ lon: number
219
+ /** Honest coarse radius in METERS — half the street's bounding-box diagonal. */
220
+ uncertaintyM: number
221
+ source: string
222
+ release: string
223
+ }
224
+
225
+ /**
226
+ * Street-centroid lookup (#1042). Like {@link AddressPointLookup}, implementations own their normalization (the shared
227
+ * `resolver-wof-sqlite/street-normalize.ts`); core depends only on this contract. Scoped by `postcode` (preferred) or
228
+ * `locality` (the base commune) — NO house number: this is the street-only tier.
229
+ */
230
+ export interface StreetCentroidLookup {
231
+ find(query: { street: string; postcode?: string; locality?: string }): StreetCentroidHit | null
232
+ }
233
+
234
+ export interface ResolveOpts {
235
+ /**
236
+ * Hard cap on how many backend lookups one tree may issue. Default 10. Prevents a tree with dozens of candidate nodes
237
+ * from triggering dozens of queries.
238
+ */
239
+ maxLookups?: number
240
+ /**
241
+ * Minimum candidate score before resolver attribution wins over the classifier's. Default 0. A higher threshold makes
242
+ * the resolver more conservative — it leaves more nodes with classifier provenance. Score scale is
243
+ * implementation-defined; tune per backend.
244
+ */
245
+ minWinningScore?: number
246
+ /**
247
+ * Maximum candidates to request from the backend per lookup. Default 5 — we only use the top candidate after
248
+ * post-scoring, but the backend may benefit from over-fetching for ranking.
249
+ */
250
+ candidatesPerLookup?: number
251
+ /**
252
+ * Default ISO-3166 alpha-2 country to constrain top-level lookups to, when no resolved parent has supplied a country
253
+ * yet. Without it, a bare component over a multi-country gazetteer (e.g. "IL") can fuzzy-match a foreign place.
254
+ * Callers should set this from the detected locale (the pipeline's locale-gate). A resolved parent's country still
255
+ * overrides it deeper in the tree.
256
+ */
257
+ defaultCountry?: string
258
+ /**
259
+ * Ordered proximity-bias points (viewport center first, then user location, …), each optionally weighted (default
260
+ * 1.0). SOFT ranking signal only — candidates near a bias point win prominence ties (the ambiguous-postcode case:
261
+ * "48026" follows the map view to Michigan or Italy); recall and filters are untouched, and omitting it keeps ranking
262
+ * byte-identical. Callers: the CLI's `--bias lat,lon[:weight]`, the demo's viewport/user hints, `GeocodeDeps.bias`.
263
+ */
264
+ bias?: Array<{ lat: number; lon: number; weight?: number }>
265
+ /**
266
+ * When a resolved parent constrains a child lookup (`parentID` is passed to the backend as a hard descendant filter)
267
+ * and that filtered lookup returns NOTHING, retry the lookup once without the parent constraint. Guards against an
268
+ * incomplete gazetteer hierarchy (a real locality whose ancestor chain is missing its region) or a mis-resolved
269
+ * parent silently turning a resolvable node unresolved. The country constraint is retained on the retry, so
270
+ * resolution still can't wander cross-border. Default true. Set false to measure the strict-parent baseline.
271
+ */
272
+ parentFallback?: boolean
273
+ /**
274
+ * Override the default ComponentTag → resolver-placetype mapping. When set, this map FULLY REPLACES
275
+ * `DEFAULT_PLACETYPE_MAP` — start from the default by spreading it (`{ ...DEFAULT_PLACETYPE_MAP, ... }`) if you want
276
+ * to extend rather than replace. The fully- replacing semantics let callers narrow the resolver scope (e.g. drop
277
+ * `locality` if the backend doesn't ship locality data for the current locale) without awkward `undefined`-as-delete
278
+ * tricks.
279
+ */
280
+ placetypeMap?: PlacetypeMap
281
+ /**
282
+ * Optional locale hint. Currently unused by the v1 resolver but reserved so the contract doesn't break when
283
+ * locale-aware resolvers land in 4.4+.
284
+ */
285
+ locale?: string
286
+ /**
287
+ * Optional postcode-anchor country posterior (#369) — a `{ countryCode: probability }` map derived from the address's
288
+ * postcode (e.g. `@mailwoman/neural`'s `extractPostcodeAnchors`). When provided, LOCALITY candidates are re-ranked by
289
+ * `score + anchorWeight * posterior[candidate.country]` before the top is picked, so a postcode that pins the country
290
+ * can pull the right-country place over a higher-BM25 foreign namesake (the "Berlin DE vs Berlin US" class the #59
291
+ * anchor→resolver harness measured). OFF by default — omit it and resolution is byte-identical. Country signal only,
292
+ * so it touches locality lookups only; admin parents already carry country via `parentID`.
293
+ */
294
+ anchorPosterior?: Record<string, number>
295
+ /**
296
+ * Weight on the anchor's country posterior in the locality re-rank (#369). Default 2.0 (the value the harness swept).
297
+ * Only consulted when `anchorPosterior` is set.
298
+ */
299
+ anchorWeight?: number
300
+ /**
301
+ * #743/#194 — a CONFIDENT coarse-placer country applied as a HARD candidate filter (`query.country`), not the soft
302
+ * {@link anchorPosterior} boost. This collapses the off-continent tail for LOW-population places the soft prior can't
303
+ * move (FI/PL — their towns lose to a high-pop namesake in the population-first gazetteer even when the country is
304
+ * pinned). On a miss the node is left UNRESOLVED ("in-region or unresolved") rather than re-resolved globally — the
305
+ * off-continent rows are precisely the ones whose locality isn't in the country's gazetteer slice, so a global
306
+ * fallback just re-admits the wrong-continent guess (measured: it collapses back to the soft-prior baseline). The win
307
+ * is coverage-bounded: tail collapse at a recall cost set by how complete the country's gazetteer is (PL −9.5pp, FI
308
+ * −32pp). Undefined (default) → byte-stable. Ignored when a resolved parent or {@link defaultCountry} already pins
309
+ * the country.
310
+ */
311
+ hardCountry?: string
312
+ /**
313
+ * Recover the dropped locality in a DUAL-ROLE-place address (#405, epic #402). Many places occupy multiple admin
314
+ * tiers under one name — city-states (Berlin/Hamburg/Bremen = city == state), capital-seat provinces (Milano,
315
+ * Madrid), UK unitary authorities — and in the international-order layout `…, Berlin, Berlin <PC>` the parser labels
316
+ * one token the region and drops the locality entirely, leaving a region but no locality (955/1500 Berlin rows
317
+ * resolved to nothing on v0.9.4).
318
+ *
319
+ * When this is on AND a region resolved AND the tree has NO locality node, the resolver consults the backend's
320
+ * precomputed coincident-roles relation ({@link ResolverBackend.coincidentLocalitiesFor}, #403) for a same-name
321
+ * coincident locality and synthesizes a node from it. The relation is the gazetteer's own structure (same name +
322
+ * descendant + centroid-coincidence, derived at build time), so the runtime is an O(1) membership lookup — no magic
323
+ * distance constant. When an admin maps to several same-name localities, the most populous wins (the principal city),
324
+ * nearest-centroid breaks a population tie, and a genuine tie ABSTAINS (no completion) rather than guess. The
325
+ * synthesized node carries `metadata.resolver_synthesized = true` (+ `relationship_type`) — it has no span in the raw
326
+ * input. ON by default (#402): it only fires for a dual-role region whose locality the parser dropped, and no-ops
327
+ * entirely when the backend has no relation (the browser WASM resolver, or a gazetteer without the `coincident_roles`
328
+ * table). Pass `false` to opt out.
329
+ */
330
+ /**
331
+ * Street-level address-point tier (#476): when the tree carries `street` + `house_number`, consult this lookup and
332
+ * (on hit) stamp the exact point onto the street node's metadata (`address_point`, `resolution_tier:
333
+ * "address_point"`). Opt-in; absent = byte-stable.
334
+ */
335
+ addressPoints?: AddressPointLookup
336
+ /**
337
+ * Pass the resolved locality's BBOX to the address-point lookup as a final scope (#247). For shards whose points
338
+ * carry no postcode/locality of their own (OSM addr nodes often don't), the postcode/locality probes miss and the
339
+ * lookup falls through to a `(street, number)` probe within the box. OFF by default — US situs never sets it, so the
340
+ * bbox arg is simply never supplied and its postcode/locality probes are byte-identical.
341
+ */
342
+ addressPointBboxFallback?: boolean
343
+ /**
344
+ * House-number interpolation tier (#483): consulted ONLY when the exact address-point tier ({@link addressPoints})
345
+ * did NOT stamp the street node — the "after the exact-point fall-through" semantics. On hit, stamps the estimate
346
+ * onto the street node's metadata under a DISTINCT key (`interpolated_point`, `resolution_tier: "interpolated"`,
347
+ * `uncertainty_m`) — never `address_point`, so a consumer reading the exact key never gets an estimate mislabeled as
348
+ * exact. Opt-in; absent = byte-stable. Independent of {@link addressPoints} (either, both, or neither may be
349
+ * passed).
350
+ */
351
+ interpolation?: InterpolationLookup
352
+ /**
353
+ * Conformal calibration multiplier for the interpolation tier's `uncertainty_m` (#374). The raw radius is half the
354
+ * matched TIGER segment length — an honest-but-TIGHT prior: a split-conformal calibration on 1562 Travis-County
355
+ * interp hits (2026-06-14) found it covers only ~72% of true errors, and that multiplying by **Q̂ ≈ 1.70** yields a
356
+ * calibrated 90% bound (91.5% empirical). When set, `applyInterpolation` reports `uncertainty_m = round(raw × this)`
357
+ * and preserves the raw value under `uncertainty_raw_m`. Absent = raw heuristic (byte-stable). The factor is the
358
+ * CALLER's (it's a property of the calibration set, not the geometry); the geocode CLI passes the TX-derived 1.70.
359
+ * Re-calibrate on a multi-region holdout before treating it as national-exact. Report:
360
+ * docs/articles/evals/calibration/2026-06-14-interp-radius-calibration.md.
361
+ */
362
+ interpolationRadiusCalibration?: number
363
+ /**
364
+ * Street-centroid tier (#1042): consulted for a STREET-ONLY query (a street/thoroughfare with NO house number) that
365
+ * neither the address-point nor the interpolation tier can serve. On a hit, injects/stamps a resolved `street` node
366
+ * carrying the street's centroid under a DISTINCT metadata key (`street_centroid`, `resolution_tier: "street"`,
367
+ * `uncertainty_m`) — never `address_point`/`interpolated_point`, so a consumer reading the exact keys never gets a
368
+ * coarse centroid mislabeled as a rooftop. The thoroughfare + commune are recovered raw-text-first (the FR no-street
369
+ * class mis-parses the thoroughfare as a locality — #901 composition-insensitive), so the tier rides the model where
370
+ * it works and recovers where it fails.
371
+ *
372
+ * A COUNTRY-KEYED PROVIDER (not a bare lookup) because the country signal for a street-only query is unreliable
373
+ * BEFORE resolution: a bare thoroughfare ("Avenue des Champs-Élysées, Paris") is a bare-locality tree the placer is
374
+ * skipped on, and the placer mis-routes some French streets ("Rue Sainte-Catherine" → IT). So the tier probes a UNION
375
+ * of candidate countries — {@link streetCountryHints} (pre-resolution: defaultCountry + the ungated placer) PLUS the
376
+ * countries the tree actually RESOLVED to — and the exact (street, base-commune) match is itself the country filter.
377
+ * Opt-in; absent = byte-stable. Never fires when a house number is present (rooftop tiers untouched) or when a
378
+ * street-level coordinate already resolved.
379
+ */
380
+ streetCentroids?: (country: string) => StreetCentroidLookup | undefined
381
+ /**
382
+ * Ordered pre-resolution country hints for the {@link streetCentroids} tier — the caller's defaultCountry and the
383
+ * (ungated) coarse-placer country. The tier unions these with the resolved-tree countries. Absent = only the resolved
384
+ * countries are tried.
385
+ */
386
+ streetCountryHints?: readonly string[]
387
+ /**
388
+ * Span-rescore tier (#370). When the tree resolved nothing, recover a dropped/fragmented locality from the raw text:
389
+ * enumerate raw-token spans, exact-match the same-country gazetteer (longest-wins + postcode-consistency gate), and
390
+ * inject the recovered locality as a resolved node. Targets the EU no-result tail the model leaves when it fragments
391
+ * an accented locality token ("Grudziądz" → "Grudzi"+"dz", #555). **Default-ON** (promoted 2026-06-25 — same-harness
392
+ * EU+AU +1pp @25km, zero regressions); set `false` to opt out (byte-stable then). Never disturbs a tree that already
393
+ * resolved (the #685 brake). Validated in `docs/articles/evals/experiments/2026-06-23-370-span-rescore.mdx` +
394
+ * `2026-06-25-eu-competitive-standing.md`.
395
+ */
396
+ spanRescore?: boolean
397
+ /**
398
+ * Postcode-consistency gate radius (km) for the span-rescore tier — reject a recovered locality farther than this
399
+ * from where the postcode resolves. Only bites when the backend has postcode coverage (else no anchor, no gate).
400
+ * Default 50.
401
+ */
402
+ spanRescoreGateKm?: number
403
+ /**
404
+ * Postal-compound recovery inside the span-rescore tier (#942). The knife-edge no-street query shape ("Kožljek 7,
405
+ * 1382 Kožljek") fails as a COMPOUND: the parse globs the trailing city into the postcode span ("1382 Kožljek"),
406
+ * which then (a) resolves as neither postcode nor locality and (b) BLOCKS its own city tokens from span-rescore's
407
+ * recovery (a confident postcode span is avoided). Proven training-composition-insensitive on #901 — five vehicles
408
+ * including a full from-scratch retrain all tip this class, so the floor lives here, model-independently.
409
+ *
410
+ * When on and the tree resolved nothing: the failed postcode span only blocks its CODE-shaped tokens (digit-bearing;
411
+ * the residual city tokens become recoverable), the postcode-consistency anchor retries with that code subset, and
412
+ * the failed postcode NODE is decorated from the code resolution (a postcode-tier coordinate floor, strictly
413
+ * subordinate to a recovered locality). Never fires on a resolved tree (the #685 brake).
414
+ *
415
+ * **Default ON** (operator-promoted 2026-07-03 after the pre-registered gate: SI 25/25 recovery at p50 0.67 km, US/FR
416
+ * byte-identical, and the insurance leg — the composition-failed v2.2.0 candidate recovers all 55 lost rows). Set
417
+ * `false` to opt out (byte-stable then).
418
+ */
419
+ postalCompoundRecovery?: boolean
420
+ /**
421
+ * Postcode-disambiguated locality selection (#370 "Lever A"). When set, AND a locality resolves far from a resolved
422
+ * sibling postcode, re-pick the same-named candidate (from the lookup's already- captured `alternatives`) nearest the
423
+ * postcode; if none reconciles within the gate, fall the coordinate back to the postcode point and flag
424
+ * `postcode_city_mismatch`. Targets the dominant failure mode on the EU/AU panel — a same-named town resolved to the
425
+ * wrong instance while the postcode that would disambiguate it sits resolved in the same tree (e.g. "06260
426
+ * Saint-Pierre" → 617 km off, postcode 06260 correct). Only bites where the backend resolved the postcode to a point
427
+ * (so it composes with postcode coverage, #193).
428
+ *
429
+ * **Default ON** (operator-promoted 2026-07-04 after the corrected gate: FI 231 wins / 0 losses, SI 37/6, CZ 47/2, US
430
+ * aggregates byte-flat with 9/2,000 rows touched — the four losses being two golden-data errors the pass correctly
431
+ * flags as `postcode_city_mismatch` and one bad ZIP centroid). Explicit `false` opts out (byte-stable then).
432
+ */
433
+ postcodeConsistency?: boolean
434
+ /**
435
+ * Gate radius (km) for {@link postcodeConsistency} — a locality farther than this from the resolved postcode is
436
+ * re-picked or demoted. Default 50.
437
+ */
438
+ postcodeConsistencyGateKm?: number
439
+ /**
440
+ * Admin descendant-consistency (#263). When a region resolved but its child locality did NOT — the greedy region pick
441
+ * (name + population) chose a foreign namesake whose descendants hold no such locality ("Portland, ME" → Messina IT;
442
+ * "Portland" then finds nothing beneath it and falls back to the region centroid) — re-pick the (region, locality)
443
+ * pair JOINTLY against the gazetteer's containment graph: the best same-named locality that descends from one of the
444
+ * region's same-named candidates. "Portland" descends from Maine, not Messina, so the pair resolves to (Maine,
445
+ * Portland-Maine). Generalizes to every country with no country prior and no list. Costs ONE unscoped locality lookup
446
+ * per triggering admin pair; only fires where a locality fell through, so the well-resolved path is byte-identical.
447
+ * Needs {@link ResolverBackend.ancestors}; no-op without it. **Default-ON** (#895 settled drift D1 — the geocode path
448
+ * had run it since #837 while raw `resolveTree` callers silently didn't); byte-stable wherever nothing fell through
449
+ * or the backend lacks `ancestors`. Pass `false` to opt out.
450
+ */
451
+ adminCoherence?: boolean
452
+ hierarchyCompletion?: boolean
453
+ /** @deprecated Renamed to {@link hierarchyCompletion} (#405 generalized #387). Still honored. */
454
+ cityStateFallback?: boolean
455
+ /**
456
+ * Attach each resolved node's ancestor lineage (#404) — the containment chain (county → region → country) the
457
+ * backend's {@link ResolverBackend.ancestors} returns — onto `metadata.ancestors`. The Pelias/Nominatim
458
+ * "always-attach-the-hierarchy" enrichment, so a consumer gets the full admin ladder from a single resolved place.
459
+ * OFF by default: omit it and resolution is byte-identical (and there's no extra query). Only attaches to nodes the
460
+ * resolver actually resolved.
461
+ */
462
+ includeAncestors?: boolean
463
+ }
464
+
465
+ /**
466
+ * Mapping from mailwoman's address-component tags to the resolver's placetype taxonomy. Components not present in the
467
+ * map are NOT queried — the resolver pass leaves their classifier attribution untouched.
468
+ *
469
+ * Phase 4.3 default ships the obvious admin-level mappings; other tags (postcode, street, venue, dependent_locality,
470
+ * prefecture, etc.) are explicitly omitted because:
471
+ *
472
+ * - `postcode` lives in a separate WOF shard (Phase 4.3.x follow-up via the postalcode loader).
473
+ * - `street` / `house_number` aren't in WOF admin — would need OSM / OpenAddresses gazetteers and license diligence
474
+ * (Phase 4.4 candidate).
475
+ * - Non-US JP-specific tags wait on a different shard entirely.
476
+ */
477
+ export type PlacetypeMap = Partial<Record<ComponentTag, string>>
478
+
479
+ export const DEFAULT_PLACETYPE_MAP: PlacetypeMap = {
480
+ country: "country",
481
+ region: "region",
482
+ locality: "locality",
483
+ dependent_locality: "locality",
484
+ subregion: "county",
485
+ // `postcode` (mailwoman tag) maps to WOF's `postalcode` placetype. Resolves only when the
486
+ // backend has the postcode shard available — `WOFSqlitePlaceLookup` auto-routes `postalcode`
487
+ // queries to a `postalcode_us` (or similarly-named) shard, falling back to main if absent.
488
+ postcode: "postalcode",
489
+ }
490
+
491
+ /**
492
+ * Placetype-equivalence groups for lookup FILTERING. WOF splits a single addressing tier across several placetypes, but
493
+ * an address's span can name ANY of them. A backend that filters to the one "obvious" placetype makes the equivalents
494
+ * unreachable, so a fuzzy same-name place in the wrong tier wins instead.
495
+ *
496
+ * Three tiers are affected (the value of each entry is the set the SQL filter should accept; the FIRST entry is the
497
+ * canonical/requested type, which shard routing keys off):
498
+ *
499
+ * - **`locality`** — `locality` (most cities), `borough` (Brooklyn, the Paris arrondissements, the London boroughs), and
500
+ * `localadmin` (FR communes, US towns/townships in New England). Without the group, Brooklyn-the-borough (pop 2.5M)
501
+ * was unreachable and the fuzzy "Brooklyn Park, MN" won.
502
+ * - **`region`** — `region` + `macroregion` (#718). WOF does NOT model every country's top-level civil division as
503
+ * `region`: Italian regions (Lombardia, Veneto, Toscana…) are `macroregion` (their PROVINCES are `region`), and the
504
+ * post-2016 French régions (Île-de-France) are `macroregion` too. An address's `region` span names exactly those, so
505
+ * a `region`-only filter resolved them to NOTHING (confirmed against the IT/FR eval rows). US states / DE
506
+ * Bundesländer / ES provincias are genuine `region`, so the EXACT-type match is preferred in ranking (see the
507
+ * resolve.ts fallback-quality annotation) — the macro is the recall safety net, not a demotion.
508
+ * - **`county`** — `county` + `macrocounty` (#718). The `subregion` ComponentTag maps to `county` via
509
+ * {@link DEFAULT_PLACETYPE_MAP}; WOF carries `macrocounty` for FR départements-grouping / DE / GB tiers above the
510
+ * county. Proactive (no eval row exercises `subregion` today) but symmetric with `region` — biasing to inclusion,
511
+ * since a missed resolution costs more than a too-broad candidate (which is QA-visible). Same exact-type preference
512
+ * applies.
513
+ *
514
+ * This table is the single source of truth for that expansion, shared by every lookup backend
515
+ * (`@mailwoman/core/resolver-wof-sqlite`, `@mailwoman/core/resolver-wof-wasm`, and the demo's httpvfs lookup) so the
516
+ * Node and browser resolvers can't drift. Keyed by the REQUESTED placetype. Placetypes without an entry pass through
517
+ * unchanged — an explicit `placetype: "borough"` query stays narrow.
518
+ */
519
+ export const PLACETYPE_FILTER_GROUPS: Readonly<Record<string, readonly string[]>> = {
520
+ locality: ["locality", "borough", "localadmin"],
521
+ region: ["region", "macroregion"],
522
+ county: ["county", "macrocounty"],
523
+ }
524
+
525
+ /**
526
+ * Expand a placetype filter through {@link PLACETYPE_FILTER_GROUPS}, deduplicated and order-preserving (the first entry
527
+ * stays first — shard routing keys off it). `null`/`undefined` (no filter) passes through untouched.
528
+ */
529
+ export function expandPlacetypeFilter(placetypes: null): null
530
+ export function expandPlacetypeFilter(placetypes: readonly string[]): string[]
531
+ export function expandPlacetypeFilter(placetypes: readonly string[] | null): string[] | null
532
+ export function expandPlacetypeFilter(placetypes: readonly string[] | null): string[] | null {
533
+ if (!placetypes) return null
534
+ const out: string[] = []
535
+
536
+ for (const placetype of placetypes) {
537
+ for (const expanded of PLACETYPE_FILTER_GROUPS[placetype] ?? [placetype]) {
538
+ if (!out.includes(expanded)) {
539
+ out.push(expanded)
540
+ }
541
+ }
542
+ }
543
+
544
+ return out
545
+ }
546
+
547
+ /**
548
+ * Macro/broader-tier members of {@link PLACETYPE_FILTER_GROUPS} — the recall safety net a query may fall through to
549
+ * when no candidate of the EXACT requested placetype exists (#718). DELIBERATELY scoped to the `macro*` tiers only: the
550
+ * `locality` group's `borough`/`localadmin` are genuine peers (Brooklyn-the-borough is a first-class locality answer,
551
+ * #404-class), NOT fallbacks — so they must NOT be deprioritized or annotated. Only `macroregion`/`macrocounty` are a
552
+ * broader admin tier standing in for a true `region`/`county`.
553
+ */
554
+ const MACRO_FALLBACK_PLACETYPES: ReadonlySet<string> = new Set(["macroregion", "macrocounty"])
555
+
556
+ /**
557
+ * Did `candidatePlacetype` resolve `requestedPlacetype` only via a BROADER admin tier (a macro-type fallback within the
558
+ * {@link PLACETYPE_FILTER_GROUPS} expansion), rather than the exact type (#718)?
559
+ *
560
+ * `region` → `region` is exact (false); `region` → `macroregion` is a fallback (true). Scoped to the `macro*` tiers
561
+ * (see {@link MACRO_FALLBACK_PLACETYPES}) so the `locality` group's borough/localadmin peers stay exact. The resolver
562
+ * uses this to (a) prefer an exact-type candidate in ranking and (b) annotate `resolutionQuality: "fallback"` when only
563
+ * a macro-type matched. A placetype outside the requested group, or any non-macro member, is treated as exact (false).
564
+ */
565
+ export function isPlacetypeFallback(requestedPlacetype: string, candidatePlacetype: string): boolean {
566
+ const group = PLACETYPE_FILTER_GROUPS[requestedPlacetype]
567
+
568
+ if (!group) return false
569
+
570
+ if (candidatePlacetype === requestedPlacetype) return false
571
+
572
+ return MACRO_FALLBACK_PLACETYPES.has(candidatePlacetype) && group.includes(candidatePlacetype)
573
+ }
574
+
575
+ /**
576
+ * The interface implemented by `createWOFResolver` and any future resolver factories.
577
+ *
578
+ * `resolveTree` returns a NEW `AddressTree` rather than mutating — keeps the input safe to inspect after the call. The
579
+ * new tree's `roots` are fresh `AddressNode` objects; nodes the resolver didn't touch are structurally cloned with
580
+ * their classifier attribution preserved.
581
+ */
582
+ export interface Resolver {
583
+ resolveTree(tree: AddressTree, opts?: ResolveOpts): Promise<AddressTree>
584
+ }