@hviana/sema 0.1.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 (110) hide show
  1. package/AGENTS.md +470 -0
  2. package/AUTHORS.md +12 -0
  3. package/COMMERCIAL-LICENSE.md +19 -0
  4. package/CONTRIBUTING.md +15 -0
  5. package/HOW_IT_WORKS.md +4210 -0
  6. package/LICENSE.md +117 -0
  7. package/README.md +290 -0
  8. package/TRADEMARKS.md +19 -0
  9. package/example/demo.ts +46 -0
  10. package/example/train_base.ts +2675 -0
  11. package/index.html +893 -0
  12. package/package.json +25 -0
  13. package/src/alphabet.ts +34 -0
  14. package/src/alu/README.md +332 -0
  15. package/src/alu/src/alu.ts +541 -0
  16. package/src/alu/src/expr.ts +339 -0
  17. package/src/alu/src/index.ts +115 -0
  18. package/src/alu/src/kernel-arith.ts +377 -0
  19. package/src/alu/src/kernel-bits.ts +199 -0
  20. package/src/alu/src/kernel-logic.ts +102 -0
  21. package/src/alu/src/kernel-nd.ts +235 -0
  22. package/src/alu/src/kernel-numeric.ts +466 -0
  23. package/src/alu/src/operation.ts +344 -0
  24. package/src/alu/src/parser.ts +574 -0
  25. package/src/alu/src/resonance.ts +161 -0
  26. package/src/alu/src/text.ts +83 -0
  27. package/src/alu/src/value.ts +327 -0
  28. package/src/alu/test/alu.test.ts +1004 -0
  29. package/src/bytes.ts +62 -0
  30. package/src/config.ts +227 -0
  31. package/src/derive/README.md +295 -0
  32. package/src/derive/src/deduction.ts +263 -0
  33. package/src/derive/src/index.ts +24 -0
  34. package/src/derive/src/priority-queue.ts +70 -0
  35. package/src/derive/src/rewrite.ts +127 -0
  36. package/src/derive/src/trie.ts +242 -0
  37. package/src/derive/test/derive.test.ts +137 -0
  38. package/src/extension.ts +42 -0
  39. package/src/geometry.ts +511 -0
  40. package/src/index.ts +38 -0
  41. package/src/ingest-cache.ts +224 -0
  42. package/src/mind/articulation.ts +137 -0
  43. package/src/mind/attention.ts +1061 -0
  44. package/src/mind/canonical.ts +107 -0
  45. package/src/mind/graph-search.ts +1100 -0
  46. package/src/mind/index.ts +18 -0
  47. package/src/mind/junction.ts +347 -0
  48. package/src/mind/learning.ts +246 -0
  49. package/src/mind/match.ts +507 -0
  50. package/src/mind/mechanisms/alu.ts +33 -0
  51. package/src/mind/mechanisms/cast.ts +568 -0
  52. package/src/mind/mechanisms/confluence.ts +268 -0
  53. package/src/mind/mechanisms/cover.ts +248 -0
  54. package/src/mind/mechanisms/extraction.ts +422 -0
  55. package/src/mind/mechanisms/recall.ts +241 -0
  56. package/src/mind/mind.ts +483 -0
  57. package/src/mind/pipeline-mechanism.ts +326 -0
  58. package/src/mind/pipeline.ts +300 -0
  59. package/src/mind/primitives.ts +201 -0
  60. package/src/mind/rationale.ts +275 -0
  61. package/src/mind/reasoning.ts +198 -0
  62. package/src/mind/recognition.ts +234 -0
  63. package/src/mind/resonance.ts +0 -0
  64. package/src/mind/trace.ts +108 -0
  65. package/src/mind/traverse.ts +556 -0
  66. package/src/mind/types.ts +281 -0
  67. package/src/rabitq-hnsw/README.md +303 -0
  68. package/src/rabitq-hnsw/src/database.ts +492 -0
  69. package/src/rabitq-hnsw/src/heap.ts +90 -0
  70. package/src/rabitq-hnsw/src/hnsw.ts +514 -0
  71. package/src/rabitq-hnsw/src/index.ts +15 -0
  72. package/src/rabitq-hnsw/src/prng.ts +39 -0
  73. package/src/rabitq-hnsw/src/rabitq.ts +308 -0
  74. package/src/rabitq-hnsw/src/store.ts +994 -0
  75. package/src/rabitq-hnsw/test/hnsw.test.ts +1213 -0
  76. package/src/store-sqlite.ts +928 -0
  77. package/src/store.ts +2148 -0
  78. package/src/vec.ts +124 -0
  79. package/test/00-extract.test.mjs +151 -0
  80. package/test/01-floor.test.mjs +20 -0
  81. package/test/02-roundtrip.test.mjs +83 -0
  82. package/test/03-recall.test.mjs +98 -0
  83. package/test/04-think.test.mjs +627 -0
  84. package/test/05-concepts.test.mjs +84 -0
  85. package/test/08-storage.test.mjs +948 -0
  86. package/test/09-edges.test.mjs +65 -0
  87. package/test/11-universality.test.mjs +180 -0
  88. package/test/13-conversation.test.mjs +228 -0
  89. package/test/14-scaling.test.mjs +503 -0
  90. package/test/15-decomposition-gap.test.mjs +0 -0
  91. package/test/16-bridge.test.mjs +250 -0
  92. package/test/17-intelligence.test.mjs +240 -0
  93. package/test/18-alu.test.mjs +209 -0
  94. package/test/19-nd.test.mjs +254 -0
  95. package/test/20-stability.test.mjs +489 -0
  96. package/test/21-partial.test.mjs +158 -0
  97. package/test/22-multihop.test.mjs +130 -0
  98. package/test/23-rationale.test.mjs +316 -0
  99. package/test/24-generalization.test.mjs +416 -0
  100. package/test/25-embedding.test.mjs +75 -0
  101. package/test/26-cooperative.test.mjs +89 -0
  102. package/test/27-saturation-drop.test.mjs +637 -0
  103. package/test/28-unknowable.test.mjs +88 -0
  104. package/test/29-counterfactual.test.mjs +476 -0
  105. package/test/30-conflict-resolution.test.mjs +166 -0
  106. package/test/31-audit.test.mjs +288 -0
  107. package/test/32-confluence.test.mjs +173 -0
  108. package/test/33-multi-candidate.test.mjs +222 -0
  109. package/test/34-cross-region.test.mjs +252 -0
  110. package/tsconfig.json +16 -0
