@mailwoman/core 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.
Files changed (129) hide show
  1. package/api/APIClient.ts +175 -0
  2. package/api/headless.ts +23 -0
  3. package/api/index.ts +11 -0
  4. package/api/responses.ts +135 -0
  5. package/coarse-placer/coarse-placer.ts +300 -0
  6. package/coarse-placer/featurize.ts +171 -0
  7. package/coarse-placer/tools/build-dataset.ts +223 -0
  8. package/coarse-placer/tools/build-outlier-exposure.ts +172 -0
  9. package/coarse-placer/tools/build-outlier-latin.ts +200 -0
  10. package/coarse-placer/tools/build-outlier-oa.ts +231 -0
  11. package/coarse-placer/tools/eval-latin-offmap.ts +140 -0
  12. package/coarse-placer/tools/eval-openset.ts +519 -0
  13. package/coarse-placer/tools/eval-quant-compare.ts +151 -0
  14. package/coarse-placer/tools/eval.ts +187 -0
  15. package/coarse-placer/tools/fnv-hash.ts +24 -0
  16. package/coarse-placer/tools/index.ts +23 -0
  17. package/coarse-placer/tools/probe-frontier.ts +216 -0
  18. package/coarse-placer/tools/quantize.ts +116 -0
  19. package/coarse-placer/tools/train.ts +244 -0
  20. package/collections.ts +134 -0
  21. package/db/schema.ts +21 -0
  22. package/decoder/build-tree.ts +228 -0
  23. package/decoder/calibration.ts +101 -0
  24. package/decoder/containment.ts +87 -0
  25. package/decoder/index.ts +17 -0
  26. package/decoder/proposals-to-tree.ts +83 -0
  27. package/decoder/resolve-proposal-overlaps.ts +79 -0
  28. package/decoder/serialize-json.ts +70 -0
  29. package/decoder/serialize-tuples.ts +61 -0
  30. package/decoder/serialize-xml.ts +209 -0
  31. package/decoder/types.ts +159 -0
  32. package/decoder/unknown-spans.ts +103 -0
  33. package/decoder/validate-tree.ts +100 -0
  34. package/env/index.ts +42 -0
  35. package/env/load.ts +14 -0
  36. package/env/paths.ts +40 -0
  37. package/env/schema.ts +125 -0
  38. package/errors/index.ts +9 -0
  39. package/errors/schema.ts +155 -0
  40. package/fs/node.ts +38 -0
  41. package/identifiers.ts +58 -0
  42. package/index.ts +13 -0
  43. package/kysley/adapter.ts +29 -0
  44. package/kysley/client.ts +30 -0
  45. package/kysley/dialect-config.ts +30 -0
  46. package/kysley/dialect.ts +67 -0
  47. package/kysley/driver.ts +175 -0
  48. package/layers/index.ts +12 -0
  49. package/layers/manifest.ts +154 -0
  50. package/layers/schema.ts +105 -0
  51. package/lifecycle/ServiceSymbol.ts +95 -0
  52. package/lifecycle/index.ts +11 -0
  53. package/lifecycle/lru-cache.ts +44 -0
  54. package/lifecycle/services.ts +322 -0
  55. package/locale/index.ts +9 -0
  56. package/locale/locale.ts +49 -0
  57. package/locale/profiles/en-us.ts +69 -0
  58. package/locale/profiles/fr-fr.ts +75 -0
  59. package/locale/profiles/index.ts +9 -0
  60. package/locale/profiles/ja-jp.ts +33 -0
  61. package/locale/registry.ts +68 -0
  62. package/logging/index.ts +8 -0
  63. package/logging/shared.ts +145 -0
  64. package/logging/utils.ts +46 -0
  65. package/objects.ts +211 -0
  66. package/package.json +195 -104
  67. package/pipeline/index.ts +46 -0
  68. package/pipeline/reconcile-lookups.ts +108 -0
  69. package/pipeline/reconcile.ts +542 -0
  70. package/pipeline/runtime-pipeline.ts +732 -0
  71. package/pipeline/span-logit-aggregation.ts +151 -0
  72. package/pipeline/span-proposer.ts +587 -0
  73. package/pipeline/types.ts +348 -0
  74. package/policy/defaults.ts +35 -0
  75. package/policy/index.ts +10 -0
  76. package/policy/policy.ts +60 -0
  77. package/policy/proposal-collection.ts +64 -0
  78. package/policy/registry.ts +149 -0
  79. package/resolver/index.ts +29 -0
  80. package/resolver/types.ts +584 -0
  81. package/resources/LocaleIndex.ts +124 -0
  82. package/resources/ResourceMapCache.ts +126 -0
  83. package/resources/collections.ts +93 -0
  84. package/resources/debugging.ts +19 -0
  85. package/resources/git.ts +54 -0
  86. package/resources/index.ts +17 -0
  87. package/resources/languages/index.ts +49 -0
  88. package/resources/languages/types.gen.ts +1368 -0
  89. package/resources/libaddressinput.ts +105 -0
  90. package/resources/libpostal.ts +182 -0
  91. package/resources/locale.ts +23 -0
  92. package/resources/set.ts +179 -0
  93. package/resources/whosonfirst/DataSourceCache.ts +72 -0
  94. package/resources/whosonfirst/PlacetypeDataSource.ts +199 -0
  95. package/resources/whosonfirst/index.ts +10 -0
  96. package/resources/whosonfirst/loader.ts +157 -0
  97. package/resources/whosonfirst/placetypes/Placetype.ts +438 -0
  98. package/resources/whosonfirst/placetypes/admin.ts +173 -0
  99. package/resources/whosonfirst/placetypes/definition.ts +135 -0
  100. package/resources/whosonfirst/placetypes/graph.ts +0 -0
  101. package/resources/whosonfirst/placetypes/index.ts +12 -0
  102. package/resources/whosonfirst/placetypes/mermaid.ts +168 -0
  103. package/resources/whosonfirst/placetypes/tree.ts +46 -0
  104. package/routing/index.ts +208 -0
  105. package/scripting/index.ts +40 -0
  106. package/scripting/utils/index.ts +106 -0
  107. package/tokenization/Graph.ts +50 -0
  108. package/tokenization/Span.ts +297 -0
  109. package/tokenization/index.ts +9 -0
  110. package/tokenization/normalizer.ts +123 -0
  111. package/tools/download-libpostal-resources.ts +98 -0
  112. package/tools/download-ssl-address.ts +99 -0
  113. package/tools/generate-language-types.ts +194 -0
  114. package/tools/index.ts +13 -0
  115. package/types/Classification.ts +211 -0
  116. package/types/classifier.ts +133 -0
  117. package/types/component.ts +75 -0
  118. package/types/index.ts +10 -0
  119. package/types/mapping.ts +81 -0
  120. package/utils/data-root.ts +56 -0
  121. package/utils/hash.ts +27 -0
  122. package/utils/index.ts +14 -0
  123. package/utils/jsonl.ts +43 -0
  124. package/utils/python-json.ts +105 -0
  125. package/utils/python-random.ts +90 -0
  126. package/utils/repo.ts +118 -0
  127. package/utils/sealed-db.ts +85 -0
  128. package/utils/stats.ts +32 -0
  129. package/vitest.config.ts +53 -0
