@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.
Files changed (150) 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/locale/index.ts +9 -0
  52. package/locale/locale.ts +49 -0
  53. package/locale/profiles/en-us.ts +69 -0
  54. package/locale/profiles/fr-fr.ts +75 -0
  55. package/locale/profiles/index.ts +9 -0
  56. package/locale/profiles/ja-jp.ts +33 -0
  57. package/locale/registry.ts +68 -0
  58. package/logging/index.ts +8 -0
  59. package/logging/shared.ts +145 -0
  60. package/logging/utils.ts +46 -0
  61. package/objects.ts +211 -0
  62. package/out/api/APIClient.d.ts.map +1 -1
  63. package/out/api/APIClient.js +2 -2
  64. package/out/api/APIClient.js.map +1 -1
  65. package/out/pipeline/types.d.ts +13 -0
  66. package/out/pipeline/types.d.ts.map +1 -1
  67. package/out/pipeline/types.js.map +1 -1
  68. package/out/scripting/utils/index.d.ts.map +1 -1
  69. package/out/scripting/utils/index.js +3 -5
  70. package/out/scripting/utils/index.js.map +1 -1
  71. package/package.json +190 -107
  72. package/pipeline/index.ts +46 -0
  73. package/pipeline/reconcile-lookups.ts +108 -0
  74. package/pipeline/reconcile.ts +542 -0
  75. package/pipeline/runtime-pipeline.ts +732 -0
  76. package/pipeline/span-logit-aggregation.ts +151 -0
  77. package/pipeline/span-proposer.ts +587 -0
  78. package/pipeline/types.ts +357 -0
  79. package/policy/defaults.ts +35 -0
  80. package/policy/index.ts +10 -0
  81. package/policy/policy.ts +60 -0
  82. package/policy/proposal-collection.ts +64 -0
  83. package/policy/registry.ts +149 -0
  84. package/resolver/index.ts +29 -0
  85. package/resolver/types.ts +584 -0
  86. package/resources/LocaleIndex.ts +124 -0
  87. package/resources/ResourceMapCache.ts +126 -0
  88. package/resources/collections.ts +93 -0
  89. package/resources/debugging.ts +19 -0
  90. package/resources/git.ts +54 -0
  91. package/resources/index.ts +17 -0
  92. package/resources/languages/index.ts +49 -0
  93. package/resources/languages/types.gen.ts +1368 -0
  94. package/resources/libaddressinput.ts +105 -0
  95. package/resources/libpostal.ts +182 -0
  96. package/resources/locale.ts +23 -0
  97. package/resources/set.ts +179 -0
  98. package/resources/whosonfirst/DataSourceCache.ts +72 -0
  99. package/resources/whosonfirst/PlacetypeDataSource.ts +199 -0
  100. package/resources/whosonfirst/index.ts +10 -0
  101. package/resources/whosonfirst/loader.ts +157 -0
  102. package/resources/whosonfirst/placetypes/Placetype.ts +438 -0
  103. package/resources/whosonfirst/placetypes/admin.ts +173 -0
  104. package/resources/whosonfirst/placetypes/definition.ts +135 -0
  105. package/resources/whosonfirst/placetypes/graph.ts +0 -0
  106. package/resources/whosonfirst/placetypes/index.ts +12 -0
  107. package/resources/whosonfirst/placetypes/mermaid.ts +168 -0
  108. package/resources/whosonfirst/placetypes/tree.ts +46 -0
  109. package/routing/index.ts +208 -0
  110. package/scripting/index.ts +40 -0
  111. package/scripting/utils/index.ts +103 -0
  112. package/tokenization/Graph.ts +50 -0
  113. package/tokenization/Span.ts +297 -0
  114. package/tokenization/index.ts +9 -0
  115. package/tokenization/normalizer.ts +123 -0
  116. package/tools/download-libpostal-resources.ts +98 -0
  117. package/tools/download-ssl-address.ts +99 -0
  118. package/tools/generate-language-types.ts +194 -0
  119. package/tools/index.ts +13 -0
  120. package/types/Classification.ts +211 -0
  121. package/types/classifier.ts +133 -0
  122. package/types/component.ts +75 -0
  123. package/types/index.ts +10 -0
  124. package/types/mapping.ts +81 -0
  125. package/utils/data-root.ts +56 -0
  126. package/utils/hash.ts +27 -0
  127. package/utils/index.ts +14 -0
  128. package/utils/jsonl.ts +43 -0
  129. package/utils/python-json.ts +105 -0
  130. package/utils/python-random.ts +90 -0
  131. package/utils/repo.ts +118 -0
  132. package/utils/sealed-db.ts +85 -0
  133. package/utils/stats.ts +32 -0
  134. package/vitest.config.ts +53 -0
  135. package/out/lifecycle/ServiceSymbol.d.ts +0 -57
  136. package/out/lifecycle/ServiceSymbol.d.ts.map +0 -1
  137. package/out/lifecycle/ServiceSymbol.js +0 -60
  138. package/out/lifecycle/ServiceSymbol.js.map +0 -1
  139. package/out/lifecycle/index.d.ts +0 -11
  140. package/out/lifecycle/index.d.ts.map +0 -1
  141. package/out/lifecycle/index.js +0 -11
  142. package/out/lifecycle/index.js.map +0 -1
  143. package/out/lifecycle/lru-cache.d.ts +0 -22
  144. package/out/lifecycle/lru-cache.d.ts.map +0 -1
  145. package/out/lifecycle/lru-cache.js +0 -31
  146. package/out/lifecycle/lru-cache.js.map +0 -1
  147. package/out/lifecycle/services.d.ts +0 -144
  148. package/out/lifecycle/services.d.ts.map +0 -1
  149. package/out/lifecycle/services.js +0 -191
  150. package/out/lifecycle/services.js.map +0 -1
