@mailwoman/kind-classifier 10.0.0 → 10.2.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/lib/poi.ts CHANGED
@@ -3,16 +3,19 @@
3
3
  * @license AGPL-3.0
4
4
  * @author Teffen Ellis, et al.
5
5
  *
6
- * POI subject detection for the `poi_query` kind. The lexicon is INJECTED (`POIPhraseLookup`) —
7
- * this package keeps its bitter-lesson invariant (no dictionaries in-tree); the phrase table
8
- * lives in `@mailwoman/poi-taxonomy` and is wired in by `createRuntimePipeline` behind the
9
- * `poiQueryKind` flag (default-ON since 2026-07-20). Spec §3.1.
6
+ * POI subject detection for the `poi_query` kind. The lexicon is injected (`POIPhraseLookup`) so this
7
+ * package keeps its bitter-lesson invariant (no dictionaries in-tree); the phrase table lives in
8
+ * `@mailwoman/poi-taxonomy` and is wired in by `createRuntimePipeline` behind the `poiQueryKind` flag.
9
+ * Spec §3.1.
10
10
  */
11
11
 
12
- import type { NormalizedInputLite, QueryShapeSegmentsView as QueryShapeLike } from "@mailwoman/query-shape"
12
+ import type { POISpatialRelation } from "@mailwoman/core/pipeline"
13
+ import type { NormalizedInputLite, QueryShapeSegmentsView as QueryShapeLike, TextSpan } from "@mailwoman/query-shape"
13
14
  /**
14
- * Comma-segment ceiling for a POI-led query. Past it the input is a venue plus a full address (`X, 350 5th Ave, New
15
- * York, NY`), which the structured-address scorer should claim instead.
15
+ * Comma-segment ceiling for a POI-led query.
16
+ *
17
+ * Past it the input is a venue plus a full address (`X, 350 5th Ave, New York, NY`),
18
+ * which the structured-address scorer should claim instead.
16
19
  */
17
20
  const MAX_POI_SEGMENTS = 3
18
21
 
@@ -21,158 +24,160 @@ const MAX_POI_SEGMENTS = 3
21
24
  */
22
25
  export interface POIPhraseMatch {
23
26
  /**
24
- * The matched subject's identifier string. For `kind: "category"`, a `@mailwoman/poi-taxonomy` category id; for
25
- * `kind: "brand"` or `kind: "name"`, the canonical display name. `matchPOISubject` treats it opaquely; the caller
26
- * (`mailwoman`'s `poi-intent.ts`) interprets it per `kind`.
27
+ * The matched subject's identifier: a `@mailwoman/poi-taxonomy` category id for
28
+ * `kind: "category"`, otherwise the canonical display name; `matchPOISubject`
29
+ * treats it opaquely and the caller interprets it per `kind`.
27
30
  */
28
31
  categoryID: string
29
32
  matchedPhrase: string
30
33
  confidence: number
31
- mechanism?: "exact" | "locale_normalized" | "typo"
32
- inputPhrase?: string
33
34
  /**
34
- * Absent = "category" (the pre-brand shape) — optional so pre-7.3 POIPhraseLookup implementors stay
35
- * source-compatible.
35
+ * How the phrase matched, or `null` when the lookup does not report it.
36
+ */
37
+ mechanism: "exact" | "locale_normalized" | "typo" | null
38
+ /**
39
+ * The phrase the lookup received, or `null` when the lookup does not report it.
36
40
  */
37
- kind?: "category" | "brand" | "name"
41
+ inputPhrase: string | null
38
42
  /**
39
- * Wikidata QID, when known. `kind: "brand"` only — absent when a brand resolved by name alone (no QID match).
43
+ * What `categoryID` identifies.
44
+ */
45
+ kind: "category" | "brand" | "name"
46
+ /**
47
+ * Wikidata QID when known, `kind: "brand"` only.
48
+ *
49
+ * It is `null` when a brand resolved using its name only, and for other kinds.
40
50
  */
41
- wikidata?: string
51
+ wikidata: string | null
42
52
  /**
43
- * Whether this hit is one member of a set the caller must search TOGETHER, rather than one candidate in a preference
44
- * list.
53
+ * How the caller reads several hits for one phrase.
45
54
  *
46
- * A lookup returning several hits means two different things, and the difference decides whether narrowing to the
47
- * first is an answer or an invented ordering. A phrase index returns the categories one typed phrase could name, the
48
- * curated reading first (`credit union` → the `bank` rollup its synonym redirects to, then the standalone
49
- * `credit_union` category), and the first entry IS the subject. An affordance rung returns every entity kind that
50
- * affords ONE activity, in a stable enumeration that is not a preference, and taking the first picks a winner nobody
51
- * authored.
55
+ * A lookup returning several hits means two different things: a phrase index
56
+ * returns the categories one typed phrase could name, the curated reading first
57
+ * (`credit union` → the `bank` rollup its synonym redirects to), while an affordance
58
+ * rung returns every entity kind that affords one activity in a stable enumeration.
59
+ * The enumeration does not express a preference.
52
60
  *
53
- * Set on every member of such a set. {@link matchPOISubject} then carries them all, the POI branch searches their
54
- * union, and the candidate ordering the resolver already owns decides the answer. Absent — the committed lexicon's
55
- * shape — keeps the first-hit reading unchanged.
61
+ * - `"preference"`: the hits are a preference list; {@link matchPOISubject} keeps the first.
62
+ * The committed lexicon's shape.
63
+ * - `"set"`: this hit is one member of a set the caller must search together,
64
+ * so {@link matchPOISubject} returns them all and the POI branch searches their union.
56
65
  */
57
- searchAsSet?: boolean
66
+ reading: POIPhraseReading
58
67
  /**
59
- * ISO 3166-1 alpha-2 countries the authority behind this hit scopes its claim to. Absent = the claim holds
60
- * everywhere.
68
+ * ISO 3166-1 alpha-2 countries the authority behind this hit scopes its claim to.
69
+ * `null` means the claim is true in every country.
61
70
  *
62
- * A scope is a statement about ESTABLISHMENTS, so it is judged against the country of the place being searched, not
63
- * the caller's locale: the locale is the lens the phrase is read through, and it says nothing about where the claim
64
- * holds. `matchPOISubject` carries the value untouched; the POI intent stage binds it once the anchor has resolved.
71
+ * A scope is a statement about establishments, so it is judged against the country of
72
+ * the place being searched rather than the caller's locale: the locale is the lens the
73
+ * phrase is read through and makes no statement about where the condition is true.
74
+ * `matchPOISubject` returns the value unchanged.
75
+ * The POI intent stage binds it once the anchor has resolved.
65
76
  */
66
- countryScope?: readonly string[]
77
+ countryScope: readonly string[] | null
67
78
  }