@@ -0,0 +1,2675 @@
1
+ //This file uses the Google SMOL dataset, made available under the CC BY 4.0 license.
2
+ //This file uses Aya and oasst2 datasets, made available under the apache-2.0 license.
3
+ //This file uses MuskumPillerum/General-Knowledge dataset, made available under the MIT license.
4
+
5
+ //This file is a more appropriate training example for Sema.
6
+ //Sema does not learn through repetition;
7
+ //it does not require a massive database.
8
+ //It needs fundamental datasets that teach basic cognitive concepts such as conversation, logic, relationships, behaviors and feelings.
9
+ //The focus is on covering fundamental patterns, not repetition.
10
+ //Tip: ontology-based adapted training datasets could be an interesting path.
11
+
12
+ // train_base.ts — streaming trainer for the SmolSent + Aya + oasst2 +
13
+ // General-Knowledge base.
14
+ //
15
+ // Training IS deposition: every source datum is translated into SEMA facts (or,
16
+ // for genuine dialogue, accumulated-context episodes), then stored in one pass.
17
+ // There are no gradients or epochs, and there is no LLM in the loop — the only
18
+ // "model" is the SEMA store itself. The ingestion structures, filtering,
19
+ // checkpointing, cache, and resume model are unchanged from the original LLM-
20
+ // base trainer; only corpus discovery and the row adapters are source-specific.
21
+ //
22
+ // Every source here is commercially licensable (cc-by-4.0 / apache-2.0).
23
+ //
24
+ // The curriculum runs in four stages, into ONE store:
25
+ // 1. SmolSent (google/smol) — sentence-level TRANSLATION pairs across 100+
26
+ // low-resource languages; see §6c. Each pair is "two names for one meaning"
27
+ // → bidirectional translation FACTS, the cross-language concept SEMA fuses
28
+ // (cf. test/05-concepts.test.mjs).
29
+ // 2. Aya Dataset — ~204k human prompt→completion pairs, 70+ languages; see §6d
30
+ // → one (question → answer) FACT each.
31
+ // 3. oasst2 — MULTI-TURN human↔assistant conversation trees; see §6e → the
32
+ // accumulated-context walk (single-turn trees are skipped, by design).
33
+ // 4. General-Knowledge (MuskumPillerum) — ~37.6k {Question, Answer} pairs; see
34
+ // §6f → one (question → answer) FACT each.
35
+ // Each stage runs only after the previous one finishes, and is recorded in the
36
+ // same completed-files set, so a single store resumes the whole curriculum.
37
+ //
38
+ // Every source is DOWNLOADED as a file and streamed from disk (never paged
39
+ // row-by-row over an HTTP API — that was slow and rate-limited): SmolSent as
40
+ // per-pair JSONL, oasst2 as a gzipped JSONL, General-Knowledge as a JSON array,
41
+ // and Aya as Snappy-Parquet read row-group by row-group with hyparquet (the one
42
+ // case the web platform can't decode alone). Resume is per-file: a fully-
43
+ // consumed file is marked complete; an interrupted one re-reads from the top
44
+ // (re-deposition is idempotent). LOCAL_PATH may hold pre-downloaded files.
45
+ //
46
+ // REPRESENTATION POLICY (one datum → one form; no replication):
47
+ // • FACTS are the default. A datum that is a RELATION (translation pair,
48
+ // question → answer) is emitted as a (context → continuation) edge SEMA
49
+ // points at and, by example across the corpus, generalizes from (cf.
50
+ // example/demo.ts). SmolSent emits two facts (both directions); Aya one.
51
+ // • EXPERIENCES (bare statements) are used only when a fact is NOT possible —
52
+ // content with no natural relational split. (No current stage needs this;
53
+ // it stays available for plain-text corpora.)
54
+ // • CUMULATIVE CONTINUOUS CONTEXT is used only when truly necessary — genuine
55
+ // MULTI-TURN dialogue, where a turn follows from the whole conversation so
56
+ // far. Only oasst2 (§6e) uses it; the fact stages do NOT synthesize a multi-
57
+ // turn walk, which would just replicate the facts (repetition SEMA avoids).
58
+ //
59
+ // The store IS the model: memories, training metadata, and the config snapshot
60
+ // all live in {DB_PATH}.sqlite, so a run resumes from the store alone.
61
+ //
62
+ // Built on web standards. All I/O except the durable disk cache uses platform
63
+ // primitives — fetch, WHATWG ReadableStream/WritableStream/TransformStream,
64
+ // DecompressionStream ("gzip" for the oasst2 file), TextDecoderStream, Blob,
65
+ // AbortController. The sole third-party code is hyparquet (+ its Snappy codec),
66
+ // used only to read Aya's Parquet over a web-standard Blob byte source. Node's
67
+ // stdlib is touched only for the filesystem (the cache), which the web platform
68
+ // does not expose. Consistency guarantees:
69
+ // • Resume from the store alone — completed stage-units, example count,
70
+ // learned-content bytes, and processed-byte total are persisted in
71
+ // {DB_PATH}.sqlite and reloaded. API stages persist a page offset; the
72
+ // oasst2 download is atomic (see below).
73
+ // • Atomic cache — a download streams to "<file>.part", is fsync'd, then
74
+ // renamed into place; a file at its final path is, by construction,
75
+ // complete, so an interrupted download can never be mistaken for a cached
76
+ // one.
77
+ // • Bounded cache — a download blocks under the MAX_CACHE_GB ceiling and the
78
+ // fully-processed file is deleted immediately.
79
+ // • Interruptible — Ctrl+C (SIGINT/SIGTERM) aborts in-flight network at once,
80
+ // stops at the next item boundary, writes a final checkpoint, and exits; an
81
+ // un-finished stage-unit is NOT marked complete, so resume re-reads it (re-
82
+ // deposition is idempotent). A second Ctrl+C, or a 60s watchdog, force-exits.
83
+ //
84
+ // Run:
85
+ // npx tsc && node dist/example/train_base.js
86
+ // MAX_MB=500 node dist/example/train_base.js
87
+ // CHECKPOINT_MB=250 node dist/example/train_base.js
88
+ // SMOLSENT_PAIRS=ha_en,zu_en node dist/example/train_base.js # a subset of pairs
89
+ // SMOLSENT=0 node dist/example/train_base.js # skip SmolSent stage
90
+ // AYA=0 node dist/example/train_base.js # skip Aya stage
91
+ // AYA_SPLIT=test node dist/example/train_base.js # small Aya slice
92
+ // OASST=0 node dist/example/train_base.js # skip oasst2 stage
93
+ // OASST_MIN_TURNS=6 node dist/example/train_base.js # deeper multi-turn only
94
+ // GENKNOW=0 node dist/example/train_base.js # skip General-Knowledge
95
+ // LOCAL_PATH=./base node dist/example/train_base.js # offline: *.jsonl/.parquet/.jsonl.gz/.json
96
+ // DB_PATH=./data/sema node dist/example/train_base.js
97
+
98
+ import { CachedIngest, Mind, SQliteStore, type Store } from "../src/index.js";
99
+ // One Node module — node:fs — and nothing else. Everything else (HTTP, byte
100
+ // streams, (de)compression, text decoding, cancellation) is a web standard:
101
+ // fetch, WHATWG ReadableStream/WritableStream/TransformStream,
102
+ // DecompressionStream, TextDecoderStream, Blob, AbortController. Reading a file
103
+ // goes through openAsBlob, which returns a web Blob (`.stream()` → web streams);
104
+ // writing a file is the single capability the web platform does not expose, so
105
+ // the download sink uses the synchronous fs descriptor calls below. The durable
106
+ // disk cache is therefore the sole, irreducible Node dependency.
107
+ import {
108
+ closeSync,
109
+ existsSync,
110
+ fsyncSync,
111
+ mkdirSync,
112
+ openAsBlob,
113
+ openSync,
114
+ readdirSync,
115
+ renameSync,
116
+ statSync,
117
+ unlinkSync,
118
+ writeSync,
119
+ } from "node:fs";
120
+ import { basename, join } from "node:path";
121
+ // The ONLY third-party dependencies, and only for the one source that ships
122
+ // exclusively as Snappy-compressed Parquet (Aya): hyparquet is a pure-JS,
123
+ // dependency-free Parquet reader driven over a web-standard Blob byte source;
124
+ // hyparquet-compressors supplies the Snappy codec. Every other source is plain
125
+ // JSONL / JSON / gzip and needs no library.
126
+ import { parquetMetadataAsync, parquetReadObjects } from "hyparquet";
127
+ import { compressors } from "hyparquet-compressors";
128
+
129
+ // ═══════════════════════════════════════════════════════════════════════
130
+ // §1 Configuration (all from the environment)
131
+ // ═══════════════════════════════════════════════════════════════════════
132
+
133
+ const env = (k: string, d: string) => process.env[k] ?? d;
134
+
135
+ // ── google/smol · SmolSent (the first training stage) ──
136
+ // SmolSent is Google's sentence-level translation set: ~863 human sentence pairs
137
+ // per language pair across 100+ low-resource languages, cc-by-4.0 (commercial-
138
+ // friendly). Each row is {sl, tl, src, trg, …} — a source sentence and its
139
+ // translation. A pair is "two names for one meaning", which is exactly the
140
+ // cross-language concept SEMA fuses (see test/05-concepts.test.mjs), so each row
141
+ // becomes FACTS that bind the two phrasings as one concept at recall time.
142
+ //
143
+ // The corpus ships as one plain JSONL file PER language pair under smolsent/ in
144
+ // the HF repo (e.g. smolsent/ha_en.jsonl). We DOWNLOAD each file and stream its
145
+ // lines — far faster and free of the rate-limiting that per-row API paging hit.
146
+ // The file list is discovered from the HF repo tree. SMOLSENT=0 disables the
147
+ // stage; SMOLSENT_PAIRS (comma-separated basenames without .jsonl, e.g.
148
+ // "ha_en,zu_en") restricts to a chosen subset.
149
+ const SMOLSENT = env("SMOLSENT", "1") !== "0";
150
+ const SMOLSENT_DATASET = env("SMOLSENT_DATASET", "google/smol");
151
+ const SMOLSENT_PAIRS = (process.env.SMOLSENT_PAIRS ?? "")
152
+ .split(",").map((s) => s.trim()).filter(Boolean);
153
+ // The resume id PREFIX for the SmolSent stage; one completed-files entry per
154
+ // file (e.g. "smolsent::ha_en.jsonl").
155
+ const SMOLSENT_ID = "smolsent";
156
+ // A SmolSent side longer than this is skipped (a sentence pair is short; a huge
157
+ // value is corruption, not a sentence).
158
+ const MAX_SMOLSENT_CHARS = Math.max(
159
+ 2_000,
160
+ Math.floor(Number(env("MAX_SMOLSENT_KB", "16")) * 1000) || 16_000,
161
+ );
162
+
163
+ const DB_PATH = env("DB_PATH", "sema"); // → {DB_PATH}.sqlite
164
+ const D = Number(env("D", "1024"));
165
+ const SEED = Number(env("SEED", "7"));
166
+ // Checkpoint cadence is measured in LEARNED CONTENT, not deposits: a snapshot
167
+ // every CHECKPOINT_MB megabytes of trained UTF-8 content (decimal MB, matching
168
+ // the bytes() helper). A floor of 1 MB: a zero/NaN value must not make every
169
+ // deposit checkpoint, nor silently disable checkpointing. The tail (a run that
170
+ // learns less than one interval, or the remainder past the last interval) is
171
+ // always saved by finish() at exit — a complete point.
172
+ const CHECKPOINT_BYTES = Math.max(
173
+ 1_000_000,
174
+ Math.floor(Number(env("CHECKPOINT_MB", "100")) * 1_000_000) || 100_000_000,
175
+ );
176
+ const LOCAL_PATH = env("LOCAL_PATH", ""); // train from a local dir of *.zip
177
+ const CACHE_DIR = env("CACHE_DIR", join(process.cwd(), "cache"));
178
+ const MAX_CACHE_BYTES = Number(env("MAX_CACHE_GB", "100")) * 1e9;
179
+ const PROGRESS_MS = Number(env("PROGRESS_MS", "250")); // panel refresh cadence
180
+ // Index maintenance at checkpoints: compact (remove garbage) then repair (fill
181
+ // gaps). Both are idempotent batch operations; INDEX_MAINTENANCE=0 disables.
182
+ const INDEX_MAINTENANCE = env("INDEX_MAINTENANCE", "1") !== "0";
183
+ const DOWNLOAD_TRIES = 5;
184
+ // In-progress downloads are written to a sibling "<dest>.part" and atomically
185
+ // renamed into place only after the bytes are fully flushed to disk. The cache
186
+ // invariant is therefore absolute: a file at its final path is, by definition,
187
+ // complete. Partial transfers (a crash, a kill, a dropped socket) leave only a
188
+ // .part file, which is swept at startup and never fed to the parser.
189
+ const PART_SUFFIX = ".part";
190
+
191
+ // A single process-wide abort signal. SIGINT/SIGTERM aborts it, which cancels
192
+ // every in-flight fetch immediately (instead of waiting out a slow socket), so
193
+ // Ctrl+C is responsive even mid-download. The deposit loop also polls it to
194
+ // stop cleanly at the next item boundary, leaving the store consistent.
195
+ const shutdown = new AbortController();
196
+ // The checkpoint recall is a best-effort diagnostic — it must NEVER stall
197
+ // training. We bound it so a slow/large store cannot freeze the deposit loop.
198
+ const INFER_TIMEOUT_MS = Number(env("INFER_TIMEOUT_MS", "15000"));
199
+
200
+ // A module-level hook so the low-level fetch retries can surface a rate-limit
201
+ // WAIT into the live progress log (set once main()'s panel exists). Without it a
202
+ // long 429 back-off would look like a silent hang. Throttled so a storm of 429s
203
+ // logs at most one "waiting" notice every few seconds.
204
+ let onThrottleWait: ((waitMs: number, label: string) => void) | null = null;
205
+ let lastThrottleLog = 0;
206
+
207
+ // Optional ceiling on how much LEARNED CONTENT to train, in megabytes (decimal,
208
+ // like CHECKPOINT_MB). Default Infinity = unbounded. The cap is checked against
209
+ // trainedContentBytes after each deposit, so a run stops at the first item that
210
+ // carries the running total to/past the ceiling (that item is still counted).
211
+ const MAX_MB = Number(env("MAX_MB", "Infinity"));
212
+ if (isNaN(MAX_MB) || MAX_MB < 0) {
213
+ process.stderr.write(
214
+ `fatal: MAX_MB must be a non-negative number or "Infinity"\n`,
215
+ );
216
+ process.exit(1);
217
+ }
218
+ const MAX_BYTES = MAX_MB * 1_000_000; // Infinity stays Infinity
219
+
220
+ // ── CohereLabs/aya_dataset (the second training stage, after SmolSent) ──
221
+ // The Aya Dataset is ~204k HUMAN-annotated prompt→completion pairs across 70+
222
+ // languages, each a clean (inputs → targets) fact in a named language. It ships
223
+ // ONLY as Snappy-compressed Parquet (no JSONL/CSV). We DOWNLOAD the one train
224
+ // Parquet file and read it row-group by row-group with `hyparquet` (a pure-JS,
225
+ // dependency-free Parquet reader) + `hyparquet-compressors` (Snappy) over a
226
+ // web-standard Blob byte source — no whole-file-in-memory load. AYA=0 disables
227
+ // the stage; AYA_URL overrides the Parquet source.
228
+ const AYA = env("AYA", "1") !== "0";
229
+ const AYA_URL = env(
230
+ "AYA_URL",
231
+ "https://huggingface.co/datasets/CohereLabs/aya_dataset/resolve/main/data/train-00000-of-00001.parquet",
232
+ );
233
+ // The resume id of the Aya stage, kept in the same completed-files set as the
234
+ // other stages, so one store records the whole curriculum.
235
+ const AYA_ID = "aya::dataset";
236
+ // A single Aya field this many chars or longer is skipped: inputs/targets range
237
+ // up to ~3.3M chars, and a multi-MB "pair" is documentation/dump noise, not a
238
+ // cognitive example.
239
+ const MAX_AYA_FIELD_CHARS = Math.max(
240
+ 10_000,
241
+ Math.floor(Number(env("MAX_AYA_FIELD_KB", "256")) * 1000) || 256_000,
242
+ );
243
+
244
+ // ── OpenAssistant/oasst2 (the fourth training stage, after Aya) ──
245
+ // oasst2 is a corpus of human↔assistant conversation TREES. Its richest, most
246
+ // stream-friendly artifact is "<date>_oasst2_ready.trees.jsonl.gz": one JSON
247
+ // conversation tree PER LINE, gzip-compressed (a web standard — Decompression
248
+ // Stream("gzip")). Each tree is {message_tree_id, prompt:{role,text,replies:[…]}}
249
+ // where `replies` nests recursively and a prompt can have several ranked
250
+ // assistant replies (rank 0 = best). We follow the best-ranked, non-deleted
251
+ // reply at each step to get ONE linear, strictly-alternating conversation per
252
+ // tree, then keep only the MULTI-TURN ones (≥ OASST_MIN_TURNS messages, i.e. at
253
+ // least two full user→assistant exchanges) — single Q→A trees are skipped, by
254
+ // design. OASST=0 disables the stage; OASST_URL overrides the source.
255
+ const OASST = env("OASST", "1") !== "0";
256
+ const OASST_URL = env(
257
+ "OASST_URL",
258
+ "https://huggingface.co/datasets/OpenAssistant/oasst2/resolve/main/2023-11-05_oasst2_ready.trees.jsonl.gz",
259
+ );
260
+ // The resume id of the oasst2 stage, in the same completed-files set as the
261
+ // other stages, so one store records the whole curriculum.
262
+ const OASST_ID = "oasst2::trees";
263
+ // Multi-turn threshold: a conversation must have at least this many turns to be
264
+ // trained (4 = user→assistant→user→assistant, the smallest real multi-turn).
265
+ const OASST_MIN_TURNS = Math.max(
266
+ 2,
267
+ Math.floor(Number(env("OASST_MIN_TURNS", "4"))) || 4,
268
+ );
269
+ // Skip a tree whose decoded JSON line exceeds this (a pathological record); the
270
+ // real maximum is far smaller, so this only guards against corruption.
271
+ const MAX_OASST_LINE_CHARS = Math.max(
272
+ 100_000,
273
+ Math.floor(Number(env("MAX_OASST_LINE_MB", "8")) * 1_000_000) || 8_000_000,
274
+ );
275
+
276
+ // ── MuskumPillerum/General-Knowledge (the fourth training stage, after oasst2) ──
277
+ // A ~37.6k-row general-knowledge Q&A set: each row is a single {Question, Answer}
278
+ // pair. A row is a pure RELATION (question → answer), so it becomes exactly ONE
279
+ // FACT, identical in shape to the Aya stage. It ships as a single JSON array
280
+ // file (output.json); we DOWNLOAD it and stream the array. GENKNOW=0 disables
281
+ // the stage; GENKNOW_URL overrides the source.
282
+ const GENKNOW = env("GENKNOW", "1") !== "0";
283
+ const GENKNOW_URL = env(
284
+ "GENKNOW_URL",
285
+ "https://huggingface.co/datasets/MuskumPillerum/General-Knowledge/resolve/main/output.json",
286
+ );
287
+ // The resume id of the General-Knowledge stage, in the same completed-files set
288
+ // as the other stages, so one store records the whole curriculum.
289
+ const GENKNOW_ID = "genknow::qa";
290
+ // A Question/Answer longer than this is skipped (answers run to a few hundred
291
+ // chars; this only guards against a corrupt/runaway field).
292
+ const MAX_GENKNOW_CHARS = Math.max(
293
+ 4_000,
294
+ Math.floor(Number(env("MAX_GENKNOW_KB", "64")) * 1000) || 64_000,
295
+ );
296
+
297
+ // ═══════════════════════════════════════════════════════════════════════
298
+ // §2 Terminal + formatting helpers
299
+ // ═══════════════════════════════════════════════════════════════════════
300
+
301
+ const CSI = "\x1b[";
302
+ const B = `${CSI}1m`, DIM = `${CSI}2m`, R = `${CSI}0m`;
303
+ const GREY = `${CSI}90m`, CYAN = `${CSI}36m`, GRN = `${CSI}32m`;
304
+ const YEL = `${CSI}33m`, RED = `${CSI}31m`;
305
+ const HIDE = `${CSI}?25l`, SHOW = `${CSI}?25h`;
306
+
307
+ /** Sleep `ms`, but wake early if the shutdown signal fires — so a long back-off
308
+ * (e.g. a rate-limit wait) never swallows Ctrl+C. Resolves either way. */
309
+ const waitMs = (ms: number): Promise<void> =>
310
+ new Promise((resolve) => {
311
+ if (shutdown.signal.aborted) return resolve();
312
+ // NOTE: the timer is deliberately NOT unref'd — an unref'd timer does not
313
+ // keep the event loop alive, so a pending wait (e.g. the pace between page
314
+ // requests, or a rate-limit back-off) would let Node exit early and the run
315
+ // would "do nothing and close". The listener lets a shutdown wake it early.
316
+ const t = setTimeout(done, ms);
317
+ function done() {
318
+ clearTimeout(t);
319
+ shutdown.signal.removeEventListener("abort", done);
320
+ resolve();
321
+ }
322
+ shutdown.signal.addEventListener("abort", done, { once: true });
323
+ });
324
+
325
+ /** Resolve `p`, but reject with a TimeoutError if it takes longer than `ms`.
326
+ * The underlying promise is left to settle on its own (we just stop waiting),
327
+ * so a slow black-box call can never wedge the caller. */
328
+ function withTimeout<T>(
329
+ p: Promise<T>,
330
+ ms: number,
331
+ label = "operation",
332
+ ): Promise<T> {
333
+ return new Promise<T>((resolve, reject) => {
334
+ const t = setTimeout(() => {
335
+ const e: Error & { name: string } = new Error(
336
+ `${label} timed out after ${ms}ms`,
337
+ );
338
+ e.name = "TimeoutError";
339
+ reject(e);
340
+ }, ms);
341
+ if (typeof (t as any).unref === "function") (t as any).unref();
342
+ p.then(
343
+ (v) => {
344
+ clearTimeout(t);
345
+ resolve(v);
346
+ },
347
+ (e) => {
348
+ clearTimeout(t);
349
+ reject(e);
350
+ },
351
+ );
352
+ });
353
+ }
354
+
355
+ /** Human-readable duration from seconds. */
356
+ function dur(seconds: number): string {
357
+ if (!isFinite(seconds) || seconds < 0) return "--";
358
+ const h = Math.floor(seconds / 3600);
359
+ const m = Math.floor((seconds % 3600) / 60);
360
+ const s = Math.floor(seconds % 60);
361
+ if (h > 0) return `${h}h ${m}m ${s}s`;
362
+ if (m > 0) return `${m}m ${s}s`;
363
+ return `${s}s`;
364
+ }
365
+
366
+ /** Human-readable byte size. */
367
+ function bytes(n: number): string {
368
+ if (!isFinite(n) || n < 0) return "--";
369
+ if (n < 1024) return `${n} B`;
370
+ if (n < 1e6) return `${(n / 1024).toFixed(1)} KB`;
371
+ if (n < 1e9) return `${(n / 1e6).toFixed(1)} MB`;
372
+ return `${(n / 1e9).toFixed(2)} GB`;
373
+ }
374
+
375
+ /** Short count: 1234567 → "1.23M". */
376
+ function num(n: number): string {
377
+ if (n >= 1e9) return `${(n / 1e9).toFixed(2)}B`;
378
+ if (n >= 1e6) return `${(n / 1e6).toFixed(2)}M`;
379
+ if (n >= 1e3) return `${(n / 1e3).toFixed(1)}K`;
380
+ return String(n);
381
+ }
382
+
383
+ const int = (n: number) => Math.round(n).toLocaleString("en-US");
384
+ const clamp01 = (f: number) => Math.max(0, Math.min(1, f));
385
+ const pct = (f: number) => `${(clamp01(f) * 100).toFixed(1)}%`;
386
+
387
+ /** A progress bar of width `w` filled to fraction `frac`. */
388
+ function bar(w: number, frac: number): string {
389
+ const filled = Math.round(clamp01(frac) * w);
390
+ return `${GRN}${"█".repeat(filled)}${GREY}${"░".repeat(w - filled)}${R}`;
391
+ }
392
+
393
+ /** Collapse whitespace and clip to `max` chars with an ellipsis. */
394
+ function clip(text: string, max: number): string {
395
+ const t = text.replace(/\s+/g, " ").trim();
396
+ if (max < 1) return "";
397
+ return t.length <= max ? t : t.slice(0, max - 1) + "…";
398
+ }
399
+
400
+ /** An HTTP error the caller tagged as transient. `.fatal` skips all retries;
401
+ * `.throttle` (a 429/503 rate-limit or overload) is retried indefinitely and
402
+ * does NOT consume the bounded attempt budget — the server told us to wait, not
403
+ * to give up. `.retryAfterMs` carries a server-suggested delay when present. */
404
+ type HttpError = Error & {
405
+ fatal?: boolean;
406
+ throttle?: boolean;
407
+ retryAfterMs?: number;
408
+ };
409
+
410
+ /** Retry `fn` with exponential backoff.
411
+ *
412
+ * Three error classes:
413
+ * • `.fatal` / AbortError → rethrown immediately (never retried).
414
+ * • `.throttle` (429/503) → the server is rate-limiting/overloaded. We are
415
+ * NOT failing — we WAIT (honouring Retry-After, else capped exponential
416
+ * back-off with jitter) and retry WITHOUT consuming an attempt, so a
417
+ * throttled request holds on until it succeeds rather than being dropped.
418
+ * Only a shutdown breaks this loop.
419
+ * • anything else → a genuine transient error, retried up to `tries`
420
+ * with exponential back-off before giving up.
421
+ *
422
+ * `onFail` is called after each non-throttle failed attempt; `onThrottle` after
423
+ * each throttle wait (for a "waiting…" notice). */
424
+ async function retry<T>(
425
+ label: string,
426
+ fn: () => Promise<T>,
427
+ tries: number,
428
+ onFail?: (attempt: number, err: Error) => void,
429
+ onThrottle?: (waitMsAmount: number) => void,
430
+ ): Promise<T> {
431
+ let wait = 1000, last = "", throttleWait = 1000, throttleHits = 0;
432
+ for (let attempt = 1; attempt <= tries;) {
433
+ if (shutdown.signal.aborted) {
434
+ const e: HttpError = new Error("aborted");
435
+ e.fatal = true;
436
+ throw e;
437
+ }
438
+ try {
439
+ return await fn();
440
+ } catch (e) {
441
+ const err = e as HttpError;
442
+ if (err.name === "AbortError" || err.fatal) throw err;
443
+
444
+ // Rate-limited / overloaded: wait it out. Does NOT advance `attempt`, so a
445
+ // busy server can never exhaust the retry budget and drop the request.
446
+ if (err.throttle && !shutdown.signal.aborted) {
447
+ throttleHits++;
448
+ // Honour Retry-After when the server sent one; else exponential back-off
449
+ // with jitter, capped, so a fleet of requests does not resynchronise.
450
+ const base = err.retryAfterMs && err.retryAfterMs > 0
451
+ ? err.retryAfterMs
452
+ : throttleWait;
453
+ const ms = Math.min(base, 60_000) +
454
+ Math.floor(base * 0.25 * Math.random());
455
+ onThrottle?.(ms);
456
+ await waitMs(ms);
457
+ throttleWait = Math.min(throttleWait * 2, 60_000);
458
+ continue;
459
+ }
460
+
461
+ last = err.message;
462
+ onFail?.(attempt, err);
463
+ attempt++;
464
+ if (attempt <= tries) {
465
+ await waitMs(wait);
466
+ wait = Math.min(wait * 2, 30_000);
467
+ }
468
+ }
469
+ }
470
+ throw new Error(`${label} failed after ${tries} attempts: ${last}`);
471
+ }
472
+
473
+ /** Classify a non-OK HTTP response into an {@link HttpError} for {@link retry}:
474
+ * • 429 / 503 → THROTTLE (rate-limited / overloaded): retried indefinitely,
475
+ * honouring a Retry-After header (seconds or an HTTP-date) when present.
476
+ * • other 5xx → transient: retried up to the caller's attempt budget.
477
+ * • other 4xx → FATAL: a real client error (404, 401, …) — not retried.
478
+ * Never throttles forever silently: the wait is interruptible by shutdown. */
479
+ function httpError(res: Response): HttpError {
480
+ const err: HttpError = new Error(`HTTP ${res.status}`);
481
+ if (res.status === 429 || res.status === 503) {
482
+ err.throttle = true;
483
+ const ra = res.headers.get("retry-after");
484
+ if (ra) {
485
+ const secs = Number(ra);
486
+ if (Number.isFinite(secs)) err.retryAfterMs = Math.max(0, secs * 1000);
487
+ else {
488
+ const when = Date.parse(ra);
489
+ if (Number.isFinite(when)) {
490
+ err.retryAfterMs = Math.max(0, when - Date.now());
491
+ }
492
+ }
493
+ }
494
+ } else if (res.status < 500) {
495
+ err.fatal = true; // genuine client error — do not retry
496
+ } // other 5xx: neither fatal nor throttle → ordinary bounded retry
497
+ return err;
498
+ }
499
+
500
+ /** GET a URL and parse JSON, with the shared retry policy: rate-limits (429/503)
501
+ * WAIT indefinitely (surfaced to the progress log via onThrottleWait, throttled
502
+ * to one notice every few seconds), other 4xx is fatal, other 5xx retried up to
503
+ * DOWNLOAD_TRIES. Used by every datasets-server API stage so all share the same
504
+ * never-drop-on-throttle behaviour. */
505
+ async function getJson(url: string, label: string): Promise<any> {
506
+ return retry(
507
+ label,
508
+ async () => {
509
+ const res = await fetch(url, { signal: shutdown.signal });
510
+ if (res.ok) return res.json();
511
+ throw httpError(res);
512
+ },
513
+ DOWNLOAD_TRIES,
514
+ undefined,
515
+ (ms) => {
516
+ const now = Date.now();
517
+ if (onThrottleWait && now - lastThrottleLog > 3000) {
518
+ lastThrottleLog = now;
519
+ onThrottleWait(ms, label);
520
+ }
521
+ },
522
+ );
523
+ }
524
+
525
+ // ═══════════════════════════════════════════════════════════════════════
526
+ // §3 Cache + download helpers (a downloaded file is bounded by MAX_CACHE_GB)
527
+ //
528
+ // SmolSent and Aya are paged from the datasets-server JSON API (no file to
529
+ // download); oasst2 downloads ONE gzipped file. So only the generic download
530
+ // helpers below survive — there is no per-language ZIP discovery or prefetch.
531
+ // ═══════════════════════════════════════════════════════════════════════
532
+
533
+ /** A cheap HEAD to learn a download's size (for the cache ceiling and a real
534
+ * ETA). Rate-limits wait; other 4xx is fatal; total failure → 0. */
535
+ async function headSize(url: string): Promise<number> {
536
+ return retry(`HEAD ${url}`, async () => {
537
+ const res = await fetch(url, { method: "HEAD", signal: shutdown.signal });
538
+ if (res.ok) return Number(res.headers.get("content-length")) || 0;
539
+ throw httpError(res);
540
+ }, 4);
541
+ }
542
+
543
+ function cacheSize(): number {
544
+ if (!existsSync(CACHE_DIR)) return 0;
545
+ let total = 0;
546
+ for (const name of readdirSync(CACHE_DIR)) {
547
+ try {
548
+ total += statSync(join(CACHE_DIR, name)).size;
549
+ } catch { /* raced with a delete */ }
550
+ }
551
+ return total;
552
+ }
553
+
554
+ /** Block until there is room for a file of `fileBytes` under the ceiling.
555
+ * A single file larger than the whole ceiling can never "fit", so we let it
556
+ * through (it is deleted right after processing) rather than wait forever. */
557
+ async function ensureCacheRoom(
558
+ fileBytes: number,
559
+ warn?: (msg: string) => void,
560
+ ): Promise<void> {
561
+ mkdirSync(CACHE_DIR, { recursive: true });
562
+ if (fileBytes >= MAX_CACHE_BYTES) return;
563
+ let warned = false;
564
+ // Stop waiting the moment a shutdown is requested — the abort signal unblocks
565
+ // a long cache-full wait so Ctrl+C is never swallowed by the ceiling.
566
+ while (
567
+ !shutdown.signal.aborted && cacheSize() + fileBytes > MAX_CACHE_BYTES
568
+ ) {
569
+ if (!warned) {
570
+ warn?.(
571
+ `${YEL}⚠${R} cache at ${
572
+ (MAX_CACHE_BYTES / 1e9).toFixed(0)
573
+ } GB ceiling — waiting for room…`,
574
+ );
575
+ warned = true;
576
+ }
577
+ await waitMs(5_000);
578
+ }
579
+ }
580
+
581
+ // ═══════════════════════════════════════════════════════════════════════
582
+ // §5 Download (streamed to disk, with retry + cleanup on failure)
583
+ // ═══════════════════════════════════════════════════════════════════════
584
+
585
+ async function downloadFile(
586
+ url: string,
587
+ destPath: string,
588
+ tries = DOWNLOAD_TRIES,
589
+ onFail?: (attempt: number, err: Error) => void,
590
+ onProgress?: (done: number, total: number) => void,
591
+ ): Promise<void> {
592
+ const partPath = destPath + PART_SUFFIX;
593
+ await retry(
594
+ `download ${basename(destPath)}`,
595
+ async () => {
596
+ // Abort promptly on shutdown rather than waiting out a slow socket.
597
+ if (shutdown.signal.aborted) {
598
+ const e: Error & { fatal?: boolean } = new Error("aborted");
599
+ e.fatal = true;
600
+ throw e;
601
+ }
602
+ const res = await fetch(url, { signal: shutdown.signal });
603
+ if (!res.ok) throw httpError(res);
604
+ if (!res.body) throw new Error("empty response body");
605
+
606
+ const total = Number(res.headers.get("content-length")) || 0;
607
+ let done = 0;
608
+
609
+ // Stream straight to a ".part" sibling using pure WHATWG streams. A
610
+ // TransformStream meters progress; pipeTo into a WritableStream gives REAL
611
+ // backpressure natively — the sink's write() returns a promise the
612
+ // readable side awaits, so a fast server can never outrun the disk (no
613
+ // whole-file heap buffering). The sink wraps a single raw fs descriptor
614
+ // (the one capability the web platform lacks); writing to disk is the only
615
+ // Node operation in the whole pipeline. The final, valid file only ever
616
+ // appears via the atomic rename below, so a crash mid-transfer can never
617
+ // leave a truncated file at the real path.
618
+ const meter = new TransformStream<Uint8Array, Uint8Array>({
619
+ transform(chunk, controller) {
620
+ done += chunk.length;
621
+ onProgress?.(done, total);
622
+ controller.enqueue(chunk);
623
+ },
624
+ });
625
+
626
+ const fd = openSync(partPath, "w");
627
+ let closed = false;
628
+ const closeFd = () => {
629
+ if (closed) return;
630
+ closed = true;
631
+ try {
632
+ closeSync(fd);
633
+ } catch { /* already closed */ }
634
+ };
635
+ const sink = new WritableStream<Uint8Array>({
636
+ write(chunk) {
637
+ // writeSync drains the whole chunk before returning, so the readable
638
+ // side is paused for exactly as long as the disk needs — backpressure.
639
+ let off = 0;
640
+ while (off < chunk.length) {
641
+ off += writeSync(fd, chunk, off, chunk.length - off);
642
+ }
643
+ },
644
+ close() {
645
+ fsyncSync(fd); // durable bytes before the rename promotes them
646
+ closeFd();
647
+ },
648
+ abort() {
649
+ closeFd();
650
+ },
651
+ });
652
+
653
+ try {
654
+ await res.body.pipeThrough(meter).pipeTo(sink, {
655
+ signal: shutdown.signal,
656
+ });
657
+ } catch (e) {
658
+ // pipeTo's abort() ran the sink's abort() (closing the descriptor); if
659
+ // it didn't (a non-abort throw), make sure the descriptor is not leaked.
660
+ closeFd();
661
+ try {
662
+ unlinkSync(partPath);
663
+ } catch { /* best effort */ }
664
+ throw e;
665
+ }
666
+
667
+ // Optional integrity guard: when the server advertised a size, a complete
668
+ // file must match it. A short read (silent truncation) is retried rather
669
+ // than promoted, so the parser never sees a partial ZIP.
670
+ try {
671
+ const got = statSync(partPath).size;
672
+ if (total > 0 && got !== total) {
673
+ try {
674
+ unlinkSync(partPath);
675
+ } catch { /* best effort */ }
676
+ throw new Error(`size mismatch: got ${got}, expected ${total}`);
677
+ }
678
+ } catch (e) {
679
+ if (e instanceof Error && e.message.startsWith("size mismatch")) {
680
+ throw e;
681
+ }
682
+ // statSync failure is non-fatal here; the rename below will surface it.
683
+ }
684
+
685
+ // Atomic publish: rename is atomic within a filesystem, so the final path
686
+ // flips from "absent" to "complete" in one step — never an in-between.
687
+ renameSync(partPath, destPath);
688
+ },
689
+ tries,
690
+ onFail,
691
+ );
692
+ }
693
+
694
+ // ═══════════════════════════════════════════════════════════════════════
695
+ // §6 Parsing — raw rows → SEMA training items
696
+ // ═══════════════════════════════════════════════════════════════════════
697
+
698
+ export interface Episode {
699
+ context: string;
700
+ continuation: string;
701
+ }
702
+ export type TrainingItem = string | Episode;
703
+
704
+ const isEpisode = (it: TrainingItem): it is Episode => typeof it !== "string";
705
+
706
+ /** Build the accumulated-context episodes of a turn sequence: each successive
707
+ * turn is the continuation of ALL the turns before it joined together. This is
708
+ * the same cumulative-context shape a multi-turn conversation deposits, so the
709
+ * store learns to continue a growing context. */
710
+ function accumulate(turns: string[]): Episode[] {
711
+ const out: Episode[] = [];
712
+ for (let i = 1; i < turns.length; i++) {
713
+ out.push({ context: turns.slice(0, i).join("\n"), continuation: turns[i] });
714
+ }
715
+ return out;
716
+ }
717
+
718
+ /** Dedup + trim a concept's items: drop empty/degenerate pairs and exact
719
+ * repeats so a concept never deposits the same form twice. */
720
+ export function refineItems(items: TrainingItem[]): TrainingItem[] {
721
+ const out: TrainingItem[] = [];
722
+ const seen = new Set<string>();
723
+ for (const it of items) {
724
+ if (!isEpisode(it)) {
725
+ const exp = it.trim();
726
+ const key = "E:" + exp;
727
+ if (exp && !seen.has(key)) {
728
+ seen.add(key);
729
+ out.push(exp);
730
+ }
731
+ continue;
732
+ }
733
+ const ctx = it.context.trim();
734
+ const cont = it.continuation.trim();
735
+ if (!ctx || !cont || ctx === cont) continue;
736
+ const key = "P:" + ctx + "\u0000" + cont;
737
+ if (seen.has(key)) continue;
738
+ seen.add(key);
739
+ out.push({ context: ctx, continuation: cont });
740
+ }
741
+ return out;
742
+ }
743
+
744
+ // ═══════════════════════════════════════════════════════════════════════
745
+ // §6c SmolSent parsing — a translation pair → SEMA facts
746
+ //
747
+ // Each SmolSent row is {sl, tl, src, trg, …}: a source sentence and its
748
+ // translation into another language — "two names for one meaning". This is the
749
+ // cross-language concept SEMA fuses (see test/05-concepts.test.mjs: "ice" and
750
+ // "hielo" become one concept because they share company, so a fact about one
751
+ // transfers to the other). So a pair is rendered as BIDIRECTIONAL translation
752
+ // FACTS — (src → trg) and (trg → src) — binding the two phrasings as one
753
+ // concept at recall time, in both directions. Two facts, no experiences and no
754
+ // cumulative walk: a sentence pair is not multi-turn, and a bare sentence on its
755
+ // own carries no relation to point at.
756
+ // ═══════════════════════════════════════════════════════════════════════
757
+
758
+ /** One normalized SmolSent row. */
759
+ export interface SmolSentRow {
760
+ src: string; // source sentence
761
+ trg: string; // its translation
762
+ sl: string; // source language code
763
+ tl: string; // target language code
764
+ }
765
+
766
+ /** Normalize a raw datasets-server row into a SmolSentRow, or null when it lacks
767
+ * both sides or a side is implausibly large (a dump, not a sentence). */
768
+ export function toSmolSentRow(row: unknown): SmolSentRow | null {
769
+ if (!row || typeof row !== "object") return null;
770
+ const r = row as Record<string, unknown>;
771
+ const src = typeof r.src === "string" ? r.src.trim() : "";
772
+ // `trg` is a single string in smolsent; tolerate a list form defensively.
773
+ const trgRaw = Array.isArray(r.trgs) ? r.trgs[0] : r.trg;
774
+ const trg = typeof trgRaw === "string" ? trgRaw.trim() : "";
775
+ if (!src || !trg) return null;
776
+ if (
777
+ src.length > MAX_SMOLSENT_CHARS || trg.length > MAX_SMOLSENT_CHARS
778
+ ) return null;
779
+ const sl = typeof r.sl === "string" ? r.sl.trim() : "";
780
+ const tl = typeof r.tl === "string" ? r.tl.trim() : "";
781
+ return { src, trg, sl, tl };
782
+ }
783
+
784
+ /** Translate ONE SmolSent pair into SEMA facts: the two sentences are one
785
+ * meaning in two languages, so bind them BOTH ways. refineItems drops the
786
+ * degenerate case where src === trg. */
787
+ export function smolSentRowToItems(row: SmolSentRow): TrainingItem[] {
788
+ const { src, trg } = row;
789
+ return refineItems([
790
+ { context: src, continuation: trg },
791
+ { context: trg, continuation: src },
792
+ ]);
793
+ }
794
+
795
+ // ═══════════════════════════════════════════════════════════════════════
796
+ // §6d Aya Dataset parsing — a human prompt→completion row → SEMA items
797
+ //
798
+ // Each Aya row is a single human-written (inputs → targets) pair in a named
799
+ // language, e.g. {inputs:"Qual é a capital da Índia?", targets:"Nova Déli.",
800
+ // language:"Portuguese", …}. That is already the canonical SEMA fact (ask →
801
+ // answer), so the translation is direct: exactly ONE (question → answer) fact.
802
+ // reasoning/scratch-work fields do not exist in this corpus, so nothing is
803
+ // stripped; the text is human prose already.
804
+
805
+ /** One normalized Aya row. */
806
+ export interface AyaRow {
807
+ inputs: string;
808
+ targets: string;
809
+ language: string;
810
+ }
811
+
812
+ /** Normalize a raw datasets-server row object into an AyaRow, or null when it
813
+ * lacks a usable prompt/answer or a field is implausibly large (a dump, not a
814
+ * cognitive example). Trims surrounding whitespace; keeps inner text verbatim
815
+ * (human prose, possibly multi-paragraph). */
816
+ export function toAyaRow(row: unknown): AyaRow | null {
817
+ if (!row || typeof row !== "object") return null;
818
+ const r = row as Record<string, unknown>;
819
+ const inputs = typeof r.inputs === "string" ? r.inputs.trim() : "";
820
+ const targets = typeof r.targets === "string" ? r.targets.trim() : "";
821
+ if (!inputs || !targets) return null;
822
+ if (
823
+ inputs.length > MAX_AYA_FIELD_CHARS || targets.length > MAX_AYA_FIELD_CHARS
824
+ ) return null;
825
+ const language = typeof r.language === "string" ? r.language.trim() : "";
826
+ return { inputs, targets, language };
827
+ }
828
+
829
+ /** Translate ONE Aya row into SEMA training items. A row is a single human
830
+ * (question → answer) exchange — exactly one FACT, the (inputs → targets) edge.
831
+ * No standalone-answer experience and no one-exchange "cumulative" walk: a lone
832
+ * Q→A is not multi-turn, and both would only replicate the same edge. */
833
+ export function ayaRowToItems(row: AyaRow): TrainingItem[] {
834
+ const { inputs, targets } = row;
835
+ return refineItems([{ context: inputs, continuation: targets }]);
836
+ }
837
+
838
+ // ═══════════════════════════════════════════════════════════════════════
839
+ // §6e OpenAssistant/oasst2 parsing — a conversation TREE → SEMA items
840
+ //
841
+ // Each tree is {prompt:{role,text,replies:[…]}}, replies nested recursively. A
842
+ // prompt can have several ranked assistant replies; we collapse the tree to ONE
843
+ // linear conversation by following the best-ranked (rank 0), non-deleted reply
844
+ // at each step. The result strictly alternates prompter/assistant. Only MULTI-
845
+ // TURN conversations (≥ OASST_MIN_TURNS messages) are kept — the explicit focus
846
+ // of this stage; single Q→A trees are dropped.
847
+ // ═══════════════════════════════════════════════════════════════════════
848
+
849
+ /** A single oasst2 message node (the fields we use; the tree nests via replies). */
850
+ interface OasstNode {
851
+ role?: string;
852
+ text?: string;
853
+ rank?: number | null;
854
+ deleted?: boolean;
855
+ replies?: OasstNode[];
856
+ }
857
+
858
+ /** One conversational turn extracted from a tree. */
859
+ export interface OasstTurn {
860
+ role: string; // "prompter" | "assistant"
861
+ text: string;
862
+ }
863
+
864
+ /** Collapse a conversation tree to ONE linear path: at each node, descend into
865
+ * its best-ranked, non-deleted reply (rank 0 preferred; unranked sorts last).
866
+ * Returns the ordered turns (already strictly alternating in this corpus). */
867
+ export function bestOasstPath(root: OasstNode): OasstTurn[] {
868
+ const turns: OasstTurn[] = [];
869
+ let node: OasstNode | undefined = root;
870
+ while (node) {
871
+ const text = typeof node.text === "string" ? node.text.trim() : "";
872
+ if (text) turns.push({ role: String(node.role ?? "?"), text });
873
+ const live: OasstNode[] = (node.replies ?? []).filter((r: OasstNode) =>
874
+ r && !r.deleted && typeof r.text === "string" && r.text.trim() !== ""
875
+ );
876
+ if (live.length === 0) break;
877
+ live.sort((a: OasstNode, b: OasstNode) =>
878
+ (a.rank ?? Number.MAX_SAFE_INTEGER) - (b.rank ?? Number.MAX_SAFE_INTEGER)
879
+ );
880
+ node = live[0];
881
+ }
882
+ return turns;
883
+ }
884
+
885
+ /** Translate ONE multi-turn oasst2 conversation into SEMA training items.
886
+ *
887
+ * This is the ONE stage where cumulative continuous context is truly necessary:
888
+ * the data is a real multi-turn dialogue, and what must be learned is how each
889
+ * turn follows from the WHOLE conversation so far — not from the previous turn
890
+ * alone. The conversation is emitted ONLY as the accumulated walk; standalone
891
+ * turn experiences and local adjacent-pair facts are NOT emitted (they are
892
+ * subsumed by it and would merely replicate the content).
893
+ *
894
+ * The walk is byte-for-byte the pattern proven in test/13-conversation.test.mjs
895
+ * ("teachConversation"): each turn is the continuation of all prior turns joined
896
+ * by "\n", with BARE turn text — NO "User:/Assistant:" labels. Roles already
897
+ * alternate by position in an oasst2 best-path (the root is a prompter), so a
898
+ * label adds nothing the position does not, while a clean continuation matches
899
+ * the test's recall (predictNext queries bare prior turns) and lets a turn share
900
+ * its gist with the same text elsewhere (e.g. an Aya question stored bare).
901
+ *
902
+ * Returns [] for a conversation below the multi-turn threshold, so callers can
903
+ * simply skip empties. */
904
+ export function oasstConversationToItems(turns: OasstTurn[]): TrainingItem[] {
905
+ if (turns.length < OASST_MIN_TURNS) return []; // not multi-turn — skip
906
+ return refineItems(accumulate(turns.map((t) => t.text)));
907
+ }
908
+
909
+ // ═══════════════════════════════════════════════════════════════════════
910
+ // §6f General-Knowledge parsing — a {Question, Answer} row → SEMA fact
911
+ //
912
+ // Each row is a single general-knowledge question with one answer — a pure
913
+ // RELATION (question → answer), so it becomes exactly ONE FACT, like the Aya
914
+ // stage. No experience (a fact is possible) and no cumulative walk (a lone Q&A
915
+ // is not multi-turn). The source over-escapes newlines (a literal "\n" two-char
916
+ // sequence) and leaves trailing whitespace, so answers are un-escaped and
917
+ // trimmed to plain prose before deposit.
918
+ // ═══════════════════════════════════════════════════════════════════════
919
+
920
+ /** One normalized General-Knowledge row. */
921
+ export interface GenKnowRow {
922
+ question: string;
923
+ answer: string;
924
+ }
925
+
926
+ /** Turn a source value into clean prose: decode the literal "\n"/"\t"/"\r"
927
+ * two-character escapes the source JSON left in the text, collapse the runs of
928
+ * whitespace that creates, and trim. */
929
+ function unescapePlain(s: string): string {
930
+ return s
931
+ .replace(/\\r\\n|\\n|\\r/g, "\n")
932
+ .replace(/\\t/g, " ")
933
+ .replace(/[ \t]+/g, " ")
934
+ .replace(/\n{3,}/g, "\n\n")
935
+ .trim();
936
+ }
937
+
938
+ /** Normalize a raw datasets-server row into a GenKnowRow, or null when it lacks
939
+ * a usable question/answer or a side is implausibly large (corruption). */
940
+ export function toGenKnowRow(row: unknown): GenKnowRow | null {
941
+ if (!row || typeof row !== "object") return null;
942
+ const r = row as Record<string, unknown>;
943
+ const question = typeof r.Question === "string"
944
+ ? unescapePlain(r.Question)
945
+ : "";
946
+ const answer = typeof r.Answer === "string" ? unescapePlain(r.Answer) : "";
947
+ if (!question || !answer) return null;
948
+ if (
949
+ question.length > MAX_GENKNOW_CHARS || answer.length > MAX_GENKNOW_CHARS
950
+ ) return null;
951
+ return { question, answer };
952
+ }
953
+
954
+ /** Translate ONE General-Knowledge row into SEMA items: exactly one
955
+ * (question → answer) FACT. refineItems drops a degenerate question === answer. */
956
+ export function genKnowRowToItems(row: GenKnowRow): TrainingItem[] {
957
+ return refineItems([{ context: row.question, continuation: row.answer }]);
958
+ }
959
+
960
+ // ═══════════════════════════════════════════════════════════════════════
961
+ // §7 Ingestion
962
+ //
963
+ // Each item is deposited directly: an experience via ingest(text), an episode
964
+ // via ingest(context, continuation). After each, the per-example callback
965
+ // receives the item's UTF-8 content size — the quantity the scaling suite
966
+ // (14-scaling.test.mjs) reports as a constant KB/s — then gates the global
967
+ // example count and checkpointing (returns false to stop). `sample` feeds the
968
+ // reservoir used for the periodic recall box.
969
+ // ═══════════════════════════════════════════════════════════════════════
970
+
971
+ const ENC = new TextEncoder();
972
+
973
+ /** Content size of a training item in UTF-8 bytes — the same quantity the
974
+ * scaling suite (14-scaling.test.mjs) measures as KB/s: for an episode the
975
+ * context plus the continuation, for a bare experience its own text. */
976
+ const itemBytes = (it: TrainingItem): number =>
977
+ isEpisode(it)
978
+ ? ENC.encode(it.context).length + ENC.encode(it.continuation).length
979
+ : ENC.encode(it).length;
980
+
981
+ async function ingestItems(
982
+ ci: CachedIngest,
983
+ items: TrainingItem[],
984
+ onItem: (contentBytes: number) => Promise<boolean>,
985
+ sample?: (it: TrainingItem) => void,
986
+ ): Promise<boolean> {
987
+ for (const it of items) {
988
+ if (isEpisode(it)) await ci.ingest(it.context, it.continuation);
989
+ else await ci.ingest(it);
990
+ sample?.(it);
991
+ if (!(await onItem(itemBytes(it)))) return false; // stop requested
992
+ }
993
+ return true;
994
+ }
995
+
996
+ // ── §7a′ oasst2 — stream the gzipped JSONL of trees and deposit multi-turn ──
997
+ //
998
+ // The file is gzipped JSONL: one conversation tree per line. We inflate with the
999
+ // web-standard DecompressionStream("gzip"), split on newlines without buffering
1000
+ // the whole file or an unbounded line, parse each tree, collapse it to its best
1001
+ // linear path, and deposit only the multi-turn ones. Robust by construction: a
1002
+ // line that fails to parse (or is oversize) is counted skipped and the stream
1003
+ // continues; a cap/signal stops cleanly at a conversation boundary.
1004
+ async function processOasst(
1005
+ filePath: string,
1006
+ ci: CachedIngest,
1007
+ onExample: (contentBytes: number) => Promise<boolean>,
1008
+ sample: (it: TrainingItem) => void,
1009
+ ): Promise<
1010
+ { examples: number; stopped: boolean; skipped: number; multi: number }
1011
+ > {
1012
+ const blob = await openAsBlob(filePath);
1013
+ const reader = blob.stream()
1014
+ .pipeThrough(new DecompressionStream("gzip"))
1015
+ .pipeThrough(new TextDecoderStream())
1016
+ .getReader();
1017
+ let examples = 0;
1018
+ let skipped = 0; // malformed/oversize lines
1019
+ let multi = 0; // multi-turn conversations deposited
1020
+ let leftover = "";
1021
+ let droppingLine = false;
1022
+
1023
+ const processLine = async (line: string): Promise<boolean> => {
1024
+ if (!line.trim()) return true;
1025
+ let tree: { prompt?: OasstNode };
1026
+ try {
1027
+ tree = JSON.parse(line);
1028
+ } catch {
1029
+ skipped++;
1030
+ return true;
1031
+ }
1032
+ if (!tree.prompt) return true;
1033
+ const turns = bestOasstPath(tree.prompt);
1034
+ const items = oasstConversationToItems(turns); // [] when not multi-turn
1035
+ if (items.length === 0) return true; // single-turn / empty — skipped
1036
+ multi++;
1037
+ return ingestItems(ci, items, async (contentBytes) => {
1038
+ examples++;
1039
+ return onExample(contentBytes);
1040
+ }, sample);
1041
+ };
1042
+
1043
+ try {
1044
+ while (true) {
1045
+ const { done, value } = await reader.read();
1046
+ if (done) break;
1047
+ let chunk = value;
1048
+ for (;;) {
1049
+ const nl = chunk.indexOf("\n");
1050
+ if (nl < 0) {
1051
+ if (!droppingLine) {
1052
+ if (leftover.length + chunk.length > MAX_OASST_LINE_CHARS) {
1053
+ leftover = "";
1054
+ droppingLine = true;
1055
+ skipped++;
1056
+ } else leftover += chunk;
1057
+ }
1058
+ break;
1059
+ }
1060
+ const part = chunk.slice(0, nl);
1061
+ chunk = chunk.slice(nl + 1);
1062
+ if (droppingLine) {
1063
+ droppingLine = false;
1064
+ leftover = "";
1065
+ continue;
1066
+ }
1067
+ if (leftover.length + part.length > MAX_OASST_LINE_CHARS) {
1068
+ leftover = "";
1069
+ skipped++;
1070
+ continue;
1071
+ }
1072
+ const line = leftover + part;
1073
+ leftover = "";
1074
+ if (!(await processLine(line))) {
1075
+ return { examples, stopped: true, skipped, multi };
1076
+ }
1077
+ }
1078
+ }
1079
+ if (!droppingLine && leftover.trim()) {
1080
+ if (!(await processLine(leftover))) {
1081
+ return { examples, stopped: true, skipped, multi };
1082
+ }
1083
+ }
1084
+ return { examples, stopped: false, skipped, multi };
1085
+ } finally {
1086
+ try {
1087
+ reader.releaseLock();
1088
+ } catch { /* best effort */ }
1089
+ }
1090
+ }
1091
+
1092
+ // ── §7b Downloaded-file processors — SmolSent, Aya, General-Knowledge ──
1093
+ //
1094
+ // Each source is DOWNLOADED to the cache and streamed from disk (via web-standard
1095
+ // Blob streams), rather than paged row-by-row over an HTTP API. This is far
1096
+ // faster, is not rate-limited, and gives a real byte-based progress/throughput
1097
+ // reading. A source stops cleanly at an item boundary on cap/signal; a file that
1098
+ // is fully consumed is marked complete so a resume skips it.
1099
+ interface FileResult {
1100
+ examples: number;
1101
+ stopped: boolean; // stopped early by MAX_MB cap or shutdown
1102
+ skipped: number; // malformed/oversize records
1103
+ }
1104
+
1105
+ /** Discover the SmolSent per-pair JSONL files from the HF repo tree, restricted
1106
+ * to SMOLSENT_PAIRS (basenames without .jsonl) when set. Each entry is the
1107
+ * repo-relative path, e.g. "smolsent/ha_en.jsonl". */
1108
+ async function listSmolSentFiles(): Promise<string[]> {
1109
+ // The dataset id ("owner/name") is a PATH here, so its "/" must not be
1110
+ // percent-encoded. `recursive=true` returns every file under smolsent/.
1111
+ const url = `https://huggingface.co/api/datasets/${SMOLSENT_DATASET}` +
1112
+ `/tree/main/smolsent?recursive=true`;
1113
+ const body = await getJson(url, `GET smol tree`);
1114
+ const paths: string[] = Array.isArray(body)
1115
+ ? body
1116
+ .filter((e: any) => e?.type === "file" && /\.jsonl$/i.test(e?.path))
1117
+ .map((e: any) => String(e.path))
1118
+ : [];
1119
+ paths.sort();
1120
+ if (!SMOLSENT_PAIRS.length) return paths;
1121
+ const want = new Set(SMOLSENT_PAIRS.map((p) => p.replace(/\.jsonl$/i, "")));
1122
+ return paths.filter((p) => want.has(basename(p).replace(/\.jsonl$/i, "")));
1123
+ }
1124
+
1125
+ /** Stream a plain-JSONL file from disk, deposit each parsed row via `toItems`.
1126
+ * Lines are split without buffering the whole file; an oversize/malformed line
1127
+ * is counted skipped and the stream continues. Shared by SmolSent (and any
1128
+ * future JSONL source). */
1129
+ async function processJsonl(
1130
+ filePath: string,
1131
+ toItems: (row: unknown) => TrainingItem[] | null,
1132
+ ci: CachedIngest,
1133
+ onExample: (contentBytes: number) => Promise<boolean>,
1134
+ sample: (it: TrainingItem) => void,
1135
+ maxLineChars: number,
1136
+ ): Promise<FileResult> {
1137
+ const blob = await openAsBlob(filePath);
1138
+ const reader = blob.stream().pipeThrough(new TextDecoderStream()).getReader();
1139
+ let examples = 0, skipped = 0, leftover = "", dropping = false;
1140
+
1141
+ const processLine = async (line: string): Promise<boolean> => {
1142
+ if (!line.trim()) return true;
1143
+ let row: unknown;
1144
+ try {
1145
+ row = JSON.parse(line);
1146
+ } catch {
1147
+ skipped++;
1148
+ return true;
1149
+ }
1150
+ const items = toItems(row);
1151
+ if (!items || items.length === 0) {
1152
+ skipped++;
1153
+ return true;
1154
+ }
1155
+ return ingestItems(ci, items, async (contentBytes) => {
1156
+ examples++;
1157
+ return onExample(contentBytes);
1158
+ }, sample);
1159
+ };
1160
+
1161
+ try {
1162
+ while (true) {
1163
+ const { done, value } = await reader.read();
1164
+ if (done) break;
1165
+ let chunk = value;
1166
+ for (;;) {
1167
+ const nl = chunk.indexOf("\n");
1168
+ if (nl < 0) {
1169
+ if (!dropping) {
1170
+ if (leftover.length + chunk.length > maxLineChars) {
1171
+ leftover = "";
1172
+ dropping = true;
1173
+ skipped++;
1174
+ } else leftover += chunk;
1175
+ }
1176
+ break;
1177
+ }
1178
+ const part = chunk.slice(0, nl);
1179
+ chunk = chunk.slice(nl + 1);
1180
+ if (dropping) {
1181
+ dropping = false;
1182
+ leftover = "";
1183
+ continue;
1184
+ }
1185
+ if (leftover.length + part.length > maxLineChars) {
1186
+ leftover = "";
1187
+ skipped++;
1188
+ continue;
1189
+ }
1190
+ const line = leftover + part;
1191
+ leftover = "";
1192
+ if (!(await processLine(line))) {
1193
+ return { examples, stopped: true, skipped };
1194
+ }
1195
+ }
1196
+ }
1197
+ if (!dropping && leftover.trim()) {
1198
+ if (!(await processLine(leftover))) {
1199
+ return { examples, stopped: true, skipped };
1200
+ }
1201
+ }
1202
+ return { examples, stopped: false, skipped };
1203
+ } finally {
1204
+ try {
1205
+ reader.releaseLock();
1206
+ } catch { /* best effort */ }
1207
+ }
1208
+ }
1209
+
1210
+ /** Read a downloaded Parquet file row-group by row-group with hyparquet (+Snappy
1211
+ * from hyparquet-compressors) over a web-standard Blob byte source, depositing
1212
+ * each row via `toItems`. Only one row-group is materialised at a time, so a
1213
+ * multi-hundred-MB file never loads whole into memory. */
1214
+ async function processParquet(
1215
+ filePath: string,
1216
+ toItems: (row: unknown) => TrainingItem[] | null,
1217
+ ci: CachedIngest,
1218
+ onExample: (contentBytes: number) => Promise<boolean>,
1219
+ sample: (it: TrainingItem) => void,
1220
+ ): Promise<FileResult> {
1221
+ const blob = await openAsBlob(filePath);
1222
+ const file = {
1223
+ byteLength: blob.size,
1224
+ slice: async (start: number, end?: number) =>
1225
+ await blob.slice(start, end ?? blob.size).arrayBuffer(),
1226
+ };
1227
+ const meta = await parquetMetadataAsync(file);
1228
+ let examples = 0, skipped = 0;
1229
+ let rowStart = 0;
1230
+ for (const rg of meta.row_groups) {
1231
+ if (shutdown.signal.aborted) return { examples, stopped: true, skipped };
1232
+ const rgRows = Number(rg.num_rows);
1233
+ const rowEnd = rowStart + rgRows;
1234
+ // Materialise exactly one row-group, then deposit its rows.
1235
+ const rows = await parquetReadObjects({
1236
+ file,
1237
+ compressors,
1238
+ rowStart,
1239
+ rowEnd,
1240
+ });
1241
+ rowStart = rowEnd;
1242
+ for (const row of rows) {
1243
+ const items = toItems(row);
1244
+ if (!items || items.length === 0) {
1245
+ skipped++;
1246
+ continue;
1247
+ }
1248
+ const ok = await ingestItems(ci, items, async (contentBytes) => {
1249
+ examples++;
1250
+ return onExample(contentBytes);
1251
+ }, sample);
1252
+ if (!ok) return { examples, stopped: true, skipped };
1253
+ }
1254
+ }
1255
+ return { examples, stopped: false, skipped };
1256
+ }
1257
+
1258
+ /** Read a downloaded JSON-array file (General-Knowledge output.json) and deposit
1259
+ * each element via `toItems`. The array is small enough (~16 MB) to parse whole;
1260
+ * a huge file would be rejected by the cache ceiling long before this. */
1261
+ async function processJsonArray(
1262
+ filePath: string,
1263
+ toItems: (row: unknown) => TrainingItem[] | null,
1264
+ ci: CachedIngest,
1265
+ onExample: (contentBytes: number) => Promise<boolean>,
1266
+ sample: (it: TrainingItem) => void,
1267
+ ): Promise<FileResult> {
1268
+ const blob = await openAsBlob(filePath);
1269
+ let arr: unknown;
1270
+ try {
1271
+ arr = JSON.parse(await blob.text());
1272
+ } catch (e) {
1273
+ throw new Error(`invalid JSON: ${(e as Error).message}`);
1274
+ }
1275
+ const rows: unknown[] = Array.isArray(arr) ? arr : [];
1276
+ let examples = 0, skipped = 0;
1277
+ for (const row of rows) {
1278
+ if (shutdown.signal.aborted) return { examples, stopped: true, skipped };
1279
+ const items = toItems(row);
1280
+ if (!items || items.length === 0) {
1281
+ skipped++;
1282
+ continue;
1283
+ }
1284
+ const ok = await ingestItems(ci, items, async (contentBytes) => {
1285
+ examples++;
1286
+ return onExample(contentBytes);
1287
+ }, sample);
1288
+ if (!ok) return { examples, stopped: true, skipped };
1289
+ }
1290
+ return { examples, stopped: false, skipped };
1291
+ }
1292
+
1293
+ // ═══════════════════════════════════════════════════════════════════════
1294
+ // §8 Progress display (a live panel pinned to the BOTTOM of stderr)
1295
+ //
1296
+ // Log lines scroll up into history above the panel; the panel always sits
1297
+ // at the bottom and only ever clears its own rows on repaint, so download
1298
+ // notices and recall boxes persist instead of being wiped each frame.
1299
+ // ═══════════════════════════════════════════════════════════════════════
1300
+
1301
+ interface ProgState {
1302
+ exampleCount: number; // training examples ingested
1303
+ target: number; // learned-content byte cap (MAX_BYTES), or Infinity
1304
+ elapsedS: number;
1305
+ trainedBytes: number; // UTF-8 content bytes trained so far
1306
+ trainedRate: number; // rolling trained-content bytes/s — the headline KB/s
1307
+ bytesDone: number; // source bytes processed so far (corpus position)
1308
+ bytesTotal: number; // total source bytes of the corpus (0 until known)
1309
+ bytesRate: number; // rolling source bytes/s (drives the corpus ETA)
1310
+ fileIndex: number; // 1-based
1311
+ fileTotal: number;
1312
+ filePath: string; // language display name
1313
+ fileSize: number; // bytes of current ZIP
1314
+ fileExamples: number; // examples ingested from the current language
1315
+ activity: "download" | "process" | "idle";
1316
+ dlSpeed: number; // bytes/s, or 0
1317
+ dlDone: number; // bytes downloaded so far for the current download (live)
1318
+ dlTotal: number; // total bytes of the current download (0 if unknown)
1319
+ storeEntries: number;
1320
+ cacheBytes: number;
1321
+ lastSample: string | null; // pre-rendered recall box, pinned in the panel
1322
+ }
1323
+
1324
+ /** A prompt/expected pair to display for an item. */
1325
+ function promptOf(
1326
+ it: TrainingItem,
1327
+ ): { prompt: string; expected: string | null; kind: "episode" | "experience" } {
1328
+ return isEpisode(it)
1329
+ ? { prompt: it.context, expected: it.continuation, kind: "episode" }
1330
+ : { prompt: it.slice(0, 200), expected: null, kind: "experience" };
1331
+ }
1332
+
1333
+ /** A coarse, honest similarity between an expected continuation and SEMA's
1334
+ * recall. Both are normalized (lowercased, whitespace-collapsed) and compared
1335
+ * by the longest shared leading run plus token overlap, so the verdict is a
1336
+ * heuristic signal of recall quality rather than a brittle fixed-prefix test. */
1337
+ function recallSimilarity(expected: string, response: string): number {
1338
+ const norm = (s: string) => s.toLowerCase().replace(/\s+/g, " ").trim();
1339
+ const a = norm(expected), b = norm(response);
1340
+ if (!a || !b) return 0;
1341
+ let lead = 0;
1342
+ const lim = Math.min(a.length, b.length);
1343
+ while (lead < lim && a[lead] === b[lead]) lead++;
1344
+ const leadFrac = lead / Math.max(1, Math.min(a.length, b.length));
1345
+ const ta = new Set(a.split(" ")), tb = new Set(b.split(" "));
1346
+ let inter = 0;
1347
+ for (const w of ta) if (tb.has(w)) inter++;
1348
+ const jac = inter / Math.max(1, ta.size + tb.size - inter);
1349
+ return Math.max(leadFrac, jac);
1350
+ }
1351
+
1352
+ /** A framed recall sample. Pinned in the panel on a TTY (so the most recent
1353
+ * example is always on screen) and logged once per checkpoint when piped. */
1354
+ function renderInferenceBox(
1355
+ prompt: string,
1356
+ expected: string | null,
1357
+ response: string,
1358
+ kind: "episode" | "experience",
1359
+ checkpointN: number,
1360
+ ): string {
1361
+ const W = 68;
1362
+ const hr = `${DIM}${"─".repeat(W)}${R}`;
1363
+ const title = kind === "episode"
1364
+ ? "latest recall"
1365
+ : "latest recall (experience)";
1366
+ const head = `${title} · checkpoint #${checkpointN} `;
1367
+ const shown = response.trim() ? response : "(empty)";
1368
+ const lines = [
1369
+ `${B}╭─ ${head}${"─".repeat(Math.max(0, W - 2 - head.length))}╮${R}`,
1370
+ `${B}│${R} ${hr}`,
1371
+ `${B}│${R} ${CYAN}${B}Context:${R} ${clip(prompt, W - 13)}`,
1372
+ ];
1373
+ if (expected) {
1374
+ lines.push(`${B}│${R} ${YEL}${B}Expected:${R} ${clip(expected, W - 13)}`);
1375
+ }
1376
+ lines.push(`${B}│${R} ${GRN}${B}SEMA:${R} ${clip(shown, W - 13)}`);
1377
+ lines.push(`${B}│${R} ${hr}`);
1378
+ let verdict: string;
1379
+ if (expected) {
1380
+ const sim = recallSimilarity(expected, response);
1381
+ const pctStr = `${Math.round(sim * 100)}%`;
1382
+ verdict = sim >= 0.6
1383
+ ? `${GRN}✓${R} recall close to expected ${DIM}(~${pctStr} overlap)${R}`
1384
+ : sim >= 0.25
1385
+ ? `${YEL}△${R} partial recall ${DIM}(~${pctStr} overlap)${R}`
1386
+ : `${RED}✗${R} recall diverges ${DIM}(~${pctStr} overlap)${R}`;
1387
+ } else {
1388
+ verdict = `${DIM}·${R} plain experience — no expected answer`;
1389
+ }
1390
+ lines.push(`${B}│${R} ${verdict}`);
1391
+ lines.push(`${B}╰${"─".repeat(W)}╯${R}`);
1392
+ return lines.join("\n");
1393
+ }
1394
+
1395
+ function renderPanel(s: ProgState): string {
1396
+ const targetKnown = isFinite(s.target);
1397
+ // Primary progress: by learned-content bytes when a MAX_MB target is set,
1398
+ // else by how far we are through the corpus on disk (bytes) — so the default
1399
+ // unbounded run still shows a real fraction and a real ETA.
1400
+ const frac = targetKnown
1401
+ ? (s.target > 0 ? s.trainedBytes / s.target : 0)
1402
+ : (s.bytesTotal > 0 ? s.bytesDone / s.bytesTotal : 0);
1403
+
1404
+ const etaStr = (() => {
1405
+ if (targetKnown) {
1406
+ return s.trainedRate > 0
1407
+ ? dur((s.target - s.trainedBytes) / s.trainedRate)
1408
+ : "∞";
1409
+ }
1410
+ if (s.bytesTotal > 0 && s.bytesRate > 0) {
1411
+ return dur((s.bytesTotal - s.bytesDone) / s.bytesRate);
1412
+ }
1413
+ return "∞";
1414
+ })();
1415
+
1416
+ const fileFrac = s.fileTotal > 0 ? s.fileIndex / s.fileTotal : 0;
1417
+
1418
+ let actIcon = `${DIM}·${R}`, actText = "waiting…";
1419
+ if (s.activity === "download") {
1420
+ actIcon = `${CYAN}⬇${R}`;
1421
+ const name = s.filePath;
1422
+ const total = s.dlTotal > 0 ? s.dlTotal : s.fileSize;
1423
+ if (total > 0 && s.dlDone > 0) {
1424
+ const dlFrac = clamp01(s.dlDone / total);
1425
+ actText =
1426
+ `downloading ${name} ${bar(18, dlFrac)} ${B}${pct(dlFrac)}${R}` +
1427
+ ` ${DIM}${bytes(s.dlDone)}/${bytes(total)}${R}`;
1428
+ if (s.dlSpeed > 0) actText += ` ${DIM}@ ${bytes(s.dlSpeed)}/s${R}`;
1429
+ } else {
1430
+ actText = total > 0
1431
+ ? `downloading ${name} · ${bytes(total)}…`
1432
+ : `downloading ${name}…`;
1433
+ }
1434
+ } else if (s.activity === "process") {
1435
+ actIcon = `${GRN}✓${R}`;
1436
+ actText = `processing ${s.filePath} · ${
1437
+ int(s.fileExamples)
1438
+ } examples so far`;
1439
+ }
1440
+
1441
+ const targetStr = targetKnown ? bytes(s.target) : "∞";
1442
+ const headExamples = targetKnown
1443
+ ? `${CYAN}${bytes(s.trainedBytes)}${R} / ${targetStr} learned ${DIM}·${R} ${
1444
+ int(s.exampleCount)
1445
+ } examples`
1446
+ : `${CYAN}${int(s.exampleCount)}${R} examples`;
1447
+ const corpusInfo = s.bytesTotal > 0
1448
+ ? `${B}📦${R} ${bytes(s.bytesDone)}/${bytes(s.bytesTotal)} (${
1449
+ pct(s.bytesDone / s.bytesTotal)
1450
+ })`
1451
+ : `${B}📦${R} ${bytes(s.bytesDone)} processed`;
1452
+ const fileInfo = s.fileTotal > 0
1453
+ ? `${B}🌐${R} ${s.fileIndex}/${s.fileTotal} (${pct(fileFrac)})`
1454
+ : `${B}🌐${R} ${s.fileIndex} languages`;
1455
+
1456
+ const panel = [
1457
+ `${B}╭${R}${B} sema train${R} ${DIM}·${R} SmolSent+Aya+oasst2 ${DIM}·${R} ` +
1458
+ `D=${D} ${DIM}·${R} seed=${SEED} ${DIM}·${R} ` +
1459
+ `store=${
1460
+ basename(DB_PATH)
1461
+ }.sqlite\n${B}╰${R} target=${CYAN}${targetStr}${R} ` +
1462
+ `learned ${DIM}·${R} checkpoint every ${bytes(CHECKPOINT_BYTES)}`,
1463
+ `\n${bar(40, frac)} ${B}${pct(frac)}${R} ${headExamples}`,
1464
+ `\n${B}⚡${R} ${bytes(s.trainedRate)}/s learned ${B}🧠${R} ${
1465
+ bytes(s.trainedBytes)
1466
+ } content ${B}⏱${R} ${dur(s.elapsedS)} elapsed ${B}🕐${R} ${etaStr} ETA`,
1467
+ `${fileInfo} ${corpusInfo} ${B}🗄${R} ${num(s.storeEntries)} entries ` +
1468
+ `${B}💾${R} cache ${bytes(s.cacheBytes)}`,
1469
+ `\n${actIcon} ${actText}`,
1470
+ ].join("");
1471
+
1472
+ return s.lastSample ? `${panel}\n${s.lastSample}` : panel;
1473
+ }
1474
+
1475
+ /** A live panel pinned to the bottom of stderr. On a TTY it redraws in place,
1476
+ * clearing only its own lines; logs are flushed into the scrollback above it.
1477
+ * Off a TTY (piped/CI) the panel is suppressed and a plain status line is
1478
+ * emitted occasionally, so logs stay clean and parseable. */
1479
+ class Progress {
1480
+ private lines = 0; // height of the panel currently on screen
1481
+ private lastPaint = 0;
1482
+ private lastStatus = 0;
1483
+ private last: ProgState | null = null;
1484
+ private readonly tty = process.stderr.isTTY === true;
1485
+
1486
+ /** True when attached to an interactive terminal (panel is live). */
1487
+ get interactive(): boolean {
1488
+ return this.tty;
1489
+ }
1490
+
1491
+ /** Cursor sequence that returns to the top of the panel and clears it. */
1492
+ private clearPanel(): string {
1493
+ if (this.lines <= 0) return "";
1494
+ const up = this.lines - 1; // cursor is on the panel's last line
1495
+ return (up > 0 ? `${CSI}${up}F` : "\r") + `${CSI}0J`;
1496
+ }
1497
+
1498
+ render(s: ProgState, force = false): void {
1499
+ this.last = s;
1500
+ const now = Date.now();
1501
+ if (!force && now - this.lastPaint < PROGRESS_MS) return;
1502
+ this.lastPaint = now;
1503
+
1504
+ if (!this.tty) {
1505
+ if (force || now - this.lastStatus >= 10_000) {
1506
+ this.lastStatus = now;
1507
+ const targetKnown = isFinite(s.target);
1508
+ const where = s.bytesTotal > 0
1509
+ ? ` ${pct(s.bytesDone / s.bytesTotal)} of corpus`
1510
+ : "";
1511
+ process.stderr.write(
1512
+ `[sema] ${bytes(s.trainedBytes)}${
1513
+ targetKnown ? "/" + bytes(s.target) : ""
1514
+ } learned · ${int(s.exampleCount)} examples · ` +
1515
+ `${
1516
+ bytes(s.trainedRate)
1517
+ }/s · lang ${s.fileIndex}/${s.fileTotal}${where} · ` +
1518
+ `${num(s.storeEntries)} entries\n`,
1519
+ );
1520
+ }
1521
+ return;
1522
+ }
1523
+
1524
+ const text = renderPanel(s);
1525
+ process.stderr.write(`${this.clearPanel()}${HIDE}${text}`);
1526
+ this.lines = text.split("\n").length;
1527
+ }
1528
+
1529
+ /** Emit a line (or block) into the scrollback above the panel; the panel is
1530
+ * redrawn immediately beneath it so it never disappears between frames. */
1531
+ log(msg: string): void {
1532
+ if (!this.tty) {
1533
+ process.stderr.write(`${msg}\n`);
1534
+ return;
1535
+ }
1536
+ let out = `${this.clearPanel()}${msg}\n`;
1537
+ this.lines = 0;
1538
+ if (this.last) {
1539
+ const text = renderPanel(this.last);
1540
+ out += `${HIDE}${text}`;
1541
+ this.lines = text.split("\n").length;
1542
+ }
1543
+ process.stderr.write(out);
1544
+ }
1545
+
1546
+ dispose(): void {
1547
+ if (this.tty) process.stderr.write(`${SHOW}\n`);
1548
+ }
1549
+ }
1550
+
1551
+ // ═══════════════════════════════════════════════════════════════════════
1552
+ // §9 Progress persistence (inside the store — resume from the store alone)
1553
+ // ═══════════════════════════════════════════════════════════════════════
1554
+
1555
+ const META_COMPLETED = "train.completedFiles";
1556
+ const META_DEPOSITS = "train.depositCount";
1557
+ const META_TRAINED_BYTES = "train.trainedContentBytes";
1558
+ const META_BYTES = "train.totalBytesProcessed";
1559
+ const META_CORPUS_BYTES = "train.totalCorpusBytes";
1560
+
1561
+ interface SavedProgress {
1562
+ completedFiles: string[];
1563
+ depositCount: number;
1564
+ trainedContentBytes: number;
1565
+ totalBytesProcessed: number;
1566
+ totalCorpusBytes: number;
1567
+ }
1568
+
1569
+ async function loadProgress(store: Store): Promise<SavedProgress> {
1570
+ try {
1571
+ const raw = await store.getMeta(META_COMPLETED);
1572
+ const deps = await store.getMeta(META_DEPOSITS);
1573
+ const b = await store.getMeta(META_BYTES);
1574
+ if (raw !== null && deps !== null && b !== null) {
1575
+ const completedFiles = JSON.parse(raw);
1576
+ if (Array.isArray(completedFiles)) {
1577
+ const trained = await store.getMeta(META_TRAINED_BYTES);
1578
+ const corpus = await store.getMeta(META_CORPUS_BYTES);
1579
+ return {
1580
+ completedFiles,
1581
+ depositCount: Number(deps) || 0,
1582
+ trainedContentBytes: Number(trained) || 0,
1583
+ totalBytesProcessed: Number(b) || 0,
1584
+ totalCorpusBytes: Number(corpus) || 0,
1585
+ };
1586
+ }
1587
+ }
1588
+ } catch { /* corrupt/missing — start fresh */ }
1589
+ return {
1590
+ completedFiles: [],
1591
+ depositCount: 0,
1592
+ trainedContentBytes: 0,
1593
+ totalBytesProcessed: 0,
1594
+ totalCorpusBytes: 0,
1595
+ };
1596
+ }
1597
+
1598
+ async function saveProgress(store: Store, p: SavedProgress): Promise<void> {
1599
+ await store.setMeta(META_COMPLETED, JSON.stringify(p.completedFiles));
1600
+ await store.setMeta(META_DEPOSITS, String(p.depositCount));
1601
+ await store.setMeta(META_TRAINED_BYTES, String(p.trainedContentBytes));
1602
+ await store.setMeta(META_BYTES, String(p.totalBytesProcessed));
1603
+ await store.setMeta(META_CORPUS_BYTES, String(p.totalCorpusBytes));
1604
+ await store.setMeta("train.updatedAt", new Date().toISOString());
1605
+ store.commit();
1606
+ }
1607
+
1608
+ // ═══════════════════════════════════════════════════════════════════════
1609
+ // §10 Main
1610
+ // ═══════════════════════════════════════════════════════════════════════
1611
+
1612
+ async function main(): Promise<void> {
1613
+ // The vector indices' single memory knob (MiB) — sizes both the SQLite page
1614
+ // cache and the decoded-code LRU of each index. Training is HNSW-insert
1615
+ // bound at scale (profiled at >80% of ingest wall-clock on a 5.5M-vector
1616
+ // store, nearly all of it cache-missing code reads), and inserts walk the
1617
+ // graph, so a cache that covers the indexed codes cuts wall-clock directly
1618
+ // (measured ~1.6× at 1 GB vs 64 MB on a 2M-node store). 1 GB caches ~5.8M
1619
+ // D=1024 codes — the whole content index of a 350 MB-corpus store — and is
1620
+ // the default; override with VECTOR_CACHE_MB (e.g. 256 on a small-RAM
1621
+ // machine, 64 for the library default).
1622
+ const VECTOR_CACHE_MB = Math.max(0, Number(env("VECTOR_CACHE_MB", "1024")));
1623
+ const store = new SQliteStore({
1624
+ path: DB_PATH,
1625
+ D,
1626
+ vectorCacheMb: VECTOR_CACHE_MB,
1627
+ });
1628
+
1629
+ // The store IS the model: memories, progress, and metadata all persist in
1630
+ // it, so a resumed run just reopens the same store and continues. Guard
1631
+ // against a changed D/SEED by comparing against what a previous run recorded.
1632
+ const mind = new Mind({ seed: SEED, store });
1633
+
1634
+ // Pre-fill the vector indices' RAM caches with sequential scans (bounded by
1635
+ // VECTOR_CACHE_MB). A resumed run over a large store otherwise spends its
1636
+ // first minutes warming those caches through random point reads — the
1637
+ // ingest hot path is cache-miss bound until then. Seconds, once, up front.
1638
+ if (VECTOR_CACHE_MB > 0) {
1639
+ const t = Date.now();
1640
+ const warmed = await store.warmVectorCaches();
1641
+ if (warmed > 0) {
1642
+ process.stderr.write(
1643
+ ` warmed vector caches: ${num(warmed)} rows in ${
1644
+ dur((Date.now() - t) / 1000)
1645
+ }\n`,
1646
+ );
1647
+ }
1648
+ }
1649
+ const ci = new CachedIngest(mind);
1650
+ const prevD = await store.getMeta("train.D");
1651
+ const prevSeed = await store.getMeta("train.seed");
1652
+ if (
1653
+ (prevD && Number(prevD) !== D) || (prevSeed && Number(prevSeed) !== SEED)
1654
+ ) {
1655
+ process.stderr.write(
1656
+ `fatal: D/SEED changed (store has D=${prevD} seed=${prevSeed}, ` +
1657
+ `requested D=${D} seed=${SEED}). Delete ${DB_PATH}.sqlite ` +
1658
+ `to start fresh.\n`,
1659
+ );
1660
+ process.exit(1);
1661
+ }
1662
+
1663
+ await store.setMeta("train.dataset", "SmolSent+Aya+oasst2");
1664
+ await store.setMeta("train.D", String(D));
1665
+ await store.setMeta("train.seed", String(SEED));
1666
+ await store.setMeta("train.createdAt", new Date().toISOString());
1667
+
1668
+ // ── counters & sampling ──
1669
+ let depositCount = 0;
1670
+ let trainedContentBytes = 0;
1671
+ let bytesSinceCkpt = 0;
1672
+ let checkpointNum = 0;
1673
+ let totalBytesProcessed = 0;
1674
+ let totalCorpusBytes = 0;
1675
+ const langTally: Record<string, number> = {};
1676
+ const t0 = Date.now();
1677
+
1678
+ // Reservoir sample: one uniformly-random item from the current window, shown
1679
+ // in the recall box at each checkpoint.
1680
+ let sampleItem: TrainingItem | null = null;
1681
+ let seenInWindow = 0;
1682
+ const sample = (it: TrainingItem) => {
1683
+ seenInWindow++;
1684
+ if (Math.random() < 1 / seenInWindow) sampleItem = it;
1685
+ };
1686
+
1687
+ // ── progress panel ──
1688
+ const progress = new Progress();
1689
+ // Surface rate-limit waits from the low-level fetch retries into the live log,
1690
+ // so a 429 back-off reads as "waiting", never a silent hang or a dropped file.
1691
+ onThrottleWait = (ms, label) => {
1692
+ progress.log(
1693
+ ` ${YEL}⏳${R} rate-limited (${label}); waiting ${
1694
+ (ms / 1000).toFixed(1)
1695
+ }s and retrying — not skipping`,
1696
+ );
1697
+ };
1698
+ const state: ProgState = {
1699
+ exampleCount: 0,
1700
+ target: MAX_BYTES,
1701
+ elapsedS: 0,
1702
+ trainedBytes: 0,
1703
+ trainedRate: 0,
1704
+ bytesDone: 0,
1705
+ bytesTotal: 0,
1706
+ bytesRate: 0,
1707
+ fileIndex: 0,
1708
+ fileTotal: 0,
1709
+ filePath: "",
1710
+ fileSize: 0,
1711
+ fileExamples: 0,
1712
+ activity: "idle",
1713
+ dlSpeed: 0,
1714
+ dlDone: 0,
1715
+ dlTotal: 0,
1716
+ storeEntries: 0,
1717
+ cacheBytes: 0,
1718
+ lastSample: null,
1719
+ };
1720
+
1721
+ // store.size() is async; refresh it on a slow cadence so the hot loop and
1722
+ // the repaint never block on a query.
1723
+ let cachedEntries = 0;
1724
+ let sizeInFlight = false;
1725
+ const refreshSize = () => {
1726
+ if (sizeInFlight) return;
1727
+ sizeInFlight = true;
1728
+ void mind.store.size()
1729
+ .then((n) => (cachedEntries = n))
1730
+ .catch(() => undefined)
1731
+ .finally(() => (sizeInFlight = false));
1732
+ };
1733
+
1734
+ // Cache size changes only at download/delete boundaries — recompute it
1735
+ // lazily rather than statting the dir on every deposit.
1736
+ let cachedCacheBytes = 0;
1737
+ let lastCacheUpdate = 0;
1738
+
1739
+ // Live download progress for the panel.
1740
+ let dlSlot: { done: number; total: number; t0: number } | null = null;
1741
+
1742
+ // Rolling throughput: a short EMA over wall-clock windows, so the headline
1743
+ // figures reflect CURRENT speed rather than a lifetime average diluted by the
1744
+ // listing and download phases (which train nothing).
1745
+ let rateT = t0;
1746
+ let rateTrained = 0;
1747
+ let rateBytes = 0;
1748
+ const syncState = () => {
1749
+ const now = Date.now();
1750
+ state.exampleCount = depositCount;
1751
+ state.trainedBytes = trainedContentBytes;
1752
+ state.elapsedS = (now - t0) / 1000;
1753
+ state.storeEntries = cachedEntries;
1754
+ state.bytesDone = totalBytesProcessed;
1755
+ state.bytesTotal = totalCorpusBytes;
1756
+
1757
+ if (dlSlot && state.activity === "download") {
1758
+ state.dlDone = dlSlot.done;
1759
+ state.dlTotal = dlSlot.total;
1760
+ const ds = (now - dlSlot.t0) / 1000;
1761
+ state.dlSpeed = ds > 0.2 ? dlSlot.done / ds : 0;
1762
+ } else {
1763
+ state.dlDone = 0;
1764
+ state.dlTotal = 0;
1765
+ }
1766
+
1767
+ const dt = (now - rateT) / 1000;
1768
+ if (dt >= 0.5) {
1769
+ const instTrained = (trainedContentBytes - rateTrained) / dt;
1770
+ const instByte = (totalBytesProcessed - rateBytes) / dt;
1771
+ const a = 0.3; // EMA weight on the newest sample
1772
+ state.trainedRate = state.trainedRate === 0
1773
+ ? instTrained
1774
+ : state.trainedRate * (1 - a) + instTrained * a;
1775
+ state.bytesRate = state.bytesRate === 0
1776
+ ? instByte
1777
+ : state.bytesRate * (1 - a) + instByte * a;
1778
+ rateT = now;
1779
+ rateTrained = trainedContentBytes;
1780
+ rateBytes = totalBytesProcessed;
1781
+ }
1782
+
1783
+ if (now - lastCacheUpdate > 2000) {
1784
+ cachedCacheBytes = cacheSize();
1785
+ lastCacheUpdate = now;
1786
+ }
1787
+ state.cacheBytes = cachedCacheBytes;
1788
+ };
1789
+
1790
+ const tick = (force = false) => {
1791
+ syncState();
1792
+ progress.render(state, force);
1793
+ };
1794
+
1795
+ const paintTimer = setInterval(() => {
1796
+ refreshSize();
1797
+ tick(false);
1798
+ }, PROGRESS_MS);
1799
+ if (typeof paintTimer.unref === "function") paintTimer.unref();
1800
+
1801
+ // ── keep-alive: the process must never exit on its own mid-training ──
1802
+ // The CPU-bound processing phase (perceive + intern + the batched vector-index
1803
+ // writes) hands control back to the event loop between batches via the store's
1804
+ // yieldToEventLoop(), which parks on an UNREF'd setImmediate so the library
1805
+ // never holds a process open by itself. node:sqlite is synchronous and the
1806
+ // vector index is in-memory, so the store's awaits resolve as microtasks with
1807
+ // no I/O handle, and the paint timer above is unref'd too. That leaves a window
1808
+ // — a batch flush that fires while we're processing an in-memory chunk, not
1809
+ // awaiting a disk read — in which the ONLY pending work is that unref'd
1810
+ // setImmediate and NOTHING is ref'd. Node's rule is to exit when only unref'd
1811
+ // handles remain, WITHOUT running them: the yield's continuation never fires,
1812
+ // main() is abandoned, and the process exits 0 silently mid-file — no error for
1813
+ // the fault-tolerance to catch. This one ref'd (NOT unref'd) timer guarantees a
1814
+ // live handle for the whole run, so the loop can never drain from under a
1815
+ // pending yield. Every real exit is an explicit process.exit() (finish(), the
1816
+ // shutdown watchdog, the second-signal path, the fatal catch), so keeping this
1817
+ // handle alive never delays a genuine shutdown; finish() clears it before that
1818
+ // final exit for tidiness. Same lesson as waitMs above (deliberately un-unref'd).
1819
+ const keepAlive = setInterval(() => {}, 1 << 30);
1820
+
1821
+ const checkpoint = () => mind.save();
1822
+
1823
+ /** Run index maintenance: compact (remove garbage) then repair (fill gaps).
1824
+ * Both are idempotent — running twice produces the same result as once.
1825
+ * Compaction frees index space first; repair then adds back the bridges
1826
+ * whose gists were evicted before indexing, completing the coverage that
1827
+ * incremental bridge promotion alone cannot guarantee.
1828
+ *
1829
+ * Logs the number of entries removed/added so a run that silently degrades
1830
+ * (growing compaction count, or repair never recovering anything) is
1831
+ * visible in the training log. */
1832
+ const runIndexMaintenance = async (): Promise<void> => {
1833
+ if (!INDEX_MAINTENANCE) return;
1834
+ try {
1835
+ const removed = await mind.store.compactContentIndex();
1836
+ if (removed > 0) {
1837
+ progress.log(
1838
+ ` ${DIM}index compact: removed ${int(removed)} isolated entries${R}`,
1839
+ );
1840
+ }
1841
+ } catch (err) {
1842
+ progress.log(
1843
+ ` ${YEL}⚠ index compact failed${R}: ${
1844
+ err instanceof Error ? err.message : String(err)
1845
+ }`,
1846
+ );
1847
+ }
1848
+ try {
1849
+ const added = await mind.repairContentIndex();
1850
+ if (added > 0) {
1851
+ progress.log(
1852
+ ` ${GRN}index repair: added ${int(added)} missing bridges${R}`,
1853
+ );
1854
+ }
1855
+ } catch (err) {
1856
+ progress.log(
1857
+ ` ${YEL}⚠ index repair failed${R}: ${
1858
+ err instanceof Error ? err.message : String(err)
1859
+ }`,
1860
+ );
1861
+ }
1862
+ };
1863
+
1864
+ // The checkpoint recall is a best-effort diagnostic. It is time-bounded so a
1865
+ // slow/large store can never freeze the deposit loop, and guarded so a still
1866
+ // running recall is never stacked on top of another.
1867
+ let inferBusy = false;
1868
+ const runRecall = async (item: TrainingItem, n: number): Promise<void> => {
1869
+ if (inferBusy) return;
1870
+ inferBusy = true;
1871
+ try {
1872
+ const info = promptOf(item);
1873
+ const r = await withTimeout(
1874
+ mind.respond(info.prompt),
1875
+ INFER_TIMEOUT_MS,
1876
+ "recall",
1877
+ );
1878
+ const resp = new TextDecoder().decode(r.bytes).replace(/\u0000+/g, "");
1879
+ const box = renderInferenceBox(
1880
+ info.prompt,
1881
+ info.expected,
1882
+ resp,
1883
+ info.kind,
1884
+ n,
1885
+ );
1886
+ state.lastSample = box;
1887
+ if (!progress.interactive) progress.log(box);
1888
+ tick(true);
1889
+ } catch (err) {
1890
+ progress.log(
1891
+ ` ${DIM}· checkpoint #${n} recall skipped: ${
1892
+ err instanceof Error ? err.message : String(err)
1893
+ }${R}`,
1894
+ );
1895
+ } finally {
1896
+ inferBusy = false;
1897
+ }
1898
+ };
1899
+
1900
+ // ── graceful shutdown (always leaves the store consistent) ──
1901
+ let stopRequested = false;
1902
+ let stopReason = "interrupted";
1903
+ let finishing = false;
1904
+
1905
+ const finish = async (why: string): Promise<void> => {
1906
+ if (finishing) return;
1907
+ finishing = true;
1908
+ shutdown.abort(); // unblock any straggling fetch/pipeTo
1909
+ tick(true);
1910
+ await store.setMeta("train.completedAt", new Date().toISOString());
1911
+ await store.setMeta("train.totalDeposits", String(depositCount));
1912
+ await store.setMeta("train.totalTrainedBytes", String(trainedContentBytes));
1913
+ await store.setMeta("train.totalBytes", String(totalBytesProcessed));
1914
+ await store.setMeta(
1915
+ "train.totalCorpusBytes",
1916
+ String(totalCorpusBytes),
1917
+ );
1918
+ await store.setMeta("train.langTally", JSON.stringify(langTally));
1919
+ try {
1920
+ await runIndexMaintenance();
1921
+ await checkpoint();
1922
+ } catch (err) {
1923
+ process.stderr.write(
1924
+ `\n ${YEL}⚠ final checkpoint failed${R}: ${
1925
+ err instanceof Error ? err.message : String(err)
1926
+ }\n`,
1927
+ );
1928
+ }
1929
+ clearInterval(paintTimer);
1930
+ clearInterval(keepAlive);
1931
+ progress.dispose();
1932
+ const elapsedS = (Date.now() - t0) / 1000;
1933
+ const elapsed = dur(elapsedS);
1934
+ const avgRate = elapsedS > 0 ? trainedContentBytes / elapsedS : 0;
1935
+ const tally = Object.entries(langTally)
1936
+ .sort((a, b) => b[1] - a[1])
1937
+ .map(([k, v]) => `${k}:${int(v)}`)
1938
+ .join(", ");
1939
+ let entries = depositCount;
1940
+ try {
1941
+ entries = await mind.store.size();
1942
+ } catch { /* best effort */ }
1943
+ console.log(
1944
+ `\n${GRN}✓${R} ${why}. ${basename(DB_PATH)}.sqlite: ` +
1945
+ `${int(entries)} entries, ${int(depositCount)} examples, ` +
1946
+ `${bytes(trainedContentBytes)} content learned ` +
1947
+ `${DIM}(${bytes(avgRate)}/s avg)${R}, ` +
1948
+ `${bytes(totalBytesProcessed)} corpus processed, ${elapsed} elapsed.` +
1949
+ (tally ? `\n ${DIM}per language:${R} ${tally}` : ""),
1950
+ );
1951
+ try {
1952
+ await store.close();
1953
+ } catch { /* best effort */ }
1954
+ process.exit(0);
1955
+ };
1956
+
1957
+ const requestStop = (reason: string) => {
1958
+ if (stopRequested) {
1959
+ process.stderr.write(`\n${YEL}⚠ second signal — exiting now${R}\n`);
1960
+ process.stderr.write(SHOW);
1961
+ process.exit(130);
1962
+ }
1963
+ stopRequested = true;
1964
+ stopReason = reason;
1965
+ shutdown.abort();
1966
+ progress.log(` ${YEL}⏸${R} ${reason} — finishing current item, saving…`);
1967
+ const watchdog = setTimeout(() => {
1968
+ process.stderr.write(
1969
+ `\n${YEL}⚠ shutdown watchdog fired — forcing exit${R}\n`,
1970
+ );
1971
+ process.stderr.write(SHOW);
1972
+ process.exit(130);
1973
+ }, 60_000);
1974
+ if (typeof watchdog.unref === "function") watchdog.unref();
1975
+ };
1976
+ process.on("SIGINT", () => requestStop("interrupted"));
1977
+ process.on("SIGTERM", () => requestStop("terminated"));
1978
+
1979
+ // ── fail-safe: a dropped connection must never kill a long run ──
1980
+ process.on("unhandledRejection", (reason) => {
1981
+ progress.log(
1982
+ ` ${YEL}⚠ unhandled rejection${R}: ${
1983
+ reason instanceof Error ? reason.message : String(reason)
1984
+ }`,
1985
+ );
1986
+ });
1987
+ process.on("uncaughtException", (err) => {
1988
+ const code = (err as any)?.code ?? (err as any)?.cause?.code;
1989
+ if (err.message === "terminated" || code === "UND_ERR_SOCKET") {
1990
+ progress.log(` ${YEL}⚠ connection error (ignored)${R}: ${err.message}`);
1991
+ return;
1992
+ }
1993
+ process.stderr.write(
1994
+ `\n${RED}uncaught exception${R}: ${err.message}\n${err.stack ?? ""}\n`,
1995
+ );
1996
+ try {
1997
+ void store.setMeta("train.crashedAt", new Date().toISOString());
1998
+ void store.setMeta("train.crashError", err.message);
1999
+ void store.setMeta("train.totalDeposits", String(depositCount));
2000
+ } catch { /* best effort */ }
2001
+ process.exit(1);
2002
+ });
2003
+
2004
+ // ── per-example callback: gates MAX_MB, drives checkpoints + samples ──
2005
+ const onDeposit = async (contentBytes: number): Promise<boolean> => {
2006
+ depositCount++;
2007
+ trainedContentBytes += contentBytes;
2008
+ bytesSinceCkpt += contentBytes;
2009
+ state.fileExamples++;
2010
+
2011
+ if (bytesSinceCkpt >= CHECKPOINT_BYTES) {
2012
+ bytesSinceCkpt %= CHECKPOINT_BYTES;
2013
+ const n = ++checkpointNum;
2014
+ const item = sampleItem;
2015
+ sampleItem = null;
2016
+ seenInWindow = 0;
2017
+ if (item) await runRecall(item, n);
2018
+ try {
2019
+ await runIndexMaintenance();
2020
+ await checkpoint();
2021
+ } catch (err) {
2022
+ progress.log(
2023
+ ` ${YEL}⚠ checkpoint failed${R}: ${
2024
+ err instanceof Error ? err.message : String(err)
2025
+ }`,
2026
+ );
2027
+ }
2028
+ tick(true);
2029
+ } else {
2030
+ tick();
2031
+ }
2032
+
2033
+ // Stop AFTER the deposit is counted/displayed so the final item is never
2034
+ // lost from the totals. A pending signal stops at this same boundary, so a
2035
+ // clean shutdown and a MAX_MB cap unwind through identical, tested code.
2036
+ return !stopRequested && trainedContentBytes < MAX_BYTES;
2037
+ };
2038
+
2039
+ const cacheWarn = (m: string) => progress.log(` ${m}`);
2040
+
2041
+ /** Acquire a source file: reuse a cached copy, else download `url` into the
2042
+ * cache under `destName` (atomic, retried, rate-limit-tolerant, shows live
2043
+ * byte progress). Returns the local path, or null on a non-abort failure
2044
+ * (logged). `label` names the file in the panel/log. */
2045
+ const acquire = async (
2046
+ url: string,
2047
+ destName: string,
2048
+ label: string,
2049
+ ): Promise<string | null> => {
2050
+ const dest = join(CACHE_DIR, destName);
2051
+ if (existsSync(dest)) {
2052
+ progress.log(` ${GRN}✓${R} ${label} ${DIM}(cached)${R}`);
2053
+ return dest;
2054
+ }
2055
+ let size = 0;
2056
+ try {
2057
+ size = await headSize(url);
2058
+ } catch { /* unknown — proceed without a cache-room reservation */ }
2059
+ state.activity = "download";
2060
+ state.filePath = label;
2061
+ state.fileSize = size;
2062
+ const slot = { done: 0, total: size, t0: Date.now() };
2063
+ dlSlot = slot;
2064
+ tick(true);
2065
+ try {
2066
+ await ensureCacheRoom(size, cacheWarn);
2067
+ slot.t0 = Date.now();
2068
+ await downloadFile(
2069
+ url,
2070
+ dest,
2071
+ DOWNLOAD_TRIES,
2072
+ (n, e) =>
2073
+ progress.log(
2074
+ ` ${YEL}⚠${R} ${label} download attempt ${n}/${DOWNLOAD_TRIES}: ${e.message}`,
2075
+ ),
2076
+ (done, total) => {
2077
+ slot.done = done;
2078
+ if (total > 0) slot.total = total;
2079
+ },
2080
+ );
2081
+ } catch (e) {
2082
+ dlSlot = null;
2083
+ if (stopRequested || (e as Error)?.name === "AbortError") return null;
2084
+ progress.log(
2085
+ ` ${RED}✗${R} ${label} download failed: ${(e as Error).message}`,
2086
+ );
2087
+ try {
2088
+ unlinkSync(dest);
2089
+ } catch { /* best effort */ }
2090
+ return null;
2091
+ }
2092
+ dlSlot = null;
2093
+ const dlS = Math.max(0.001, (Date.now() - slot.t0) / 1000);
2094
+ const sz = statSync(dest).size;
2095
+ progress.log(
2096
+ ` ${CYAN}⬇${R} ${label} ${bytes(sz)} ${DIM}${dur(dlS)} @ ${
2097
+ bytes(sz / dlS)
2098
+ }/s${R}`,
2099
+ );
2100
+ return dest;
2101
+ };
2102
+
2103
+ // ── §10a SmolSent stage (the FIRST stage) ──
2104
+ //
2105
+ // Downloads each SmolSent per-pair JSONL file and streams its lines. Resume is
2106
+ // per-file: a fully-consumed file is recorded in completedFiles
2107
+ // ("smolsent::<name>"); an interrupted file is re-streamed from the top on
2108
+ // resume (re-deposition is idempotent). LOCAL_PATH may hold pre-downloaded
2109
+ // smolsent *.jsonl files.
2110
+ const smolToItems = (row: unknown): TrainingItem[] | null => {
2111
+ const r = toSmolSentRow(row);
2112
+ return r ? smolSentRowToItems(r) : null;
2113
+ };
2114
+ const trainSmolSent = async (): Promise<void> => {
2115
+ if (!SMOLSENT) return;
2116
+ if (trainedContentBytes >= MAX_BYTES || stopRequested) return;
2117
+
2118
+ // Work-list: local *.jsonl in LOCAL_PATH, else the repo's smolsent/ files.
2119
+ let files: Array<
2120
+ { id: string; name: string; local?: string; url?: string }
2121
+ >;
2122
+ if (LOCAL_PATH) {
2123
+ files = readdirSync(LOCAL_PATH)
2124
+ .filter((f: string) => /\.jsonl$/i.test(f))
2125
+ .sort()
2126
+ .map((f: string) => ({
2127
+ id: `${SMOLSENT_ID}::${f}`,
2128
+ name: f,
2129
+ local: join(LOCAL_PATH, f),
2130
+ }));
2131
+ if (SMOLSENT_PAIRS.length) {
2132
+ const want = new Set(
2133
+ SMOLSENT_PAIRS.map((p) => p.replace(/\.jsonl$/i, "")),
2134
+ );
2135
+ files = files.filter((f) => want.has(f.name.replace(/\.jsonl$/i, "")));
2136
+ }
2137
+ } else {
2138
+ let paths: string[];
2139
+ try {
2140
+ paths = await listSmolSentFiles();
2141
+ } catch (e) {
2142
+ if (stopRequested || (e as Error)?.name === "AbortError") return;
2143
+ progress.log(
2144
+ ` ${RED}✗${R} SmolSent file listing failed: ${(e as Error).message}`,
2145
+ );
2146
+ return;
2147
+ }
2148
+ files = paths.map((path) => ({
2149
+ id: `${SMOLSENT_ID}::${basename(path)}`,
2150
+ name: basename(path),
2151
+ // owner/name and the file path are URL PATH segments — do not encode "/".
2152
+ url:
2153
+ `https://huggingface.co/datasets/${SMOLSENT_DATASET}/resolve/main/${path}`,
2154
+ }));
2155
+ }
2156
+ if (files.length === 0) {
2157
+ progress.log(` ${DIM}· no SmolSent files found — skipping${R}`);
2158
+ return;
2159
+ }
2160
+
2161
+ const p = await loadProgress(store);
2162
+ const done = new Set(p.completedFiles);
2163
+ const remaining = files.filter((f) => !done.has(f.id));
2164
+ if (remaining.length === 0) {
2165
+ progress.log(` ${DIM}· SmolSent already trained — skipping${R}`);
2166
+ return;
2167
+ }
2168
+ state.fileTotal = files.length;
2169
+ progress.log(
2170
+ ` ${GRN}✓${R} SmolSent: ${remaining.length}/${files.length} translation file(s) to train`,
2171
+ );
2172
+
2173
+ let idx = 0;
2174
+ for (const f of files) {
2175
+ if (trainedContentBytes >= MAX_BYTES || stopRequested) break;
2176
+ idx++;
2177
+ if (done.has(f.id)) continue;
2178
+
2179
+ // Acquire (download or reuse), then stream the JSONL.
2180
+ let path = f.local ?? "";
2181
+ let downloaded = false;
2182
+ if (!path) {
2183
+ const got = await acquire(
2184
+ f.url!,
2185
+ f.id.replace(/[^A-Za-z0-9._-]+/g, "_"),
2186
+ `SmolSent ${f.name}`,
2187
+ );
2188
+ if (!got) {
2189
+ if (stopRequested) break;
2190
+ continue; // a single failed file never aborts the stage
2191
+ }
2192
+ path = got;
2193
+ downloaded = true;
2194
+ }
2195
+
2196
+ // Accumulate known corpus bytes so the progress bar shows a
2197
+ // meaningful ETA — grows as each file's size is discovered.
2198
+ try {
2199
+ totalCorpusBytes += statSync(path).size;
2200
+ } catch { /* best effort */ }
2201
+
2202
+ state.activity = "process";
2203
+ state.fileIndex = idx;
2204
+ state.filePath = `SmolSent ${f.name}`;
2205
+ state.fileExamples = 0;
2206
+ tick(true);
2207
+ const p0 = Date.now();
2208
+ let res: FileResult;
2209
+ try {
2210
+ res = await processJsonl(
2211
+ path,
2212
+ smolToItems,
2213
+ ci,
2214
+ onDeposit,
2215
+ sample,
2216
+ MAX_SMOLSENT_CHARS * 4,
2217
+ );
2218
+ } catch (e) {
2219
+ if (stopRequested || (e as Error)?.name === "AbortError") break;
2220
+ progress.log(
2221
+ ` ${RED}✗${R} SmolSent ${f.name} parse failed: ${
2222
+ (e as Error).message
2223
+ }`,
2224
+ );
2225
+ if (downloaded) {
2226
+ try {
2227
+ unlinkSync(path);
2228
+ } catch { /* best effort */ }
2229
+ }
2230
+ continue;
2231
+ }
2232
+ langTally["smolsent"] = (langTally["smolsent"] ?? 0) + res.examples;
2233
+ progress.log(
2234
+ ` ${GRN}✓${R} ${
2235
+ f.name.replace(/\.jsonl$/i, "")
2236
+ } ${DIM}[translation]${R} → ${int(res.examples)} facts ${DIM}in ${
2237
+ dur((Date.now() - p0) / 1000)
2238
+ }${R}` +
2239
+ (res.skipped
2240
+ ? ` ${YEL}· ${int(res.skipped)} unusable row(s) skipped${R}`
2241
+ : "") +
2242
+ (res.stopped ? ` ${YEL}(stopped early)${R}` : ""),
2243
+ );
2244
+
2245
+ if (!res.stopped) {
2246
+ try {
2247
+ totalBytesProcessed += statSync(path).size;
2248
+ } catch { /* best effort */ }
2249
+ if (downloaded) {
2250
+ try {
2251
+ unlinkSync(path);
2252
+ } catch { /* best effort */ }
2253
+ }
2254
+ done.add(f.id);
2255
+ p.completedFiles.push(f.id);
2256
+ }
2257
+ try {
2258
+ await saveProgress(store, {
2259
+ completedFiles: p.completedFiles,
2260
+ depositCount,
2261
+ trainedContentBytes,
2262
+ totalBytesProcessed,
2263
+ totalCorpusBytes,
2264
+ });
2265
+ await store.setMeta("train.langTally", JSON.stringify(langTally));
2266
+ } catch { /* best effort — finish() will retry */ }
2267
+ if (res.stopped) break; // cap/signal — leave file un-completed for resume
2268
+ }
2269
+ };
2270
+
2271
+ // ── §10b Aya Dataset stage (runs AFTER SmolSent) ──
2272
+ //
2273
+ // Downloads the one train Parquet file and reads it row-group by row-group
2274
+ // (hyparquet + Snappy) — one (inputs → targets) fact per row. Marked complete
2275
+ // only when fully consumed; an interrupted run re-reads from the top on resume
2276
+ // (re-deposition is idempotent). LOCAL_PATH may hold a pre-downloaded *.parquet.
2277
+ const ayaToItems = (row: unknown): TrainingItem[] | null => {
2278
+ const r = toAyaRow(row);
2279
+ return r ? ayaRowToItems(r) : null;
2280
+ };
2281
+ const trainAya = async (): Promise<void> => {
2282
+ if (!AYA) return;
2283
+ if (trainedContentBytes >= MAX_BYTES || stopRequested) return;
2284
+
2285
+ const p = await loadProgress(store);
2286
+ if (p.completedFiles.includes(AYA_ID)) {
2287
+ progress.log(` ${DIM}· Aya Dataset already trained — skipping${R}`);
2288
+ return;
2289
+ }
2290
+
2291
+ let path = "", downloaded = false;
2292
+ if (LOCAL_PATH) {
2293
+ const hit = readdirSync(LOCAL_PATH).find((f: string) =>
2294
+ /aya.*\.parquet$/i.test(f) || /\.parquet$/i.test(f)
2295
+ );
2296
+ if (!hit) {
2297
+ progress.log(
2298
+ ` ${DIM}· no Aya *.parquet in ${LOCAL_PATH} — skipping${R}`,
2299
+ );
2300
+ return;
2301
+ }
2302
+ path = join(LOCAL_PATH, hit);
2303
+ } else {
2304
+ const got = await acquire(AYA_URL, "aya_train.parquet", "Aya Dataset");
2305
+ if (!got) return;
2306
+ path = got;
2307
+ downloaded = true;
2308
+ }
2309
+
2310
+ try {
2311
+ totalCorpusBytes += statSync(path).size;
2312
+ } catch { /* best effort */ }
2313
+ state.fileTotal = 1;
2314
+ state.fileIndex = 1;
2315
+
2316
+ state.activity = "process";
2317
+ state.filePath = "Aya Dataset";
2318
+ state.fileExamples = 0;
2319
+ tick(true);
2320
+ const p0 = Date.now();
2321
+ let res: FileResult;
2322
+ try {
2323
+ res = await processParquet(path, ayaToItems, ci, onDeposit, sample);
2324
+ } catch (e) {
2325
+ if (stopRequested || (e as Error)?.name === "AbortError") return;
2326
+ progress.log(
2327
+ ` ${RED}✗${R} Aya processing failed: ${(e as Error).message}`,
2328
+ );
2329
+ return;
2330
+ }
2331
+ langTally["aya"] = (langTally["aya"] ?? 0) + res.examples;
2332
+ progress.log(
2333
+ ` ${GRN}✓${R} Aya Dataset ${DIM}[multilingual chat]${R} → ${
2334
+ int(res.examples)
2335
+ } facts ${DIM}in ${dur((Date.now() - p0) / 1000)}${R}` +
2336
+ (res.skipped
2337
+ ? ` ${YEL}· ${int(res.skipped)} unusable row(s) skipped${R}`
2338
+ : "") +
2339
+ (res.stopped ? ` ${YEL}(stopped early)${R}` : ""),
2340
+ );
2341
+
2342
+ if (!res.stopped) {
2343
+ try {
2344
+ totalBytesProcessed += statSync(path).size;
2345
+ } catch { /* best effort */ }
2346
+ if (downloaded) {
2347
+ try {
2348
+ unlinkSync(path);
2349
+ } catch { /* best effort */ }
2350
+ }
2351
+ p.completedFiles.push(AYA_ID);
2352
+ }
2353
+ try {
2354
+ await saveProgress(store, {
2355
+ completedFiles: p.completedFiles,
2356
+ depositCount,
2357
+ trainedContentBytes,
2358
+ totalBytesProcessed,
2359
+ totalCorpusBytes,
2360
+ });
2361
+ await store.setMeta("train.langTally", JSON.stringify(langTally));
2362
+ } catch { /* best effort — finish() will retry */ }
2363
+ };
2364
+
2365
+ // ── §10c oasst2 stage (multi-turn conversations; runs AFTER Aya; both modes) ──
2366
+ //
2367
+ // Resolves the source (a local *trees*.jsonl.gz in
2368
+ // LOCAL_PATH, else the gzip downloaded to the cache), streams it, and marks
2369
+ // OASST_ID complete only when fully consumed (an interrupted run re-streams
2370
+ // from the top; re-deposition is idempotent). Only multi-turn conversations
2371
+ // are deposited — single Q→A trees are skipped inside processOasst.
2372
+ const trainOasst = async (): Promise<void> => {
2373
+ if (!OASST) return;
2374
+ if (trainedContentBytes >= MAX_BYTES || stopRequested) return;
2375
+
2376
+ const p = await loadProgress(store);
2377
+ if (p.completedFiles.includes(OASST_ID)) {
2378
+ progress.log(` ${DIM}· oasst2 already trained — skipping${R}`);
2379
+ return;
2380
+ }
2381
+
2382
+ let gzPath = "";
2383
+ let downloaded = false;
2384
+ if (LOCAL_PATH) {
2385
+ const hit = readdirSync(LOCAL_PATH).find((f: string) =>
2386
+ /oasst.*trees.*\.jsonl\.gz$/i.test(f) || /oasst.*\.jsonl\.gz$/i.test(f)
2387
+ );
2388
+ if (!hit) {
2389
+ progress.log(
2390
+ ` ${DIM}· no oasst2 *trees*.jsonl.gz in ${LOCAL_PATH} — skipping${R}`,
2391
+ );
2392
+ return;
2393
+ }
2394
+ gzPath = join(LOCAL_PATH, hit);
2395
+ } else {
2396
+ const dest = join(CACHE_DIR, "oasst2_ready.trees.jsonl.gz");
2397
+ if (existsSync(dest)) {
2398
+ gzPath = dest; // reuse a copy left by a previous interrupted run
2399
+ progress.log(` ${GRN}✓${R} oasst2 trees ${DIM}(cached)${R}`);
2400
+ } else {
2401
+ let size = 0;
2402
+ try {
2403
+ size = await headSize(OASST_URL);
2404
+ } catch { /* unknown — proceed without a cache-room reservation */ }
2405
+ state.activity = "download";
2406
+ state.filePath = "oasst2 trees";
2407
+ state.fileSize = size;
2408
+ const slot = { done: 0, total: size, t0: Date.now() };
2409
+ dlSlot = slot;
2410
+ tick(true);
2411
+ try {
2412
+ await ensureCacheRoom(size, cacheWarn);
2413
+ slot.t0 = Date.now();
2414
+ await downloadFile(
2415
+ OASST_URL,
2416
+ dest,
2417
+ DOWNLOAD_TRIES,
2418
+ (n, e) =>
2419
+ progress.log(
2420
+ ` ${YEL}⚠${R} oasst2 download attempt ${n}/${DOWNLOAD_TRIES}: ${e.message}`,
2421
+ ),
2422
+ (done, total) => {
2423
+ slot.done = done;
2424
+ if (total > 0) slot.total = total;
2425
+ },
2426
+ );
2427
+ } catch (e) {
2428
+ dlSlot = null;
2429
+ if (stopRequested || (e as Error)?.name === "AbortError") return;
2430
+ progress.log(
2431
+ ` ${RED}✗${R} oasst2 download failed: ${(e as Error).message}`,
2432
+ );
2433
+ try {
2434
+ unlinkSync(dest);
2435
+ } catch { /* best effort */ }
2436
+ return;
2437
+ }
2438
+ dlSlot = null;
2439
+ const dlS = Math.max(0.001, (Date.now() - slot.t0) / 1000);
2440
+ const sz = statSync(dest).size;
2441
+ progress.log(
2442
+ ` ${CYAN}⬇${R} oasst2 trees ${bytes(sz)} ` +
2443
+ `${DIM}${dur(dlS)} @ ${bytes(sz / dlS)}/s${R}`,
2444
+ );
2445
+ gzPath = dest;
2446
+ downloaded = true;
2447
+ }
2448
+ }
2449
+
2450
+ try {
2451
+ totalCorpusBytes += statSync(gzPath).size;
2452
+ } catch { /* best effort */ }
2453
+ state.fileTotal = 1;
2454
+ state.fileIndex = 1;
2455
+
2456
+ // Stream the trees.
2457
+ state.activity = "process";
2458
+ state.filePath = "oasst2 (multi-turn)";
2459
+ state.fileExamples = 0;
2460
+ tick(true);
2461
+ const p0 = Date.now();
2462
+ let result: {
2463
+ examples: number;
2464
+ stopped: boolean;
2465
+ skipped: number;
2466
+ multi: number;
2467
+ };
2468
+ try {
2469
+ result = await processOasst(gzPath, ci, onDeposit, sample);
2470
+ } catch (e) {
2471
+ if (stopRequested || (e as Error)?.name === "AbortError") return;
2472
+ progress.log(
2473
+ ` ${RED}✗${R} oasst2 processing failed: ${(e as Error).message}`,
2474
+ );
2475
+ return;
2476
+ }
2477
+ const { examples, stopped, skipped, multi } = result;
2478
+ langTally["oasst2"] = (langTally["oasst2"] ?? 0) + examples;
2479
+ progress.log(
2480
+ ` ${GRN}✓${R} oasst2 ${DIM}[multi-turn chat]${R} → ${
2481
+ int(examples)
2482
+ } examples from ${int(multi)} conversation(s) ${DIM}in ${
2483
+ dur((Date.now() - p0) / 1000)
2484
+ }${R}` +
2485
+ (skipped
2486
+ ? ` ${YEL}· ${int(skipped)} malformed line(s) skipped${R}`
2487
+ : "") +
2488
+ (stopped ? ` ${YEL}(stopped early)${R}` : ""),
2489
+ );
2490
+
2491
+ // Only mark complete (and reclaim the cache) when fully consumed.
2492
+ if (!stopped) {
2493
+ try {
2494
+ totalBytesProcessed += statSync(gzPath).size;
2495
+ } catch { /* best effort */ }
2496
+ if (downloaded) {
2497
+ try {
2498
+ unlinkSync(gzPath);
2499
+ } catch { /* best effort */ }
2500
+ }
2501
+ p.completedFiles.push(OASST_ID);
2502
+ }
2503
+ try {
2504
+ await saveProgress(store, {
2505
+ completedFiles: p.completedFiles,
2506
+ depositCount,
2507
+ trainedContentBytes,
2508
+ totalBytesProcessed,
2509
+ totalCorpusBytes,
2510
+ });
2511
+ await store.setMeta("train.langTally", JSON.stringify(langTally));
2512
+ } catch { /* best effort — finish() will retry */ }
2513
+ };
2514
+
2515
+ // ── §10d General-Knowledge stage (runs AFTER oasst2) ──
2516
+ //
2517
+ // Downloads the single JSON-array file (output.json) and deposits each
2518
+ // {Question, Answer} as one fact. Marked complete only when fully consumed.
2519
+ // LOCAL_PATH may hold a pre-downloaded *.json.
2520
+ const genToItems = (row: unknown): TrainingItem[] | null => {
2521
+ const r = toGenKnowRow(row);
2522
+ return r ? genKnowRowToItems(r) : null;
2523
+ };
2524
+ const trainGenKnow = async (): Promise<void> => {
2525
+ if (!GENKNOW) return;
2526
+ if (trainedContentBytes >= MAX_BYTES || stopRequested) return;
2527
+
2528
+ const p = await loadProgress(store);
2529
+ if (p.completedFiles.includes(GENKNOW_ID)) {
2530
+ progress.log(
2531
+ ` ${DIM}· General-Knowledge already trained — skipping${R}`,
2532
+ );
2533
+ return;
2534
+ }
2535
+
2536
+ let path = "", downloaded = false;
2537
+ if (LOCAL_PATH) {
2538
+ const hit = readdirSync(LOCAL_PATH).find((f: string) =>
2539
+ /general.*knowledge.*\.json$/i.test(f) || /output\.json$/i.test(f)
2540
+ );
2541
+ if (!hit) {
2542
+ progress.log(
2543
+ ` ${DIM}· no General-Knowledge *.json in ${LOCAL_PATH} — skipping${R}`,
2544
+ );
2545
+ return;
2546
+ }
2547
+ path = join(LOCAL_PATH, hit);
2548
+ } else {
2549
+ const got = await acquire(
2550
+ GENKNOW_URL,
2551
+ "general_knowledge.json",
2552
+ "General-Knowledge",
2553
+ );
2554
+ if (!got) return;
2555
+ path = got;
2556
+ downloaded = true;
2557
+ }
2558
+
2559
+ try {
2560
+ totalCorpusBytes += statSync(path).size;
2561
+ } catch { /* best effort */ }
2562
+ state.fileTotal = 1;
2563
+ state.fileIndex = 1;
2564
+
2565
+ state.activity = "process";
2566
+ state.filePath = "General-Knowledge";
2567
+ state.fileExamples = 0;
2568
+ tick(true);
2569
+ const p0 = Date.now();
2570
+ let res: FileResult;
2571
+ try {
2572
+ res = await processJsonArray(path, genToItems, ci, onDeposit, sample);
2573
+ } catch (e) {
2574
+ if (stopRequested || (e as Error)?.name === "AbortError") return;
2575
+ progress.log(
2576
+ ` ${RED}✗${R} General-Knowledge processing failed: ${
2577
+ (e as Error).message
2578
+ }`,
2579
+ );
2580
+ return;
2581
+ }
2582
+ langTally["genknow"] = (langTally["genknow"] ?? 0) + res.examples;
2583
+ progress.log(
2584
+ ` ${GRN}✓${R} General-Knowledge ${DIM}[Q&A facts]${R} → ${
2585
+ int(res.examples)
2586
+ } facts ${DIM}in ${dur((Date.now() - p0) / 1000)}${R}` +
2587
+ (res.skipped
2588
+ ? ` ${YEL}· ${int(res.skipped)} unusable row(s) skipped${R}`
2589
+ : "") +
2590
+ (res.stopped ? ` ${YEL}(stopped early)${R}` : ""),
2591
+ );
2592
+
2593
+ if (!res.stopped) {
2594
+ try {
2595
+ totalBytesProcessed += statSync(path).size;
2596
+ } catch { /* best effort */ }
2597
+ if (downloaded) {
2598
+ try {
2599
+ unlinkSync(path);
2600
+ } catch { /* best effort */ }
2601
+ }
2602
+ p.completedFiles.push(GENKNOW_ID);
2603
+ }
2604
+ try {
2605
+ await saveProgress(store, {
2606
+ completedFiles: p.completedFiles,
2607
+ depositCount,
2608
+ trainedContentBytes,
2609
+ totalBytesProcessed,
2610
+ totalCorpusBytes,
2611
+ });
2612
+ await store.setMeta("train.langTally", JSON.stringify(langTally));
2613
+ } catch { /* best effort — finish() will retry */ }
2614
+ };
2615
+
2616
+ // ── §10 Train the curriculum (resume-aware; one store records all stages) ──
2617
+ //
2618
+ // Every source is paged from an HTTP API (SmolSent, Aya) or a single
2619
+ // downloaded file (oasst2) — there is no per-file ZIP loop. Each stage closure
2620
+ // reads the authoritative completed-set from the store, skips itself when
2621
+ // already done, and persists its own progress, so the whole curriculum resumes
2622
+ // from the store alone. LOCAL_PATH lets oasst2 read a local *.jsonl.gz.
2623
+ tick(true);
2624
+
2625
+ // ── resume — restore counters and the per-source tally from the store ──
2626
+ const prog = await loadProgress(store);
2627
+ depositCount = prog.depositCount;
2628
+ trainedContentBytes = prog.trainedContentBytes;
2629
+ totalBytesProcessed = prog.totalBytesProcessed;
2630
+ totalCorpusBytes = prog.totalCorpusBytes;
2631
+ rateTrained = trainedContentBytes;
2632
+ rateBytes = totalBytesProcessed;
2633
+ try {
2634
+ const t = await store.getMeta("train.langTally");
2635
+ if (t) {
2636
+ const parsed = JSON.parse(t);
2637
+ if (parsed && typeof parsed === "object") {
2638
+ for (const [k, v] of Object.entries(parsed)) {
2639
+ langTally[k] = Number(v) || 0;
2640
+ }
2641
+ }
2642
+ }
2643
+ } catch { /* fresh tally */ }
2644
+ if (prog.completedFiles.length > 0) {
2645
+ progress.log(
2646
+ ` ${CYAN}↻${R} resuming: ${prog.completedFiles.length} stage-unit(s) done, ` +
2647
+ `${int(depositCount)} examples, ${bytes(trainedContentBytes)} learned`,
2648
+ );
2649
+ }
2650
+
2651
+ // Stage 1 (SmolSent translation facts), 2 (Aya multilingual chat), 3 (oasst2
2652
+ // multi-turn), 4 (General-Knowledge Q&A facts). Each is skipped on a resume
2653
+ // that already finished it.
2654
+ if (!stopRequested) await trainSmolSent();
2655
+ if (!stopRequested) await trainAya();
2656
+ if (!stopRequested) await trainOasst();
2657
+ if (!stopRequested) await trainGenKnow();
2658
+
2659
+ await finish(stopRequested ? stopReason : "done");
2660
+ }
2661
+
2662
+ // ═══════════════════════════════════════════════════════════════════════
2663
+ // §11 Entry point — only run when invoked directly, so importing the parser
2664
+ // functions above (e.g. for tests) never starts training.
2665
+ // ═══════════════════════════════════════════════════════════════════════
2666
+
2667
+ const isMain = import.meta.url === `file://${process.argv[1]}` ||
2668
+ process.argv[1]?.endsWith("train_base.js");
2669
+ if (isMain) {
2670
+ main().catch((e) => {
2671
+ process.stderr.write(SHOW);
2672
+ console.error(`\n${RED}fatal:${R}`, e);
2673
+ process.exit(1);
2674
+ });
2675
+ }