@@ -0,0 +1,348 @@
1
+ /**
2
+ * @copyright Sister Software
3
+ * @license AGPL-3.0
4
+ * @author Teffen Ellis, et al.
5
+ *
6
+ * Types for the runtime pipeline coordinator (`runPipeline`).
7
+ *
8
+ * Generic over its stage implementations — each stage is an injected function or class, defined
9
+ * structurally. Keeps `@mailwoman/core` free of dependencies on the concrete neural / normalize /
10
+ * query-shape / resolver packages while still composing them at runtime when callers wire them
11
+ * up.
12
+ *
13
+ * See `docs/articles/plan/reference/STAGES.md` for the full contract this implements.
14
+ */
15
+
16
+ import type { AddressTree } from "../decoder/types.ts"
17
+ import type { ResolveOpts, Resolver, ResolverBackend } from "../resolver/types.ts"
18
+ import type { Section } from "../types/classifier.ts"
19
+
20
+ export type LocaleTag = string
21
+
22
+ /** Optional user-location signal for Stage 6 resolver scoring. */
23
+ export type UserLocation = { lat: number; lon: number } | { country: string } | { region: string; country: string }
24
+
25
+ /** Common opts threaded through every stage. */
26
+ export interface PipelineOpts {
27
+ locale?: LocaleTag
28
+ userLocation?: UserLocation
29
+ /**
30
+ * Disable fast-path shortcuts; always run the full pipeline. Does NOT bypass the poi_query branch — that's a routing
31
+ * decision (the kind classifier + `stages.poiIntent`), not a fast-path shortcut, so a `poi_query`-classified input
32
+ * still takes the poi branch regardless of this flag.
33
+ */
34
+ forceFullPipeline?: boolean
35
+ /**
36
+ * The joint-reconcile path (Stage 5 beam search). Promoted to default by Route A Phase II (#427), then RETIRED AS
37
+ * DEFAULT 2026-06-14: a reconcile-vs-raw-neural audit found it breaks the street+house_number geocode precondition on
38
+ * 77-84% of clean US addresses (golden v0.1.2 US+FR, n=4507: street -25.6pp, house_number -23.1pp; worse-or-flat on
39
+ * every tag, venue included). The phrase grouper bundles the house number into the STREET_PHRASE and reconcileSpans
40
+ * fuses the span. The #427 "DE +25pp" gains were loose street-string recall on OOD inputs, not the geocode
41
+ * precondition. Default (unset) is now `false` (argmax). It still requires a phrase grouper + a classifier exposing
42
+ * `parseWithLogits`; when either is absent the pipeline uses argmax regardless.
43
+ *
44
+ * Set `jointReconcile: true` to opt back into reconcile (the A/B harnesses do). Report:
45
+ * docs/articles/evals/experiments/2026-06-14-reconcile-retirement.md.
46
+ */
47
+ jointReconcile?: boolean
48
+ /** @deprecated Use {@link jointReconcile}. Retained as an explicit override for the A/B harnesses. */
49
+ forceJointReconcile?: boolean
50
+ /** Hard cap on lookups the resolver may issue; passed through. */
51
+ resolveOpts?: ResolveOpts
52
+ /**
53
+ * #690: title-case detected all-caps ASCII input before the Stage 3 classifier (helps on all-caps registry/compliance
54
+ * data). Threaded to `ClassifierOpts.normalizeCase`. Detection-gated
55
+ *
56
+ * - **Default-ON** (#895 settled drift D2; the classifier applies it when unset) — byte-stable for mixed-case input
57
+ * either way. Pass `false` to restore the raw-case parse.
58
+ */
59
+ normalizeCase?: boolean
60
+ /**
61
+ * #743/#194: promote a CONFIDENT coarse-placer guess from the soft `anchorPosterior` boost to a HARD country filter
62
+ * (empty→unresolved) — see {@link ResolveOpts.hardCountry}. Gated three ways: the placer's confidence ≥
63
+ * `HARD_PLACE_COUNTRY_MIN_CONF` (ambiguous DK↔NO stay soft), the country is in the coverage
64
+ * `HARD_PLACE_COUNTRY_SAFELIST` (or a {@link hardCountrySafelist} override), and no caller
65
+ * `hardCountry`/`defaultCountry` is already set. **Default-ON** in the shipped
66
+ * `createRuntimePipeline`/`geocodeAddress` (#743, 2026-06-22) — but the safelist confines the hard filter to
67
+ * well-covered countries, so the low-coverage tail (FI/PL) keeps its recall on the soft path with no regression. Pass
68
+ * `false` to force the pre-#194 soft-only behavior.
69
+ */
70
+ hardPlaceCountry?: boolean
71
+ /**
72
+ * #743/#194: override the coverage safelist that gates {@link hardPlaceCountry}. Undefined → the built-in
73
+ * `HARD_PLACE_COUNTRY_SAFELIST` (production). Supply a set to test/measure a different coverage frontier — the
74
+ * resolver eval passes the full in-map country set to measure ungated hard-resolve-rates (which is how the production
75
+ * safelist is grown).
76
+ */
77
+ hardCountrySafelist?: ReadonlySet<string>
78
+ signal?: AbortSignal
79
+ }
80
+
81
+ /** Minimal structural shape `NormalizedInput` must satisfy. Compatible with @mailwoman/normalize. */
82
+ export interface NormalizedInputLite {
83
+ raw: string
84
+ normalized: string
85
+ appliedLocale?: string
86
+ }
87
+
88
+ /** Minimal structural shape `QueryShape` must satisfy. Compatible with @mailwoman/query-shape. */
89
+ export interface QueryShapeLite {
90
+ knownFormats: ReadonlyArray<{
91
+ format: string
92
+ span: { start: number; end: number }
93
+ confidence: number
94
+ }>
95
+ segments?: ReadonlyArray<{ body: string; index: number }>
96
+ characterClass?: string
97
+ totalLength?: number
98
+ }
99
+
100
+ /** Detected (or asserted) locale + alternatives. */
101
+ export interface LocaleHint {
102
+ locale: LocaleTag
103
+ confidence: number
104
+ alternatives: ReadonlyArray<{ locale: LocaleTag; confidence: number }>
105
+ source: "caller" | "detected" | "ensemble"
106
+ }
107
+
108
+ /** Kind classifier output. */
109
+ export type QueryKind =
110
+ | "postcode_only"
111
+ | "locality_only"
112
+ | "structured_address"
113
+ | "intersection"
114
+ | "po_box"
115
+ | "landmark"
116
+ | "poi_query"
117
+ | "vague"
118
+
119
+ export interface QueryKindResult {
120
+ kind: QueryKind
121
+ confidence: number
122
+ alternatives: ReadonlyArray<{ kind: QueryKind; confidence: number }>
123
+ }
124
+
125
+ /**
126
+ * The structured POI intent — the pluggable boundary between detection (kind classifier), the executors (Plan 3's
127
+ * poi.db SQL compiler), and the export formats (OverpassQL emitter). Category ids are `@mailwoman/poi-taxonomy` ids
128
+ * carried as plain strings — core stays lexicon-free; the branded type lives with the data package. Spec §3.2:
129
+ * docs/superpowers/specs/2026-07-18-spatial-layers-and-poi-design.md
130
+ */
131
+ export interface POIIntent {
132
+ subject:
133
+ | { kind: "category"; categoryID: string; matched: string }
134
+ | { kind: "brand"; name: string; wikidata?: string; matched: string }
135
+ | { kind: "name"; text: string }
136
+ /** Spatial anchor: the split-off remainder text and its parse, when the query carried one. */
137
+ anchor?: {
138
+ text?: string
139
+ tree?: AddressTree
140
+ /** Caller-supplied bias point ("near me"); executors treat it as the anchor when no tree resolved. */
141
+ biasPoint?: { latitude: number; longitude: number }
142
+ radiusM?: number
143
+ }
144
+ limit?: number
145
+ }
146
+
147
+ /** One executed POI search result (spec §3.4; produced by the executor, absent pre-execution). */
148
+ export interface POIResult {
149
+ name: string | null
150
+ categoryID: string | null
151
+ brandWikidata: string | null
152
+ latitude: number
153
+ longitude: number
154
+ country: string
155
+ confidence: number
156
+ distanceM?: number
157
+ }
158
+
159
+ /**
160
+ * Outcome of the poi-intent stage. `abstain` = the query is POI-shaped but unanswerable as asked (e.g. no executor
161
+ * wired for a build-local-only category) — surfaces map it to their native empty-result envelope instead of a mangled
162
+ * parse.
163
+ */
164
+ export type POIIntentOutcome =
165
+ | { type: "intent"; intent: POIIntent; results?: POIResult[] }
166
+ | { type: "abstain"; reason: string }
167
+
168
+ /**
169
+ * Stage 2.7 phrase grouper output. Coarse phrase-shape hypothesis attached to a `Section` (sub-Span of the tokenized
170
+ * input). The classifier (Stage 3) conditions on these proposals so it can answer the simpler "what type is this
171
+ * proposed span?" instead of jointly discovering boundaries and types. The reconciler (Stage 5) consumes them as
172
+ * boundary candidates for joint decoding.
173
+ *
174
+ * Taxonomy is purely structural — no place-name knowledge. A `LOCALITY_PHRASE` proposal is "this looks shaped like a
175
+ * multi-word capitalized phrase that could be a city name" — not "this IS New York." Typing the span is the
176
+ * classifier's job.
177
+ *
178
+ * See `docs/articles/concepts/the-knowledge-ladder.md` § Phrase grouper for the design rationale.
179
+ */
180
+ export type PhraseKind =
181
+ | "NUMERIC"
182
+ | "STREET_PHRASE"
183
+ | "LOCALITY_PHRASE"
184
+ | "REGION_ABBREVIATION"
185
+ | "POSTCODE"
186
+ | "VENUE_PHRASE"
187
+ | "HYPHENATED_COMPOUND"
188
+
189
+ /**
190
+ * One phrase proposal emitted by Stage 2.7. The contract:
191
+ *
192
+ * - `span`: the input slice (sub-Span of the tokenized input) the proposal applies to.
193
+ * - `kindHypothesis`: structural shape this slice looks like.
194
+ * - `confidence`: 0..1 score. Used by downstream stages to weight proposals.
195
+ *
196
+ * Per "possibilities not constraints", emit a proposal whenever a rule fires — overlapping proposals over the same
197
+ * tokens are expected (e.g. `Saint Petersburg` may surface as one `LOCALITY_PHRASE` AND two `LOCALITY_PHRASE`s, with
198
+ * confidence ordering signalling which the grouper prefers).
199
+ */
200
+ export interface PhraseProposal {
201
+ span: Section
202
+ kindHypothesis: PhraseKind
203
+ confidence: number
204
+ }
205
+
206
+ /**
207
+ * Stage 2.7 contract. Structural — any of the rule-based grouper (`@mailwoman/phrase-grouper`), a learned span proposer
208
+ * (future), or a fake for tests satisfies this. Async so the coordinator can stay uniform even when implementations
209
+ * call into models.
210
+ */
211
+ export interface PhraseGrouper {
212
+ group(input: NormalizedInputLite, shape: QueryShapeLite, locale: LocaleHint): Promise<PhraseProposal[]>
213
+ }
214
+
215
+ /**
216
+ * Stage 3 contract: classifier that turns a text into an `AddressTree`. Structural — any of `@mailwoman/neural`'s
217
+ * `NeuralAddressClassifier`, a rule-based classifier, or a fake for tests satisfies this.
218
+ */
219
+ /**
220
+ * Structural type for the FST gazetteer matcher, compatible with
221
+ *
222
+ * @mailwoman/core/resolver-wof-sqlite's FSTMatcher.
223
+ */
224
+ export interface FSTMatcherLike {
225
+ walk(tokens: string[]): { stateID: number; accepted: boolean; depth: number } | null
226
+ walkFrom(
227
+ prev: { stateID: number; depth: number },
228
+ token: string
229
+ ): { stateID: number; accepted: boolean; depth: number } | null
230
+ accepting(stateID: number): Array<{ wofID: number; placetype: string; importance: number }>
231
+ }
232
+
233
+ export interface ClassifierOpts {
234
+ queryShape?: QueryShapeLite
235
+ fst?: FSTMatcherLike
236
+ fstBiasScale?: number
237
+ /** Run the deterministic postcode regex repair pass (v0.7 #35) on the decoded labels. */
238
+ postcodeRepair?: boolean
239
+ /**
240
+ * #690: title-case a detected all-caps ASCII input before the model (all-caps registry/compliance data is partly
241
+ * OOD). Detection-gated — mixed-case + non-ASCII input is untouched. **Default-ON** (#895 settled drift D2); `false`
242
+ * restores the raw-case parse.
243
+ */
244
+ normalizeCase?: boolean
245
+ /**
246
+ * Per-word BIO consistency repair (#727): force each SentencePiece word whose pieces DISAGREE in type to one tag via
247
+ * a confidence-weighted vote. Structural mirror of `@mailwoman/neural`'s `WordConsistencyOpts` (core carries no
248
+ * neural dependency) — see `neural/word-consistency.ts` for the semantics of each gate.
249
+ */
250
+ enforceWordConsistency?:
251
+ | boolean
252
+ | { minMeanConfidence?: number; skipByteFallbackWords?: boolean; splitOnPunctuation?: boolean }
253
+ }
254
+
255
+ /**
256
+ * The word-consistency setting production parses ship with (2026-07-15): heal intra-word tag disagreement, with the
257
+ * punctuation-separator + byte-fallback gates on and no confidence floor — the configuration that cleared golden
258
+ * us/fr/adversarial and the parity floors with zero per-file regressions. One constant so the pipeline's
259
+ * `safeClassify`, `parseForGeocode`, and the eval harness can't drift apart.
260
+ */
261
+ export const WORD_CONSISTENCY_SHIP_DEFAULT = {
262
+ skipByteFallbackWords: true,
263
+ splitOnPunctuation: true,
264
+ } as const satisfies ClassifierOpts["enforceWordConsistency"]
265
+
266
+ export interface AddressClassifier {
267
+ parse(text: string, opts?: ClassifierOpts): Promise<AddressTree>
268
+ }
269
+
270
+ /**
271
+ * Injectable stage implementations. All optional — when a stage is absent, the coordinator either skips it (resolver)
272
+ * or substitutes a no-op stub (normalize / queryShape / locale gate / kind classifier). The classifier is required for
273
+ * the full pipeline path; without it, the coordinator can only fast-path on QueryShape known-formats.
274
+ */
275
+ export interface RuntimePipelineStages {
276
+ normalize?: (raw: string, opts?: { locale?: string }) => NormalizedInputLite
277
+ computeQueryShape?: (input: NormalizedInputLite | string, opts?: { locale?: string }) => QueryShapeLite
278
+ detectLocale?: (input: NormalizedInputLite, shape: QueryShapeLite, opts?: { hint?: LocaleTag }) => Promise<LocaleHint>
279
+ classifyKind?: (input: NormalizedInputLite, shape: QueryShapeLite, locale: LocaleHint) => Promise<QueryKindResult>
280
+ /**
281
+ * Coarse country router (#244). A `(normalizedText) → { country, confidence, posterior? }` predictor (a
282
+ * `CoarsePlacer`-backed fn); `country: null` ⇒ abstained, `"OTHER"` ⇒ off-map. When provided, a confident IN-MAP
283
+ * guess becomes a SOFT country prior fed into the resolver's #369 `anchorPosterior` re-rank (boosts the right-country
284
+ * candidate, never filters); it defers to a caller-supplied posterior (a stronger postcode anchor) and is a no-op on
285
+ * abstain/OTHER. Off by default → byte-stable.
286
+ *
287
+ * `posterior` (residual upgrade) is the full per-in-map-country distribution: when present it IS the
288
+ * `anchorPosterior` (so the resolver breaks country-ambiguous ties with its own place-level evidence); when absent
289
+ * the coordinator falls back to the one-hot `{ [country]: confidence }`. See
290
+ * docs/articles/plan/2026-06-14-coarse-placer-soft-signal-spec.md.
291
+ */
292
+ placeCountry?: (normalizedText: string) => {
293
+ country: string | null
294
+ confidence: number
295
+ posterior?: Record<string, number>
296
+ }
297
+ /**
298
+ * POI intent stage (spec §3.1). Runs ONLY when the kind classifier emitted `poi_query`. Returns the extracted intent,
299
+ * an abstain, or `null` to fall through to the full pipeline (the mis-detection safety valve — a `poi_query` kind
300
+ * with no extractable subject parses normally). Absent by default; wired by `createRuntimePipeline({ poiQueryKind:
301
+ * true })`.
302
+ */
303
+ poiIntent?: (input: NormalizedInputLite, locale: LocaleHint, opts?: PipelineOpts) => Promise<POIIntentOutcome | null>
304
+ /**
305
+ * Stage 2.7 phrase grouper. Emits coherent input-unit proposals consumed by Stage 3 (as conditioning) and Stage 5 (as
306
+ * boundary candidates). Hard dep in v0.5.0; pre-v0.5.0 callers run with no grouper and the result `phraseProposals`
307
+ * field is empty.
308
+ */
309
+ groupPhrases?: (input: NormalizedInputLite, shape: QueryShapeLite, locale: LocaleHint) => Promise<PhraseProposal[]>
310
+ classifier?: AddressClassifier
311
+ /**
312
+ * Pre-built FST gazetteer matcher. When provided, gazetteer matches produce additive emission biases during
313
+ * classification.
314
+ */
315
+ fst?: FSTMatcherLike
316
+ resolver?: Resolver
317
+ /**
318
+ * The gazetteer BACKEND (lower-level than `resolver`), enabling the reconciler's concordance axes (#478): a bounded
319
+ * pre-fetch turns it into the resolver-candidate + parent-chain lookups `reconcileSpans` scores with. Optional —
320
+ * absent, reconcile runs classifier-only (today's behavior, byte-stable).
321
+ */
322
+ resolverBackend?: ResolverBackend
323
+ }
324
+
325
+ export interface PipelineTiming {
326
+ [stage: string]: number // ms
327
+ }
328
+
329
+ /** Result of one `runPipeline` call. */
330
+ export interface PipelineResult {
331
+ input: string
332
+ normalized: NormalizedInputLite
333
+ queryShape: QueryShapeLite
334
+ locale: LocaleHint
335
+ kind: QueryKindResult
336
+ /**
337
+ * Stage 2.7 phrase proposals when a grouper was wired. Empty array when the coordinator ran with no grouper
338
+ * (pre-v0.5.0 callers) or when the fast-path skipped Stage 2.7. Stage 3 consumes this as conditioning; Stage 5
339
+ * consumes it as boundary candidates.
340
+ */
341
+ phraseProposals: PhraseProposal[]
342
+ tree: AddressTree
343
+ /** Present only when the poi-intent stage produced an outcome (path === "poi"). */
344
+ poiIntent?: POIIntentOutcome
345
+ timing: PipelineTiming
346
+ /** Which path the coordinator took. `"fast-path"` skipped stages 3-5; `"poi"` took the intent branch. */
347
+ path: "fast-path" | "full" | "poi"
348
+ }
@@ -0,0 +1,35 @@
1
+ /**
2
+ * @copyright Sister Software
3
+ * @license AGPL-3.0
4
+ * @author Teffen Ellis, et al.
5
+ *
6
+ * Default policy table: every component is `rule_only` until per-tag golden-set metrics justify a
7
+ * migration. This file is the canonical place to record such migrations; each Phase 2+ rollout
8
+ * edits one entry here with a commit-message rationale.
9
+ */
10
+
11
+ import { COMPONENT_TAGS, type ComponentTag } from "@mailwoman/core/types"
12
+
13
+ import type { ClassifierPolicy, PolicyMode } from "./policy.ts"
14
+
15
+ /**
16
+ * Build a fresh array of policies — one per `ComponentTag`, all in `mode`. Returns a new array on each call; callers
17
+ * may mutate it freely.
18
+ *
19
+ * `mode` defaults to `rule_only` (the historical default — every component rule-sourced until a per-tag migration). The
20
+ * input-shape router (#478 increment 2) passes a shape-derived default (e.g. `neural_preferred` for OOD-script input)
21
+ * so the whole table starts from the routed prior before per-tag config overlays.
22
+ */
23
+ export function buildDefaultPolicies(mode: PolicyMode = "rule_only"): ClassifierPolicy[] {
24
+ return COMPONENT_TAGS.map<ClassifierPolicy>((component) => ({
25
+ component,
26
+ mode,
27
+ }))
28
+ }
29
+
30
+ /**
31
+ * Convenience accessor for a single-component default. `mode` defaults to `rule_only`.
32
+ */
33
+ export function defaultPolicyFor(component: ComponentTag, mode: PolicyMode = "rule_only"): ClassifierPolicy {
34
+ return { component, mode }
35
+ }
@@ -0,0 +1,10 @@
1
+ /**
2
+ * @copyright Sister Software
3
+ * @license AGPL-3.0
4
+ * @author Teffen Ellis, et al.
5
+ */
6
+
7
+ export * from "./defaults.ts"
8
+ export * from "./policy.ts"
9
+ export * from "./proposal-collection.ts"
10
+ export * from "./registry.ts"
@@ -0,0 +1,60 @@
1
+ /**
2
+ * @copyright Sister Software
3
+ * @license AGPL-3.0
4
+ * @author Teffen Ellis, et al.
5
+ *
6
+ * Classifier policy types (per #6). A `ClassifierPolicy` declares which classifier family (rule /
7
+ * neural / both / preferred) has authority for each `ComponentTag`, optionally narrowed by
8
+ * locale. The default table starts every component in `rule_only` mode; migrations to
9
+ * neural-backed modes happen one component at a time, gated on golden-set metrics.
10
+ */
11
+
12
+ import type { ClassificationProposal, ComponentTag } from "@mailwoman/core/types"
13
+
14
+ /**
15
+ * How a component is sourced.
16
+ *
17
+ * - `rule_only`: keep only `source === "rule"` proposals (default).
18
+ * - `neural_only`: keep only `source === "neural"` proposals.
19
+ * - `both`: keep proposals from any source.
20
+ * - `neural_preferred`: keep all proposals, but drop rule proposals when at least one neural proposal exists for the same
21
+ * component.
22
+ * - `rule_preferred`: mirror of `neural_preferred`, with rule winning.
23
+ */
24
+ export type PolicyMode = "rule_only" | "neural_only" | "both" | "neural_preferred" | "rule_preferred"
25
+
26
+ /**
27
+ * A single policy entry. Locale-less entries are the global default; locale-scoped entries override the global default
28
+ * for that locale.
29
+ */
30
+ export interface ClassifierPolicy {
31
+ component: ComponentTag
32
+ mode: PolicyMode
33
+
34
+ /**
35
+ * Minimum confidence for a proposal to be retained. Applied before the policy-mode filter. Inclusive ([threshold,
36
+ * 1.0]). Undefined means "no threshold."
37
+ */
38
+ confidence_threshold?: number
39
+
40
+ /**
41
+ * Locale scope. If absent, the entry applies to every locale unless overridden by a locale-specific entry.
42
+ */
43
+ locale?: string
44
+ }
45
+
46
+ /**
47
+ * Read-side view of the policy table.
48
+ */
49
+ export interface PolicyRegistry {
50
+ /**
51
+ * Look up the effective policy for a (component, locale) pair. A locale-specific entry wins over a global one; if
52
+ * neither exists, the registry-wide default (`rule_only`, no threshold) is returned.
53
+ */
54
+ lookup(component: ComponentTag, locale?: string): ClassifierPolicy
55
+
56
+ /**
57
+ * Apply policy filtering to a flat list of proposals. Output is a new array; the input is not mutated.
58
+ */
59
+ apply(proposals: readonly ClassificationProposal[], locale?: string): ClassificationProposal[]
60
+ }
@@ -0,0 +1,64 @@
1
+ /**
2
+ * @copyright Sister Software
3
+ * @license AGPL-3.0
4
+ * @author Teffen Ellis, et al.
5
+ *
6
+ * Generic proposal collection + policy filtering.
7
+ *
8
+ * Fan a list of `ProposalClassifier`s out across a list of sections, then optionally filter the
9
+ * merged proposal stream through a `PolicyRegistry`. Both classifier families (neural, and any
10
+ * future rule wrapper) satisfy the same `ProposalClassifier` shape, so this pair is engine-neutral.
11
+ *
12
+ * Rehomed here from the (deleted) `core/parser/proposal-pipeline.ts` during the v7 rules-parser
13
+ * excision — the parser-era `TokenContext` writeback half went with the solver; these two generic
14
+ * helpers survive because the neural `--policy` CLI path still uses them.
15
+ *
16
+ * Pure module: no resource imports, no top-level await. Safe to import from anywhere.
17
+ */
18
+
19
+ import type { Section } from "../types/classifier.ts"
20
+ import { type ClassificationProposal, type ClassifierContext, type ProposalClassifier } from "../types/index.ts"
21
+ import type { PolicyRegistry } from "./policy.ts"
22
+
23
+ /**
24
+ * Run every classifier against every section, concatenate the results.
25
+ *
26
+ * Classifiers that throw are isolated — their failure logs but does not block other classifiers' proposals from being
27
+ * collected. (Per the `ProposalClassifier` contract, implementations are supposed to swallow errors, but
28
+ * defense-in-depth lives here.)
29
+ */
30
+ export async function collectProposals(
31
+ sections: readonly Section[],
32
+ classifiers: readonly ProposalClassifier[],
33
+ context: ClassifierContext = {}
34
+ ): Promise<ClassificationProposal[]> {
35
+ const tasks: Array<Promise<ClassificationProposal[]>> = []
36
+
37
+ for (const classifier of classifiers) {
38
+ for (const section of sections) {
39
+ tasks.push(
40
+ classifier.classify(section, context).catch((err) => {
41
+ console.warn(`[proposal-collection] ${classifier.id} threw on section "${section.body}":`, err)
42
+
43
+ return []
44
+ })
45
+ )
46
+ }
47
+ }
48
+ const results = await Promise.all(tasks)
49
+
50
+ return results.flat()
51
+ }
52
+
53
+ /**
54
+ * Optional policy filter. An explicit `policy` registry is authoritative; without one the input is returned unchanged.
55
+ */
56
+ export function filterByPolicy(
57
+ proposals: readonly ClassificationProposal[],
58
+ policy: PolicyRegistry | undefined,
59
+ locale: string | undefined
60
+ ): ClassificationProposal[] {
61
+ if (!policy) return [...proposals]
62
+
63
+ return policy.apply(proposals, locale)
64
+ }
@@ -0,0 +1,149 @@
1
+ /**
2
+ * @copyright Sister Software
3
+ * @license AGPL-3.0
4
+ * @author Teffen Ellis, et al.
5
+ *
6
+ * In-memory `PolicyRegistry`. Stores per-(component, locale) policy entries and applies them to a
7
+ * flat list of `ClassificationProposal`s.
8
+ *
9
+ * Mutation API (`set`, `remove`) lives here so that locale profiles (#6 §LocaleProfile) can install
10
+ * per-locale overrides at startup. Look-up and `apply` are pure.
11
+ */
12
+
13
+ import type { ClassificationProposal, ComponentTag } from "@mailwoman/core/types"
14
+
15
+ import { buildDefaultPolicies, defaultPolicyFor } from "./defaults.ts"
16
+ import type { ClassifierPolicy, PolicyMode, PolicyRegistry } from "./policy.ts"
17
+
18
+ const GLOBAL_LOCALE_KEY = "*"
19
+
20
+ function policyKey(component: ComponentTag, locale: string | undefined): string {
21
+ return `${component}::${locale ?? GLOBAL_LOCALE_KEY}`
22
+ }
23
+
24
+ /**
25
+ * Concrete registry implementation. Construct empty with `new InMemoryPolicyRegistry()` and load entries via `set()`,
26
+ * or pre-load defaults via `InMemoryPolicyRegistry.withDefaults()`.
27
+ */
28
+ export class InMemoryPolicyRegistry implements PolicyRegistry {
29
+ #entries = new Map<string, ClassifierPolicy>()
30
+
31
+ /**
32
+ * Build a registry pre-loaded with `mode` for every component (default `rule_only`). The input-shape router (#478)
33
+ * passes a shape-derived default so the whole table starts from the routed prior.
34
+ */
35
+ static withDefaults(mode: PolicyMode = "rule_only"): InMemoryPolicyRegistry {
36
+ const registry = new InMemoryPolicyRegistry()
37
+
38
+ for (const policy of buildDefaultPolicies(mode)) {
39
+ registry.set(policy)
40
+ }
41
+
42
+ return registry
43
+ }
44
+
45
+ /** Install a policy entry. Replaces any prior entry with the same key. */
46
+ set(policy: ClassifierPolicy): void {
47
+ this.#entries.set(policyKey(policy.component, policy.locale), policy)
48
+ }
49
+
50
+ /** Remove a policy entry, if present. */
51
+ remove(component: ComponentTag, locale?: string): void {
52
+ this.#entries.delete(policyKey(component, locale))
53
+ }
54
+
55
+ /** All current entries, in insertion order. */
56
+ entries(): ClassifierPolicy[] {
57
+ return Array.from(this.#entries.values())
58
+ }
59
+
60
+ lookup(component: ComponentTag, locale?: string): ClassifierPolicy {
61
+ if (locale) {
62
+ const localized = this.#entries.get(policyKey(component, locale))
63
+
64
+ if (localized) return localized
65
+ }
66
+ const global = this.#entries.get(policyKey(component, undefined))
67
+
68
+ if (global) return global
69
+
70
+ return defaultPolicyFor(component)
71
+ }
72
+
73
+ apply(proposals: readonly ClassificationProposal[], locale?: string): ClassificationProposal[] {
74
+ const passedThreshold: ClassificationProposal[] = []
75
+ const policyByComponent = new Map<ComponentTag, ClassifierPolicy>()
76
+
77
+ for (const proposal of proposals) {
78
+ const policy = policyByComponent.get(proposal.component) ?? this.lookup(proposal.component, locale)
79
+ policyByComponent.set(proposal.component, policy)
80
+
81
+ if (typeof policy.confidence_threshold === "number" && proposal.confidence < policy.confidence_threshold) {
82
+ continue
83
+ }
84
+
85
+ if (!matchesMode(proposal, policy.mode)) continue
86
+
87
+ passedThreshold.push(proposal)
88
+ }
89
+
90
+ return applyPreferenceFilters(passedThreshold, policyByComponent)
91
+ }
92
+ }
93
+
94
+ function matchesMode(proposal: ClassificationProposal, mode: PolicyMode): boolean {
95
+ switch (mode) {
96
+ case "rule_only":
97
+ return proposal.source === "rule"
98
+ case "neural_only":
99
+ return proposal.source === "neural"
100
+ case "both":
101
+ case "rule_preferred":
102
+ case "neural_preferred":
103
+ return proposal.source === "rule" || proposal.source === "neural" || proposal.source === "merged"
104
+ }
105
+ }
106
+
107
+ /**
108
+ * Second pass for `rule_preferred` / `neural_preferred`: within each component, drop the dispreferred source when the
109
+ * preferred source has at least one survivor.
110
+ */
111
+ function applyPreferenceFilters(
112
+ proposals: readonly ClassificationProposal[],
113
+ policyByComponent: ReadonlyMap<ComponentTag, ClassifierPolicy>
114
+ ): ClassificationProposal[] {
115
+ const grouped = new Map<ComponentTag, ClassificationProposal[]>()
116
+
117
+ for (const proposal of proposals) {
118
+ const list = grouped.get(proposal.component) ?? []
119
+ list.push(proposal)
120
+ grouped.set(proposal.component, list)
121
+ }
122
+
123
+ const out: ClassificationProposal[] = []
124
+
125
+ for (const [component, list] of grouped) {
126
+ const policy = policyByComponent.get(component)
127
+
128
+ if (!policy) {
129
+ out.push(...list)
130
+ continue
131
+ }
132
+
133
+ if (policy.mode === "neural_preferred") {
134
+ const hasNeural = list.some((p) => p.source === "neural")
135
+ out.push(...(hasNeural ? list.filter((p) => p.source !== "rule") : list))
136
+ continue
137
+ }
138
+
139
+ if (policy.mode === "rule_preferred") {
140
+ const hasRule = list.some((p) => p.source === "rule")
141
+ out.push(...(hasRule ? list.filter((p) => p.source !== "neural") : list))
142
+ continue
143
+ }
144
+
145
+ out.push(...list)
146
+ }
147
+
148
+ return out
149
+ }