@mailwoman/core 7.2.0 → 7.3.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/api/APIClient.ts +175 -0
- package/api/headless.ts +23 -0
- package/api/index.ts +11 -0
- package/api/responses.ts +135 -0
- package/coarse-placer/coarse-placer.ts +300 -0
- package/coarse-placer/featurize.ts +171 -0
- package/coarse-placer/tools/build-dataset.ts +223 -0
- package/coarse-placer/tools/build-outlier-exposure.ts +172 -0
- package/coarse-placer/tools/build-outlier-latin.ts +200 -0
- package/coarse-placer/tools/build-outlier-oa.ts +231 -0
- package/coarse-placer/tools/eval-latin-offmap.ts +140 -0
- package/coarse-placer/tools/eval-openset.ts +519 -0
- package/coarse-placer/tools/eval-quant-compare.ts +151 -0
- package/coarse-placer/tools/eval.ts +187 -0
- package/coarse-placer/tools/fnv-hash.ts +24 -0
- package/coarse-placer/tools/index.ts +23 -0
- package/coarse-placer/tools/probe-frontier.ts +216 -0
- package/coarse-placer/tools/quantize.ts +116 -0
- package/coarse-placer/tools/train.ts +244 -0
- package/collections.ts +134 -0
- package/db/schema.ts +21 -0
- package/decoder/build-tree.ts +228 -0
- package/decoder/calibration.ts +101 -0
- package/decoder/containment.ts +87 -0
- package/decoder/index.ts +17 -0
- package/decoder/proposals-to-tree.ts +83 -0
- package/decoder/resolve-proposal-overlaps.ts +79 -0
- package/decoder/serialize-json.ts +70 -0
- package/decoder/serialize-tuples.ts +61 -0
- package/decoder/serialize-xml.ts +209 -0
- package/decoder/types.ts +159 -0
- package/decoder/unknown-spans.ts +103 -0
- package/decoder/validate-tree.ts +100 -0
- package/env/index.ts +42 -0
- package/env/load.ts +14 -0
- package/env/paths.ts +40 -0
- package/env/schema.ts +125 -0
- package/errors/index.ts +9 -0
- package/errors/schema.ts +155 -0
- package/fs/node.ts +38 -0
- package/identifiers.ts +58 -0
- package/index.ts +13 -0
- package/kysley/adapter.ts +29 -0
- package/kysley/client.ts +30 -0
- package/kysley/dialect-config.ts +30 -0
- package/kysley/dialect.ts +67 -0
- package/kysley/driver.ts +175 -0
- package/layers/index.ts +12 -0
- package/layers/manifest.ts +154 -0
- package/layers/schema.ts +105 -0
- package/locale/index.ts +9 -0
- package/locale/locale.ts +49 -0
- package/locale/profiles/en-us.ts +69 -0
- package/locale/profiles/fr-fr.ts +75 -0
- package/locale/profiles/index.ts +9 -0
- package/locale/profiles/ja-jp.ts +33 -0
- package/locale/registry.ts +68 -0
- package/logging/index.ts +8 -0
- package/logging/shared.ts +145 -0
- package/logging/utils.ts +46 -0
- package/objects.ts +211 -0
- package/out/api/APIClient.d.ts.map +1 -1
- package/out/api/APIClient.js +2 -2
- package/out/api/APIClient.js.map +1 -1
- package/out/pipeline/types.d.ts +13 -0
- package/out/pipeline/types.d.ts.map +1 -1
- package/out/pipeline/types.js.map +1 -1
- package/out/scripting/utils/index.d.ts.map +1 -1
- package/out/scripting/utils/index.js +3 -5
- package/out/scripting/utils/index.js.map +1 -1
- package/package.json +190 -107
- package/pipeline/index.ts +46 -0
- package/pipeline/reconcile-lookups.ts +108 -0
- package/pipeline/reconcile.ts +542 -0
- package/pipeline/runtime-pipeline.ts +732 -0
- package/pipeline/span-logit-aggregation.ts +151 -0
- package/pipeline/span-proposer.ts +587 -0
- package/pipeline/types.ts +357 -0
- package/policy/defaults.ts +35 -0
- package/policy/index.ts +10 -0
- package/policy/policy.ts +60 -0
- package/policy/proposal-collection.ts +64 -0
- package/policy/registry.ts +149 -0
- package/resolver/index.ts +29 -0
- package/resolver/types.ts +584 -0
- package/resources/LocaleIndex.ts +124 -0
- package/resources/ResourceMapCache.ts +126 -0
- package/resources/collections.ts +93 -0
- package/resources/debugging.ts +19 -0
- package/resources/git.ts +54 -0
- package/resources/index.ts +17 -0
- package/resources/languages/index.ts +49 -0
- package/resources/languages/types.gen.ts +1368 -0
- package/resources/libaddressinput.ts +105 -0
- package/resources/libpostal.ts +182 -0
- package/resources/locale.ts +23 -0
- package/resources/set.ts +179 -0
- package/resources/whosonfirst/DataSourceCache.ts +72 -0
- package/resources/whosonfirst/PlacetypeDataSource.ts +199 -0
- package/resources/whosonfirst/index.ts +10 -0
- package/resources/whosonfirst/loader.ts +157 -0
- package/resources/whosonfirst/placetypes/Placetype.ts +438 -0
- package/resources/whosonfirst/placetypes/admin.ts +173 -0
- package/resources/whosonfirst/placetypes/definition.ts +135 -0
- package/resources/whosonfirst/placetypes/graph.ts +0 -0
- package/resources/whosonfirst/placetypes/index.ts +12 -0
- package/resources/whosonfirst/placetypes/mermaid.ts +168 -0
- package/resources/whosonfirst/placetypes/tree.ts +46 -0
- package/routing/index.ts +208 -0
- package/scripting/index.ts +40 -0
- package/scripting/utils/index.ts +103 -0
- package/tokenization/Graph.ts +50 -0
- package/tokenization/Span.ts +297 -0
- package/tokenization/index.ts +9 -0
- package/tokenization/normalizer.ts +123 -0
- package/tools/download-libpostal-resources.ts +98 -0
- package/tools/download-ssl-address.ts +99 -0
- package/tools/generate-language-types.ts +194 -0
- package/tools/index.ts +13 -0
- package/types/Classification.ts +211 -0
- package/types/classifier.ts +133 -0
- package/types/component.ts +75 -0
- package/types/index.ts +10 -0
- package/types/mapping.ts +81 -0
- package/utils/data-root.ts +56 -0
- package/utils/hash.ts +27 -0
- package/utils/index.ts +14 -0
- package/utils/jsonl.ts +43 -0
- package/utils/python-json.ts +105 -0
- package/utils/python-random.ts +90 -0
- package/utils/repo.ts +118 -0
- package/utils/sealed-db.ts +85 -0
- package/utils/stats.ts +32 -0
- package/vitest.config.ts +53 -0
- package/out/lifecycle/ServiceSymbol.d.ts +0 -57
- package/out/lifecycle/ServiceSymbol.d.ts.map +0 -1
- package/out/lifecycle/ServiceSymbol.js +0 -60
- package/out/lifecycle/ServiceSymbol.js.map +0 -1
- package/out/lifecycle/index.d.ts +0 -11
- package/out/lifecycle/index.d.ts.map +0 -1
- package/out/lifecycle/index.js +0 -11
- package/out/lifecycle/index.js.map +0 -1
- package/out/lifecycle/lru-cache.d.ts +0 -22
- package/out/lifecycle/lru-cache.d.ts.map +0 -1
- package/out/lifecycle/lru-cache.js +0 -31
- package/out/lifecycle/lru-cache.js.map +0 -1
- package/out/lifecycle/services.d.ts +0 -144
- package/out/lifecycle/services.d.ts.map +0 -1
- package/out/lifecycle/services.js +0 -191
- package/out/lifecycle/services.js.map +0 -1
|
@@ -0,0 +1,732 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @copyright Sister Software
|
|
3
|
+
* @license AGPL-3.0
|
|
4
|
+
* @author Teffen Ellis, et al.
|
|
5
|
+
*
|
|
6
|
+
* `runPipeline` — the runtime coordinator that composes all six stages.
|
|
7
|
+
*
|
|
8
|
+
* Generic over stage implementations (see `types.ts::RuntimePipelineStages`). Each stage is
|
|
9
|
+
* injected; the coordinator handles composition, timing, fast-path routing, and graceful
|
|
10
|
+
* degradation when stages are absent.
|
|
11
|
+
*
|
|
12
|
+
* Implementation contract per `docs/articles/plan/reference/STAGES.md`.
|
|
13
|
+
*/
|
|
14
|
+
|
|
15
|
+
import type { AddressNode, AddressTree } from "../decoder/types.ts"
|
|
16
|
+
import type { ComponentTag } from "../types/component.ts"
|
|
17
|
+
import { prefetchReconcileLookups } from "./reconcile-lookups.ts"
|
|
18
|
+
import type { ClassifierCandidate } from "./reconcile.ts"
|
|
19
|
+
import { reconcileSpans } from "./reconcile.ts"
|
|
20
|
+
import { aggregateSpanLogits } from "./span-logit-aggregation.ts"
|
|
21
|
+
import { WORD_CONSISTENCY_SHIP_DEFAULT } from "./types.ts"
|
|
22
|
+
import type {
|
|
23
|
+
AddressClassifier,
|
|
24
|
+
ClassifierOpts,
|
|
25
|
+
FSTMatcherLike,
|
|
26
|
+
LocaleHint,
|
|
27
|
+
LocaleTag,
|
|
28
|
+
NormalizedInputLite,
|
|
29
|
+
PhraseProposal,
|
|
30
|
+
PipelineOpts,
|
|
31
|
+
PipelineResult,
|
|
32
|
+
QueryKindResult,
|
|
33
|
+
QueryShapeLite,
|
|
34
|
+
RuntimePipelineStages,
|
|
35
|
+
} from "./types.ts"
|
|
36
|
+
|
|
37
|
+
/**
|
|
38
|
+
* Known QueryShape format strings that indicate "this token is a postcode". Mirrors the set in
|
|
39
|
+
* `@mailwoman/kind-classifier` — kept duplicated so core/pipeline has no dep on kind-classifier.
|
|
40
|
+
*/
|
|
41
|
+
const POSTCODE_FORMATS: ReadonlySet<string> = new Set([
|
|
42
|
+
"us_zip",
|
|
43
|
+
"us_zip4",
|
|
44
|
+
"uk_postcode",
|
|
45
|
+
"fr_postcode",
|
|
46
|
+
"de_postcode",
|
|
47
|
+
"ca_postcode",
|
|
48
|
+
"jp_postcode",
|
|
49
|
+
])
|
|
50
|
+
|
|
51
|
+
function isPostcodeFormat(format: string): boolean {
|
|
52
|
+
return POSTCODE_FORMATS.has(format)
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
/**
|
|
56
|
+
* Anchor weight for the coarse-placer's country prior (#244). Lower than the postcode anchor's 2.0 default — a
|
|
57
|
+
* whole-string country guess is a broader, softer signal than a postcode that pins the country, so it blends more
|
|
58
|
+
* gently with the candidate score.
|
|
59
|
+
*/
|
|
60
|
+
const COARSE_PLACER_ANCHOR_WEIGHT = 1.0
|
|
61
|
+
|
|
62
|
+
// #194: minimum placer confidence to promote the soft country prior to a HARD filter (empty→unresolved).
|
|
63
|
+
// The placer already abstains below 0.9 in-map MASS (open-set rule), but the per-country argmax prob
|
|
64
|
+
// can still be split across neighbours (DK↔NO, EE↔LT↔LV); requiring a high argmax confidence keeps the
|
|
65
|
+
// hard filter to the cases the model is sure of (FI/PL routinely score ~1.0) and leaves the ambiguous
|
|
66
|
+
// ones on the soft path. Deliberately strict — a wrong hard country is the #244 M2 misroute failure.
|
|
67
|
+
const HARD_PLACE_COUNTRY_MIN_CONF = 0.9
|
|
68
|
+
|
|
69
|
+
// #743/#194 coverage guard: countries whose candidate gazetteer is complete enough that hard-filtering
|
|
70
|
+
// is a PURE WIN — measured hard-resolve-rate ≥ 95% on held-out OpenAddresses points, so a hard-filter
|
|
71
|
+
// "miss → unresolved" is rare and almost always a genuine non-match, not a coverage gap. A confident
|
|
72
|
+
// placement OUTSIDE this set stays on the SOFT prior, so the low-coverage tail (FI/PL/…) keeps its
|
|
73
|
+
// recall until its gazetteer is filled (#193) — the win for covered countries, no recall regression
|
|
74
|
+
// for the rest (DeepSeek-advised, 2026-06-22). Measured resolve-rate under hard: US 100, FR 100, DE
|
|
75
|
+
// 100, ES 99.8, NL 97.3, IT 96.8 (in); FI 69.5, PL 77.8 (out). Grow as more countries clear the bar.
|
|
76
|
+
// Override per-call with `PipelineOpts.hardCountrySafelist` (the eval measures ungated to grow it).
|
|
77
|
+
// GB + CA added at the #928 promote (2026-07-06): the postcodeCountryPrior format signal routes them
|
|
78
|
+
// confidently (the language placer conflated both with US), and their OSM-panel gates passed with the
|
|
79
|
+
// hard filter on — GB 271/300 ok / 7 unresolved, CA 200/300 ok / 31 unresolved (night 34).
|
|
80
|
+
export const HARD_PLACE_COUNTRY_SAFELIST: ReadonlySet<string> = new Set([
|
|
81
|
+
"US",
|
|
82
|
+
"ES",
|
|
83
|
+
"IT",
|
|
84
|
+
"NL",
|
|
85
|
+
"DE",
|
|
86
|
+
"FR",
|
|
87
|
+
"GB",
|
|
88
|
+
"CA",
|
|
89
|
+
// AU added with the #244 AU placer class (2026-07-06): 150k-row G-NAF training → AU test-acc 100%,
|
|
90
|
+
// and the hard filter is recall-SAFE on the AU panel (unresolved 4→2 while abroad 43→20).
|
|
91
|
+
"AU",
|
|
92
|
+
])
|
|
93
|
+
|
|
94
|
+
/**
|
|
95
|
+
* #912 lever 1 — is this parse a single BARE locality ("Paris", "Dublin")? The coarse placer is out-of-distribution on
|
|
96
|
+
* one-token city names (trained on full addresses): measured on the gauntlet's bare-namesake rows it emitted Paris→IT
|
|
97
|
+
* .35, Melbourne→GB .66 — all wrong, and even sub-threshold the SOFT posterior still re-ranks the resolver toward the
|
|
98
|
+
* wrong country. A bare locality carries no country evidence the placer can read that the resolver's exact-tier +
|
|
99
|
+
* population ranking doesn't already use better — so both production placeCountry call sites (the runtime pipeline and
|
|
100
|
+
* `geocodeAddress`) ABSTAIN on this shape. Any second non-empty component makes the input address-shaped and the placer
|
|
101
|
+
* runs as before.
|
|
102
|
+
*/
|
|
103
|
+
export function isBareLocalityTree(tree: AddressTree): boolean {
|
|
104
|
+
let sawLocality = false
|
|
105
|
+
const stack = [...tree.roots]
|
|
106
|
+
|
|
107
|
+
while (stack.length > 0) {
|
|
108
|
+
const node = stack.pop()!
|
|
109
|
+
|
|
110
|
+
if (node.tag === "locality") {
|
|
111
|
+
sawLocality = true
|
|
112
|
+
} else if (node.value.trim() !== "") return false
|
|
113
|
+
stack.push(...node.children)
|
|
114
|
+
}
|
|
115
|
+
|
|
116
|
+
return sawLocality
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
/**
|
|
120
|
+
* #743/#194: the shared coverage-guard gate — decide whether a confident coarse-placer country should become a HARD
|
|
121
|
+
* candidate filter. Exported so the two production placeCountry call sites (the runtime pipeline AND `geocodeAddress`)
|
|
122
|
+
* apply the SAME three gates and can't drift: confidence ≥ {@link HARD_PLACE_COUNTRY_MIN_CONF}, country in the safelist
|
|
123
|
+
* (override or the default {@link HARD_PLACE_COUNTRY_SAFELIST}), and no caller-set hard/default country to respect.
|
|
124
|
+
* Returns the country to hard-filter, or `undefined` to stay on the soft prior.
|
|
125
|
+
*/
|
|
126
|
+
export function hardCountryFor(
|
|
127
|
+
placedCountry: string,
|
|
128
|
+
placedConfidence: number,
|
|
129
|
+
existing: { hardCountry?: string; defaultCountry?: string },
|
|
130
|
+
hardPlaceCountry: boolean | undefined,
|
|
131
|
+
safelist: ReadonlySet<string> | undefined
|
|
132
|
+
): string | undefined {
|
|
133
|
+
if (!hardPlaceCountry) return undefined
|
|
134
|
+
|
|
135
|
+
if (placedConfidence < HARD_PLACE_COUNTRY_MIN_CONF) return undefined
|
|
136
|
+
|
|
137
|
+
if (!(safelist ?? HARD_PLACE_COUNTRY_SAFELIST).has(placedCountry)) return undefined
|
|
138
|
+
|
|
139
|
+
if (existing.hardCountry || existing.defaultCountry) return undefined
|
|
140
|
+
|
|
141
|
+
return placedCountry
|
|
142
|
+
}
|
|
143
|
+
|
|
144
|
+
function isPostcodeFormatHit(hit: { format: string }): boolean {
|
|
145
|
+
return isPostcodeFormat(hit.format)
|
|
146
|
+
}
|
|
147
|
+
|
|
148
|
+
/** Pass-through normalize used when no `normalize` stage is wired. */
|
|
149
|
+
function identityNormalize(raw: string, opts?: { locale?: string }): NormalizedInputLite {
|
|
150
|
+
return { raw, normalized: raw, appliedLocale: opts?.locale }
|
|
151
|
+
}
|
|
152
|
+
|
|
153
|
+
/** No-op query-shape used when no `computeQueryShape` stage is wired. */
|
|
154
|
+
function emptyQueryShape(): QueryShapeLite {
|
|
155
|
+
return { knownFormats: [] }
|
|
156
|
+
}
|
|
157
|
+
|
|
158
|
+
/** Default locale detector: trusts the caller's hint, or falls back to `und`. */
|
|
159
|
+
async function defaultDetectLocale(
|
|
160
|
+
_input: NormalizedInputLite,
|
|
161
|
+
_shape: QueryShapeLite,
|
|
162
|
+
opts?: { hint?: LocaleTag }
|
|
163
|
+
): Promise<LocaleHint> {
|
|
164
|
+
const locale = opts?.hint ?? "und"
|
|
165
|
+
|
|
166
|
+
return {
|
|
167
|
+
locale,
|
|
168
|
+
confidence: opts?.hint ? 1.0 : 0.0,
|
|
169
|
+
alternatives: [],
|
|
170
|
+
source: opts?.hint ? "caller" : "detected",
|
|
171
|
+
}
|
|
172
|
+
}
|
|
173
|
+
|
|
174
|
+
/** Default kind classifier: always returns `structured_address` with low confidence (no fast-path). */
|
|
175
|
+
async function defaultClassifyKind(
|
|
176
|
+
_input: NormalizedInputLite,
|
|
177
|
+
_shape: QueryShapeLite,
|
|
178
|
+
_locale: LocaleHint
|
|
179
|
+
): Promise<QueryKindResult> {
|
|
180
|
+
return {
|
|
181
|
+
kind: "structured_address",
|
|
182
|
+
confidence: 0.0,
|
|
183
|
+
alternatives: [],
|
|
184
|
+
}
|
|
185
|
+
}
|
|
186
|
+
|
|
187
|
+
/**
|
|
188
|
+
* Decide whether to short-circuit stages 3-5 and go straight to resolve. Conservative: requires high kind-classifier
|
|
189
|
+
* confidence AND a matching QueryShape known-format hit. See `STAGES.md#fast-path-routing` for the rationale.
|
|
190
|
+
*/
|
|
191
|
+
function canShortCircuit(kind: QueryKindResult, shape: QueryShapeLite, opts?: PipelineOpts): boolean {
|
|
192
|
+
if (opts?.forceFullPipeline) return false
|
|
193
|
+
|
|
194
|
+
if (kind.confidence < 0.95) return false
|
|
195
|
+
|
|
196
|
+
if (kind.kind === "postcode_only") {
|
|
197
|
+
return shape.knownFormats.some(isPostcodeFormatHit)
|
|
198
|
+
}
|
|
199
|
+
|
|
200
|
+
if (kind.kind === "locality_only") {
|
|
201
|
+
return (shape.totalLength ?? Infinity) <= 30 && shape.characterClass === "alpha"
|
|
202
|
+
}
|
|
203
|
+
|
|
204
|
+
return false
|
|
205
|
+
}
|
|
206
|
+
|
|
207
|
+
/**
|
|
208
|
+
* Build a stub `AddressTree` for the fast-path case (no classifier ran). Single root node tagged by the QueryShape's
|
|
209
|
+
* known-format hit.
|
|
210
|
+
*/
|
|
211
|
+
function buildFastPathTree(text: string, kind: QueryKindResult, shape: QueryShapeLite): AddressTree {
|
|
212
|
+
if (kind.kind === "postcode_only") {
|
|
213
|
+
const hit = shape.knownFormats.find((f) => isPostcodeFormat(f.format))
|
|
214
|
+
|
|
215
|
+
if (hit) {
|
|
216
|
+
return {
|
|
217
|
+
raw: text,
|
|
218
|
+
roots: [
|
|
219
|
+
{
|
|
220
|
+
tag: "postcode",
|
|
221
|
+
value: text.slice(hit.span.start, hit.span.end),
|
|
222
|
+
start: hit.span.start,
|
|
223
|
+
end: hit.span.end,
|
|
224
|
+
confidence: hit.confidence,
|
|
225
|
+
children: [],
|
|
226
|
+
source: "query-shape",
|
|
227
|
+
sourceID: hit.format,
|
|
228
|
+
},
|
|
229
|
+
],
|
|
230
|
+
}
|
|
231
|
+
}
|
|
232
|
+
}
|
|
233
|
+
|
|
234
|
+
if (kind.kind === "locality_only") {
|
|
235
|
+
return {
|
|
236
|
+
raw: text,
|
|
237
|
+
roots: [
|
|
238
|
+
{
|
|
239
|
+
tag: "locality",
|
|
240
|
+
value: text.trim(),
|
|
241
|
+
start: 0,
|
|
242
|
+
end: text.length,
|
|
243
|
+
confidence: kind.confidence,
|
|
244
|
+
children: [],
|
|
245
|
+
source: "query-shape",
|
|
246
|
+
sourceID: "kind:locality_only",
|
|
247
|
+
},
|
|
248
|
+
],
|
|
249
|
+
}
|
|
250
|
+
}
|
|
251
|
+
|
|
252
|
+
return { raw: text, roots: [] }
|
|
253
|
+
}
|
|
254
|
+
|
|
255
|
+
/**
|
|
256
|
+
* Run the runtime pipeline.
|
|
257
|
+
*
|
|
258
|
+
* Composition order (per STAGES.md):
|
|
259
|
+
*
|
|
260
|
+
* 1. Normalize (or identity)
|
|
261
|
+
* 2. Compute QueryShape (or empty)
|
|
262
|
+
* 3. Locale gate (or caller-trust)
|
|
263
|
+
* 4. Kind classifier (or default structured_address)
|
|
264
|
+
* 5. Branch: fast-path → resolver; full → classifier → resolver
|
|
265
|
+
*
|
|
266
|
+
* Per-stage timing recorded on `result.timing`. Fast-path stages are absent from the timing map.
|
|
267
|
+
*/
|
|
268
|
+
export async function runPipeline(
|
|
269
|
+
raw: string,
|
|
270
|
+
stages: RuntimePipelineStages,
|
|
271
|
+
opts?: PipelineOpts
|
|
272
|
+
): Promise<PipelineResult> {
|
|
273
|
+
const timing: Record<string, number> = {}
|
|
274
|
+
const t0 = performance.now()
|
|
275
|
+
|
|
276
|
+
const normalize = stages.normalize ?? identityNormalize
|
|
277
|
+
const computeQueryShape = stages.computeQueryShape ?? emptyQueryShape
|
|
278
|
+
const detectLocale = stages.detectLocale ?? defaultDetectLocale
|
|
279
|
+
const classifyKind = stages.classifyKind ?? defaultClassifyKind
|
|
280
|
+
|
|
281
|
+
throwIfAborted(opts)
|
|
282
|
+
const normalized = normalize(raw, { locale: opts?.locale })
|
|
283
|
+
timing["normalize"] = performance.now() - t0
|
|
284
|
+
|
|
285
|
+
// Coarse country router (#244, soft prior). A confident in-map guess becomes an `anchorPosterior`
|
|
286
|
+
// the resolver's #369 re-rank BOOSTS (never filters); abstain/OTHER → no signal. Defers to a
|
|
287
|
+
// caller-supplied posterior (a stronger postcode anchor — never overwrite it). Off (no stage) →
|
|
288
|
+
// `effectiveOpts === opts` → byte-stable. See the soft-signal wiring spec.
|
|
289
|
+
let effectiveOpts = opts
|
|
290
|
+
// #912 lever 1: true when the anchorPosterior in effectiveOpts came from the placer (not the
|
|
291
|
+
// caller) — the post-parse bare-locality abstention below only strips what the placer added.
|
|
292
|
+
let placerAnchorApplied = false
|
|
293
|
+
|
|
294
|
+
if (stages.placeCountry) {
|
|
295
|
+
const tPlace = performance.now()
|
|
296
|
+
const placed = stages.placeCountry(normalized.normalized)
|
|
297
|
+
timing["place-country"] = performance.now() - tPlace
|
|
298
|
+
|
|
299
|
+
if (placed.country && placed.country !== "OTHER" && !opts?.resolveOpts?.anchorPosterior) {
|
|
300
|
+
// #194/#743: promote a CONFIDENT placement to a HARD country filter (empty→unresolved) when the
|
|
301
|
+
// caller opts in, the confidence clears the bar, AND the country is in the coverage SAFELIST. The
|
|
302
|
+
// soft posterior alone can't move a LOW-population place (a FI town loses to a high-pop namesake
|
|
303
|
+
// even when FI is pinned); the hard filter does. Three gates: confidence (ambiguous DK↔NO stay
|
|
304
|
+
// soft), the safelist (only well-covered countries — where a miss is a genuine non-match, not a
|
|
305
|
+
// coverage gap — hard-filter; the low-coverage tail keeps its recall on the soft path), and the
|
|
306
|
+
// caller's own hardCountry/defaultCountry is never overwritten. Pass `hardCountrySafelist` to
|
|
307
|
+
// override the default set (the eval measures ungated to grow it).
|
|
308
|
+
const hardCountry = hardCountryFor(
|
|
309
|
+
placed.country,
|
|
310
|
+
placed.confidence,
|
|
311
|
+
opts?.resolveOpts ?? {},
|
|
312
|
+
opts?.hardPlaceCountry,
|
|
313
|
+
opts?.hardCountrySafelist
|
|
314
|
+
)
|
|
315
|
+
placerAnchorApplied = true
|
|
316
|
+
effectiveOpts = {
|
|
317
|
+
...opts,
|
|
318
|
+
resolveOpts: {
|
|
319
|
+
...opts?.resolveOpts,
|
|
320
|
+
// The full in-map distribution when the placer supplies it (resolver breaks ties); else the
|
|
321
|
+
// one-hot argmax (the M2 behavior).
|
|
322
|
+
anchorPosterior: placed.posterior ?? { [placed.country]: placed.confidence },
|
|
323
|
+
anchorWeight: opts?.resolveOpts?.anchorWeight ?? COARSE_PLACER_ANCHOR_WEIGHT,
|
|
324
|
+
...(hardCountry ? { hardCountry } : {}),
|
|
325
|
+
},
|
|
326
|
+
}
|
|
327
|
+
}
|
|
328
|
+
}
|
|
329
|
+
|
|
330
|
+
throwIfAborted(opts)
|
|
331
|
+
const tQs = performance.now()
|
|
332
|
+
const queryShape = computeQueryShape(normalized, { locale: opts?.locale })
|
|
333
|
+
timing["query-shape"] = performance.now() - tQs
|
|
334
|
+
|
|
335
|
+
throwIfAborted(opts)
|
|
336
|
+
const tLocale = performance.now()
|
|
337
|
+
const locale = await detectLocale(normalized, queryShape, { hint: opts?.locale })
|
|
338
|
+
timing["locale-gate"] = performance.now() - tLocale
|
|
339
|
+
|
|
340
|
+
throwIfAborted(opts)
|
|
341
|
+
const tKind = performance.now()
|
|
342
|
+
const kind = await classifyKind(normalized, queryShape, locale)
|
|
343
|
+
timing["kind-classifier"] = performance.now() - tKind
|
|
344
|
+
|
|
345
|
+
// POI branch (spec §3.1). Only reachable when a poi-aware kind classifier was wired (the
|
|
346
|
+
// default classifier never emits `poi_query`), and only acts when the stage is present —
|
|
347
|
+
// both absent by default, so the flag-off pipeline is byte-identical by construction. A
|
|
348
|
+
// `null` outcome falls through to the full pipeline: a poi_query kind with no extractable
|
|
349
|
+
// subject is a mis-detection, and the address path is the safe interpretation.
|
|
350
|
+
if (kind.kind === "poi_query" && stages.poiIntent) {
|
|
351
|
+
throwIfAborted(opts)
|
|
352
|
+
const tPoi = performance.now()
|
|
353
|
+
const poiOutcome = await stages.poiIntent(normalized, locale, effectiveOpts)
|
|
354
|
+
timing["poi-intent"] = performance.now() - tPoi
|
|
355
|
+
|
|
356
|
+
if (poiOutcome) {
|
|
357
|
+
const emptyTree: AddressTree = { raw: normalized.normalized, roots: [] }
|
|
358
|
+
const tree = poiOutcome.type === "intent" ? (poiOutcome.intent.anchor?.tree ?? emptyTree) : emptyTree
|
|
359
|
+
|
|
360
|
+
return {
|
|
361
|
+
input: raw,
|
|
362
|
+
normalized,
|
|
363
|
+
queryShape,
|
|
364
|
+
locale,
|
|
365
|
+
kind,
|
|
366
|
+
phraseProposals: [],
|
|
367
|
+
tree,
|
|
368
|
+
poiIntent: poiOutcome,
|
|
369
|
+
timing,
|
|
370
|
+
path: "poi",
|
|
371
|
+
}
|
|
372
|
+
}
|
|
373
|
+
}
|
|
374
|
+
|
|
375
|
+
// Fast-path: trivial inputs short-circuit stages 3-5. The fast-path tree is built from
|
|
376
|
+
// QueryShape's format hits + kind alone — useful even without a wired resolver (a consumer
|
|
377
|
+
// who just wants the parsed structure for a bare postcode shouldn't be forced to pay for the
|
|
378
|
+
// classifier).
|
|
379
|
+
if (canShortCircuit(kind, queryShape, opts)) {
|
|
380
|
+
let tree = buildFastPathTree(normalized.normalized, kind, queryShape)
|
|
381
|
+
|
|
382
|
+
if (stages.resolver) {
|
|
383
|
+
throwIfAborted(opts)
|
|
384
|
+
const tResolve = performance.now()
|
|
385
|
+
tree = await safeResolve(stages.resolver, tree, effectiveOpts)
|
|
386
|
+
timing["resolve"] = performance.now() - tResolve
|
|
387
|
+
}
|
|
388
|
+
|
|
389
|
+
return {
|
|
390
|
+
input: raw,
|
|
391
|
+
normalized,
|
|
392
|
+
queryShape,
|
|
393
|
+
locale,
|
|
394
|
+
kind,
|
|
395
|
+
phraseProposals: [],
|
|
396
|
+
tree,
|
|
397
|
+
timing,
|
|
398
|
+
path: "fast-path",
|
|
399
|
+
}
|
|
400
|
+
}
|
|
401
|
+
|
|
402
|
+
// Full pipeline.
|
|
403
|
+
// Stage 2.7 — phrase grouper. Optional injection; runs when wired. Proposals flow forward to
|
|
404
|
+
// stages 3 + 5 (today: surfaced on the result; tomorrow: passed in as classifier conditioning).
|
|
405
|
+
let phraseProposals: PhraseProposal[] = []
|
|
406
|
+
|
|
407
|
+
if (stages.groupPhrases) {
|
|
408
|
+
throwIfAborted(opts)
|
|
409
|
+
const tGroup = performance.now()
|
|
410
|
+
phraseProposals = await safeGroupPhrases(stages.groupPhrases, normalized, queryShape, locale)
|
|
411
|
+
timing["phrase-grouper"] = performance.now() - tGroup
|
|
412
|
+
}
|
|
413
|
+
|
|
414
|
+
let tree: AddressTree = { raw: normalized.normalized, roots: [] }
|
|
415
|
+
// Captured from the joint-reconcile path so the grouper-audit can defer to the classifier's
|
|
416
|
+
// per-span verdict on orphaned spans (see the assignment + grouperAudit below).
|
|
417
|
+
let auditClassifierTopK: ClassifierCandidate[] | undefined
|
|
418
|
+
|
|
419
|
+
// Joint-reconcile path: RETIRED AS DEFAULT 2026-06-14 (#427 promoted it; this de-promotes it).
|
|
420
|
+
// A reconcile-vs-raw-neural audit on two non-circular US holdouts (Travis E-911 + 7-state
|
|
421
|
+
// OpenAddresses) found it BREAKS the street+house_number geocode precondition on 77-84% of clean
|
|
422
|
+
// US addresses and fixes 0% — the phrase grouper bundles the house number into the STREET_PHRASE
|
|
423
|
+
// ("3075 Hill Street") and reconcileSpans then fuses the whole span into one node, leaving no
|
|
424
|
+
// separate `street`. Confirmed on golden v0.1.2 US+FR (n=4507, per-tag recall vs raw argmax):
|
|
425
|
+
// street -25.6pp, house_number -23.1pp, locality -2.3pp, venue -0.6pp, region/postcode/unit flat.
|
|
426
|
+
// It is worse-or-flat on EVERY tag — including venue, the thing #427 promoted it for. The #427
|
|
427
|
+
// re-gate's "DE +25pp / IT-ES +15pp" was loose street-STRING recall on OOD inputs (where raw
|
|
428
|
+
// neural mangles the street); it never measured the geocode precondition our evals grade on raw
|
|
429
|
+
// neural, so the regression was invisible. The destructive piece is the grouper HN-bundling (see
|
|
430
|
+
// the tracked issue); until that's fixed, argmax is the correct default. Set `jointReconcile: true`
|
|
431
|
+
// to opt back into reconcile (the A/B harnesses do). Report:
|
|
432
|
+
// docs/articles/evals/experiments/2026-06-14-reconcile-retirement.md.
|
|
433
|
+
const jointEnabled = opts?.jointReconcile ?? opts?.forceJointReconcile ?? false
|
|
434
|
+
const useJointReconcile =
|
|
435
|
+
jointEnabled && phraseProposals.length > 0 && stages.classifier && "parseWithLogits" in stages.classifier
|
|
436
|
+
|
|
437
|
+
if (useJointReconcile) {
|
|
438
|
+
const classifierWithLogits = stages.classifier as AddressClassifier & {
|
|
439
|
+
parseWithLogits: (
|
|
440
|
+
text: string,
|
|
441
|
+
opts?: ClassifierOpts
|
|
442
|
+
) => Promise<{ tree: AddressTree; logits: number[][]; pieces: Array<{ start: number; end: number }> }>
|
|
443
|
+
}
|
|
444
|
+
|
|
445
|
+
throwIfAborted(opts)
|
|
446
|
+
const tClassify = performance.now()
|
|
447
|
+
const {
|
|
448
|
+
tree: argmaxTree,
|
|
449
|
+
logits,
|
|
450
|
+
pieces,
|
|
451
|
+
} = await classifierWithLogits.parseWithLogits(normalized.normalized, { queryShape, fst: stages.fst })
|
|
452
|
+
timing["token-classify"] = performance.now() - tClassify
|
|
453
|
+
|
|
454
|
+
throwIfAborted(opts)
|
|
455
|
+
const tReconcile = performance.now()
|
|
456
|
+
|
|
457
|
+
// The classifier must expose its label vocabulary so the aggregation can strip BIO prefixes.
|
|
458
|
+
// NeuralAddressClassifier surfaces this as `cfg.labels` — extracted via structural typing here.
|
|
459
|
+
const labels: readonly string[] =
|
|
460
|
+
"labels" in classifierWithLogits ? (classifierWithLogits as unknown as { labels: readonly string[] }).labels : []
|
|
461
|
+
|
|
462
|
+
const classifierTopK = aggregateSpanLogits(
|
|
463
|
+
logits,
|
|
464
|
+
pieces,
|
|
465
|
+
phraseProposals.map((p) => ({ start: p.span.start, end: p.span.end })),
|
|
466
|
+
{ labels, text: normalized.normalized }
|
|
467
|
+
)
|
|
468
|
+
|
|
469
|
+
if (classifierTopK.length > 0) {
|
|
470
|
+
// Concordance axes (#478): when the caller wires a backend, one bounded pre-fetch
|
|
471
|
+
// activates the resolver-candidate + parent-chain scoring the reconciler already
|
|
472
|
+
// implements. Absent backend = classifier-only reconcile (byte-stable).
|
|
473
|
+
// Country constraint from the locale gate's BCP-47 tag ("en-US" -> "US"); absent or
|
|
474
|
+
// und-like tags pass no constraint (ranking alone decides — matches resolveTree's default).
|
|
475
|
+
const localeCountry = locale.locale.split("-")[1]?.toUpperCase()
|
|
476
|
+
const lookups = stages.resolverBackend
|
|
477
|
+
? await prefetchReconcileLookups(
|
|
478
|
+
stages.resolverBackend,
|
|
479
|
+
normalized.normalized,
|
|
480
|
+
classifierTopK,
|
|
481
|
+
localeCountry && localeCountry.length === 2 ? { defaultCountry: localeCountry } : {}
|
|
482
|
+
)
|
|
483
|
+
: undefined
|
|
484
|
+
const result = reconcileSpans({
|
|
485
|
+
raw: normalized.normalized,
|
|
486
|
+
phraseProposals,
|
|
487
|
+
classifierTopK,
|
|
488
|
+
...(lookups ? { resolverCandidates: lookups.resolverCandidates, parentChain: lookups.parentChain } : {}),
|
|
489
|
+
})
|
|
490
|
+
tree = result.tree
|
|
491
|
+
// The reconciler can leave a span uncovered (e.g. it picked the single-token street
|
|
492
|
+
// `Trento` over `Via Trento`, orphaning `Via`). The grouper-audit below would then promote
|
|
493
|
+
// that orphan's LOCALITY_PHRASE proposal to a `locality` node — even though the classifier
|
|
494
|
+
// confidently typed it `street`. Hand the audit the classifier's per-span verdict so it
|
|
495
|
+
// respects that opinion instead of trusting the structural phrase kind (#425 re-gate).
|
|
496
|
+
auditClassifierTopK = classifierTopK
|
|
497
|
+
} else {
|
|
498
|
+
tree = argmaxTree
|
|
499
|
+
}
|
|
500
|
+
timing["reconcile"] = performance.now() - tReconcile
|
|
501
|
+
} else if (stages.classifier) {
|
|
502
|
+
throwIfAborted(opts)
|
|
503
|
+
const tClassify = performance.now()
|
|
504
|
+
tree = await safeClassify(stages.classifier, normalized.normalized, queryShape, stages.fst, opts?.normalizeCase)
|
|
505
|
+
timing["token-classify"] = performance.now() - tClassify
|
|
506
|
+
}
|
|
507
|
+
|
|
508
|
+
if (phraseProposals.length > 0 && tree.roots.length >= 0) {
|
|
509
|
+
const tAudit = performance.now()
|
|
510
|
+
tree = grouperAudit(tree, phraseProposals, normalized.normalized, auditClassifierTopK)
|
|
511
|
+
timing["grouper-audit"] = performance.now() - tAudit
|
|
512
|
+
}
|
|
513
|
+
|
|
514
|
+
if (stages.resolver) {
|
|
515
|
+
throwIfAborted(opts)
|
|
516
|
+
const tResolve = performance.now()
|
|
517
|
+
|
|
518
|
+
// #912 lever 1: the placer abstains on a single bare locality — strip ONLY the anchor it
|
|
519
|
+
// added (a caller-supplied posterior was never overwritten and passes through untouched).
|
|
520
|
+
if (placerAnchorApplied && isBareLocalityTree(tree)) {
|
|
521
|
+
effectiveOpts = opts
|
|
522
|
+
}
|
|
523
|
+
tree = await safeResolve(stages.resolver, tree, effectiveOpts)
|
|
524
|
+
timing["resolve"] = performance.now() - tResolve
|
|
525
|
+
}
|
|
526
|
+
|
|
527
|
+
return {
|
|
528
|
+
input: raw,
|
|
529
|
+
normalized,
|
|
530
|
+
queryShape,
|
|
531
|
+
locale,
|
|
532
|
+
kind,
|
|
533
|
+
phraseProposals,
|
|
534
|
+
tree,
|
|
535
|
+
timing,
|
|
536
|
+
path: "full",
|
|
537
|
+
}
|
|
538
|
+
}
|
|
539
|
+
|
|
540
|
+
/**
|
|
541
|
+
* Throws the signal's reason if aborted. Coarse-grained cancellation: we check between stages, so the longest
|
|
542
|
+
* cancellation latency is one stage's runtime. Fine-grained mid-stage cancellation requires plumbing `signal` into each
|
|
543
|
+
* stage's contract (`detectLocale`, `classifyKind`, `classifier.parse`, `resolver.resolveTree`) — a future enhancement
|
|
544
|
+
* once stage authors are ready for it. For now, in-flight stages always run to completion before the abort takes
|
|
545
|
+
* effect.
|
|
546
|
+
*/
|
|
547
|
+
function throwIfAborted(opts?: PipelineOpts): void {
|
|
548
|
+
if (opts?.signal?.aborted) {
|
|
549
|
+
throw opts.signal.reason ?? new DOMException("Pipeline aborted", "AbortError")
|
|
550
|
+
}
|
|
551
|
+
}
|
|
552
|
+
|
|
553
|
+
/** Defensive wrapper: if the classifier throws, return an empty tree rather than abort the pipeline. */
|
|
554
|
+
async function safeClassify(
|
|
555
|
+
classifier: AddressClassifier,
|
|
556
|
+
text: string,
|
|
557
|
+
queryShape: QueryShapeLite,
|
|
558
|
+
fst?: FSTMatcherLike,
|
|
559
|
+
normalizeCase?: boolean
|
|
560
|
+
): Promise<AddressTree> {
|
|
561
|
+
try {
|
|
562
|
+
// Postcode regex repair on by default (v0.7 #35, operator-signed). #690 normalizeCase forwards as-is —
|
|
563
|
+
// default-ON at the classifier since #895 (unset runs it; explicit false pins the raw-case parse).
|
|
564
|
+
// Word-consistency heal on by default (2026-07-15): arbitrates intra-word tag disagreement only, with the
|
|
565
|
+
// punctuation-separator + byte-fallback gates — clean win across golden us/fr/adversarial + parity floors.
|
|
566
|
+
// Semantics in neural/word-consistency.ts.
|
|
567
|
+
return await classifier.parse(text, {
|
|
568
|
+
queryShape,
|
|
569
|
+
fst,
|
|
570
|
+
postcodeRepair: true,
|
|
571
|
+
normalizeCase,
|
|
572
|
+
enforceWordConsistency: WORD_CONSISTENCY_SHIP_DEFAULT,
|
|
573
|
+
})
|
|
574
|
+
} catch {
|
|
575
|
+
return { raw: text, roots: [] }
|
|
576
|
+
}
|
|
577
|
+
}
|
|
578
|
+
|
|
579
|
+
/** Defensive wrapper: a grouper failure returns an empty proposal list rather than abort. */
|
|
580
|
+
async function safeGroupPhrases(
|
|
581
|
+
groupPhrases: NonNullable<RuntimePipelineStages["groupPhrases"]>,
|
|
582
|
+
normalized: NormalizedInputLite,
|
|
583
|
+
shape: QueryShapeLite,
|
|
584
|
+
locale: LocaleHint
|
|
585
|
+
): Promise<PhraseProposal[]> {
|
|
586
|
+
try {
|
|
587
|
+
return await groupPhrases(normalized, shape, locale)
|
|
588
|
+
} catch {
|
|
589
|
+
return []
|
|
590
|
+
}
|
|
591
|
+
}
|
|
592
|
+
|
|
593
|
+
// ---------------------------------------------------------------------------
|
|
594
|
+
// Grouper-audit pass
|
|
595
|
+
// ---------------------------------------------------------------------------
|
|
596
|
+
|
|
597
|
+
const GROUPER_TYPING_PENALTY = 0.55
|
|
598
|
+
|
|
599
|
+
const PHRASE_KIND_TO_TAG: ReadonlyMap<string, ComponentTag> = new Map([
|
|
600
|
+
["VENUE_PHRASE", "venue"],
|
|
601
|
+
["LOCALITY_PHRASE", "locality"],
|
|
602
|
+
["REGION_ABBREVIATION", "region"],
|
|
603
|
+
["POSTCODE", "postcode"],
|
|
604
|
+
["STREET_PHRASE", "street"],
|
|
605
|
+
["NUMERIC", "house_number"],
|
|
606
|
+
])
|
|
607
|
+
|
|
608
|
+
/**
|
|
609
|
+
* Post-classification audit: for each phrase-grouper proposal whose span is entirely unlabeled (all-O) in the
|
|
610
|
+
* classifier output, inject a provisional node using the grouper's structural hypothesis. This rescues spans the neural
|
|
611
|
+
* model couldn't type — primarily venue text.
|
|
612
|
+
*
|
|
613
|
+
* When `classifierTopK` is supplied (the joint-reconcile path), the audit defers to the classifier's own verdict for
|
|
614
|
+
* the orphaned span: if the classifier confidently typed it as a DIFFERENT component than the phrase kind, we inject
|
|
615
|
+
* the classifier's tag rather than the structural guess. Without this, a reconciler that leaves a street-prefix word
|
|
616
|
+
* like `Via` orphaned (because it picked the single `Trento` street span) would see the audit promote `Via`'s
|
|
617
|
+
* LOCALITY_PHRASE to a spurious `locality` node — burying the real trailing city. The classifier said `street:0.73` for
|
|
618
|
+
* `Via`; trust it (#425).
|
|
619
|
+
*/
|
|
620
|
+
export function grouperAudit(
|
|
621
|
+
tree: AddressTree,
|
|
622
|
+
proposals: PhraseProposal[],
|
|
623
|
+
text: string,
|
|
624
|
+
classifierTopK?: ClassifierCandidate[]
|
|
625
|
+
): AddressTree {
|
|
626
|
+
if (proposals.length === 0) return tree
|
|
627
|
+
|
|
628
|
+
const roots = [...tree.roots]
|
|
629
|
+
|
|
630
|
+
const allNodes: Array<{ start: number; end: number }> = []
|
|
631
|
+
const collectNodes = (nodes: typeof roots): void => {
|
|
632
|
+
for (const n of nodes) {
|
|
633
|
+
allNodes.push({ start: n.start, end: n.end })
|
|
634
|
+
|
|
635
|
+
if (n.children) {
|
|
636
|
+
collectNodes(n.children as typeof roots)
|
|
637
|
+
}
|
|
638
|
+
}
|
|
639
|
+
}
|
|
640
|
+
collectNodes(roots)
|
|
641
|
+
|
|
642
|
+
// Index the classifier's single best tag per exact span (start:end) so the audit can defer to it.
|
|
643
|
+
const CLASSIFIER_OVERRIDE_MIN = 0.4
|
|
644
|
+
const bestTagBySpan = new Map<string, { tag: ComponentTag; score: number }>()
|
|
645
|
+
|
|
646
|
+
for (const c of classifierTopK ?? []) {
|
|
647
|
+
const k = `${c.span.start}:${c.span.end}`
|
|
648
|
+
const cur = bestTagBySpan.get(k)
|
|
649
|
+
|
|
650
|
+
if (!cur || c.score > cur.score) {
|
|
651
|
+
bestTagBySpan.set(k, { tag: c.tag, score: c.score })
|
|
652
|
+
}
|
|
653
|
+
}
|
|
654
|
+
|
|
655
|
+
// Tags that may appear AT MOST ONCE per address. On the joint path, the reconciler has already
|
|
656
|
+
// placed the confident locality/region/postcode; a SECOND one injected here is almost always a
|
|
657
|
+
// street-name word the OOD model mistyped ("Via Francesca Nord" → `Francesca`) or an area-line
|
|
658
|
+
// prefix ("LUGAR …" / "URBANIZACION …"). Suppressing the duplicate keeps the real trailing city
|
|
659
|
+
// from being shadowed by an earlier-positioned spurious node in `decodeAsJSON` (#425 residual tail).
|
|
660
|
+
const SINGLETON_TAGS: ReadonlySet<ComponentTag> = new Set<ComponentTag>(["locality", "region", "postcode", "country"])
|
|
661
|
+
const presentSingletons = new Set<ComponentTag>()
|
|
662
|
+
const collectSingletons = (nodes: typeof roots): void => {
|
|
663
|
+
for (const n of nodes) {
|
|
664
|
+
if (SINGLETON_TAGS.has(n.tag)) {
|
|
665
|
+
presentSingletons.add(n.tag)
|
|
666
|
+
}
|
|
667
|
+
|
|
668
|
+
if (n.children) {
|
|
669
|
+
collectSingletons(n.children as typeof roots)
|
|
670
|
+
}
|
|
671
|
+
}
|
|
672
|
+
}
|
|
673
|
+
collectSingletons(roots)
|
|
674
|
+
const dedupeSingletons = classifierTopK !== undefined
|
|
675
|
+
|
|
676
|
+
// joint path only — argmax stays byte-stable
|
|
677
|
+
|
|
678
|
+
for (const proposal of proposals) {
|
|
679
|
+
const phraseTag = PHRASE_KIND_TO_TAG.get(proposal.kindHypothesis)
|
|
680
|
+
|
|
681
|
+
if (!phraseTag) continue
|
|
682
|
+
|
|
683
|
+
const pStart = proposal.span.start
|
|
684
|
+
const pEnd = pStart + proposal.span.body.length
|
|
685
|
+
|
|
686
|
+
const covered = allNodes.some((node) => node.start < pEnd && pStart < node.end)
|
|
687
|
+
|
|
688
|
+
if (covered) continue
|
|
689
|
+
|
|
690
|
+
// Defer to the classifier when it confidently typed this exact span as something else.
|
|
691
|
+
const classifierVerdict = bestTagBySpan.get(`${proposal.span.start}:${proposal.span.end}`)
|
|
692
|
+
const tag =
|
|
693
|
+
classifierVerdict && classifierVerdict.score >= CLASSIFIER_OVERRIDE_MIN ? classifierVerdict.tag : phraseTag
|
|
694
|
+
|
|
695
|
+
// Don't inject a second singleton-tag node when the reconciler already produced one.
|
|
696
|
+
if (dedupeSingletons && SINGLETON_TAGS.has(tag) && presentSingletons.has(tag)) continue
|
|
697
|
+
|
|
698
|
+
const provisionalNode: AddressNode = {
|
|
699
|
+
tag,
|
|
700
|
+
value: text.slice(pStart, pEnd),
|
|
701
|
+
start: pStart,
|
|
702
|
+
end: pEnd,
|
|
703
|
+
confidence: proposal.confidence * GROUPER_TYPING_PENALTY,
|
|
704
|
+
children: [],
|
|
705
|
+
source: "grouper-audit",
|
|
706
|
+
sourceID: `grouper:${proposal.kindHypothesis}`,
|
|
707
|
+
}
|
|
708
|
+
|
|
709
|
+
roots.push(provisionalNode)
|
|
710
|
+
|
|
711
|
+
if (SINGLETON_TAGS.has(tag)) {
|
|
712
|
+
presentSingletons.add(tag)
|
|
713
|
+
}
|
|
714
|
+
}
|
|
715
|
+
|
|
716
|
+
roots.sort((a, b) => a.start - b.start)
|
|
717
|
+
|
|
718
|
+
return { raw: tree.raw, roots }
|
|
719
|
+
}
|
|
720
|
+
|
|
721
|
+
/** Defensive wrapper: a resolver failure leaves the classifier tree intact. */
|
|
722
|
+
async function safeResolve(
|
|
723
|
+
resolver: NonNullable<RuntimePipelineStages["resolver"]>,
|
|
724
|
+
tree: AddressTree,
|
|
725
|
+
opts?: PipelineOpts
|
|
726
|
+
): Promise<AddressTree> {
|
|
727
|
+
try {
|
|
728
|
+
return await resolver.resolveTree(tree, opts?.resolveOpts)
|
|
729
|
+
} catch {
|
|
730
|
+
return tree
|
|
731
|
+
}
|
|
732
|
+
}
|