@@ -0,0 +1,175 @@
1
+ /**
2
+ * @copyright Sister Software
3
+ * @license AGPL-3.0
4
+ * @author Teffen Ellis, et al.
5
+ */
6
+
7
+ import { ConsoleLogger, type IRuntimeLogger } from "@mailwoman/core/logging"
8
+ import { isAsyncDisposable } from "async-init"
9
+ import Axios, { type AxiosInstance, type AxiosRequestConfig, type AxiosResponse, type CreateAxiosDefaults } from "axios"
10
+ import {
11
+ type AxiosCacheInstance,
12
+ type CacheAxiosResponse,
13
+ type CacheOptions,
14
+ setupCache,
15
+ } from "axios-cache-interceptor"
16
+
17
+ import { delegateAxiosError } from "./responses.ts"
18
+
19
+ export type { IRuntimeLogger }
20
+
21
+ /**
22
+ * Configuration for an API client.
23
+ */
24
+ export interface APIClientConfig {
25
+ /**
26
+ * The logged display name of the API client.
27
+ */
28
+ displayName: string
29
+
30
+ /**
31
+ * Options for caching responses.
32
+ */
33
+ caching?: CacheOptions
34
+
35
+ /**
36
+ * How many requests to make per minute before enforcing a cooldown.
37
+ */
38
+ requestsPerMinute?: number
39
+
40
+ /**
41
+ * Axios configuration.
42
+ */
43
+ axios?: CreateAxiosDefaults
44
+ }
45
+
46
+ /**
47
+ * A base class for API clients used in Mailwoman, providing features like request cooldowns, response caching, and
48
+ * integrated logging.
49
+ */
50
+ export class APIClient<C extends APIClientConfig = APIClientConfig> extends EventTarget implements AsyncDisposable {
51
+ public readonly config: C
52
+
53
+ #cooldownWithResolvers: PromiseWithResolvers<void> | null = null
54
+ #requestInterval = 0
55
+ #requestCountWithinCooldown = 0
56
+ #lastRequestTime = 0
57
+
58
+ public get $cooldown(): Promise<void> {
59
+ return this.#cooldownWithResolvers?.promise || Promise.resolve()
60
+ }
61
+
62
+ /**
63
+ * The prefixed logger for the API client.
64
+ */
65
+ public readonly logger: IRuntimeLogger
66
+ /**
67
+ * The Axios instance for the API client.
68
+ */
69
+ public readonly axios: AxiosInstance | AxiosCacheInstance
70
+
71
+ constructor(config: C) {
72
+ super()
73
+
74
+ this.config = config
75
+ this.logger = ConsoleLogger.prefix(config.displayName)
76
+
77
+ const axiosInstance = Axios.create({
78
+ ...config.axios,
79
+ })
80
+
81
+ if (config.caching) {
82
+ this.axios = setupCache(axiosInstance, {
83
+ debug: (msg) => {
84
+ this.logger.info(msg)
85
+ },
86
+ ttl: 60 * 60 * 1000, // 1 hour
87
+ ...config.caching,
88
+ })
89
+ } else {
90
+ this.axios = axiosInstance
91
+ }
92
+
93
+ this.axios.interceptors.response.use((response: CacheAxiosResponse | AxiosResponse) => {
94
+ const cachedLabel = (response as CacheAxiosResponse).cached ? " (cached)" : "(uncached)"
95
+
96
+ this.logger.debug(
97
+ `${response.status} ${cachedLabel} ${response.config.method?.toUpperCase()}: ${response.config.url}`
98
+ )
99
+
100
+ return response
101
+ })
102
+
103
+ this.axios.interceptors.response.use(undefined, delegateAxiosError)
104
+
105
+ this.#requestInterval = typeof config.requestsPerMinute === "number" ? 60000 / config.requestsPerMinute : 0
106
+
107
+ if (this.#requestInterval) {
108
+ this.axios.interceptors.response.use(this.updateCooldownAfterResponse)
109
+ }
110
+ }
111
+
112
+ /**
113
+ * Perform a fetch operation using the API's Axios instance.
114
+ */
115
+ public fetch = async <T>(options: AxiosRequestConfig): Promise<AxiosResponse<T>> => {
116
+ await this.$cooldown
117
+
118
+ const method = options.method?.toUpperCase() || "GET"
119
+ this.logger.debug(`${method}: ${options.url}`)
120
+
121
+ return this.axios(options)
122
+ }
123
+
124
+ protected setCooldown = (nextCooldown: number): void => {
125
+ const nextCooldownWithResolvers = Promise.withResolvers<void>()
126
+
127
+ setTimeout(() => {
128
+ this.#requestCountWithinCooldown = 0
129
+ nextCooldownWithResolvers.resolve()
130
+
131
+ this.dispatchEvent(new Event("cooldown_end"))
132
+ }, nextCooldown)
133
+
134
+ this.#cooldownWithResolvers = nextCooldownWithResolvers
135
+ this.dispatchEvent(new Event("cooldown_start"))
136
+ }
137
+
138
+ protected updateCooldownAfterResponse = (
139
+ response: CacheAxiosResponse | AxiosResponse
140
+ ): CacheAxiosResponse | AxiosResponse<unknown, unknown> => {
141
+ this.#cooldownWithResolvers?.resolve()
142
+ const now = Date.now()
143
+ const previousRequestTime = this.#lastRequestTime
144
+ this.#lastRequestTime = now
145
+
146
+ if (!this.config.requestsPerMinute) return response
147
+
148
+ this.#requestCountWithinCooldown++
149
+
150
+ const elapsed = now - previousRequestTime
151
+ const cooldown = this.#requestInterval - elapsed
152
+
153
+ if (this.#requestCountWithinCooldown >= this.config.requestsPerMinute) {
154
+ this.setCooldown(cooldown)
155
+ }
156
+
157
+ return response
158
+ }
159
+
160
+ public async [Symbol.asyncDispose](): Promise<void> {
161
+ this.#cooldownWithResolvers?.resolve()
162
+
163
+ const storedCache = this.config.caching?.storage
164
+
165
+ if (isAsyncDisposable(storedCache)) {
166
+ await storedCache[Symbol.asyncDispose]()
167
+ }
168
+
169
+ return Promise.resolve()
170
+ }
171
+
172
+ public override toString() {
173
+ return `${this.config.displayName} API Client`
174
+ }
175
+ }
@@ -0,0 +1,23 @@
1
+ /**
2
+ * @copyright Sister Software
3
+ * @license AGPL-3.0
4
+ * @author Teffen Ellis, et al.
5
+ *
6
+ * Headless browser utilities.
7
+ */
8
+
9
+ /**
10
+ * Common user agent strings.
11
+ */
12
+ export const UserAgent = {
13
+ /**
14
+ * IPad OS 13.0 Safari.
15
+ */
16
+ iPadSafari:
17
+ "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/13.0 Safari/605.1.15",
18
+ } as const
19
+
20
+ /**
21
+ * Common user agent strings.
22
+ */
23
+ export type UserAgent = (typeof UserAgent)[keyof typeof UserAgent]
package/api/index.ts ADDED
@@ -0,0 +1,11 @@
1
+ /**
2
+ * @copyright Sister Software
3
+ * @license AGPL-3.0
4
+ * @author Teffen Ellis, et al.
5
+ *
6
+ * Core API utilities.
7
+ */
8
+
9
+ export * from "./APIClient.ts"
10
+ export * from "./headless.ts"
11
+ export * from "./responses.ts"
@@ -0,0 +1,135 @@
1
+ /**
2
+ * @copyright Sister Software
3
+ * @license AGPL-3.0
4
+ * @author Teffen Ellis, et al.
5
+ *
6
+ * API response utilities.
7
+ */
8
+
9
+ import { AxiosError, HttpStatusCode, isAxiosError } from "axios"
10
+
11
+ import { ResourceError } from "../errors/schema.ts"
12
+ import { ConsoleLogger } from "../logging/index.ts"
13
+
14
+ /**
15
+ * A response container, wrapping the actual response body.
16
+ */
17
+ export interface ResponseContainer<Body> {
18
+ data: Body
19
+ }
20
+
21
+ export type ResponseLike<Body> = ResponseContainer<Body> | Body
22
+
23
+ /**
24
+ * Type-helper to pluck the response body, possibly from within an Axios response.
25
+ *
26
+ * This is useful when normalizing a new Axios response and a cached local response.
27
+ *
28
+ * @internal
29
+ */
30
+ export type ExtractResponseData<T> = T extends ResponseContainer<infer Body> ? Body : T
31
+
32
+ function isResponseContainer<Body>(responseContainer: ResponseLike<Body>): responseContainer is ResponseContainer<Body>
33
+ function isResponseContainer<Body>(body: Body): body is Body
34
+ function isResponseContainer<Body>(input: ResponseLike<Body>): input is ResponseContainer<Body> {
35
+ return typeof input === "object" && input !== null && "data" in input
36
+ }
37
+
38
+ /**
39
+ * Helper function to pluck the response body from an Axios response.
40
+ */
41
+ function pluckResponseBody<Body>(responseContainer: ResponseContainer<Body>): Body
42
+ function pluckResponseBody<Body>(rawBody: Body): Body
43
+ function pluckResponseBody<Body>(input: ResponseContainer<Body> | Body): Body {
44
+ if (isResponseContainer(input)) return input.data
45
+
46
+ return input
47
+ }
48
+
49
+ /**
50
+ * Type-helper to recursively pluck the `data` property from a response body.
51
+ *
52
+ * This is useful when an API nests the actual response body within a `data` property.
53
+ *
54
+ * @internal
55
+ */
56
+ export type ExtractResponseBodyData<Body> = Body extends {
57
+ data: infer Data
58
+ }
59
+ ? ExtractResponseBodyData<Data>
60
+ : Body
61
+
62
+ /**
63
+ * Helper function to recursively pluck the `data` property from a response body.
64
+ *
65
+ * This is useful when an API nests the actual response body within a `data` property.
66
+ *
67
+ * @internal
68
+ */
69
+ export function pluckResponseData<Body>(responseContainer: ResponseContainer<Body>): ExtractResponseBodyData<Body>
70
+ export function pluckResponseData<Body>(input: ResponseContainer<Body> | Body): ExtractResponseBodyData<Body> {
71
+ const body = pluckResponseBody(input)
72
+
73
+ if (isResponseContainer(body)) return pluckResponseData(body)
74
+
75
+ return body as ExtractResponseBodyData<Body>
76
+ }
77
+
78
+ export function checkConnectivity(
79
+ connectivityURL: URL | string = "https://connectivitycheck.gstatic.com/generate_204"
80
+ ): Promise<boolean> {
81
+ return fetch(connectivityURL, {
82
+ method: "HEAD",
83
+ })
84
+ .then((response) => response.ok)
85
+ .catch(() => false)
86
+ }
87
+
88
+ /**
89
+ * Delegate Axios errors to an appropriate error handler.
90
+ *
91
+ * @internal
92
+ */
93
+ export async function delegateAxiosError(error: unknown): Promise<unknown> {
94
+ {
95
+ if (!isAxiosError(error)) return Promise.reject(error)
96
+
97
+ const { response, code: networkErrorCode } = error
98
+
99
+ if (networkErrorCode === "ENOTFOUND") {
100
+ const internetReachable = await checkConnectivity()
101
+
102
+ if (!internetReachable)
103
+ throw ResourceError.from(
104
+ 500,
105
+ "Could not reach host. Are we connected to the internet?",
106
+ "axios",
107
+ "network",
108
+ "unreachable"
109
+ )
110
+ }
111
+
112
+ if (!response) throw ResourceError.from(500, "Internal Server Error", "axios", "response", "missing")
113
+
114
+ if (response.status === HttpStatusCode.Unauthorized) {
115
+ throw ResourceError.from(401, "Unauthorized")
116
+ }
117
+
118
+ if (!networkErrorCode) {
119
+ throw ResourceError.from(500, "Internal Server Error", "axios", "code", "missing")
120
+ }
121
+
122
+ switch (networkErrorCode) {
123
+ case AxiosError.ERR_NETWORK:
124
+ throw ResourceError.from(503, "Service Unavailable")
125
+ case AxiosError.ERR_CANCELED:
126
+ case AxiosError.ECONNABORTED:
127
+ case AxiosError.ETIMEDOUT:
128
+ return Promise.resolve()
129
+ default:
130
+ ConsoleLogger.warn(`Unhandled network error: ${networkErrorCode}`)
131
+ }
132
+
133
+ return Promise.reject(error)
134
+ }
135
+ }
@@ -0,0 +1,300 @@
1
+ /**
2
+ * @copyright Sister Software
3
+ * @license AGPL-3.0
4
+ * @author Teffen Ellis, et al.
5
+ *
6
+ * The #244 coarse-placer: a tiny always-resident linear classifier over hashed char-n-gram + script
7
+ * features ({@link featurize}). Maps an address string → a coarse country/region with a
8
+ * TEMPERATURE-CALIBRATED confidence, and ABSTAINS below a threshold ("probably off my loaded
9
+ * map") rather than emit a confident mis-placement. Pure + dependency-free — runs in node and the
10
+ * browser.
11
+ */
12
+
13
+ import { $public } from "../env/index.ts"
14
+ import { COARSE_CLASSES, FEATURE_DIM, featurize } from "./featurize.ts"
15
+
16
+ /** Serialized model: metadata in JSON, the dense `weights` (row-major [class][feature]) alongside. */
17
+ export interface CoarsePlacerArtifact {
18
+ classes: readonly string[]
19
+ featureDim: number
20
+ /** Temperature for confidence calibration (logits are divided by this before softmax). */
21
+ temperature: number
22
+ bias: number[]
23
+ /** Flat row-major weight matrix, length `classes.length * featureDim`. */
24
+ weights: Float32Array
25
+ }
26
+
27
+ /**
28
+ * On-disk `meta.json` shape. The fp32 artifact omits `quantization`/`scales`; the int8 artifact (from
29
+ * `scripts/coarse-placer/quantize.mjs`) sets `quantization: "int8-per-row"` and carries one `scale` per class, so
30
+ * `weights.bin` can be a 4×-smaller `Int8Array` dequantized as `int8 * scales[class]`.
31
+ */
32
+ export interface CoarsePlacerMeta {
33
+ classes: string[]
34
+ featureDim: number
35
+ temperature: number
36
+ bias: number[]
37
+ quantization?: "int8-per-row"
38
+ /** Per-class dequantization scale; present iff `quantization === "int8-per-row"`. */
39
+ scales?: number[]
40
+ }
41
+
42
+ /**
43
+ * Dequantize a per-row int8 weight matrix back to fp32: `W[c][i] = int8[c*dim + i] * scales[c]`. The predict path stays
44
+ * fp32 (identical math); quantization only shrinks the serialized/wire artifact. Pure — usable in the browser loader
45
+ * too.
46
+ */
47
+ export function dequantizeInt8Weights(
48
+ int8: Int8Array,
49
+ scales: readonly number[],
50
+ classCount: number,
51
+ dim: number
52
+ ): Float32Array {
53
+ const expected = classCount * dim
54
+
55
+ if (int8.length !== expected) throw new Error(`dequantize: int8 length ${int8.length} ≠ classes×dim ${expected}`)
56
+
57
+ if (scales.length !== classCount) throw new Error(`dequantize: ${scales.length} scales ≠ ${classCount} classes`)
58
+ const out = new Float32Array(expected)
59
+
60
+ for (let c = 0; c < classCount; c++) {
61
+ const s = scales[c]!
62
+ const base = c * dim
63
+
64
+ for (let i = 0; i < dim; i++) {
65
+ out[base + i] = int8[base + i]! * s
66
+ }
67
+ }
68
+
69
+ return out
70
+ }
71
+
72
+ export interface CoarsePrediction {
73
+ /** The predicted class, or `null` when the model abstained (confidence below the threshold). */
74
+ country: string | null
75
+ /** Calibrated probability of the top class (the abstention signal). */
76
+ confidence: number
77
+ abstained: boolean
78
+ /** The full calibrated class distribution. */
79
+ probs: Record<string, number>
80
+ }
81
+
82
+ export interface CoarsePlacerOpts {
83
+ /** Abstain when the calibrated top-class confidence is below this (default 0.5). */
84
+ abstainBelow?: number
85
+ /**
86
+ * Open-set reject rule (#244 M2). When `true`, the ABSTAIN decision uses the total IN-MAP probability mass `1 -
87
+ * P(OTHER)` instead of the single top-class prob, and a KEEP routes to the argmax IN-MAP class (never `OTHER`). This
88
+ * decouples "is it in-map at all?" (the reject question) from "which country?" (the routing question) — so a
89
+ * clearly-in-map-but-country-ambiguous address (mass split across several in-map countries) is KEPT rather than
90
+ * wrongly rejected. It clears the 90/90 the default max-prob rule cannot (post-hoc, no retrain: heldout-family
91
+ * generalization 89→91 — see docs/articles/evals/resolver-geo/2026-06-14-coarse-placer-m2-openset.md). The returned
92
+ * `confidence` becomes the routed in-map country's marginal probability (the soft-prior posterior weight). Default
93
+ * `false` = the M1 max-prob rule (byte-stable; can still return `OTHER`).
94
+ */
95
+ openSet?: boolean
96
+ }
97
+
98
+ export class CoarsePlacer {
99
+ readonly #classes: readonly string[]
100
+ readonly #dim: number
101
+ readonly #temp: number
102
+ readonly #bias: Float32Array
103
+ readonly #weights: Float32Array
104
+ readonly #threshold: number
105
+ readonly #openSet: boolean
106
+
107
+ constructor(artifact: CoarsePlacerArtifact, opts: CoarsePlacerOpts = {}) {
108
+ this.#classes = artifact.classes
109
+ this.#dim = artifact.featureDim
110
+ this.#temp = artifact.temperature || 1
111
+ this.#bias = Float32Array.from(artifact.bias)
112
+ this.#weights = artifact.weights
113
+ this.#threshold = opts.abstainBelow ?? 0.5
114
+ this.#openSet = opts.openSet ?? false
115
+ const expected = this.#classes.length * this.#dim
116
+
117
+ if (this.#weights.length !== expected) {
118
+ throw new Error(`CoarsePlacer: weights length ${this.#weights.length} ≠ classes×dim ${expected}`)
119
+ }
120
+ }
121
+
122
+ /**
123
+ * Load a placer from an artifact directory holding `meta.json` + `weights.bin` (the layout
124
+ * `scripts/coarse-placer/train.mjs` and `quantize.mjs` write). Handles both the fp32 artifact (`weights.bin` is a
125
+ * `Float32Array`) and the int8 artifact (`meta.quantization === "int8-per-row"`, `weights.bin` is an `Int8Array`
126
+ * dequantized via `meta.scales`). Node-only — the `node:` imports are dynamic so bundling the class for the browser
127
+ * doesn't pull them in.
128
+ */
129
+ static async fromArtifactDir(dir: string, opts?: CoarsePlacerOpts): Promise<CoarsePlacer> {
130
+ const { readFile } = await import("node:fs/promises")
131
+ const { join } = await import("node:path")
132
+ const meta = JSON.parse(await readFile(join(dir, "meta.json"), "utf8")) as CoarsePlacerMeta
133
+ const buf = await readFile(join(dir, "weights.bin"))
134
+ // Copy out of the (possibly pooled, possibly mis-aligned) Buffer into a fresh ArrayBuffer so the
135
+ // typed-array view is always validly aligned.
136
+ const bytes = buf.buffer.slice(buf.byteOffset, buf.byteOffset + buf.byteLength)
137
+ let weights: Float32Array
138
+
139
+ if (meta.quantization === "int8-per-row") {
140
+ if (!meta.scales) throw new Error(`CoarsePlacer.fromArtifactDir: int8 artifact at ${dir} has no scales`)
141
+ weights = dequantizeInt8Weights(new Int8Array(bytes), meta.scales, meta.classes.length, meta.featureDim)
142
+ } else {
143
+ weights = new Float32Array(bytes)
144
+ }
145
+
146
+ return new CoarsePlacer(
147
+ { classes: meta.classes, featureDim: meta.featureDim, temperature: meta.temperature, bias: meta.bias, weights },
148
+ opts
149
+ )
150
+ }
151
+
152
+ /**
153
+ * Load the int8 model bundled in `@mailwoman/core` (`core/data/coarse-placer/`). Node-only — uses the package path
154
+ * builder (the #481-corrected `__isCompiledTree` makes this resolve to the shipped `data/` in source, compiled, AND
155
+ * installed-package layouts). Override the directory with `$MAILWOMAN_COARSE_PLACER_DIR`. Callers set `abstainBelow`
156
+ * per their use (the soft-country-prior wiring passes 0.9 — see
157
+ * docs/articles/plan/2026-06-14-coarse-placer-soft-signal-spec.md).
158
+ */
159
+ static async fromBundled(opts?: CoarsePlacerOpts): Promise<CoarsePlacer> {
160
+ const dir = $public.MAILWOMAN_COARSE_PLACER_DIR
161
+
162
+ if (dir) return CoarsePlacer.fromArtifactDir(dir, opts)
163
+ const { corePackagePath } = await import("../utils/repo.ts")
164
+
165
+ return CoarsePlacer.fromArtifactDir(corePackagePath("data", "coarse-placer"), opts)
166
+ }
167
+
168
+ predict(text: string): CoarsePrediction {
169
+ const feats = featurize(text)
170
+ const C = this.#classes.length
171
+ const logits = new Float32Array(C)
172
+
173
+ for (let c = 0; c < C; c++) {
174
+ let s = this.#bias[c]!
175
+ const base = c * this.#dim
176
+
177
+ for (const i of feats) {
178
+ s += this.#weights[base + i]!
179
+ }
180
+ logits[c] = s / this.#temp
181
+ }
182
+ // Numerically-stable softmax.
183
+ let maxLogit = -Infinity
184
+
185
+ for (let c = 0; c < C; c++)
186
+ if (logits[c]! > maxLogit) {
187
+ maxLogit = logits[c]!
188
+ }
189
+ let sum = 0
190
+ const probs = new Float32Array(C)
191
+
192
+ for (let c = 0; c < C; c++) {
193
+ const e = Math.exp(logits[c]! - maxLogit)
194
+ probs[c] = e
195
+ sum += e
196
+ }
197
+ let topIdx = 0
198
+ let topProb = -1
199
+ let otherProb = 0
200
+ // argmax + prob over the IN-MAP classes only (excludes OTHER) — used by the open-set rule.
201
+ let inMapIdx = -1
202
+ let inMapProb = -1
203
+ const distribution: Record<string, number> = {}
204
+
205
+ for (let c = 0; c < C; c++) {
206
+ const p = probs[c]! / sum
207
+ distribution[this.#classes[c]!] = p
208
+
209
+ if (p > topProb) {
210
+ topProb = p
211
+ topIdx = c
212
+ }
213
+
214
+ if (this.#classes[c] === "OTHER") {
215
+ otherProb = p
216
+ } else if (p > inMapProb) {
217
+ inMapProb = p
218
+ inMapIdx = c
219
+ }
220
+ }
221
+
222
+ // Open-set rule (#244 M2): reject on total in-map MASS, route on the in-map argmax. Decouples
223
+ // "is it in-map?" from "which country?". The posterior weight is the routed country's marginal.
224
+ if (this.#openSet) {
225
+ const inMapMass = 1 - otherProb
226
+ const abstained = inMapMass < this.#threshold
227
+
228
+ return {
229
+ country: abstained || inMapIdx < 0 ? null : this.#classes[inMapIdx]!,
230
+ confidence: abstained ? inMapMass : inMapProb,
231
+ abstained,
232
+ probs: distribution,
233
+ }
234
+ }
235
+
236
+ const abstained = topProb < this.#threshold
237
+
238
+ return {
239
+ country: abstained ? null : this.#classes[topIdx]!,
240
+ confidence: topProb,
241
+ abstained,
242
+ probs: distribution,
243
+ }
244
+ }
245
+ }
246
+
247
+ /**
248
+ * The coarse placer's country POSTERIOR, shaped for the resolver: a per-country probability map like `{GB: 0.8, FR:
249
+ * 0.06}` — "given this address text, how likely is each country?" ("posterior" in the Bayesian sense: the model's
250
+ * belief AFTER seeing the input; see the glossary). Every in-map class except `OTHER` is included; returns `null` when
251
+ * the model abstained or routed off-map. The resolver consumes it as `anchorPosterior`: each candidate's rank gains
252
+ * `anchorWeight × posterior[candidate.country]`, so EVERY plausible country is boosted proportionally, and
253
+ * country-ambiguous inputs (mass split DK↔NO) let the resolver's own place evidence break the tie — strictly more
254
+ * informative than committing to the single argmax. Values are raw marginals in [0, 1] (un-renormalized; they sum to
255
+ * the in-map mass `1 − P(OTHER)`), matching the one-hot `confidence` scale so `anchorWeight` needs no retuning.
256
+ */
257
+ export function inMapPosterior(
258
+ prediction: CoarsePrediction,
259
+ opts?: {
260
+ /**
261
+ * Epsilon floor (see the glossary): drop countries whose probability falls below this cutoff before the resolver
262
+ * sees the posterior, so implausible tails cannot influence ranking. Domain [0, 1]: `0` (the DEFAULT) passes the
263
+ * full distribution through unchanged; raising it keeps only stronger beliefs — at the extreme only the argmax
264
+ * survives (a one-hot). The default is 0 deliberately: the #928 investigation swept 0.05–0.30 against the misroute
265
+ * battery and every value was byte-identical (the drift's real cause was the anchor re-rank's score key, fixed
266
+ * separately) — no nonzero default has a measured basis, and the shipped distribution contract stays
267
+ * byte-identical. The knob exists for distribution-mode experiments (`--posterior-floor` on the misroute eval).
268
+ */
269
+ epsilonFloor?: number
270
+ }
271
+ ): Record<string, number> | null {
272
+ if (prediction.country === null || prediction.country === "OTHER") return null
273
+ const floor = opts?.epsilonFloor ?? 0
274
+ const posterior: Record<string, number> = {}
275
+
276
+ for (const [cls, prob] of Object.entries(prediction.probs)) {
277
+ if (cls !== "OTHER" && prob >= floor) {
278
+ posterior[cls] = prob
279
+ }
280
+ }
281
+
282
+ // The argmax always survives (it is ≥ every other marginal; if even it fell below the floor the
283
+ // prediction would have abstained upstream) — but guard anyway so the posterior is never empty.
284
+ if (Object.keys(posterior).length === 0) {
285
+ posterior[prediction.country] = prediction.confidence
286
+ }
287
+
288
+ return posterior
289
+ }
290
+
291
+ /** Load a coarse-placer from a JSON metadata file + a sibling `.weights.bin` (Float32). */
292
+ export async function loadCoarsePlacer(
293
+ metaJson: { classes: string[]; featureDim: number; temperature: number; bias: number[] },
294
+ weights: Float32Array,
295
+ opts?: CoarsePlacerOpts
296
+ ): Promise<CoarsePlacer> {
297
+ return new CoarsePlacer({ ...metaJson, weights }, opts)
298
+ }
299
+
300
+ export { COARSE_CLASSES, FEATURE_DIM, featurize }