68
79
 
69
80
  /**
70
- * Injected phrase→category lookup. Exact-phrase, locale-aware; returns [] on miss.
81
+ * How several hits for one phrase are read, as {@link POIPhraseMatch.reading} describes.
71
82
  */
72
- export type POIPhraseLookup = (phrase: string, locale?: string) => ReadonlyArray<POIPhraseMatch>
83
+ export type POIPhraseReading = "preference" | "set"
73
84
 
74
- export type POISpatialRelation = "comma" | "near" | "in" | "at" | "around" | "to"
85
+ /**
86
+ * Injected phrase→category lookup, exact-phrase and locale-aware, returning `[]` on miss.
87
+ */
88
+ export type POIPhraseLookup = (phrase: string, locale?: string) => ReadonlyArray<POIPhraseMatch>
75
89
 
76
- export interface POIQuerySpan {
77
- text: string
78
- /**
79
- * Half-open character offsets into the normalized input.
80
- */
81
- start: number
82
- end: number
83
- }
90
+ /**
91
+ * A span of the normalized input, with half-open character offsets.
92
+ */
93
+ export type POIQuerySpan = TextSpan
84
94
 
85
95
  /**
86
- * Which lexicon this hit came from. Existing category lookups set `"category"` (backward-compatible default).
96
+ * The subject phrase {@link matchPOISubject} chose and the lexicon hits for it.
87
97
  */
88
98
  export interface POISubjectMatch {
89
99
  /**
90
- * The hit the subject SCORES under — its kind and its confidence. Always `matches[0]`; the two are built together in
91
- * one place so they cannot disagree.
100
+ * The hit the subject scores under.
101
+ *
102
+ * Always `matches[0]`, built together in one place so they cannot disagree.
92
103
  */
93
104
  match: POIPhraseMatch
94
105
  /**
95
- * Every category the subject reaches, `match` first.
96
- *
97
- * One entry unless the lookup returned a {@link POIPhraseMatch.searchAsSet} set, in which case it holds the whole set
98
- * and the POI branch searches their union. The order is the order the lookup returned and states no preference:
99
- * nothing downstream may read position as rank.
106
+ * Every category the subject reaches, `match` first: one entry unless the lookup
107
+ * returned a `"set"` {@link POIPhraseMatch.reading}, in which case it holds the
108
+ * whole set and the POI branch searches their union.
109
+ * The order is the lookup's and states no preference.
100
110
  */
101
111
  matches: POIPhraseMatch[]
102
- /**
103
- * The matched subject text as it appeared in the query.
104
- */
105
112
  subject: string
106
113
  subjectSpan: POIQuerySpan
107
114
  /**
108
115
  * The relation crossing from the subject span to the anchor span.
109
116
  */
110
- relation?: POISpatialRelation
111
- relationSpan?: POIQuerySpan
117
+ relation: POISpatialRelation | null
118
+ relationSpan: POIQuerySpan | null
112
119
  /**
113
120
  * The anchor remainder after the separator; `""` when the whole input matched.
114
121
  */
115
122
  remainder: string
116
- anchorSpan?: POIQuerySpan
123
+ anchorSpan: POIQuerySpan | null
117
124
  }
