@mailwoman/core 7.1.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 (149) 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/out/layers/index.d.ts +12 -0
  67. package/out/layers/index.d.ts.map +1 -0
  68. package/out/layers/index.js +12 -0
  69. package/out/layers/index.js.map +1 -0
  70. package/out/layers/manifest.d.ts +64 -0
  71. package/out/layers/manifest.d.ts.map +1 -0
  72. package/out/layers/manifest.js +102 -0
  73. package/out/layers/manifest.js.map +1 -0
  74. package/out/layers/schema.d.ts +72 -0
  75. package/out/layers/schema.d.ts.map +1 -0
  76. package/out/layers/schema.js +61 -0
  77. package/out/layers/schema.js.map +1 -0
  78. package/out/pipeline/index.d.ts +1 -1
  79. package/out/pipeline/index.d.ts.map +1 -1
  80. package/out/pipeline/runtime-pipeline.d.ts.map +1 -1
  81. package/out/pipeline/runtime-pipeline.js +27 -0
  82. package/out/pipeline/runtime-pipeline.js.map +1 -1
  83. package/out/pipeline/types.d.ts +74 -4
  84. package/out/pipeline/types.d.ts.map +1 -1
  85. package/out/pipeline/types.js.map +1 -1
  86. package/package.json +21 -21
  87. package/pipeline/index.ts +46 -0
  88. package/pipeline/reconcile-lookups.ts +108 -0
  89. package/pipeline/reconcile.ts +542 -0
  90. package/pipeline/runtime-pipeline.ts +732 -0
  91. package/pipeline/span-logit-aggregation.ts +151 -0
  92. package/pipeline/span-proposer.ts +587 -0
  93. package/pipeline/types.ts +348 -0
  94. package/policy/defaults.ts +35 -0
  95. package/policy/index.ts +10 -0
  96. package/policy/policy.ts +60 -0
  97. package/policy/proposal-collection.ts +64 -0
  98. package/policy/registry.ts +149 -0
  99. package/resolver/index.ts +29 -0
  100. package/resolver/types.ts +584 -0
  101. package/resources/LocaleIndex.ts +124 -0
  102. package/resources/ResourceMapCache.ts +126 -0
  103. package/resources/collections.ts +93 -0
  104. package/resources/debugging.ts +19 -0
  105. package/resources/git.ts +54 -0
  106. package/resources/index.ts +17 -0
  107. package/resources/languages/index.ts +49 -0
  108. package/resources/languages/types.gen.ts +1368 -0
  109. package/resources/libaddressinput.ts +105 -0
  110. package/resources/libpostal.ts +182 -0
  111. package/resources/locale.ts +23 -0
  112. package/resources/set.ts +179 -0
  113. package/resources/whosonfirst/DataSourceCache.ts +72 -0
  114. package/resources/whosonfirst/PlacetypeDataSource.ts +199 -0
  115. package/resources/whosonfirst/index.ts +10 -0
  116. package/resources/whosonfirst/loader.ts +157 -0
  117. package/resources/whosonfirst/placetypes/Placetype.ts +438 -0
  118. package/resources/whosonfirst/placetypes/admin.ts +173 -0
  119. package/resources/whosonfirst/placetypes/definition.ts +135 -0
  120. package/resources/whosonfirst/placetypes/graph.ts +0 -0
  121. package/resources/whosonfirst/placetypes/index.ts +12 -0
  122. package/resources/whosonfirst/placetypes/mermaid.ts +168 -0
  123. package/resources/whosonfirst/placetypes/tree.ts +46 -0
  124. package/routing/index.ts +208 -0
  125. package/scripting/index.ts +40 -0
  126. package/scripting/utils/index.ts +106 -0
  127. package/tokenization/Graph.ts +50 -0
  128. package/tokenization/Span.ts +297 -0
  129. package/tokenization/index.ts +9 -0
  130. package/tokenization/normalizer.ts +123 -0
  131. package/tools/download-libpostal-resources.ts +98 -0
  132. package/tools/download-ssl-address.ts +99 -0
  133. package/tools/generate-language-types.ts +194 -0
  134. package/tools/index.ts +13 -0
  135. package/types/Classification.ts +211 -0
  136. package/types/classifier.ts +133 -0
  137. package/types/component.ts +75 -0
  138. package/types/index.ts +10 -0
  139. package/types/mapping.ts +81 -0
  140. package/utils/data-root.ts +56 -0
  141. package/utils/hash.ts +27 -0
  142. package/utils/index.ts +14 -0
  143. package/utils/jsonl.ts +43 -0
  144. package/utils/python-json.ts +105 -0
  145. package/utils/python-random.ts +90 -0
  146. package/utils/repo.ts +118 -0
  147. package/utils/sealed-db.ts +85 -0
  148. package/utils/stats.ts +32 -0
  149. package/vitest.config.ts +53 -0
