@mailwoman/resolver 9.0.0 → 9.1.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 CHANGED
@@ -118,6 +118,8 @@ export function applyAddressPoint(roots: AddressNode[], lookup: AddressPointLook
118
118
 
119
119
  if (!street || !houseNumber) return
120
120
 
121
+ if (street.metadata?.["resolution_tier"] === "address_point") return
122
+
121
123
  // #247 OSM bbox fall-through: when enabled (an OSM shard is wired) and the locality resolved to a
122
124
  // coordinate, scope a final `(street, number)` probe by the locality's box — recovering OSM points that
123
125
  // carry no postcode/locality tag of their own. US situs never enables it, so its probes are byte-identical.
@@ -0,0 +1,278 @@
1
+ /**
2
+ * @copyright Sister Software
3
+ * @license AGPL-3.0
4
+ * @author Teffen Ellis, et al.
5
+ *
6
+ * #17 bare city-name disambiguation — two SOFT ranking keys for the bare-toponym class.
7
+ *
8
+ * A bare city name is the one query shape where the resolver has no geography to reason with: no
9
+ * postcode to anchor against, no region to scope by, no country the address itself named. All that
10
+ * is left is a prior over which same-named place a person typing that word alone probably meant.
11
+ * The shipped prior is POPULATION, and population is measurably the wrong prior for this class —
12
+ * the panel run of 2026-08-10 caught it four times over:
13
+ *
14
+ * | query | population winner | gold | miss |
15
+ * | ------- | -------------------- | --------------------- | -------- |
16
+ * | Whitby | Whitby ON (128,377) | Whitby, N Yorks (13,130) | 5,508 km |
17
+ * | Warwick | Warwick RI (82,999) | Warwick, Warks (32,719) | 5,211 km |
18
+ * | Epping | Epping VIC (32,395) | Epping, Essex (12,547) | 16,874 km |
19
+ * | Windsor | Windsor ON (217,188) | Windsor, Berks (26,885) | 6,007 km |
20
+ *
21
+ * Every one of those is a place people know for something other than its size, and the gazetteer
22
+ * already measures that: `admin-global-priority-importance.db` ranks all four the RIGHT way round
23
+ * (Whitby GB 0.5496 over CA 0.5089; Windsor GB 0.5648 over CA 0.5607 — a 0.004 margin population
24
+ * inverts by a factor of eight). What it measures is a BLENDED global toponym prior
25
+ * (`ResolvedPlace.importance`): the concordance's encyclopedia-derived channel where a concordance
26
+ * matched, a population-derived proxy everywhere else — the one scale on which every bearer of a
27
+ * name is scored comparably, which is the precondition for comparing them at all.
28
+ * {@link rankByImportance} consumes it. (The STRICT encyclopedia-evidence channel keeps its own
29
+ * reserved slot, `ResolvedPlace.encyclopedic`, which no ranking key reads and no shipped artifact
30
+ * yet populates — see `core/resolver/types.ts`.)
31
+ *
32
+ * {@link rankByCountryPrior} covers the other half of the class — the query where a country IS
33
+ * known, but only because a locale said so. See `span-rescore.ts` for where that one applies.
34
+ *
35
+ * Both obey the same three house rules, and neither is a gate:
36
+ *
37
+ * 1. **Tier-safe.** `exactMatch` stays the primary key. A soft prior re-orders WITHIN a tier; it never
38
+ * promotes a partial match over an exact one.
39
+ * 2. **Positive evidence only.** An absent score is unmeasured, not zero (the meaning-of-zero rule), so an
40
+ * unscored candidate is never moved BY the signal and never penalized FOR lacking it — it keeps the
41
+ * rank population gave it while the scored rows reorder among themselves. On a candidate.db built
42
+ * before the #28 `importance` column, nothing is scored, so {@link rankByImportance} is
43
+ * byte-stable by construction.
44
+ * 3. **Stable.** Equal keys keep their incoming order, so the backend's own ranking survives underneath.
45
+ */
46
+
47
+ import type { ResolvedPlace } from "@mailwoman/core/resolver"
48
+
49
+ /**
50
+ * Weight of the locale-country bonus, in the same log10-population units the candidate backend's `prominence` uses
51
+ * (`-neg_rank` = log10(population + 1)). 2 == "the in-country place may be up to 100x smaller and still win".
52
+ *
53
+ * The value is the resolver's existing `anchorWeight` default (`resolve.ts`), reused deliberately: that knob is the
54
+ * postcode-anchor country pin, and this is the same quantity from a weaker source, so the two should not disagree about
55
+ * what a country signal is worth. Calibrated against the live board (2026-08-10, shipped `candidate.db`), it moves
56
+ * exactly the queries where the locale is implausible and leaves the rest alone:
57
+ *
58
+ * - `Zürich` en-US — Zurich KS 1.91 + 2 = 3.91 loses to Zürich CH 5.65. **Flips** (was 8,043 km off).
59
+ * - `Berlin` en-US — Berlin CT 4.30 + 2 = 6.30 loses to Berlin DE 6.56. **Flips.**
60
+ * - `Manchester` en-US — Manchester NH 5.06 + 2 = 7.06 beats Manchester GB 5.74. **Held.**
61
+ * - `Springfield` en-US — every bearer is US, so the bonus is uniform. **Held.**
62
+ * - `Moscow` en-US — Moscow ID 4.42 + 2 = 6.42 beats Москва 6.10. **Held.**
63
+ * - `Fulda` en-US — Fulda MN 3.13 + 2 = 5.13 beats Fulda DE 4.84. **Held.**
64
+ */
65
+ export const DEFAULT_COUNTRY_PRIOR_WEIGHT = 2
66
+
67
+ /**
68
+ * Importance margin below which two SAME-COUNTRY bearers are a tie, and the tie falls back to referential (size) order.
69
+ * Ratified 2026-08-11 (the five bare-query flip decisions): bare `Springfield` must stay on the referential answer —
70
+ * the live chain is IL 0.612605 → MA 0.611142 → MO 0.596195 (adjacent gaps 0.0015 and 0.0149, full span 0.0164), so the
71
+ * band must cover at least the 0.0149 adjacent gap for the trio to chain into one cluster.
72
+ *
73
+ * The band never compares across countries, and that scope is forced by decided rows, not preference: Windsor's
74
+ * accepted flip (GB 0.564842 over CA 0.560687) sits at a 0.0042 gap — inside ANY band that covers Springfield. The two
75
+ * decisions are only co-satisfiable if the band binds same-country pairs alone. That is also what the §2 referential
76
+ * policy (ROAD_TO_V9) says: within a country the geocoder ranks referentially; the blended prior's job is the
77
+ * cross-country question — which country's bearer a bare query meant.
78
+ */
79
+ export const SAME_COUNTRY_IMPORTANCE_TIE_BAND = 0.02
80
+
81
+ /**
82
+ * The fields a ranking key reads. Structural rather than `ResolvedPlace` so the backend's own `PlaceCandidate` (a
83
+ * structural twin) can be ranked without a cast.
84
+ */
85
+ type Rankable = Pick<ResolvedPlace, "score"> &
86
+ Partial<Pick<ResolvedPlace, "country" | "exactMatch" | "importance" | "prominence">>
87
+
88
+ /**
89
+ * Partition into (exact, rest), sort each half with `key` DESC, and re-join. The partition is what keeps a soft prior
90
+ * soft: it can only ever re-order candidates the backend already considers equally good matches. Backends that don't
91
+ * stamp `exactMatch` land every row in one tier, which is the correct degradation — the key then applies to the whole
92
+ * list.
93
+ */
94
+ function rankWithinTier<T extends Rankable>(candidates: readonly T[], compare: (a: T, b: T) => number): T[] {
95
+ const exact: T[] = []
96
+ const rest: T[] = []
97
+
98
+ for (const c of candidates) {
99
+ // `exactMatch` is TRI-STATE: true / false / undefined (a backend path that stamps no flag —
100
+ // e.g. WOFSqlitePlaceLookup's postcode-area neighbours from #fetchLocalitiesByID). Only a
101
+ // stated TRUE earns the exact tier; undefined must not outrank a real fuzzy name match
102
+ // (the 2026-08-10 de.native_locality incident: 75 Saxon towns lost to nameless neighbours).
103
+ ;(c.exactMatch === true ? exact : rest).push(c)
104
+ }
105
+
106
+ // `toSorted` is stable, so equal keys keep the backend's incoming order.
107
+ return [...exact.toSorted(compare), ...rest.toSorted(compare)]
108
+ }
109
+
110
+ /**
111
+ * Size, in the backend's own units — the candidate backend's `prominence` is log10(population + 1); a backend that
112
+ * computes no prominence falls back to its raw `score`.
113
+ */
114
+ const size = (c: Rankable): number => c.prominence ?? c.score
115
+
116
+ /**
117
+ * A candidate the gazetteer actually scored. An absent value means "the score source never measured this place" OR
118
+ * "this artifact predates the column" OR "the join refused the row" — three different things, none of them zero.
119
+ */
120
+ const measured = (c: Rankable): boolean => typeof c.importance === "number" && Number.isFinite(c.importance)
121
+
122
+ /**
123
+ * Reorder ONLY the measured candidates, and only among the positions they already occupy.
124
+ *
125
+ * This is what "positive evidence only" has to mean when coverage is partial, which it always is — measured on the
126
+ * shipped importance artifact, the four bare GB panel rows have 2/7, 8/10, 8/10 and 9/10 of their candidates scored. A
127
+ * blanket "abstain unless everything is measured" throws the signal away on all four; treating absent as 0 would let a
128
+ * scored hamlet leapfrog an unscored metropolis. Neither is right, and the resolution is that an unmeasured row simply
129
+ * does not participate: it holds the rank population gave it, and the scored rows permute among the slots they hold
130
+ * between them.
131
+ *
132
+ * So for `Whitby` — CA(0.5089), GB(0.5496), TC(—), then four unscored bearers — the swap is confined to slots 0 and 1,
133
+ * GB takes the lead, and TC never moves.
134
+ */
135
+ function reorderMeasured<T extends Rankable>(tier: readonly T[], order: (measuredRows: T[]) => T[]): T[] {
136
+ const slots: number[] = []
137
+
138
+ for (const [i, c] of tier.entries()) {
139
+ if (measured(c)) {
140
+ slots.push(i)
141
+ }
142
+ }
143
+
144
+ if (slots.length < 2) return [...tier]
145
+ const sorted = order(slots.map((i) => tier[i]!))
146
+ const out = [...tier]
147
+
148
+ for (const [k, slot] of slots.entries()) {
149
+ out[slot] = sorted[k]!
150
+ }
151
+
152
+ return out
153
+ }
154
+
155
+ /**
156
+ * The importance ordering over MEASURED rows, with the {@link SAME_COUNTRY_IMPORTANCE_TIE_BAND} applied.
157
+ *
158
+ * Same-country bearers whose adjacent importance gaps sit inside the band chain into one cluster (transitive on purpose
159
+ * — otherwise the boundary would depend on comparison order), and a cluster orders its members referentially (size
160
+ * DESC). Clusters — including every cross-country row, which is always its own cluster — rank by their most important
161
+ * member, then head size, then input order. A cluster therefore moves as a unit: a same-country near-tie cannot be
162
+ * split by a foreign row falling between its members' scores.
163
+ */
164
+ function orderMeasuredByImportance<T extends Rankable>(rows: readonly T[]): T[] {
165
+ // Group by country in first-appearance order; a row without a country can never substantiate a
166
+ // same-country tie, so it stays a singleton.
167
+ const groups = new Map<string, { firstIndex: number; members: T[] }>()
168
+ const clusters: Array<{ firstIndex: number; members: T[] }> = []
169
+
170
+ for (const [i, row] of rows.entries()) {
171
+ const country = row.country?.toUpperCase()
172
+
173
+ if (!country) {
174
+ clusters.push({ firstIndex: i, members: [row] })
175
+
176
+ continue
177
+ }
178
+
179
+ const group = groups.get(country)
180
+
181
+ if (group) {
182
+ group.members.push(row)
183
+ } else {
184
+ groups.set(country, { firstIndex: i, members: [row] })
185
+ }
186
+ }
187
+
188
+ for (const group of groups.values()) {
189
+ const sorted = group.members.toSorted((a, b) => b.importance! - a.importance! || size(b) - size(a))
190
+ let open: T[] = []
191
+
192
+ for (const row of sorted) {
193
+ if (open.length && open.at(-1)!.importance! - row.importance! > SAME_COUNTRY_IMPORTANCE_TIE_BAND) {
194
+ clusters.push({ firstIndex: group.firstIndex, members: open })
195
+ open = []
196
+ }
197
+
198
+ open.push(row)
199
+ }
200
+
201
+ if (open.length) {
202
+ clusters.push({ firstIndex: group.firstIndex, members: open })
203
+ }
204
+ }
205
+
206
+ const keyed = clusters.map((cluster) => ({
207
+ firstIndex: cluster.firstIndex,
208
+ key: Math.max(...cluster.members.map((m) => m.importance!)),
209
+ members: cluster.members.toSorted((a, b) => size(b) - size(a)),
210
+ }))
211
+
212
+ keyed.sort((a, b) => b.key - a.key || size(b.members[0]!) - size(a.members[0]!) || a.firstIndex - b.firstIndex)
213
+
214
+ return keyed.flatMap((c) => c.members)
215
+ }
216
+
217
+ /**
218
+ * Importance-first ordering — the #28 fame prior, consumed.
219
+ *
220
+ * Ranks by `importance` DESC within the exact tier, with `prominence`/`score` as the tiebreak (two places of equal fame
221
+ * separate on size). Candidates the gazetteer never scored do not participate — they hold the rank population gave them
222
+ * while the scored rows permute among their own slots (see {@link reorderMeasured}). Returns the input untouched when
223
+ * fewer than two candidates are scored.
224
+ *
225
+ * The producer is the candidate build's `importance` column (#28) — the BLENDED prior (the concordance's
226
+ * encyclopedia-derived channel where a concordance matched, a population-derived proxy elsewhere; see
227
+ * `candidate-schema.ts` → `CandidateTable.importance` for why the strict channel is deliberately NOT what lands there).
228
+ * On an artifact predating the column, `importance` is `undefined` on every candidate the backend produces and the
229
+ * abstention below keeps the ranking byte-stable.
230
+ *
231
+ * Flip decisions, ratified 2026-08-11: bare `Moscow`→Москва, `Manchester`→GB, `Fulda`→DE, `Cambridge`→GB are ACCEPTED
232
+ * behavior — all cross-country contests, where this prior answers the question population cannot. Bare `Springfield`
233
+ * ABSTAINS to the referential answer via {@link SAME_COUNTRY_IMPORTANCE_TIE_BAND}; no candidate is dropped, so the
234
+ * runner-up survives as a declared alternative downstream.
235
+ */
236
+ export function rankByImportance<T extends Rankable>(candidates: readonly T[]): T[] {
237
+ if (candidates.length < 2) return [...candidates]
238
+
239
+ // Abstain entirely until at least one candidate carries a MEASURED score — the tier split
240
+ // below is only meaningful as a tiebreak among scored rows. Without this, wiring the consumer
241
+ // before the #28 producer reordered candidates on the exactMatch flag alone (meaning-of-zero:
242
+ // an absent score must not act as evidence).
243
+ if (!candidates.some(measured)) return [...candidates]
244
+
245
+ const exact: T[] = []
246
+ const rest: T[] = []
247
+
248
+ for (const c of candidates) {
249
+ // Tri-state exactMatch: only a stated TRUE earns the exact tier (see rankWithinTier).
250
+ ;(c.exactMatch === true ? exact : rest).push(c)
251
+ }
252
+
253
+ return [...reorderMeasured(exact, orderMeasuredByImportance), ...reorderMeasured(rest, orderMeasuredByImportance)]
254
+ }
255
+
256
+ /**
257
+ * Soft locale-country prior: `(prominence ?? score) + weight` for a candidate in `country`.
258
+ *
259
+ * Additive, never a filter — a far more prominent foreign namesake still wins (Zürich CH over Zurich KS) while a close
260
+ * contest goes to the locale (Manchester NH over Manchester GB). No-op without a `country`, so the un-scoped path stays
261
+ * byte-identical.
262
+ *
263
+ * The units matter: `prominence` on the candidate backend is log10(population + 1), so `weight` is read as "orders of
264
+ * magnitude of population the in-country place is allowed to give away". Pass a large weight to make the country
265
+ * effectively hard, `0` to disable.
266
+ */
267
+ export function rankByCountryPrior<T extends Rankable>(
268
+ candidates: readonly T[],
269
+ country: string | undefined,
270
+ weight: number = DEFAULT_COUNTRY_PRIOR_WEIGHT
271
+ ): T[] {
272
+ if (!country || candidates.length < 2) return [...candidates]
273
+ const target = country.toUpperCase()
274
+
275
+ const key = (c: T): number => size(c) + (c.country?.toUpperCase() === target ? weight : 0)
276
+
277
+ return rankWithinTier(candidates, (a, b) => key(b) - key(a))
278
+ }