118
125
 
119
126
  /**
120
- * Anchor separator between subject and place: comma, or near/in/at/around/to — scanned left-to-right until a prefix
121
- * hits the lexicon.
127
+ * Anchor separator between subject and place: comma, or near/in/at/around/to —
128
+ * scanned left-to-right until a prefix hits the lexicon.
129
+ *
130
+ * Linear by construction (no polynomial ReDoS): neither alternative places an unbounded
131
+ * whitespace quantifier before its required literal, the classic `js/polynomial-redos` shape.
132
+ * The comma alternative starts at the literal `,`.
122
133
  *
123
- * Linear by construction (no polynomial ReDoS): neither alternative places an unbounded whitespace quantifier _before_
124
- * its required literal — the classic `\s*`/`\s+`-then-literal backtracking shape that CodeQL's `js/polynomial-redos`
125
- * flags. The comma alternative starts at the literal `,`; the anchor alternative starts at a single `\s` immediately
126
- * before a fixed anchor word. Every remaining quantifier (`,\s*`, `…\s+`) is _trailing_ — it runs only after the
127
- * required literal has already matched and nothing follows it, so it never backtracks. Each start offset does O(1)
128
- * work, making `matchAll` O(n).
134
+ * The anchor alternative starts at one `\s` before a fixed anchor word.
135
+ * Every remaining quantifier is trailing and runs only after the required literal matches.
136
+ * Each start offset does O(1) work, so `matchAll` is O(n).
129
137
  *
130
- * Behaviour is byte-identical to the previous `\s*,\s*|\s+(?:…)\s+` because `matchPOISubject` `.trim()`s both the
131
- * subject (text before `.index`) and the remainder (text after the match), so surrounding whitespace on either side of
132
- * the separator is redundant. The leading `\s*`/`\s+` only shifted the match _start_ within a whitespace run — trim
133
- * absorbs that — while the retained _trailing_ greedy quantifier keeps the match _end_ (and thus `matchAll`'s
134
- * lastIndex) identical, preserving the exact subsequent-match sequence. Verified: 0 divergences across 22.7k inputs
135
- * (systematic + fuzzed adversarial whitespace + shared-whitespace anchor/comma chains).
138
+ * Behavior is byte-identical to the previous `\s*,\s*|\s+(?:…)\s+`, because `matchPOISubject`
139
+ * trims both the subject and the remainder, so surrounding whitespace is redundant.
140
+ * The leading quantifier only shifted the match start within a whitespace run, while the retained
141
+ * trailing greedy quantifier keeps the match end and thus `matchAll`'s lastIndex identical.
136
142
  */
137
143
  const ANCHOR_SEPARATOR = /,\s*|\s(near|in|at|around|to)\s+/gi
138
144
 
139
145
  /**
140
- * Longest subject we accept, in tokens. Eight covers compound taxonomy phrases while bounding lexicon probes.
146
+ * Longest subject accepted, in tokens: eight covers compound taxonomy phrases
147
+ * while bounding lexicon probes.
141
148
  */
142
149
  const MAX_SUBJECT_TOKENS = 8
143
150
 
144
151
  /**
145
- * The categories one candidate subject reaches, from the hits the lookup returned for it.
152
+ * The categories one candidate subject reaches: the whole array when the first hit reads
153
+ * as a `"set"` ({@link POIPhraseMatch.reading}), preserved as the lookup returned it
154
+ * and never filtered, so a rung that flagged only some members keeps every member.
146
155
  *
147
- * The whole array when the first hit declares {@link POIPhraseMatch.searchAsSet} — carried as the lookup returned it,
148
- * never filtered, so a rung that flagged only some of its members loses nothing here and the inconsistency stays
149
- * visible to whoever reads the set. Otherwise the first hit alone, which is the preference-list reading the committed
150
- * phrase index has always had.
156
+ * The inconsistency stays visible.
157
+ * Otherwise, use only the first hit.
151
158
  */