@@ -0,0 +1,187 @@
1
+ /**
2
+ * @copyright Sister Software
3
+ * @license AGPL-3.0
4
+ * @author Teffen Ellis, et al.
5
+ *
6
+ * Evaluate the #244 coarse-placer: in-distribution accuracy + per-class + calibration (ECE) on the
7
+ * held-out test split, AND the abstention story on the multi-script set — off-map scripts
8
+ * (Cyrillic, Arabic, Thai, …, none of them in the 11 trained countries) SHOULD draw low
9
+ * confidence → abstain, which is the "probably off my loaded map" behavior the design wants.
10
+ *
11
+ * Run: `mailwoman placer eval in-distribution [--model <dir>] [--abstain 0.5]`
12
+ */
13
+
14
+ import { readFileSync } from "node:fs"
15
+ import * as path from "node:path"
16
+
17
+ import { dataRootPath } from "../../utils/data-root.ts"
18
+ import { repoRootPath } from "../../utils/repo.ts"
19
+ import { CoarsePlacer, type CoarsePlacerMeta, type CoarsePrediction } from "../coarse-placer.ts"
20
+
21
+ interface TestRow {
22
+ raw: string
23
+ country: string
24
+ }
25
+
26
+ interface MultiScriptRow {
27
+ raw: string
28
+ country: string
29
+ script: string
30
+ }
31
+
32
+ /** Options for {@linkcode evalCoarsePlacer}. */
33
+ export interface EvalCoarsePlacerOptions {
34
+ /** Model artifact dir. Default `$MAILWOMAN_DATA_ROOT/coarse-placer/model`. */
35
+ model?: string
36
+ /** Abstention threshold. Default 0.5. */
37
+ abstain?: number
38
+ /** Dataset dir (`test.jsonl`). Default `<repo>/data/coarse-placer`. */
39
+ data?: string
40
+ }
41
+
42
+ /** Result of {@linkcode evalCoarsePlacer}. */
43
+ export interface EvalCoarsePlacerResult {
44
+ n: number
45
+ /** Overall accuracy in percent. */
46
+ accuracy: number
47
+ /** 10-bucket expected calibration error. */
48
+ ece: number
49
+ }
50
+
51
+ /** Coarse-placer in-distribution eval — see the module doc. Emits the report to stdout. */
52
+ export async function evalCoarsePlacer(options: EvalCoarsePlacerOptions = {}): Promise<EvalCoarsePlacerResult> {
53
+ const modelDir = options.model || dataRootPath("coarse-placer", "model")
54
+ const abstain = options.abstain ?? 0.5
55
+ const dataDir = options.data || repoRootPath("data", "coarse-placer")
56
+
57
+ const meta = JSON.parse(readFileSync(path.join(modelDir, "meta.json"), "utf8")) as CoarsePlacerMeta
58
+ const weights = new Float32Array(readFileSync(path.join(modelDir, "weights.bin")).buffer)
59
+ const placer = new CoarsePlacer({ ...meta, weights }, { abstainBelow: abstain })
60
+
61
+ // --- In-distribution test: accuracy + per-class + ECE ---
62
+ const test: TestRow[] = readFileSync(path.join(dataDir, "test.jsonl"), "utf8")
63
+ .trim()
64
+ .split("\n")
65
+ .map((l) => JSON.parse(l) as TestRow)
66
+ let correct = 0
67
+ const perClass: Record<string, { n: number; ok: number }> = {} // country → {n, ok}
68
+ const confusion: Record<string, Record<string, number>> = {} // true → {pred → n}
69
+ const buckets = Array.from({ length: 10 }, () => ({ n: 0, ok: 0 }))
70
+
71
+ // ECE deciles
72
+ for (const r of test) {
73
+ const p = placer.predict(r.raw)
74
+ const pred = p.country ?? "(abstain)"
75
+ ;(perClass[r.country] ??= { n: 0, ok: 0 }).n++
76
+ ;(confusion[r.country] ??= {})[pred] = ((confusion[r.country] ??= {})[pred] ?? 0) + 1
77
+ const hit = pred === r.country
78
+
79
+ if (hit) {
80
+ correct++
81
+ perClass[r.country]!.ok++
82
+ }
83
+ const b = Math.min(9, Math.floor(p.confidence * 10))
84
+ buckets[b]!.n++
85
+
86
+ if (hit) {
87
+ buckets[b]!.ok++
88
+ }
89
+ }
90
+ console.log(`coarse-placer eval — test n=${test.length}`)
91
+ console.log(` overall accuracy: ${((100 * correct) / test.length).toFixed(2)}% (abstain threshold ${abstain})`)
92
+ console.log(` per-class recall:`)
93
+
94
+ for (const c of meta.classes) {
95
+ const s = perClass[c]
96
+
97
+ if (s) {
98
+ console.log(` ${c}: ${((100 * s.ok) / s.n).toFixed(1)}% (n=${s.n})`)
99
+ }
100
+ }
101
+ let ece = 0
102
+ const N = test.length
103
+
104
+ for (let i = 0; i < 10; i++) {
105
+ const bk = buckets[i]!
106
+
107
+ if (bk.n === 0) continue
108
+ const acc = bk.ok / bk.n
109
+ const conf = (i + 0.5) / 10
110
+ ece += (bk.n / N) * Math.abs(acc - conf)
111
+ }
112
+ console.log(` ECE (10-bucket): ${ece.toFixed(4)}`)
113
+
114
+ // Top confusions
115
+ const confLines: string[] = []
116
+
117
+ for (const t of meta.classes) {
118
+ for (const [pred, n] of Object.entries(confusion[t] ?? {})) {
119
+ if (pred !== t && n >= 20) {
120
+ confLines.push(` ${t}→${pred}: ${n}`)
121
+ }
122
+ }
123
+ }
124
+
125
+ if (confLines.length) {
126
+ console.log(` notable confusions (≥20):`)
127
+ console.log(confLines.sort().join("\n"))
128
+ }
129
+
130
+ // --- Abstention on the multi-script set (off-map scripts should abstain) ---
131
+ const msPath = repoRootPath("data", "eval", "multi-script", "v0.5.0-a0.jsonl")
132
+
133
+ try {
134
+ const ms: MultiScriptRow[] = readFileSync(msPath, "utf8")
135
+ .trim()
136
+ .split("\n")
137
+ .map((l) => JSON.parse(l) as MultiScriptRow)
138
+ const TRAINED_SCRIPTS = new Set(["latin", "cjk"]) // the only scripts among the 11 trained countries
139
+ // With the OTHER class, an off-map input is HANDLED if it routes to OTHER or abstains — either way
140
+ // it's not a confident mis-placement onto a wrong country.
141
+ const handled = (p: CoarsePrediction): boolean => p.abstained || p.country === "OTHER"
142
+ let offN = 0,
143
+ offOk = 0,
144
+ missN = 0,
145
+ missOk = 0
146
+ const offMiss: string[] = []
147
+
148
+ for (const r of ms) {
149
+ const p = placer.predict(r.raw)
150
+ const offMap = !TRAINED_SCRIPTS.has(r.script)
151
+
152
+ if (offMap) {
153
+ offN++
154
+
155
+ if (handled(p)) {
156
+ offOk++
157
+ } else if (offMiss.length < 8) {
158
+ offMiss.push(
159
+ ` ${r.script}/${r.country} → ${p.country} @${p.confidence.toFixed(2)} «${r.raw.slice(0, 30)}»`
160
+ )
161
+ }
162
+ } else {
163
+ missN++
164
+
165
+ if (handled(p)) {
166
+ missOk++
167
+ } // a latin/cjk in-map input mis-routed to OTHER = a false abstention
168
+ }
169
+ }
170
+ console.log(`\nmulti-script off-map handling (n=${ms.length}):`)
171
+ console.log(
172
+ ` OFF-map scripts (Cyrillic/Arabic/Thai/…) routed to OTHER-or-abstain: ${offOk}/${offN} (${((100 * offOk) / Math.max(1, offN)).toFixed(0)}%) ← want HIGH`
173
+ )
174
+ console.log(
175
+ ` ON-map scripts (latin/cjk) wrongly OTHER-or-abstain: ${missOk}/${missN} (${((100 * missOk) / Math.max(1, missN)).toFixed(0)}%) ← want LOW`
176
+ )
177
+
178
+ if (offMiss.length) {
179
+ console.log(` off-map still mis-placed (the Latin-off-map residual — needs full off-map addresses, M3):`)
180
+ console.log(offMiss.join("\n"))
181
+ }
182
+ } catch (e) {
183
+ console.log(`\n(multi-script set not found at ${msPath}: ${(e as Error).message})`)
184
+ }
185
+
186
+ return { n: test.length, accuracy: (100 * correct) / test.length, ece }
187
+ }
@@ -0,0 +1,24 @@
1
+ /**
2
+ * @copyright Sister Software
3
+ * @license AGPL-3.0
4
+ * @author Teffen Ellis, et al.
5
+ *
6
+ * The coarse-placer tools' shared FNV-1a hash — the one home for the four byte-identical copies
7
+ * the 2026-07-09 dedupe survey found (`build-dataset` / `build-outlier-{oa,latin,exposure}`).
8
+ * Deterministic ordering + variant choice depends on this exact stream — datasets rebuilt with a
9
+ * different hash won't reproduce. Internal to the tools; deliberately NOT exported from
10
+ * `@mailwoman/core` (featurize.ts carries its own FNV, bucketed mod FEATURE_DIM — different
11
+ * contract, do not merge).
12
+ */
13
+
14
+ /** FNV-1a → uint32, for deterministic ordering/variant choice. */
15
+ export function hashFNV1a(s: string): number {
16
+ let h = 2166136261
17
+
18
+ for (let i = 0; i < s.length; i++) {
19
+ h ^= s.charCodeAt(i)
20
+ h = Math.imul(h, 16777619)
21
+ }
22
+
23
+ return h >>> 0
24
+ }
@@ -0,0 +1,23 @@
1
+ /**
2
+ * @copyright Sister Software
3
+ * @license AGPL-3.0
4
+ * @author Teffen Ellis, et al.
5
+ *
6
+ * Coarse-placer (#244) operator tools — the `run()`-style modules behind `mailwoman placer …`
7
+ * commands (see the 2026-07-09 scripts→Pastel spec). No argv, no `process.exit`: commands own
8
+ * parsing, rendering, and exit codes. Heavy deps that are core devDependencies
9
+ * (`@duckdb/node-api`, `@mailwoman/codex`) are lazy-imported inside their entry fns. `fnv-hash.ts`
10
+ * is deliberately NOT re-exported — it's internal to the dataset builders.
11
+ */
12
+
13
+ export * from "./build-dataset.ts"
14
+ export * from "./build-outlier-exposure.ts"
15
+ export * from "./build-outlier-latin.ts"
16
+ export * from "./build-outlier-oa.ts"
17
+ export * from "./eval.ts"
18
+ export * from "./eval-latin-offmap.ts"
19
+ export * from "./eval-openset.ts"
20
+ export * from "./eval-quant-compare.ts"
21
+ export * from "./probe-frontier.ts"
22
+ export * from "./quantize.ts"
23
+ export * from "./train.ts"
@@ -0,0 +1,216 @@
1
+ /**
2
+ * @copyright Sister Software
3
+ * @license AGPL-3.0
4
+ * @author Teffen Ellis, et al.
5
+ *
6
+ * #822 PLACER-FRONTIER PROBE (night 2026-06-28, Phase A) — for the placer-recoverable countries (a
7
+ * country hint resolves them, so growing the placer captures the win), measure whether the DEPLOYED
8
+ * coarse placer can actually emit that country. Per query (`<City>, <Country>` from cities15000):
9
+ *
10
+ * - `in_class_set` — is the true country even in the placer's class set? (a class the model can't
11
+ * represent can't be recovered by any threshold change — that's a DATA gap)
12
+ * - `top1_correct` — did the placer's argmax land on the true country?
13
+ * - `prob_1` — the calibrated top-class confidence (vs `HARD_PLACE_COUNTRY_MIN_CONF` = 0.9)
14
+ *
15
+ * Branch (plan Phase 2): `in_class_set` false >5% → DATA GAP, defer to a class-set-widening retrain.
16
+ * in-set + top1>80% + median prob_1 < 0.9 → UNDER-CONFIDENT, M2 mass-rule fix. in-set + top1<80% →
17
+ * low-quality signal, defer. The probe is a LINEAR model (no ONNX), so it is heat-safe.
18
+ *
19
+ * Run: `mailwoman placer probe-frontier [--model <dir>] [--n 2000] [--out <md>]`
20
+ */
21
+
22
+ import { readFileSync, writeFileSync } from "node:fs"
23
+
24
+ import { dataRootPath } from "../../utils/data-root.ts"
25
+ import { corePackagePath } from "../../utils/repo.ts"
26
+ import { median } from "../../utils/stats.ts"
27
+ import { CoarsePlacer, type CoarsePlacerMeta } from "../coarse-placer.ts"
28
+
29
+ /** Options for {@linkcode probeFrontier}. */
30
+ export interface ProbeFrontierOptions {
31
+ /**
32
+ * Model artifact dir. Default: the DEPLOYED placer bundled in `@mailwoman/core` (`core/data/coarse-placer`), NOT the
33
+ * `$MAILWOMAN_DATA_ROOT` training output — match the runtime.
34
+ */
35
+ model?: string
36
+ /** Queries sampled (shortest first). Default 2000. */
37
+ n?: number
38
+ /** Also write the markdown report here. */
39
+ out?: string
40
+ }
41
+
42
+ /** Result of {@linkcode probeFrontier}. */
43
+ export interface ProbeFrontierResult {
44
+ /** The Phase-2 branch verdict line. */
45
+ branch: string
46
+ n: number
47
+ markdown: string
48
+ }
49
+
50
+ const HARD_PLACE_COUNTRY_MIN_CONF = 0.9 // mirrors core/pipeline/runtime-pipeline.ts
51
+
52
+ // The placer-recoverable tranche from the 2026-06-26 frontier diagnostic (a country hint resolves them).
53
+ const RECOVERABLE = [
54
+ "AO",
55
+ "AR",
56
+ "BO",
57
+ "CN",
58
+ "EC",
59
+ "BH",
60
+ "LK",
61
+ "MY",
62
+ "RS",
63
+ "SK",
64
+ "TH",
65
+ "UA",
66
+ "AU",
67
+ "BY",
68
+ "CA",
69
+ "CR",
70
+ "EG",
71
+ "IE",
72
+ "MA",
73
+ "RU",
74
+ "SG",
75
+ "ZA",
76
+ "AE",
77
+ "BD",
78
+ "BG",
79
+ "CI",
80
+ "CO",
81
+ "CU",
82
+ "DO",
83
+ "DZ",
84
+ "LV",
85
+ "NZ",
86
+ "SA",
87
+ "TR",
88
+ "UY",
89
+ "VE",
90
+ ]
91
+
92
+ /** Coarse-placer frontier probe (#822) — see the module doc. Emits the report head to stdout. */
93
+ export async function probeFrontier(
94
+ options: ProbeFrontierOptions = {},
95
+ report?: (line: string) => void
96
+ ): Promise<ProbeFrontierResult> {
97
+ const modelDir = options.model || corePackagePath("data", "coarse-placer")
98
+ const maxN = options.n ?? 2000
99
+
100
+ // `@mailwoman/codex` is a devDependency of core (operator tooling) — lazy-imported inside the fn.
101
+ const { ISO2_TO_NAME } = await import("@mailwoman/codex/country")
102
+
103
+ const meta = JSON.parse(readFileSync(`${modelDir}/meta.json`, "utf8")) as CoarsePlacerMeta
104
+ // The deployed bundle is int8-per-row quantized — fromArtifactDir dequantizes via meta.scales.
105
+ const placer = await CoarsePlacer.fromArtifactDir(modelDir, { abstainBelow: 0 })
106
+ const classSet = new Set(meta.classes)
107
+
108
+ // Build `<City>, <Country>` queries from cities15000 for the recoverable set, shortest first.
109
+ const CITIES = dataRootPath("geonames", "cities15000.txt")
110
+ const want = new Set(RECOVERABLE)
111
+ interface Q {
112
+ q: string
113
+ cc: string
114
+ }
115
+ const all: Q[] = []
116
+
117
+ for (const line of readFileSync(CITIES, "utf8").split("\n")) {
118
+ if (!line) continue
119
+ const f = line.split("\t")
120
+ const name = f[1]
121
+ const cc = f[8]
122
+
123
+ if (!name || !cc || !want.has(cc)) continue
124
+ const country = ISO2_TO_NAME.get(cc)
125
+
126
+ if (!country) continue
127
+ all.push({ q: `${name}, ${country}`, cc })
128
+ }
129
+ all.sort((a, b) => a.q.length - b.q.length)
130
+ const queries = all.slice(0, maxN)
131
+
132
+ interface Stat {
133
+ cc: string
134
+ n: number
135
+ inClass: number
136
+ top1Correct: number
137
+ probs: number[]
138
+ }
139
+ const per = new Map<string, Stat>()
140
+
141
+ for (const { q, cc } of queries) {
142
+ const p = placer.predict(q)
143
+ const s = per.get(cc) ?? { cc, n: 0, inClass: 0, top1Correct: 0, probs: [] }
144
+ s.n++
145
+
146
+ if (classSet.has(cc)) {
147
+ s.inClass++
148
+ }
149
+
150
+ if (p.country === cc) {
151
+ s.top1Correct++
152
+ s.probs.push(p.confidence)
153
+ }
154
+ per.set(cc, s)
155
+ }
156
+
157
+ const rows = [...per.values()].sort((a, b) => a.cc.localeCompare(b.cc))
158
+ const N = queries.length
159
+ const inClass = rows.reduce((t, r) => t + r.inClass, 0)
160
+ const top1 = rows.reduce((t, r) => t + r.top1Correct, 0)
161
+ const inClassCorrectProbs = rows.flatMap((r) => r.probs)
162
+ // NOTE(phase4b): `pct` stays local — core's formatPercent has no Math.max(1, b) zero-denominator
163
+ // guard (it renders "—") and appends its own "%", where this report composes the sign itself.
164
+ const pct = (a: number, b: number): string => ((100 * a) / Math.max(1, b)).toFixed(1)
165
+ const inClassFalseRate = 1 - inClass / N
166
+ const top1OfInClass = rows.reduce((t, r) => t + (classSet.has(r.cc) ? r.top1Correct : 0), 0)
167
+ const inClassN = rows.reduce((t, r) => t + r.inClass, 0)
168
+
169
+ const branch =
170
+ inClassFalseRate > 0.05
171
+ ? "DATA GAP — class set does not cover the recoverable tranche; defer to a class-set-widening retrain."
172
+ : top1OfInClass / Math.max(1, inClassN) < 0.8
173
+ ? "LOW-QUALITY SIGNAL — in-set top1 < 80%; lowering the threshold would hard-filter wrong guesses. Defer."
174
+ : (median(inClassCorrectProbs) ?? 0) < HARD_PLACE_COUNTRY_MIN_CONF
175
+ ? "UNDER-CONFIDENT — in-set + top1 ≥ 80% but median prob_1 < 0.9; the M2 mass rule is the CPU fix (default-off)."
176
+ : "NO CHANGE — in-set, confident, correct; the recoverable countries already clear the bar."
177
+
178
+ const L: string[] = []
179
+ L.push("# #822 placer-frontier probe — can the deployed placer emit the recoverable tranche?")
180
+ L.push("")
181
+ L.push(`_Model: \`${modelDir}\` (${meta.classes.length} classes). ${N} \`City, Country\` queries (shortest`)
182
+ L.push(
183
+ `first) across ${RECOVERABLE.length} placer-recoverable countries. prob_1 vs HARD_PLACE_COUNTRY_MIN_CONF = 0.9._`
184
+ )
185
+ L.push("")
186
+ L.push(
187
+ `- in_class_set: **${pct(inClass, N)}%** (${inClass}/${N}) — false rate **${(100 * inClassFalseRate).toFixed(1)}%**`
188
+ )
189
+ L.push(`- top1_correct (all): **${pct(top1, N)}%** (${top1}/${N})`)
190
+ L.push(`- top1_correct (in-set only): **${pct(top1OfInClass, inClassN)}%** (${top1OfInClass}/${inClassN})`)
191
+ L.push(`- median prob_1 (in-set correct): **${(median(inClassCorrectProbs) ?? 0).toFixed(3)}**`)
192
+ L.push("")
193
+ L.push(`## Branch: ${branch}`)
194
+ L.push("")
195
+ L.push(`Classes (${meta.classes.length}): \`${meta.classes.join(" ")}\``)
196
+ L.push("")
197
+ L.push("| Country | ISO2 | in-class | n | top1-correct | median prob_1 |")
198
+ L.push("| --- | --- | :---: | ---: | ---: | ---: |")
199
+
200
+ for (const r of rows) {
201
+ L.push(
202
+ `| ${ISO2_TO_NAME.get(r.cc) ?? r.cc} | ${r.cc} | ${classSet.has(r.cc) ? "✓" : "—"} | ${r.n} | ${pct(r.top1Correct, r.n)}% | ${(median(r.probs) ?? 0).toFixed(2)} |`
203
+ )
204
+ }
205
+
206
+ const md = L.join("\n")
207
+ console.log(md.split("\n").slice(0, 12).join("\n"))
208
+ console.log("…")
209
+
210
+ if (options.out) {
211
+ writeFileSync(options.out, `${md}\n`)
212
+ report?.(`[probe] wrote ${options.out}`)
213
+ }
214
+
215
+ return { branch, n: N, markdown: md }
216
+ }
@@ -0,0 +1,116 @@
1
+ /**
2
+ * @copyright Sister Software
3
+ * @license AGPL-3.0
4
+ * @author Teffen Ellis, et al.
5
+ *
6
+ * Int8-quantize the #244 coarse-placer (milestone 3). The placer is a linear classifier, so the
7
+ * only weight is a dense [class][feature] fp32 matrix (12×65536 = 3.0 MB). Per-CLASS symmetric
8
+ * int8 quantization — `scale[c] = max(|W[c]|) / 127`, `q = round(W / scale)` clamped to [-127,
9
+ * 127] — shrinks it to 0.75 MB (4×) while preserving the linear math exactly up to rounding (the
10
+ * logit is `bias[c] + scale[c] * Σ int8`, dequantized on load by `CoarsePlacer.fromArtifactDir`).
11
+ * Per-class scales matter because class weight magnitudes differ (OTHER's outlier-exposure rows
12
+ * push bigger weights than the in-map countries).
13
+ *
14
+ * Verify the accuracy cost with `mailwoman placer eval quant-compare` (target: within ~1pp).
15
+ *
16
+ * Run: `mailwoman placer quantize [--in <fp32 dir>] [--out <int8 dir>]`
17
+ */
18
+
19
+ import { mkdirSync, readFileSync, writeFileSync } from "node:fs"
20
+ import * as path from "node:path"
21
+
22
+ import { dataRootPath } from "../../utils/data-root.ts"
23
+ import type { CoarsePlacerMeta } from "../coarse-placer.ts"
24
+
25
+ /** Options for {@linkcode quantizeCoarsePlacer}. */
26
+ export interface QuantizeCoarsePlacerOptions {
27
+ /** Fp32 artifact dir. Default `$MAILWOMAN_DATA_ROOT/coarse-placer/model`. */
28
+ in?: string
29
+ /** Int8 output dir. Default `$MAILWOMAN_DATA_ROOT/coarse-placer/model-int8`. */
30
+ out?: string
31
+ }
32
+
33
+ /** Result of {@linkcode quantizeCoarsePlacer}. */
34
+ export interface QuantizeCoarsePlacerResult {
35
+ outDir: string
36
+ fp32Bytes: number
37
+ int8Bytes: number
38
+ maxAbsErr: number
39
+ rmse: number
40
+ }
41
+
42
+ /** Coarse-placer int8 quantizer — see the module doc. */
43
+ export async function quantizeCoarsePlacer(
44
+ options: QuantizeCoarsePlacerOptions = {},
45
+ report?: (line: string) => void
46
+ ): Promise<QuantizeCoarsePlacerResult> {
47
+ const inDir = options.in || dataRootPath("coarse-placer", "model")
48
+ const outDir = options.out || dataRootPath("coarse-placer", "model-int8")
49
+
50
+ const meta = JSON.parse(readFileSync(path.join(inDir, "meta.json"), "utf8")) as CoarsePlacerMeta
51
+ const buf = readFileSync(path.join(inDir, "weights.bin"))
52
+ const ab = buf.buffer.slice(buf.byteOffset, buf.byteOffset + buf.byteLength)
53
+ const w = new Float32Array(ab)
54
+ const C = meta.classes.length
55
+ const dim = meta.featureDim
56
+
57
+ if (w.length !== C * dim) throw new Error(`weights length ${w.length} ≠ classes×dim ${C * dim}`)
58
+
59
+ const int8 = new Int8Array(C * dim)
60
+ const scales: number[] = []
61
+ let maxAbsErr = 0
62
+ let sumSqErr = 0
63
+
64
+ for (let c = 0; c < C; c++) {
65
+ const base = c * dim
66
+ let maxAbs = 0
67
+
68
+ for (let i = 0; i < dim; i++) {
69
+ const a = Math.abs(w[base + i]!)
70
+
71
+ if (a > maxAbs) {
72
+ maxAbs = a
73
+ }
74
+ }
75
+ const scale = maxAbs / 127 || 1 // all-zero row → scale 1 (q stays 0)
76
+ scales.push(scale)
77
+
78
+ for (let i = 0; i < dim; i++) {
79
+ let q = Math.round(w[base + i]! / scale)
80
+
81
+ if (q > 127) {
82
+ q = 127
83
+ } else if (q < -127) {
84
+ q = -127
85
+ } // symmetric range; avoid -128 so |q|≤127
86
+ int8[base + i] = q
87
+ const err = Math.abs(q * scale - w[base + i]!)
88
+
89
+ if (err > maxAbsErr) {
90
+ maxAbsErr = err
91
+ }
92
+ sumSqErr += err * err
93
+ }
94
+ }
95
+
96
+ mkdirSync(outDir, { recursive: true })
97
+ writeFileSync(path.join(outDir, "weights.bin"), Buffer.from(int8.buffer))
98
+ writeFileSync(
99
+ path.join(outDir, "meta.json"),
100
+ JSON.stringify({ ...meta, quantization: "int8-per-row", scales }, null, 2)
101
+ )
102
+
103
+ const fp32Bytes = w.length * 4
104
+ const int8Bytes = int8.length
105
+ const rmse = Math.sqrt(sumSqErr / w.length)
106
+ report?.(`coarse-placer int8 quantization`)
107
+ report?.(` in: ${inDir}`)
108
+ report?.(` out: ${outDir}`)
109
+ report?.(
110
+ ` weights: ${(fp32Bytes / 1e6).toFixed(2)} MB fp32 → ${(int8Bytes / 1e6).toFixed(2)} MB int8 (${(fp32Bytes / int8Bytes).toFixed(1)}×)`
111
+ )
112
+ report?.(` per-class scales: [${scales.map((s) => s.toExponential(2)).join(", ")}]`)
113
+ report?.(` weight reconstruction error: max ${maxAbsErr.toExponential(2)}, rmse ${rmse.toExponential(2)}`)
114
+
115
+ return { outDir, fp32Bytes, int8Bytes, maxAbsErr, rmse }
116
+ }