@mailwoman/resolver 7.2.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.
- package/index.ts +39 -0
- package/package.json +35 -15
- package/plausibility.ts +170 -0
- package/remote-resolver.ts +103 -0
- package/rerank.ts +135 -0
- package/resolve.ts +1379 -0
- package/span-rescore.ts +316 -0
- package/street-evidence.ts +190 -0
- package/vitest.config.ts +39 -0
package/span-rescore.ts
ADDED
|
@@ -0,0 +1,316 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @copyright Sister Software
|
|
3
|
+
* @license AGPL-3.0
|
|
4
|
+
* @author Teffen Ellis, et al.
|
|
5
|
+
*
|
|
6
|
+
* #370 span-rescore — recover a dropped/fragmented locality from the RAW text when a parse fails to
|
|
7
|
+
* resolve. The model sometimes fragments an accented or non-ASCII locality token ("Grudziądz"
|
|
8
|
+
* splits into "Grudzi" + "dz" on the ą combining mark, #555), so neither fragment resolves and
|
|
9
|
+
* the address comes back with no coordinate. But the whole word sits intact in the raw input — a
|
|
10
|
+
* whitespace tokenizer sees it where the model's subword tokenizer didn't.
|
|
11
|
+
*
|
|
12
|
+
* This module is the PURE, backend-agnostic core: enumerate contiguous raw-token spans, exact-match
|
|
13
|
+
* them against the same-country gazetteer, and return the best locality candidate. The resolver
|
|
14
|
+
* (`resolve.ts` → `applySpanRescore`) owns the integration: it runs this ONLY on an unresolved
|
|
15
|
+
* tree (the #685 brake — never second-guess a working coordinate) and injects the recovered
|
|
16
|
+
* locality as a resolved node. Default-ON (#370, promoted 2026-06-25 — same-harness EU+AU +1pp
|
|
17
|
+
* @25km, zero regressions); explicit opt-out via `ResolveOpts.spanRescore: false`, byte-stable then.
|
|
18
|
+
*
|
|
19
|
+
* The design + thresholds are validated on a 7-locale coordinate panel
|
|
20
|
+
* (`scripts/eval/span-rescore-validate.ts`, eval
|
|
21
|
+
* `docs/articles/evals/experiments/2026-06-23-370-span-rescore.mdx`): longest-exact-match-wins (the gold
|
|
22
|
+
* locality is usually the LONGER, more-specific name — shortest- wins grabs the ambiguous prefix
|
|
23
|
+
* "Tomaszów" of "Tomaszów Mazowiecki", 135 km off), and a postcode- consistency gate that rejects
|
|
24
|
+
* a match far from where the postcode resolves (kills coverage-gap false-positives where the
|
|
25
|
+
* backend has postcode coverage).
|
|
26
|
+
*/
|
|
27
|
+
|
|
28
|
+
import type { AddressNode } from "@mailwoman/core/decoder"
|
|
29
|
+
import type { ResolvedPlace, ResolverBackend } from "@mailwoman/core/resolver"
|
|
30
|
+
import { haversineKm } from "@mailwoman/spatial"
|
|
31
|
+
|
|
32
|
+
export interface SpanRescoreOptions {
|
|
33
|
+
/**
|
|
34
|
+
* ISO-3166 alpha-2 country to constrain the gazetteer match (the parse's detected/ default country).
|
|
35
|
+
*/
|
|
36
|
+
country?: string
|
|
37
|
+
/**
|
|
38
|
+
* Sibling postcode — used both as the backend disambiguation hint AND the consistency-gate anchor.
|
|
39
|
+
*/
|
|
40
|
+
postcode?: string
|
|
41
|
+
/**
|
|
42
|
+
* Reject a candidate whose coordinate is farther than this (km) from the postcode anchor. The gate only fires when
|
|
43
|
+
* the postcode resolves to a point in the backend; otherwise it can't and the match is accepted (so it never
|
|
44
|
+
* penalizes a backend without postcode coverage). 0 disables. Default 50.
|
|
45
|
+
*/
|
|
46
|
+
gateKm?: number
|
|
47
|
+
/** Max contiguous raw tokens to treat as one locality span. Default 4. */
|
|
48
|
+
maxSpanTokens?: number
|
|
49
|
+
/**
|
|
50
|
+
* Min confidence for a street/house_number/postcode node to count as a span-blocking constituent. Default 0.7.
|
|
51
|
+
*/
|
|
52
|
+
confidentThreshold?: number
|
|
53
|
+
/**
|
|
54
|
+
* #942 postal-compound recovery. A globbed postcode span ("1382 Kožljek") normally (a) fails to anchor (the compound
|
|
55
|
+
* matches no bare-code gazetteer row) and (b) blocks its own trailing city tokens from recovery. When on: the anchor
|
|
56
|
+
* retries with the postcode's code-shaped (digit-bearing) token subset, and an UNRESOLVED postcode node blocks only
|
|
57
|
+
* those code tokens — the residual name tokens become span material. Street/affix blocking is untouched (the "Ave,
|
|
58
|
+
* France" guard). Default false.
|
|
59
|
+
*/
|
|
60
|
+
postalCompoundRecovery?: boolean
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
/** The recovered locality: the raw span and the gazetteer place it resolved to. */
|
|
64
|
+
export interface RescoreCandidate {
|
|
65
|
+
/** The raw text of the winning span. */
|
|
66
|
+
text: string
|
|
67
|
+
/** Char offsets of the span in the raw input. */
|
|
68
|
+
start: number
|
|
69
|
+
end: number
|
|
70
|
+
/** The resolved gazetteer place (decorate a node with this). */
|
|
71
|
+
place: ResolvedPlace
|
|
72
|
+
/**
|
|
73
|
+
* Whether the postcode-consistency gate FIRED for this recovery — i.e. the postcode resolved to a point and the match
|
|
74
|
+
* was validated within `gateKm` of it. `true` = high-precision (postcode- consistent); `false` = ungated (no
|
|
75
|
+
* postcode→point coverage for this country, so the match wasn't geo-validated — the ~83%-precision case). The caller
|
|
76
|
+
* surfaces this as `metadata.rescore_gated` so a consumer can threshold on it WITHOUT a hidden per-country coverage
|
|
77
|
+
* map. Deliberately NOT folded into the calibrated `confidence` — that would break the isotonic guarantee (a true
|
|
78
|
+
* calibrated 0.83 must not be confused with a rescore plug-in estimate).
|
|
79
|
+
*/
|
|
80
|
+
gated: boolean
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
/** Normalize for exact comparison: lowercase, strip diacritics + punctuation, collapse whitespace. */
|
|
84
|
+
const norm = (s: string): string =>
|
|
85
|
+
s
|
|
86
|
+
.toLowerCase()
|
|
87
|
+
.normalize("NFD")
|
|
88
|
+
.replace(/[^a-z0-9 ]/g, " ")
|
|
89
|
+
.replace(/\s+/g, " ")
|
|
90
|
+
.trim()
|
|
91
|
+
|
|
92
|
+
interface RawTok {
|
|
93
|
+
text: string
|
|
94
|
+
start: number
|
|
95
|
+
end: number
|
|
96
|
+
}
|
|
97
|
+
/** Whitespace/punctuation tokenization of the raw input, char offsets preserved, diacritics intact. */
|
|
98
|
+
function tokenizeRaw(raw: string): RawTok[] {
|
|
99
|
+
const toks: RawTok[] = []
|
|
100
|
+
const re = /[^\s,;/]+/g
|
|
101
|
+
let m: RegExpExecArray | null
|
|
102
|
+
|
|
103
|
+
while ((m = re.exec(raw)) !== null) {
|
|
104
|
+
toks.push({ text: m[0], start: m.index, end: m.index + m[0].length })
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
return toks
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
/**
|
|
111
|
+
* The code-shaped (digit-bearing) token subset of a postcode string — "1382 Kožljek" → "1382", "SW1A 1AA London" →
|
|
112
|
+
* "SW1A 1AA". The #942 recovery resolves THIS against the gazetteer's bare-code rows when the globbed compound fails.
|
|
113
|
+
* Empty string when no token carries a digit.
|
|
114
|
+
*/
|
|
115
|
+
export function postcodeCodeSubset(postcode: string): string {
|
|
116
|
+
return postcode
|
|
117
|
+
.split(/[\s,;/]+/)
|
|
118
|
+
.filter((t) => /\d/.test(t))
|
|
119
|
+
.join(" ")
|
|
120
|
+
.trim()
|
|
121
|
+
}
|
|
122
|
+
|
|
123
|
+
/** True if any node in the tree already carries a resolved place id — the #685 brake. */
|
|
124
|
+
export function hasResolvedPlace(roots: readonly AddressNode[]): boolean {
|
|
125
|
+
const stack: AddressNode[] = [...roots]
|
|
126
|
+
|
|
127
|
+
while (stack.length) {
|
|
128
|
+
const n = stack.pop()!
|
|
129
|
+
|
|
130
|
+
if (n.placeID) return true
|
|
131
|
+
|
|
132
|
+
if (n.children?.length) {
|
|
133
|
+
stack.push(...n.children)
|
|
134
|
+
}
|
|
135
|
+
}
|
|
136
|
+
|
|
137
|
+
return false
|
|
138
|
+
}
|
|
139
|
+
|
|
140
|
+
/**
|
|
141
|
+
* Char ranges of confident street / house_number / postcode constituents, including the street affixes (`street_prefix`
|
|
142
|
+
* / `street_suffix`) — a locality span must not overlap them. The affixes matter: a confident "Ave" in "350 5th Ave,
|
|
143
|
+
* NY" is a street suffix, not a locality, and without this guard the recovery exact-matches it against a same-named
|
|
144
|
+
* place ("Ave", France) and injects a bogus locality.
|
|
145
|
+
*/
|
|
146
|
+
function confidentRanges(
|
|
147
|
+
roots: readonly AddressNode[],
|
|
148
|
+
threshold: number,
|
|
149
|
+
raw: string,
|
|
150
|
+
postalCompoundRecovery: boolean
|
|
151
|
+
): Array<[number, number]> {
|
|
152
|
+
const out: Array<[number, number]> = []
|
|
153
|
+
const stack: AddressNode[] = [...roots]
|
|
154
|
+
|
|
155
|
+
while (stack.length) {
|
|
156
|
+
const n = stack.pop()!
|
|
157
|
+
|
|
158
|
+
if (
|
|
159
|
+
(n.tag === "postcode" ||
|
|
160
|
+
n.tag === "house_number" ||
|
|
161
|
+
n.tag === "street" ||
|
|
162
|
+
n.tag === "street_prefix" ||
|
|
163
|
+
n.tag === "street_suffix") &&
|
|
164
|
+
(n.confidence ?? 0) >= threshold &&
|
|
165
|
+
Number.isFinite(n.start) &&
|
|
166
|
+
Number.isFinite(n.end)
|
|
167
|
+
) {
|
|
168
|
+
// #942: an UNRESOLVED postcode span blocks only its code-shaped tokens — the globbed trailing
|
|
169
|
+
// city name ("1382 Kožljek") is exactly the recoverable material. Resolved postcodes and the
|
|
170
|
+
// street family keep the full-range block (the "Ave, France" guard).
|
|
171
|
+
if (postalCompoundRecovery && n.tag === "postcode" && !n.placeID) {
|
|
172
|
+
for (const t of tokenizeRaw(raw.slice(n.start, n.end))) {
|
|
173
|
+
if (/\d/.test(t.text)) {
|
|
174
|
+
out.push([n.start + t.start, n.start + t.end])
|
|
175
|
+
}
|
|
176
|
+
}
|
|
177
|
+
} else {
|
|
178
|
+
out.push([n.start, n.end])
|
|
179
|
+
}
|
|
180
|
+
}
|
|
181
|
+
|
|
182
|
+
if (n.children?.length) {
|
|
183
|
+
stack.push(...n.children)
|
|
184
|
+
}
|
|
185
|
+
}
|
|
186
|
+
|
|
187
|
+
return out
|
|
188
|
+
}
|
|
189
|
+
|
|
190
|
+
/**
|
|
191
|
+
* Find the best locality the raw text exact-matches in the gazetteer. Returns null when nothing matches (or the
|
|
192
|
+
* postcode gate rejects every match). Callers gate on `hasResolvedPlace` first.
|
|
193
|
+
*/
|
|
194
|
+
export async function findRescoreCandidate(
|
|
195
|
+
raw: string,
|
|
196
|
+
roots: readonly AddressNode[],
|
|
197
|
+
backend: ResolverBackend,
|
|
198
|
+
opts: SpanRescoreOptions = {}
|
|
199
|
+
): Promise<RescoreCandidate | null> {
|
|
200
|
+
const gateKm = opts.gateKm ?? 50
|
|
201
|
+
const maxSpan = opts.maxSpanTokens ?? 4
|
|
202
|
+
const threshold = opts.confidentThreshold ?? 0.7
|
|
203
|
+
const country = opts.country
|
|
204
|
+
const postcode = opts.postcode?.trim() || undefined
|
|
205
|
+
|
|
206
|
+
// Postcode-consistency anchor: where does the postcode itself resolve? (No-op when the backend has
|
|
207
|
+
// no postcode coverage — findPlace returns nothing → no anchor → gate can't fire → match accepted.)
|
|
208
|
+
let anchor: { lat: number; lon: number } | null = null
|
|
209
|
+
|
|
210
|
+
if (postcode && gateKm > 0) {
|
|
211
|
+
// #961: both anchor probes are postalcode-TYPED. Untyped, a truncated code fragment (v5.3.0
|
|
212
|
+
// emits "250 Zabiče" → subset "250") name-matches arbitrary places ("Chak No 250", PK) and the
|
|
213
|
+
// false anchor then GATES OUT the true village. A typed miss leaves anchor=null → the match is
|
|
214
|
+
// accepted ungated, which is the correct degradation for an unverifiable code.
|
|
215
|
+
const pcHits = await backend.findPlace({ text: postcode, country, placetype: "postalcode", limit: 2 })
|
|
216
|
+
const a = pcHits.find((h) => h.lat !== 0 || h.lon !== 0)
|
|
217
|
+
|
|
218
|
+
if (a) {
|
|
219
|
+
anchor = { lat: a.lat, lon: a.lon }
|
|
220
|
+
}
|
|
221
|
+
|
|
222
|
+
// #942: the globbed compound ("1382 Kožljek") matches no bare-code row — retry the anchor with
|
|
223
|
+
// the code-shaped token subset so the consistency gate can validate the recovered city.
|
|
224
|
+
if (!anchor && opts.postalCompoundRecovery) {
|
|
225
|
+
const code = postcodeCodeSubset(postcode)
|
|
226
|
+
|
|
227
|
+
if (code && code !== postcode) {
|
|
228
|
+
const codeHits = await backend.findPlace({ text: code, country, placetype: "postalcode", limit: 2 })
|
|
229
|
+
const c = codeHits.find((h) => h.lat !== 0 || h.lon !== 0)
|
|
230
|
+
|
|
231
|
+
if (c) {
|
|
232
|
+
anchor = { lat: c.lat, lon: c.lon }
|
|
233
|
+
}
|
|
234
|
+
}
|
|
235
|
+
}
|
|
236
|
+
}
|
|
237
|
+
|
|
238
|
+
const toks = tokenizeRaw(raw)
|
|
239
|
+
const avoid = confidentRanges(roots, threshold, raw, opts.postalCompoundRecovery ?? false)
|
|
240
|
+
const overlapsAvoid = (s: number, e: number) => avoid.some(([as, ae]) => s < ae && as < e)
|
|
241
|
+
|
|
242
|
+
// Enumerate contiguous spans, LONGEST first — the gold locality is usually the more-specific
|
|
243
|
+
// (longer) name; longest-wins lets it beat its own ambiguous prefix.
|
|
244
|
+
interface Span {
|
|
245
|
+
text: string
|
|
246
|
+
start: number
|
|
247
|
+
end: number
|
|
248
|
+
len: number
|
|
249
|
+
}
|
|
250
|
+
const spans: Span[] = []
|
|
251
|
+
|
|
252
|
+
for (let len = Math.min(maxSpan, toks.length); len >= 1; len--) {
|
|
253
|
+
for (let i = 0; i + len <= toks.length; i++) {
|
|
254
|
+
const start = toks[i]!.start
|
|
255
|
+
const end = toks[i + len - 1]!.end
|
|
256
|
+
|
|
257
|
+
if (overlapsAvoid(start, end)) continue
|
|
258
|
+
spans.push({ text: raw.slice(start, end), start, end, len })
|
|
259
|
+
}
|
|
260
|
+
}
|
|
261
|
+
spans.sort((a, b) => b.len - a.len)
|
|
262
|
+
|
|
263
|
+
for (const sp of spans) {
|
|
264
|
+
const key = norm(sp.text)
|
|
265
|
+
|
|
266
|
+
if (key.length < 2 || /^\d+$/.test(key)) continue // skip bare numbers / empties
|
|
267
|
+
const hits = await backend.findPlace({ text: sp.text, country, postcode, placetype: "locality", limit: 5 })
|
|
268
|
+
const exact = hits.filter((h) => h.exactMatch && norm(h.name) === key && (h.lat !== 0 || h.lon !== 0))
|
|
269
|
+
|
|
270
|
+
for (const h of exact) {
|
|
271
|
+
if (anchor && gateKm > 0 && haversineKm(anchor.lat, anchor.lon, h.lat, h.lon) > gateKm) continue
|
|
272
|
+
|
|
273
|
+
// gated = the postcode anchor existed AND validated this match (within gateKm). When no anchor
|
|
274
|
+
// (no postcode→point coverage), the match is ungated — returned, but flagged lower-precision.
|
|
275
|
+
return { text: sp.text, start: sp.start, end: sp.end, place: h, gated: anchor !== null }
|
|
276
|
+
}
|
|
277
|
+
}
|
|
278
|
+
|
|
279
|
+
// #961 joint country recovery: the caller's `country` is a LOCALE DEFAULT, not knowledge — the
|
|
280
|
+
// CLI's en-US default scoped both the anchor and the village probe to US, so the SI floor never
|
|
281
|
+
// fired through geocode-core while the same rows resolved 25/25 on the resolver harness. When the
|
|
282
|
+
// scoped pass finds nothing and a postcode is present, re-probe the spans UNSCOPED (the admin
|
|
283
|
+
// gazetteer is one shard, all countries), then verify each exact candidate against the postcode's
|
|
284
|
+
// code subset resolved in the CANDIDATE's own country (postcode shards route by country). A
|
|
285
|
+
// cross-country promotion is accepted ONLY postcode-verified within the gate — never ungated —
|
|
286
|
+
// so a US-shaped query can't wander abroad on a name coincidence (the 48026 guard: resolved
|
|
287
|
+
// trees never reach this code, and unresolved ones must pass the joint postcode check).
|
|
288
|
+
if (opts.postalCompoundRecovery && postcode && gateKm > 0) {
|
|
289
|
+
const code = postcodeCodeSubset(postcode) || postcode.trim()
|
|
290
|
+
|
|
291
|
+
for (const sp of spans) {
|
|
292
|
+
const key = norm(sp.text)
|
|
293
|
+
|
|
294
|
+
if (key.length < 2 || /^\d+$/.test(key)) continue
|
|
295
|
+
const hits = await backend.findPlace({ text: sp.text, placetype: "locality", limit: 5 })
|
|
296
|
+
const exact = hits.filter((h) => h.exactMatch && norm(h.name) === key && (h.lat !== 0 || h.lon !== 0))
|
|
297
|
+
|
|
298
|
+
for (const h of exact) {
|
|
299
|
+
if (!h.country || h.country === country) continue // the scoped pass already covered `country`
|
|
300
|
+
const pcHits = await backend.findPlace({
|
|
301
|
+
text: code,
|
|
302
|
+
country: h.country,
|
|
303
|
+
placetype: "postalcode",
|
|
304
|
+
limit: 2,
|
|
305
|
+
})
|
|
306
|
+
const verified = pcHits.find((p) => p.lat !== 0 || p.lon !== 0)
|
|
307
|
+
|
|
308
|
+
if (verified && haversineKm(verified.lat, verified.lon, h.lat, h.lon) <= gateKm) {
|
|
309
|
+
return { text: sp.text, start: sp.start, end: sp.end, place: h, gated: true }
|
|
310
|
+
}
|
|
311
|
+
}
|
|
312
|
+
}
|
|
313
|
+
}
|
|
314
|
+
|
|
315
|
+
return null
|
|
316
|
+
}
|
|
@@ -0,0 +1,190 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @copyright Sister Software
|
|
3
|
+
* @license AGPL-3.0
|
|
4
|
+
* @author Teffen Ellis, et al.
|
|
5
|
+
*
|
|
6
|
+
* #727 stage-2 phase 4c — street-NAME existence as the k-best arbiter signal.
|
|
7
|
+
*
|
|
8
|
+
* Phase 4a measured the planned arbiter (full-geocode resolution tier) at exactly ZERO collected
|
|
9
|
+
* headroom: the failing class is context-free fragments, which never reach rooftop layers, so
|
|
10
|
+
* every hypothesis ties at admin tier. The corrected signal is street-NAME existence — "does this
|
|
11
|
+
* hypothesis's street surface exist as a street name in the national register?" — which IS
|
|
12
|
+
* queryable for a bare fragment. Measured on the FR fragment board over the v3.10.1 8k span model:
|
|
13
|
+
* the rerank collects +6.0pp street@1 (0.791 → 0.851), 96 fixes / 3 breaks (32:1), the value
|
|
14
|
+
* concentrated on the date-name class (+16.7pp). Receipts:
|
|
15
|
+
* `docs/articles/evals/2026-07-17-v3101-span-head-8k-result.md`, spec
|
|
16
|
+
* `docs/superpowers/specs/2026-07-17-727-phase4c-street-name-evidence.md`.
|
|
17
|
+
*
|
|
18
|
+
* THE ANTI-PELIAS RULE (shared with `rerank.ts`): ONE bit of evidence, not a score. We do NOT
|
|
19
|
+
* blend the name signal into the parse scores — those already share a partition function and rank
|
|
20
|
+
* fine within an input. The reranker's only job is to prefer a sibling hypothesis whose street the
|
|
21
|
+
* world confirms exists, over a rank-1 whose street it does not. Positive evidence only: the
|
|
22
|
+
* ABSENCE of a name is never evidence against a parse (index incompleteness is the default state
|
|
23
|
+
* of the world), so the policy always fails open to the model's own ranking.
|
|
24
|
+
*
|
|
25
|
+
* This module is PURE — the interface + the fold + the measured pick policy, no SQLite. The FR BAN
|
|
26
|
+
* backend lives in `@mailwoman/resolver-wof-sqlite` (`SQLiteStreetNameLookup`); callers inject it,
|
|
27
|
+
* mirroring the `PlaceLookup` pattern.
|
|
28
|
+
*/
|
|
29
|
+
|
|
30
|
+
/**
|
|
31
|
+
* A street-name existence probe. Backend-agnostic; the FR instance is BAN street-centroids, a future US instance is
|
|
32
|
+
* TIGER, etc. (per the registry-backed-structured-prediction doctrine tiers).
|
|
33
|
+
*/
|
|
34
|
+
export interface StreetLocalityEvidence {
|
|
35
|
+
/**
|
|
36
|
+
* True when `streetSurface` exists as a street name — optionally scoped to a locality or postcode when the hypothesis
|
|
37
|
+
* carries one (fragments usually don't; unscoped is the measured mode). The implementation is responsible for folding
|
|
38
|
+
* the surface with {@link foldStreetSurface} so the caller passes raw text.
|
|
39
|
+
*
|
|
40
|
+
* POSITIVE EVIDENCE ONLY: return `false` on any doubt — a missing index, an unsupported country, a read error — so
|
|
41
|
+
* {@link pickByStreetEvidence} fails open to the model's ranking. Absence is never a veto.
|
|
42
|
+
*/
|
|
43
|
+
hasStreetName(streetSurface: string, scope?: StreetEvidenceScope): boolean
|
|
44
|
+
/** ISO-2 (upper-case) countries this instance can answer for. Anything else → no evidence, never a veto. */
|
|
45
|
+
readonly countries: ReadonlySet<string>
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
export interface StreetEvidenceScope {
|
|
49
|
+
locality?: string
|
|
50
|
+
postcode?: string
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
/**
|
|
54
|
+
* The fold CONTRACT — the index builder and every runtime prober MUST share this exact function, or lookups silently
|
|
55
|
+
* miss (the 4 v1-policy breaks were fold mismatches: `pillet-will` stored unhyphenated). NFD strip-diacritics,
|
|
56
|
+
* lowercase, hyphen/apostrophe → space, whitespace-collapse. Import this beside the interface; never re-implement it.
|
|
57
|
+
*/
|
|
58
|
+
export function foldStreetSurface(surface: string): string {
|
|
59
|
+
return surface
|
|
60
|
+
.normalize("NFD")
|
|
61
|
+
.replace(/[̀-ͯ]/g, "")
|
|
62
|
+
.toLowerCase()
|
|
63
|
+
.replace(/['’‐-―-]/g, " ")
|
|
64
|
+
.replace(/\s+/g, " ")
|
|
65
|
+
.trim()
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
/**
|
|
69
|
+
* FR street-type + particle vocabulary — the G1 guard. A street surface made ONLY of these words carries no NAME (bare
|
|
70
|
+
* `rue`/`chemin` is a truncation, and it IS in the index), so it earns no evidence credit. Folded forms (particles are
|
|
71
|
+
* pre-folded: `l'` → `l`). Kept small and lexical — it is a dictionary fact, not a tuned weight (the anti-Pelias
|
|
72
|
+
* line).
|
|
73
|
+
*/
|
|
74
|
+
const FR_STREET_TYPE_WORDS: ReadonlySet<string> = new Set([
|
|
75
|
+
"rue",
|
|
76
|
+
"avenue",
|
|
77
|
+
"boulevard",
|
|
78
|
+
"chemin",
|
|
79
|
+
"route",
|
|
80
|
+
"allee",
|
|
81
|
+
"impasse",
|
|
82
|
+
"place",
|
|
83
|
+
"quai",
|
|
84
|
+
"passage",
|
|
85
|
+
"sentier",
|
|
86
|
+
"square",
|
|
87
|
+
"cours",
|
|
88
|
+
"voie",
|
|
89
|
+
"chaussee",
|
|
90
|
+
"rond",
|
|
91
|
+
"point",
|
|
92
|
+
"clos",
|
|
93
|
+
"villa",
|
|
94
|
+
"cite",
|
|
95
|
+
"de",
|
|
96
|
+
"du",
|
|
97
|
+
"des",
|
|
98
|
+
"la",
|
|
99
|
+
"le",
|
|
100
|
+
"les",
|
|
101
|
+
"l",
|
|
102
|
+
"d",
|
|
103
|
+
"en",
|
|
104
|
+
"aux",
|
|
105
|
+
"au",
|
|
106
|
+
"sur",
|
|
107
|
+
"sous",
|
|
108
|
+
])
|
|
109
|
+
|
|
110
|
+
/** True when the folded surface contains no token outside {@link FR_STREET_TYPE_WORDS} — i.e. it is pure type/particle. */
|
|
111
|
+
export function isPureTypeVocabulary(foldedSurface: string): boolean {
|
|
112
|
+
const tokens = foldedSurface.split(" ").filter(Boolean)
|
|
113
|
+
|
|
114
|
+
if (tokens.length === 0) return true
|
|
115
|
+
|
|
116
|
+
return tokens.every((t) => FR_STREET_TYPE_WORDS.has(t))
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
/** One candidate parse for the street-evidence rerank — its street surface + its (within-input comparable) score. */
|
|
120
|
+
export interface StreetCandidate<T = unknown> {
|
|
121
|
+
/** The candidate's street surface (raw; folded internally). Empty string = no street parsed → never the evidence pick. */
|
|
122
|
+
streetSurface: string
|
|
123
|
+
/** The parse score, comparable to its siblings from the SAME input. Higher is better. */
|
|
124
|
+
score: number
|
|
125
|
+
/** Opaque caller payload carried through to the result (the segmentation, the tree, …). */
|
|
126
|
+
payload?: T
|
|
127
|
+
}
|
|
128
|
+
|
|
129
|
+
export interface PickByStreetEvidenceOpts {
|
|
130
|
+
/** Locality/postcode scope forwarded to {@link StreetLocalityEvidence.hasStreetName} (fragments usually carry none). */
|
|
131
|
+
scope?: StreetEvidenceScope
|
|
132
|
+
/**
|
|
133
|
+
* G2 — the margin cap. A candidate whose score is more than this far below rank-1 is never promoted by evidence
|
|
134
|
+
* (without it, evidence reaches deep down the list and moves off correct rank-1 parses). Default 2.5 — the value the
|
|
135
|
+
* v2 board measured (148 fixes / 3 breaks). UNCALIBRATED across models: re-fit when the span head retrains, since raw
|
|
136
|
+
* score margins are not comparable across models. (Plan #1134 pre-registers an isotonic ambiguity gate to replace
|
|
137
|
+
* it.)
|
|
138
|
+
*/
|
|
139
|
+
marginCap?: number
|
|
140
|
+
}
|
|
141
|
+
|
|
142
|
+
export interface StreetEvidencePick<T = unknown> {
|
|
143
|
+
/** The chosen candidate — the first evidence-passing sibling, or rank-1 when none passes (fail-open). */
|
|
144
|
+
candidate: StreetCandidate<T>
|
|
145
|
+
/** Index of the chosen candidate in the input array. */
|
|
146
|
+
index: number
|
|
147
|
+
/** True when evidence MOVED the pick off rank-1 (a rank-2-beats-rank-1 correction — loggable training signal). */
|
|
148
|
+
moved: boolean
|
|
149
|
+
}
|
|
150
|
+
|
|
151
|
+
/**
|
|
152
|
+
* The measured v2 rerank policy. Given candidates in PARSE-SCORE order (rank-1 first) and an evidence probe, return the
|
|
153
|
+
* first candidate whose street surface passes ALL of: (1) exists in the index, (2) G1 — not pure type vocabulary, (3)
|
|
154
|
+
* G2 — within `marginCap` of rank-1. If none passes, return rank-1 (fail-open). Positive evidence only; the model's
|
|
155
|
+
* order is preserved among equal-evidence candidates. This is the `resolver/rerank.ts` anti-Pelias discipline applied
|
|
156
|
+
* to the name signal: one bit, no blending.
|
|
157
|
+
*
|
|
158
|
+
* @param candidates Parse candidates, rank-1 FIRST (the caller sorts by score descending).
|
|
159
|
+
*/
|
|
160
|
+
export function pickByStreetEvidence<T>(
|
|
161
|
+
candidates: ReadonlyArray<StreetCandidate<T>>,
|
|
162
|
+
evidence: StreetLocalityEvidence,
|
|
163
|
+
opts: PickByStreetEvidenceOpts = {}
|
|
164
|
+
): StreetEvidencePick<T> {
|
|
165
|
+
const marginCap = opts.marginCap ?? 2.5
|
|
166
|
+
|
|
167
|
+
if (candidates.length === 0) {
|
|
168
|
+
throw new Error("pickByStreetEvidence: no candidates")
|
|
169
|
+
}
|
|
170
|
+
const rank1 = candidates[0]!
|
|
171
|
+
const topScore = rank1.score
|
|
172
|
+
|
|
173
|
+
for (let i = 0; i < candidates.length; i++) {
|
|
174
|
+
const c = candidates[i]!
|
|
175
|
+
|
|
176
|
+
if (!c.streetSurface) continue
|
|
177
|
+
|
|
178
|
+
// G2: candidates are score-ordered, so once one falls past the cap nothing deeper qualifies either.
|
|
179
|
+
if (topScore - c.score > marginCap) break
|
|
180
|
+
|
|
181
|
+
// G1: a pure street-type/particle surface (bare `rue`) carries no name — no evidence credit.
|
|
182
|
+
if (isPureTypeVocabulary(foldStreetSurface(c.streetSurface))) continue
|
|
183
|
+
|
|
184
|
+
if (evidence.hasStreetName(c.streetSurface, opts.scope)) {
|
|
185
|
+
return { candidate: c, index: i, moved: i > 0 }
|
|
186
|
+
}
|
|
187
|
+
}
|
|
188
|
+
|
|
189
|
+
return { candidate: rank1, index: 0, moved: false }
|
|
190
|
+
}
|
package/vitest.config.ts
ADDED
|
@@ -0,0 +1,39 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @copyright Sister Software
|
|
3
|
+
* @license AGPL-3.0
|
|
4
|
+
* @author Teffen Ellis, et al.
|
|
5
|
+
*
|
|
6
|
+
* Per-package vitest config for @mailwoman/resolver. The resolver's OWN files run from source
|
|
7
|
+
* (vitest transpiles ./resolve.ts etc.); its workspace deps — @mailwoman/core, /spatial, /codex —
|
|
8
|
+
* resolve to their compiled `out/` (built by `tsc -b`). vitest's default resolution doesn't
|
|
9
|
+
* traverse a sibling workspace's package-exports for a transitive import (e.g. spatial →
|
|
10
|
+
* @mailwoman/core/ objects), so the aliases below pin them explicitly. Most subpaths are
|
|
11
|
+
* directories (→ `<dir>/ index.js`); the handful that are bare files (`objects`) get a
|
|
12
|
+
* more-specific alias FIRST.
|
|
13
|
+
*/
|
|
14
|
+
|
|
15
|
+
import { resolve } from "node:path"
|
|
16
|
+
|
|
17
|
+
import { defineConfig } from "vitest/config"
|
|
18
|
+
|
|
19
|
+
const here = import.meta.dirname
|
|
20
|
+
const out = (pkg: string, sub: string) => resolve(here, `../${pkg}/out/${sub}`)
|
|
21
|
+
|
|
22
|
+
export default defineConfig({
|
|
23
|
+
resolve: {
|
|
24
|
+
alias: [
|
|
25
|
+
// Order matters — file-subpaths (objects.ts → objects.js) before the directory regex.
|
|
26
|
+
{ find: /^@mailwoman\/core\/objects$/, replacement: out("core", "objects.js") },
|
|
27
|
+
{ find: /^@mailwoman\/core\/(.+)$/, replacement: resolve(here, "../core/out/$1/index.js") },
|
|
28
|
+
{ find: /^@mailwoman\/core$/, replacement: out("core", "index.js") },
|
|
29
|
+
{ find: /^@mailwoman\/spatial\/(.+)$/, replacement: resolve(here, "../spatial/out/$1/index.js") },
|
|
30
|
+
{ find: /^@mailwoman\/spatial$/, replacement: out("spatial", "index.js") },
|
|
31
|
+
{ find: /^@mailwoman\/codex\/(.+)$/, replacement: resolve(here, "../codex/out/$1/index.js") },
|
|
32
|
+
{ find: /^@mailwoman\/codex$/, replacement: out("codex", "index.js") },
|
|
33
|
+
],
|
|
34
|
+
},
|
|
35
|
+
test: {
|
|
36
|
+
isolate: true,
|
|
37
|
+
exclude: ["**/node_modules/**", "**/out/**", "**/dist/**"],
|
|
38
|
+
},
|
|
39
|
+
})
|