152
159
  function reachedMatches(hits: ReadonlyArray<POIPhraseMatch>): POIPhraseMatch[] {
153
- return hits[0]!.searchAsSet ? [...hits] : [hits[0]!]
160
+ return hits[0]!.reading === "set" ? [...hits] : [hits[0]!]
154
161
  }
155
162
 
156
163
  /**
157
- * Match a POI subject: the whole input, or the text before the FIRST anchor separator WHOSE PREFIX HITS THE LEXICON (≤
158
- * 8 tokens). Scans separator occurrences left-to-right — a lexicon phrase may itself contain a bare separator word
159
- * (e.g. "walk in clinic"), so the first separator isn't necessarily the right split point. Returns null when the
160
- * lexicon never fires — including comma-ridden full addresses whose leading segment isn't a lexicon phrase.
164
+ * Match a POI subject: the whole input, or the text before the first anchor
165
+ * separator whose prefix hits the lexicon (≤ 8 tokens).
166
+ *
167
+ * Scans separators left-to-right, because a lexicon phrase may itself contain a bare separator
168
+ * word ("walk in clinic") and the first separator is not necessarily the right split point.
169
+ * Returns null when the lexicon never fires, including comma-ridden full addresses
170
+ * whose leading segment is not a phrase.
161
171
  *
162
- * The winning candidate's hits are carried per {@link reachedMatches}: the first hit, or the whole set when the lookup
163
- * declared one.
172
+ * The winning candidate's hits are listed per {@link reachedMatches}.
164
173
  */
