@mailwoman/resolver 8.6.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/index.ts +8 -0
- package/out/index.d.ts +2 -0
- package/out/index.d.ts.map +1 -1
- package/out/index.js +1 -0
- package/out/index.js.map +1 -1
- package/out/postcode-country-coherence.d.ts +211 -0
- package/out/postcode-country-coherence.d.ts.map +1 -0
- package/out/postcode-country-coherence.js +369 -0
- package/out/postcode-country-coherence.js.map +1 -0
- package/out/postcode-prefix.d.ts +101 -0
- package/out/postcode-prefix.d.ts.map +1 -0
- package/out/postcode-prefix.js +124 -0
- package/out/postcode-prefix.js.map +1 -0
- package/out/postcode-shape-coherence.d.ts +113 -0
- package/out/postcode-shape-coherence.d.ts.map +1 -0
- package/out/postcode-shape-coherence.js +193 -0
- package/out/postcode-shape-coherence.js.map +1 -0
- package/out/resolve.d.ts.map +1 -1
- package/out/resolve.js +183 -17
- package/out/resolve.js.map +1 -1
- package/out/span-rescore.d.ts +28 -0
- package/out/span-rescore.d.ts.map +1 -1
- package/out/span-rescore.js +98 -6
- package/out/span-rescore.js.map +1 -1
- package/out/street-tier.d.ts.map +1 -1
- package/out/street-tier.js +2 -0
- package/out/street-tier.js.map +1 -1
- package/out/toponym-prior.d.ts +115 -0
- package/out/toponym-prior.d.ts.map +1 -0
- package/out/toponym-prior.js +240 -0
- package/out/toponym-prior.js.map +1 -0
- package/package.json +12 -4
- package/postcode-country-coherence.ts +509 -0
- package/postcode-prefix.ts +165 -0
- package/postcode-shape-coherence.ts +248 -0
- package/resolve.ts +247 -23
- package/span-rescore.ts +144 -6
- package/street-tier.ts +2 -0
- package/toponym-prior.ts +278 -0
package/span-rescore.ts
CHANGED
|
@@ -29,6 +29,8 @@ import type { AddressNode } from "@mailwoman/core/decoder"
|
|
|
29
29
|
import type { ResolvedPlace, ResolverBackend } from "@mailwoman/core/resolver"
|
|
30
30
|
import { haversineKm } from "@mailwoman/spatial"
|
|
31
31
|
|
|
32
|
+
import { DEFAULT_COUNTRY_PRIOR_WEIGHT, rankByCountryPrior, rankByImportance } from "./toponym-prior.ts"
|
|
33
|
+
|
|
32
34
|
export interface SpanRescoreOptions {
|
|
33
35
|
/**
|
|
34
36
|
* ISO-3166 alpha-2 country to constrain the gazetteer match (the parse's detected/ default country).
|
|
@@ -60,6 +62,17 @@ export interface SpanRescoreOptions {
|
|
|
60
62
|
* France" guard). Default false.
|
|
61
63
|
*/
|
|
62
64
|
postalCompoundRecovery?: boolean
|
|
65
|
+
/**
|
|
66
|
+
* #17 bare-toponym soft country. When the span covers the WHOLE unqualified input, treat {@link country} as an
|
|
67
|
+
* additive prior instead of a hard gazetteer filter (see the block comment on {@link findRescoreCandidate}'s bare
|
|
68
|
+
* branch). Default true; `false` restores the hard filter byte-for-byte.
|
|
69
|
+
*/
|
|
70
|
+
bareToponymSoftCountry?: boolean
|
|
71
|
+
/**
|
|
72
|
+
* Weight of that prior, in log10-population units. Default {@link DEFAULT_COUNTRY_PRIOR_WEIGHT} (2). A large value
|
|
73
|
+
* makes the country effectively hard again without changing the code path; 0 removes the locale's say entirely.
|
|
74
|
+
*/
|
|
75
|
+
bareToponymCountryWeight?: number
|
|
63
76
|
}
|
|
64
77
|
|
|
65
78
|
/**
|
|
@@ -88,6 +101,23 @@ export interface RescoreCandidate {
|
|
|
88
101
|
* calibrated 0.83 must not be confused with a rescore plug-in estimate).
|
|
89
102
|
*/
|
|
90
103
|
gated: boolean
|
|
104
|
+
/**
|
|
105
|
+
* The SAME-SPAN namesake runner-ups — the other exact-name matches this recovery's own lookup already returned, in
|
|
106
|
+
* the backend's rank order, minus the winner and minus anything the postcode gate rejected. Empty when the span named
|
|
107
|
+
* exactly one place.
|
|
108
|
+
*
|
|
109
|
+
* #1537: these were being discarded. A name the model reads as a `street` ("Springfield", "Berlin", "Manchester",
|
|
110
|
+
* "Moscow", "Fulda") never reaches the admin walk, so the whole tree comes back unresolved and THIS tier is what
|
|
111
|
+
* recovers it — and it decorated the injected node with no alternatives at all. The result was that the geocode
|
|
112
|
+
* path's `candidates` array held one entry, and the top-1-vs-top-2 dominance margin that `declared_ambiguity` reads
|
|
113
|
+
* was uncomputable, for exactly the famous-homonym class that marker exists for. Measured on the shipped candidate
|
|
114
|
+
* backend, 2026-08-07: those five queries returned 1 candidate each while `Cambridge`/`Athens`/`Paris` — the same
|
|
115
|
+
* class, but parsed as `locality` — returned 4-5.
|
|
116
|
+
*
|
|
117
|
+
* The winner is unchanged by their presence: the pick is still the first gate-passing exact match, and these are the
|
|
118
|
+
* ones that came after it. This costs no extra query — they were in the same `findPlace` response.
|
|
119
|
+
*/
|
|
120
|
+
alternatives: ResolvedPlace[]
|
|
91
121
|
}
|
|
92
122
|
|
|
93
123
|
/**
|
|
@@ -135,6 +165,44 @@ export function postcodeCodeSubset(postcode: string): string {
|
|
|
135
165
|
.trim()
|
|
136
166
|
}
|
|
137
167
|
|
|
168
|
+
/**
|
|
169
|
+
* Over-fetch for the #17 bare-toponym probe. Without a country filter the top 5 worldwide bearers of a common name are
|
|
170
|
+
* often all in one country, and the candidate the soft prior exists to promote sits below the fold — "Warwick" puts
|
|
171
|
+
* five US rows ahead of Warwick, Warwickshire. The backend orders by the same population key either way, so a wider
|
|
172
|
+
* window only admits more of the same list.
|
|
173
|
+
*/
|
|
174
|
+
const BARE_TOPONYM_FETCH = 20
|
|
175
|
+
|
|
176
|
+
/**
|
|
177
|
+
* True when the tree names its OWN admin context — a region, subregion, country, postcode or house number the parser
|
|
178
|
+
* read out of the input. Such a query is not relying on a locale guess, so the #17 soft-country prior stands down and
|
|
179
|
+
* the hard filter keeps its say: this is what holds 'Berlin, Wisconsin' on Berlin, Wisconsin.
|
|
180
|
+
*/
|
|
181
|
+
function hasAdminQualifier(roots: readonly AddressNode[]): boolean {
|
|
182
|
+
const stack: AddressNode[] = [...roots]
|
|
183
|
+
|
|
184
|
+
while (stack.length) {
|
|
185
|
+
const n = stack.pop()!
|
|
186
|
+
|
|
187
|
+
if (
|
|
188
|
+
(n.tag === "region" ||
|
|
189
|
+
n.tag === "subregion" ||
|
|
190
|
+
n.tag === "country" ||
|
|
191
|
+
n.tag === "postcode" ||
|
|
192
|
+
n.tag === "house_number") &&
|
|
193
|
+
n.value.trim().length
|
|
194
|
+
) {
|
|
195
|
+
return true
|
|
196
|
+
}
|
|
197
|
+
|
|
198
|
+
if (n.children?.length) {
|
|
199
|
+
stack.push(...n.children)
|
|
200
|
+
}
|
|
201
|
+
}
|
|
202
|
+
|
|
203
|
+
return false
|
|
204
|
+
}
|
|
205
|
+
|
|
138
206
|
/**
|
|
139
207
|
* True if any node in the tree already carries a resolved place id — the #685 brake.
|
|
140
208
|
*/
|
|
@@ -279,19 +347,81 @@ export async function findRescoreCandidate(
|
|
|
279
347
|
|
|
280
348
|
spans.sort((a, b) => b.len - a.len)
|
|
281
349
|
|
|
350
|
+
// #17 bare-toponym soft country. The caller's `country` is a LOCALE DEFAULT, not knowledge — the #961
|
|
351
|
+
// block below already says so, and for a bare city name it is the ONLY country signal there is, which
|
|
352
|
+
// makes hard-filtering on it the worst possible use of it. Measured through the compiled CLI on
|
|
353
|
+
// 2026-08-10: `--locale en-US 'Zürich'` returned Zurich, Kansas (population 81) 8,043 km off, and
|
|
354
|
+
// `--locale en-GB 'Zürich'` returned nothing at all, because GB holds no Zurich to filter down to.
|
|
355
|
+
//
|
|
356
|
+
// So for this ONE query shape the filter is demoted to an additive prior: probe the gazetteer
|
|
357
|
+
// unscoped, then rank with `rankByCountryPrior` so an in-country place may be up to 100x smaller and
|
|
358
|
+
// still win. This is the #912 lever ("Paris under en-US must not be hard-scoped to Paris, Texas")
|
|
359
|
+
// applied at the tier that actually decides the class — #912 lives upstream in the CLI and keys on a
|
|
360
|
+
// `locality`-tagged tree, but the model reads a bare famous name as a `street`, so the shape that
|
|
361
|
+
// needs it most is exactly the shape that guard cannot see.
|
|
362
|
+
//
|
|
363
|
+
// The shape gate is deliberately narrow. `qualified` below is the D-rule guard: a postcode, a region,
|
|
364
|
+
// a country or a house number in the tree means the address named its own context and a locale guess
|
|
365
|
+
// is no longer the only evidence — 'Berlin, Wisconsin' keeps resolving to Berlin, Wisconsin. And the
|
|
366
|
+
// span must cover the WHOLE input: a sub-span of a longer query is not a bare toponym, so
|
|
367
|
+
// "Weimar Thüringen" falls back to the country-scoped probe that lands the gold.
|
|
368
|
+
const softCountry = opts.bareToponymSoftCountry !== false
|
|
369
|
+
const countryWeight = opts.bareToponymCountryWeight ?? DEFAULT_COUNTRY_PRIOR_WEIGHT
|
|
370
|
+
const qualified = !!postcode || hasAdminQualifier(roots)
|
|
371
|
+
const wholeInput = toks.length ? { start: toks[0]!.start, end: toks.at(-1)!.end } : null
|
|
372
|
+
// Everything the prior needs EXCEPT the span itself — hoisted so the per-span test is one comparison.
|
|
373
|
+
const softCountryEligible = softCountry && !!country && !qualified && !!wholeInput
|
|
374
|
+
|
|
282
375
|
for (const sp of spans) {
|
|
283
376
|
const key = norm(sp.text)
|
|
284
377
|
|
|
285
378
|
if (key.length < 2 || /^\d+$/.test(key)) continue // skip bare numbers / empties
|
|
286
|
-
const
|
|
287
|
-
|
|
379
|
+
const bare = softCountryEligible && sp.start === wholeInput!.start && sp.end === wholeInput!.end
|
|
380
|
+
|
|
381
|
+
const hits = bare
|
|
382
|
+
? rankByCountryPrior(
|
|
383
|
+
await backend.findPlace({ text: sp.text, postcode, placetype: "locality", limit: BARE_TOPONYM_FETCH }),
|
|
384
|
+
country,
|
|
385
|
+
countryWeight
|
|
386
|
+
)
|
|
387
|
+
: await backend.findPlace({ text: sp.text, country, postcode, placetype: "locality", limit: 5 })
|
|
388
|
+
|
|
389
|
+
// #1546: NO primary-name re-check here — the backend's `exactMatch` IS the name-OR-alias surface
|
|
390
|
+
// equality (the names table / alt_names bag), so a query matches a place when ANY stored name
|
|
391
|
+
// equals it. Re-comparing only the PRIMARY name folded to [a-z0-9 ] excluded exactly the
|
|
392
|
+
// non-Latin-primary class: Москва folds to "" and could never equal "moscow", so Moscow RU never
|
|
393
|
+
// entered the list and Moscow, Idaho won by default among the Latin-named bearers — population-
|
|
394
|
+
// first ranking starved, not violated. The alias surface is the recall; ranking then does its job.
|
|
395
|
+
// The postcode gate below still applies to every admitted candidate, Moscow RU included.
|
|
396
|
+
//
|
|
397
|
+
// #17: importance-first WITHIN the admitted set. The key is the #28 blended fame prior
|
|
398
|
+
// (`PlaceCandidate.importance`, produced by the candidate build) — the only key that separates
|
|
399
|
+
// the bare GB panel rows; on an artifact predating the column it abstains and changes no pick.
|
|
400
|
+
// See `toponym-prior.ts`. It runs after the country prior deliberately: fame is the stronger
|
|
401
|
+
// signal when it has been measured, and leaves an unscored candidate exactly where population
|
|
402
|
+
// put it.
|
|
403
|
+
const exact = rankByImportance(hits.filter((h) => h.exactMatch && (h.lat !== 0 || h.lon !== 0)))
|
|
404
|
+
|
|
405
|
+
const withinGate = (p: ResolvedPlace): boolean =>
|
|
406
|
+
!anchor || gateKm <= 0 || haversineKm(anchor.lat, anchor.lon, p.lat, p.lon) <= gateKm
|
|
288
407
|
|
|
289
408
|
for (const h of exact) {
|
|
290
|
-
if (
|
|
409
|
+
if (!withinGate(h)) continue
|
|
291
410
|
|
|
292
411
|
// gated = the postcode anchor existed AND validated this match (within gateKm). When no anchor
|
|
293
412
|
// (no postcode→point coverage), the match is ungated — returned, but flagged lower-precision.
|
|
294
|
-
|
|
413
|
+
//
|
|
414
|
+
// #1537: carry the rest of the SAME lookup's exact matches as the namesake runner-ups. Gate-filtered on the
|
|
415
|
+
// same rule as the winner — a candidate the postcode gate rejected is not a namesake worth offering, it is a
|
|
416
|
+
// place the evidence already excluded. Rank order is the backend's, preserved by `filter`.
|
|
417
|
+
return {
|
|
418
|
+
text: sp.text,
|
|
419
|
+
start: sp.start,
|
|
420
|
+
end: sp.end,
|
|
421
|
+
place: h,
|
|
422
|
+
gated: anchor !== null,
|
|
423
|
+
alternatives: exact.filter((a) => a !== h && withinGate(a)),
|
|
424
|
+
}
|
|
295
425
|
}
|
|
296
426
|
}
|
|
297
427
|
|
|
@@ -312,7 +442,10 @@ export async function findRescoreCandidate(
|
|
|
312
442
|
|
|
313
443
|
if (key.length < 2 || /^\d+$/.test(key)) continue
|
|
314
444
|
const hits = await backend.findPlace({ text: sp.text, placetype: "locality", limit: 5 })
|
|
315
|
-
|
|
445
|
+
// #1546: same alias-surface admission as the scoped pass — `exactMatch` is name-OR-alias, so a
|
|
446
|
+
// non-Latin primary (Москва) admitted via its Latin alias stays eligible here too. The
|
|
447
|
+
// per-candidate postcode verification below remains the sole admission bar.
|
|
448
|
+
const exact = hits.filter((h) => h.exactMatch && (h.lat !== 0 || h.lon !== 0))
|
|
316
449
|
|
|
317
450
|
for (const h of exact) {
|
|
318
451
|
if (!h.country || h.country === country) continue
|
|
@@ -328,7 +461,12 @@ export async function findRescoreCandidate(
|
|
|
328
461
|
const verified = pcHits.find((p) => p.lat !== 0 || p.lon !== 0)
|
|
329
462
|
|
|
330
463
|
if (verified && haversineKm(verified.lat, verified.lon, h.lat, h.lon) <= gateKm) {
|
|
331
|
-
|
|
464
|
+
// No alternatives from this pass, deliberately. Admission here is per-candidate postcode
|
|
465
|
+
// verification — one `findPlace` per runner-up — and the class it serves is the opposite of the
|
|
466
|
+
// namesake one: a postcode is present and has already picked the country, so there is nothing
|
|
467
|
+
// ambiguous left to declare. The bare-toponym queries #1537 is about never reach this branch (it
|
|
468
|
+
// requires a postcode).
|
|
469
|
+
return { text: sp.text, start: sp.start, end: sp.end, place: h, gated: true, alternatives: [] }
|
|
332
470
|
}
|
|
333
471
|
}
|
|
334
472
|
}
|
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.
|
package/toponym-prior.ts
ADDED
|
@@ -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
|
+
}
|