165
- export function matchPOISubject(
166
- text: string,
167
- locale: string | undefined,
168
- lookup: POIPhraseLookup
169
- ): POISubjectMatch | null {
174
+ export function matchPOISubject(text: string, locale: string | null, lookup: POIPhraseLookup): POISubjectMatch | null {
170
175
  const trimmed = text.trim()
171
176
  const inputStart = text.indexOf(trimmed)
172
177
 
173
178
  if (!trimmed) return null
174
179
 
175
- const whole = lookup(trimmed, locale)
180
+ const whole = lookup(trimmed, locale ?? undefined)
176
181
 
177
182
  if (whole.length) {
178
183
  const matches = reachedMatches(whole)
@@ -182,7 +187,10 @@ export function matchPOISubject(
182
187
  matches,
183
188
  subject: trimmed,
184
189
  subjectSpan: { text: trimmed, start: inputStart, end: inputStart + trimmed.length },
190
+ relation: null,
191
+ relationSpan: null,
185
192
  remainder: "",
193
+ anchorSpan: null,
186
194
  }
187
195
  }
188
196
 
@@ -191,11 +199,11 @@ export function matchPOISubject(
191
199
 
192
200
  const subject = trimmed.slice(0, separator.index).trim()
193
201
 
194
- // Subjects only grow as the scan moves right — once over budget, later splits are too. Whitespace-only
195
- // split, not `wordsOf`: a comma inside a subject is real content here, not a separator to erase.
202
+ // Subjects only grow as the scan moves right, so once over budget later splits are too.
203
+ // Whitespace-only split rather than `wordsOf`, because a comma inside a subject is real content.
196
204
  if (subject.split(/\s+/).length > MAX_SUBJECT_TOKENS) break
197
205
 
198
- const hits = lookup(subject, locale)
206
+ const hits = lookup(subject, locale ?? undefined)
199
207
 
200
208
  if (!hits.length) continue
201
209
 
@@ -237,17 +245,19 @@ export function matchPOISubject(
237
245
  }
238
246
 
239
247
  /**
240
- * `poi_query` scorer over an injected lexicon. Confidence bands: whole-input lexicon hit 0.92 (above venue-landmark's
241
- * 0.88 ceiling — an exact lexicon phrase beats a shape heuristic); subject + anchor 0.9. Guards below keep venue-led
242
- * FULL addresses (class 2) on the structured-address path: a remainder that leads with a house number, or a 4+-segment
243
- * input, scores 0 here.
248
+ * `poi_query` scorer over an injected lexicon, with confidence bands: a whole-input lexicon hit
249
+ * scores 0.92 (above venue-landmark's 0.88 ceiling, because an exact phrase beats a shape heuristic)
250
+ * and a subject plus anchor 0.9.
251
+ *
252
+ * The guards keep venue-led full addresses (class 2) on the structured-address path:
253
+ * a remainder leading with a house number, or a 4+-segment input, scores 0.
244
254
  */
245
255
  export function createScorePOIQuery(
246
256
  lookup: POIPhraseLookup,
247
257
  locale?: string
248
258
  ): (input: NormalizedInputLite, shape: QueryShapeLike) => number {
249
259
  return (input, shape) => {
250
- const matched = matchPOISubject(input.normalized, locale ?? input.appliedLocale, lookup)
260
+ const matched = matchPOISubject(input.normalized, locale ?? input.appliedLocale ?? null, lookup)
251
261
 
252
262
  if (!matched) return 0
253
263
 
@@ -265,51 +275,51 @@ export function createScorePOIQuery(
265
275
  }
266
276
 
267
277
  /**
268
- * Confidence band for a bare category. One notch above `poi_query`'s whole-input band (0.92) so the anchorless subset
269
- * takes the top slot from it, and only from it — every anchored POI query keeps scoring `poi_query` exactly as before.
270
- * The coordinator's POI branch accepts both kinds, so the routing is identical either way; the split exists so the
271
- * marker can say "you named a category and no place", which is a different thing to tell a caller.
278
+ * Confidence band for a bare category, one notch above `poi_query`'s whole-input
279
+ * band (0.92) so only the anchorless subset takes the top slot and every anchored
280
+ * POI query keeps scoring `poi_query` as before.
281
+ *
282
+ * The coordinator's POI branch accepts both kinds, so the routing is identical either way.
283
+ * The split exists so the marker can say "you supplied a category and no place".
272
284
  */
273
285
  const POI_CATEGORY_CONFIDENCE = 0.93
274
286
 
275
287
  /**
276
- * `poi_category` scorer (ROAD_TO_V9 §4.4) — a bare taxonomy category with nowhere to search: "tacos", "grocery store",
277
- * "drinking fountain".
288
+ * `poi_category` scorer (ROAD_TO_V9 §4.4) — a bare taxonomy category with nowhere
289
+ * to search: "tacos", "grocery store", "drinking fountain".
290
+ *
291
+ * Fires only on a whole-input lexicon hit (`remainder === ""`) whose subject is a category.
292
+ * A brand (`kind: "brand"`) is excluded because `POIPhraseMatch.categoryID`
293
+ * then holds the brand's display name.
278
294
  *
279
- * Fires ONLY on a whole-input lexicon hit (`remainder === ""`) whose subject is a CATEGORY. A brand (`kind: "brand"`)
280
- * is excluded: a bare "Starbucks" is a name lookup, not a category, and the taxonomy id a category marker promises to
281
- * carry does not exist for it — `POIPhraseMatch.categoryID` holds the brand's display name in that case, which would
282
- * make the marker's `categoryID` evidence a lie.
295
+ * That value would misrepresent the marker's `categoryID` evidence.
283
296
  */
284
297
  export function createScorePOICategory(
285
298
  lookup: POIPhraseLookup,
286
299
  locale?: string
287
300
  ): (input: NormalizedInputLite, shape: QueryShapeLike) => number {
288
301
  return (input, _shape) => {
289
- const matched = matchPOISubject(input.normalized, locale ?? input.appliedLocale, lookup)
302
+ const matched = matchPOISubject(input.normalized, locale ?? input.appliedLocale ?? null, lookup)
290
303
 
291
304
  if (!matched || matched.remainder !== "") return 0
292
305
 
293
- if ((matched.match.kind ?? "category") !== "category") return 0
306
+ if (matched.match.kind !== "category") return 0
294
307
 
295
308
  return POI_CATEGORY_CONFIDENCE * matched.match.confidence
296
309
  }
297
310
  }
298
311
 
299
312
  /**
300
- * The whole-input category hit behind a `poi_category` verdict, for the marker's evidence. `null` when the input is not
301
- * a bare category — same conditions as {@link createScorePOICategory}, so the two cannot disagree.
313
+ * The whole-input category hit behind a `poi_category` verdict, for the marker's evidence;
314
+ * `null` when the input is not a bare category, under the same conditions as
315
+ * {@link createScorePOICategory} so the two cannot disagree.
302
316
  */
303
- export function matchPOICategory(
304
- text: string,
305
- locale: string | undefined,
306
- lookup: POIPhraseLookup
307
- ): POIPhraseMatch | null {
317
+ export function matchPOICategory(text: string, locale: string | null, lookup: POIPhraseLookup): POIPhraseMatch | null {
308
318
  const matched = matchPOISubject(text, locale, lookup)
309
319
 
310
320
  if (!matched || matched.remainder !== "") return null
311
321
 
312
- if ((matched.match.kind ?? "category") !== "category") return null
322
+ if (matched.match.kind !== "category") return null
313
323
 
314
324
  return matched.match
315
325
  }