taskforce-model-foundry 0.0.0-stage → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (54) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +133 -2
  3. package/bin/tmf.mjs +353 -0
  4. package/docs/acceptance/2026-11-22-hf-peft-public-pilot.md +75 -0
  5. package/docs/acceptance/evidence/cp62-eval-report.json +279 -0
  6. package/docs/acceptance/r1-r7-reconciliation.md +185 -0
  7. package/docs/integration.md +228 -0
  8. package/docs/releases/v0.2.0.md +24 -0
  9. package/docs/tutorial.md +340 -0
  10. package/integrations/hermes-plugin/taskforce_model_foundry/__init__.py +193 -0
  11. package/integrations/hermes-plugin/taskforce_model_foundry/bridge.mjs +46 -0
  12. package/integrations/hermes-plugin/taskforce_model_foundry/plugin.yaml +7 -0
  13. package/integrations/hermes-plugin/tests/test_register.py +230 -0
  14. package/integrations/openclaw-plugin/index.mjs +27 -0
  15. package/integrations/openclaw-plugin/tools.mjs +73 -0
  16. package/openclaw.plugin.json +25 -0
  17. package/package.json +70 -4
  18. package/scripts/e2e-demo.sh +56 -0
  19. package/src/api.mjs +341 -0
  20. package/src/config.mjs +342 -0
  21. package/src/core/autograd.mjs +451 -0
  22. package/src/core/fsx.mjs +65 -0
  23. package/src/core/hash.mjs +47 -0
  24. package/src/core/rng.mjs +70 -0
  25. package/src/data/clean.mjs +115 -0
  26. package/src/data/dedupe.mjs +125 -0
  27. package/src/data/ingest.mjs +184 -0
  28. package/src/data/pii.mjs +142 -0
  29. package/src/data/pipeline.mjs +183 -0
  30. package/src/data/provenance.mjs +88 -0
  31. package/src/data/split.mjs +193 -0
  32. package/src/data/synth.mjs +198 -0
  33. package/src/eval/evaluator.mjs +137 -0
  34. package/src/eval/gates.mjs +114 -0
  35. package/src/eval/metrics.mjs +90 -0
  36. package/src/export/package.mjs +365 -0
  37. package/src/index.mjs +26 -0
  38. package/src/integrations/async-evaluate-worker.mjs +39 -0
  39. package/src/integrations/async-evaluate.mjs +125 -0
  40. package/src/integrations/hermes.mjs +177 -0
  41. package/src/integrations/openclaw.mjs +164 -0
  42. package/src/jobs/evaluate.mjs +172 -0
  43. package/src/jobs/runner.mjs +323 -0
  44. package/src/jobs/train.mjs +303 -0
  45. package/src/model/lora.mjs +53 -0
  46. package/src/model/tokenizer.mjs +73 -0
  47. package/src/model/transformer.mjs +276 -0
  48. package/src/train/backends/builtin-js.mjs +367 -0
  49. package/src/train/backends/hf-peft.mjs +597 -0
  50. package/src/train/backends/hf_peft_runner.py +397 -0
  51. package/src/train/backends/index.mjs +92 -0
  52. package/src/train/dataset.mjs +56 -0
  53. package/src/train/optimizer.mjs +99 -0
  54. package/src/version.mjs +5 -0
@@ -0,0 +1,451 @@
1
+ // Minimal reverse-mode autodiff over 2D float32 tensors.
2
+ //
3
+ // Scope is deliberately narrow: the builtin trainer processes one sequence at a
4
+ // time, so every activation in the model is a [rows, cols] matrix. Keeping the
5
+ // engine 2D-only removes the stride bookkeeping a general tensor library needs
6
+ // while still supporting a real transformer with real gradients.
7
+
8
+ export class Tensor {
9
+ constructor(data, rows, cols, { requiresGrad = false, name = null } = {}) {
10
+ if (data.length !== rows * cols) {
11
+ throw new Error(`tensor data length ${data.length} does not match shape ${rows}x${cols}`);
12
+ }
13
+ this.data = data instanceof Float32Array ? data : new Float32Array(data);
14
+ this.rows = rows;
15
+ this.cols = cols;
16
+ this.requiresGrad = requiresGrad;
17
+ this.name = name;
18
+ this.grad = null;
19
+ this.parents = [];
20
+ this.backwardFn = null;
21
+ }
22
+
23
+ get size() {
24
+ return this.rows * this.cols;
25
+ }
26
+
27
+ get isLeaf() {
28
+ return this.parents.length === 0;
29
+ }
30
+
31
+ // Grads are materialized lazily: a frozen leaf never allocates one.
32
+ ensureGrad() {
33
+ if (!this.grad) this.grad = new Float32Array(this.size);
34
+ return this.grad;
35
+ }
36
+
37
+ zeroGrad() {
38
+ if (this.grad) this.grad.fill(0);
39
+ }
40
+
41
+ at(r, c) {
42
+ return this.data[r * this.cols + c];
43
+ }
44
+
45
+ clone({ requiresGrad = this.requiresGrad, name = this.name } = {}) {
46
+ return new Tensor(this.data.slice(), this.rows, this.cols, { requiresGrad, name });
47
+ }
48
+
49
+ toArray() {
50
+ const out = [];
51
+ for (let r = 0; r < this.rows; r += 1) out.push(Array.from(this.data.subarray(r * this.cols, (r + 1) * this.cols)));
52
+ return out;
53
+ }
54
+ }
55
+
56
+ export function tensor(values, rows, cols, opts) {
57
+ const flat = Array.isArray(values[0]) ? values.flat() : values;
58
+ const r = rows ?? (Array.isArray(values[0]) ? values.length : 1);
59
+ const c = cols ?? (Array.isArray(values[0]) ? values[0].length : flat.length);
60
+ return new Tensor(new Float32Array(flat), r, c, opts);
61
+ }
62
+
63
+ export function zeros(rows, cols, opts) {
64
+ return new Tensor(new Float32Array(rows * cols), rows, cols, opts);
65
+ }
66
+
67
+ export function filled(rows, cols, value, opts) {
68
+ const d = new Float32Array(rows * cols);
69
+ d.fill(value);
70
+ return new Tensor(d, rows, cols, opts);
71
+ }
72
+
73
+ export function randn(rows, cols, rng, std = 0.02, opts) {
74
+ const d = new Float32Array(rows * cols);
75
+ for (let i = 0; i < d.length; i += 1) d[i] = rng.normal(0, std);
76
+ return new Tensor(d, rows, cols, opts);
77
+ }
78
+
79
+ // A tensor participates in the graph when it is trainable itself or descends
80
+ // from something trainable.
81
+ function tracked(...parents) {
82
+ return parents.some((p) => p.requiresGrad || !p.isLeaf);
83
+ }
84
+
85
+ function makeNode(out, parents, backwardFn) {
86
+ if (!tracked(...parents)) return out;
87
+ out.parents = parents;
88
+ out.backwardFn = backwardFn;
89
+ return out;
90
+ }
91
+
92
+ function accumulate(t, fn) {
93
+ // Frozen leaves (base weights during LoRA training) are dead ends: no grad
94
+ // is needed by anything upstream, so skip the work entirely.
95
+ if (t.isLeaf && !t.requiresGrad) return;
96
+ fn(t.ensureGrad());
97
+ }
98
+
99
+ export function matmul(a, b) {
100
+ if (a.cols !== b.rows) throw new Error(`matmul shape mismatch ${a.rows}x${a.cols} @ ${b.rows}x${b.cols}`);
101
+ const m = a.rows;
102
+ const k = a.cols;
103
+ const n = b.cols;
104
+ const out = zeros(m, n);
105
+ const ad = a.data;
106
+ const bd = b.data;
107
+ const od = out.data;
108
+ for (let i = 0; i < m; i += 1) {
109
+ const aRow = i * k;
110
+ const oRow = i * n;
111
+ for (let p = 0; p < k; p += 1) {
112
+ const av = ad[aRow + p];
113
+ if (av === 0) continue;
114
+ const bRow = p * n;
115
+ for (let j = 0; j < n; j += 1) od[oRow + j] += av * bd[bRow + j];
116
+ }
117
+ }
118
+ return makeNode(out, [a, b], (g) => {
119
+ accumulate(a, (ga) => {
120
+ for (let i = 0; i < m; i += 1) {
121
+ for (let p = 0; p < k; p += 1) {
122
+ let s = 0;
123
+ const bRow = p * n;
124
+ const gRow = i * n;
125
+ for (let j = 0; j < n; j += 1) s += g[gRow + j] * bd[bRow + j];
126
+ ga[i * k + p] += s;
127
+ }
128
+ }
129
+ });
130
+ accumulate(b, (gb) => {
131
+ for (let p = 0; p < k; p += 1) {
132
+ for (let j = 0; j < n; j += 1) {
133
+ let s = 0;
134
+ for (let i = 0; i < m; i += 1) s += ad[i * k + p] * g[i * n + j];
135
+ gb[p * n + j] += s;
136
+ }
137
+ }
138
+ });
139
+ });
140
+ }
141
+
142
+ export function matmulT(a, b) {
143
+ // a [m,k] @ b[n,k]^T -> [m,n]; avoids materializing the transpose in attention.
144
+ if (a.cols !== b.cols) throw new Error(`matmulT shape mismatch ${a.rows}x${a.cols} @ (${b.rows}x${b.cols})^T`);
145
+ const m = a.rows;
146
+ const k = a.cols;
147
+ const n = b.rows;
148
+ const out = zeros(m, n);
149
+ const ad = a.data;
150
+ const bd = b.data;
151
+ for (let i = 0; i < m; i += 1) {
152
+ for (let j = 0; j < n; j += 1) {
153
+ let s = 0;
154
+ for (let p = 0; p < k; p += 1) s += ad[i * k + p] * bd[j * k + p];
155
+ out.data[i * n + j] = s;
156
+ }
157
+ }
158
+ return makeNode(out, [a, b], (g) => {
159
+ accumulate(a, (ga) => {
160
+ for (let i = 0; i < m; i += 1) {
161
+ for (let p = 0; p < k; p += 1) {
162
+ let s = 0;
163
+ for (let j = 0; j < n; j += 1) s += g[i * n + j] * bd[j * k + p];
164
+ ga[i * k + p] += s;
165
+ }
166
+ }
167
+ });
168
+ accumulate(b, (gb) => {
169
+ for (let j = 0; j < n; j += 1) {
170
+ for (let p = 0; p < k; p += 1) {
171
+ let s = 0;
172
+ for (let i = 0; i < m; i += 1) s += g[i * n + j] * ad[i * k + p];
173
+ gb[j * k + p] += s;
174
+ }
175
+ }
176
+ });
177
+ });
178
+ }
179
+
180
+ export function add(a, b) {
181
+ if (a.rows !== b.rows || a.cols !== b.cols) throw new Error('add requires identical shapes');
182
+ const out = zeros(a.rows, a.cols);
183
+ for (let i = 0; i < out.size; i += 1) out.data[i] = a.data[i] + b.data[i];
184
+ return makeNode(out, [a, b], (g) => {
185
+ accumulate(a, (ga) => { for (let i = 0; i < g.length; i += 1) ga[i] += g[i]; });
186
+ accumulate(b, (gb) => { for (let i = 0; i < g.length; i += 1) gb[i] += g[i]; });
187
+ });
188
+ }
189
+
190
+ export function addRow(a, bias) {
191
+ // bias is [1, cols], broadcast down the rows.
192
+ if (bias.rows !== 1 || bias.cols !== a.cols) throw new Error('addRow requires a [1,cols] bias');
193
+ const out = zeros(a.rows, a.cols);
194
+ for (let r = 0; r < a.rows; r += 1) {
195
+ for (let c = 0; c < a.cols; c += 1) out.data[r * a.cols + c] = a.data[r * a.cols + c] + bias.data[c];
196
+ }
197
+ return makeNode(out, [a, bias], (g) => {
198
+ accumulate(a, (ga) => { for (let i = 0; i < g.length; i += 1) ga[i] += g[i]; });
199
+ accumulate(bias, (gb) => {
200
+ for (let r = 0; r < a.rows; r += 1) for (let c = 0; c < a.cols; c += 1) gb[c] += g[r * a.cols + c];
201
+ });
202
+ });
203
+ }
204
+
205
+ export function scale(a, factor) {
206
+ const out = zeros(a.rows, a.cols);
207
+ for (let i = 0; i < out.size; i += 1) out.data[i] = a.data[i] * factor;
208
+ return makeNode(out, [a], (g) => {
209
+ accumulate(a, (ga) => { for (let i = 0; i < g.length; i += 1) ga[i] += g[i] * factor; });
210
+ });
211
+ }
212
+
213
+ export function mul(a, b) {
214
+ if (a.rows !== b.rows || a.cols !== b.cols) throw new Error('mul requires identical shapes');
215
+ const out = zeros(a.rows, a.cols);
216
+ for (let i = 0; i < out.size; i += 1) out.data[i] = a.data[i] * b.data[i];
217
+ return makeNode(out, [a, b], (g) => {
218
+ accumulate(a, (ga) => { for (let i = 0; i < g.length; i += 1) ga[i] += g[i] * b.data[i]; });
219
+ accumulate(b, (gb) => { for (let i = 0; i < g.length; i += 1) gb[i] += g[i] * a.data[i]; });
220
+ });
221
+ }
222
+
223
+ const GELU_C = Math.sqrt(2 / Math.PI);
224
+
225
+ export function gelu(a) {
226
+ const out = zeros(a.rows, a.cols);
227
+ for (let i = 0; i < out.size; i += 1) {
228
+ const x = a.data[i];
229
+ out.data[i] = 0.5 * x * (1 + Math.tanh(GELU_C * (x + 0.044715 * x * x * x)));
230
+ }
231
+ return makeNode(out, [a], (g) => {
232
+ accumulate(a, (ga) => {
233
+ for (let i = 0; i < g.length; i += 1) {
234
+ const x = a.data[i];
235
+ const inner = GELU_C * (x + 0.044715 * x * x * x);
236
+ const t = Math.tanh(inner);
237
+ const dInner = GELU_C * (1 + 3 * 0.044715 * x * x);
238
+ ga[i] += g[i] * (0.5 * (1 + t) + 0.5 * x * (1 - t * t) * dInner);
239
+ }
240
+ });
241
+ });
242
+ }
243
+
244
+ export function layerNorm(x, gamma, beta, eps = 1e-5) {
245
+ const { rows, cols } = x;
246
+ const out = zeros(rows, cols);
247
+ const cache = { mean: new Float64Array(rows), invStd: new Float64Array(rows), xhat: new Float64Array(rows * cols) };
248
+ for (let r = 0; r < rows; r += 1) {
249
+ let mean = 0;
250
+ for (let c = 0; c < cols; c += 1) mean += x.data[r * cols + c];
251
+ mean /= cols;
252
+ let variance = 0;
253
+ for (let c = 0; c < cols; c += 1) {
254
+ const d = x.data[r * cols + c] - mean;
255
+ variance += d * d;
256
+ }
257
+ variance /= cols;
258
+ const invStd = 1 / Math.sqrt(variance + eps);
259
+ cache.mean[r] = mean;
260
+ cache.invStd[r] = invStd;
261
+ for (let c = 0; c < cols; c += 1) {
262
+ const xh = (x.data[r * cols + c] - mean) * invStd;
263
+ cache.xhat[r * cols + c] = xh;
264
+ out.data[r * cols + c] = xh * gamma.data[c] + beta.data[c];
265
+ }
266
+ }
267
+ return makeNode(out, [x, gamma, beta], (g) => {
268
+ accumulate(gamma, (gg) => {
269
+ for (let r = 0; r < rows; r += 1) for (let c = 0; c < cols; c += 1) gg[c] += g[r * cols + c] * cache.xhat[r * cols + c];
270
+ });
271
+ accumulate(beta, (gb) => {
272
+ for (let r = 0; r < rows; r += 1) for (let c = 0; c < cols; c += 1) gb[c] += g[r * cols + c];
273
+ });
274
+ accumulate(x, (gx) => {
275
+ for (let r = 0; r < rows; r += 1) {
276
+ let sumDxhat = 0;
277
+ let sumDxhatXhat = 0;
278
+ for (let c = 0; c < cols; c += 1) {
279
+ const dxhat = g[r * cols + c] * gamma.data[c];
280
+ sumDxhat += dxhat;
281
+ sumDxhatXhat += dxhat * cache.xhat[r * cols + c];
282
+ }
283
+ for (let c = 0; c < cols; c += 1) {
284
+ const dxhat = g[r * cols + c] * gamma.data[c];
285
+ gx[r * cols + c] += cache.invStd[r] * (dxhat - sumDxhat / cols - cache.xhat[r * cols + c] * sumDxhatXhat / cols);
286
+ }
287
+ }
288
+ });
289
+ });
290
+ }
291
+
292
+ export function causalSoftmax(scores) {
293
+ // scores is [T,T]; position i may only attend to j <= i.
294
+ const { rows, cols } = scores;
295
+ if (rows !== cols) throw new Error('causalSoftmax expects a square [T,T] score matrix');
296
+ const out = zeros(rows, cols);
297
+ for (let i = 0; i < rows; i += 1) {
298
+ let max = -Infinity;
299
+ for (let j = 0; j <= i; j += 1) max = Math.max(max, scores.data[i * cols + j]);
300
+ let sum = 0;
301
+ for (let j = 0; j <= i; j += 1) {
302
+ const e = Math.exp(scores.data[i * cols + j] - max);
303
+ out.data[i * cols + j] = e;
304
+ sum += e;
305
+ }
306
+ for (let j = 0; j <= i; j += 1) out.data[i * cols + j] /= sum;
307
+ }
308
+ return makeNode(out, [scores], (g) => {
309
+ accumulate(scores, (gs) => {
310
+ for (let i = 0; i < rows; i += 1) {
311
+ let dot = 0;
312
+ for (let j = 0; j <= i; j += 1) dot += g[i * cols + j] * out.data[i * cols + j];
313
+ for (let j = 0; j <= i; j += 1) {
314
+ const p = out.data[i * cols + j];
315
+ gs[i * cols + j] += p * (g[i * cols + j] - dot);
316
+ }
317
+ }
318
+ });
319
+ });
320
+ }
321
+
322
+ export function sliceCols(a, start, end) {
323
+ const width = end - start;
324
+ const out = zeros(a.rows, width);
325
+ for (let r = 0; r < a.rows; r += 1) {
326
+ for (let c = 0; c < width; c += 1) out.data[r * width + c] = a.data[r * a.cols + start + c];
327
+ }
328
+ return makeNode(out, [a], (g) => {
329
+ accumulate(a, (ga) => {
330
+ for (let r = 0; r < a.rows; r += 1) for (let c = 0; c < width; c += 1) ga[r * a.cols + start + c] += g[r * width + c];
331
+ });
332
+ });
333
+ }
334
+
335
+ export function concatCols(parts) {
336
+ const rows = parts[0].rows;
337
+ const cols = parts.reduce((n, p) => n + p.cols, 0);
338
+ const out = zeros(rows, cols);
339
+ let offset = 0;
340
+ for (const part of parts) {
341
+ for (let r = 0; r < rows; r += 1) {
342
+ for (let c = 0; c < part.cols; c += 1) out.data[r * cols + offset + c] = part.data[r * part.cols + c];
343
+ }
344
+ offset += part.cols;
345
+ }
346
+ return makeNode(out, parts, (g) => {
347
+ let off = 0;
348
+ for (const part of parts) {
349
+ const localOff = off;
350
+ accumulate(part, (gp) => {
351
+ for (let r = 0; r < rows; r += 1) {
352
+ for (let c = 0; c < part.cols; c += 1) gp[r * part.cols + c] += g[r * cols + localOff + c];
353
+ }
354
+ });
355
+ off += part.cols;
356
+ }
357
+ });
358
+ }
359
+
360
+ export function embeddingLookup(table, ids) {
361
+ const out = zeros(ids.length, table.cols);
362
+ for (let i = 0; i < ids.length; i += 1) {
363
+ const id = ids[i];
364
+ if (id < 0 || id >= table.rows) throw new Error(`embedding id ${id} out of range 0..${table.rows - 1}`);
365
+ out.data.set(table.data.subarray(id * table.cols, (id + 1) * table.cols), i * table.cols);
366
+ }
367
+ return makeNode(out, [table], (g) => {
368
+ accumulate(table, (gt) => {
369
+ for (let i = 0; i < ids.length; i += 1) {
370
+ const base = ids[i] * table.cols;
371
+ for (let c = 0; c < table.cols; c += 1) gt[base + c] += g[i * table.cols + c];
372
+ }
373
+ });
374
+ });
375
+ }
376
+
377
+ export function crossEntropy(logits, targets, ignoreIndex = -1) {
378
+ // Mean token-level negative log likelihood over non-ignored positions.
379
+ const { rows, cols } = logits;
380
+ if (targets.length !== rows) throw new Error('crossEntropy needs one target per logit row');
381
+ const probs = new Float64Array(rows * cols);
382
+ let total = 0;
383
+ let counted = 0;
384
+ for (let r = 0; r < rows; r += 1) {
385
+ if (targets[r] === ignoreIndex) continue;
386
+ let max = -Infinity;
387
+ for (let c = 0; c < cols; c += 1) max = Math.max(max, logits.data[r * cols + c]);
388
+ let sum = 0;
389
+ for (let c = 0; c < cols; c += 1) {
390
+ const e = Math.exp(logits.data[r * cols + c] - max);
391
+ probs[r * cols + c] = e;
392
+ sum += e;
393
+ }
394
+ for (let c = 0; c < cols; c += 1) probs[r * cols + c] /= sum;
395
+ total += -Math.log(Math.max(probs[r * cols + targets[r]], 1e-12));
396
+ counted += 1;
397
+ }
398
+ const loss = counted > 0 ? total / counted : 0;
399
+ const out = new Tensor(new Float32Array([loss]), 1, 1);
400
+ out.tokenCount = counted;
401
+ // The float32 cell is what the graph carries; `lossValue` keeps the float64
402
+ // accumulation so evaluation metrics and gradient checks are not limited by
403
+ // the storage precision of a single scalar.
404
+ out.lossValue = loss;
405
+ return makeNode(out, [logits], (g) => {
406
+ accumulate(logits, (gl) => {
407
+ if (counted === 0) return;
408
+ const upstream = g[0] / counted;
409
+ for (let r = 0; r < rows; r += 1) {
410
+ if (targets[r] === ignoreIndex) continue;
411
+ for (let c = 0; c < cols; c += 1) {
412
+ gl[r * cols + c] += upstream * (probs[r * cols + c] - (c === targets[r] ? 1 : 0));
413
+ }
414
+ }
415
+ });
416
+ });
417
+ }
418
+
419
+ export function sum(a) {
420
+ let s = 0;
421
+ for (let i = 0; i < a.size; i += 1) s += a.data[i];
422
+ const out = new Tensor(new Float32Array([s]), 1, 1);
423
+ return makeNode(out, [a], (g) => {
424
+ accumulate(a, (ga) => { for (let i = 0; i < ga.length; i += 1) ga[i] += g[0]; });
425
+ });
426
+ }
427
+
428
+ export function backward(root) {
429
+ if (root.size !== 1) throw new Error('backward expects a scalar root');
430
+ const order = [];
431
+ const seen = new Set();
432
+ const stack = [[root, false]];
433
+ while (stack.length) {
434
+ const frame = stack.pop();
435
+ const [node, expanded] = frame;
436
+ if (expanded) {
437
+ order.push(node);
438
+ continue;
439
+ }
440
+ if (seen.has(node)) continue;
441
+ seen.add(node);
442
+ stack.push([node, true]);
443
+ for (const parent of node.parents) if (!seen.has(parent)) stack.push([parent, false]);
444
+ }
445
+ root.ensureGrad()[0] = 1;
446
+ for (let i = order.length - 1; i >= 0; i -= 1) {
447
+ const node = order[i];
448
+ if (node.backwardFn && node.grad) node.backwardFn(node.grad);
449
+ }
450
+ return order.length;
451
+ }
@@ -0,0 +1,65 @@
1
+ // Filesystem helpers. Writes go through a temp file + rename so a crashed or
2
+ // cancelled job never leaves a half-written checkpoint or report behind.
3
+
4
+ import { mkdir, writeFile, rename, readFile, rm, access } from 'node:fs/promises';
5
+ import { constants } from 'node:fs';
6
+ import path from 'node:path';
7
+
8
+ export async function ensureDir(dir) {
9
+ await mkdir(dir, { recursive: true });
10
+ return dir;
11
+ }
12
+
13
+ export async function writeFileAtomic(file, content) {
14
+ await ensureDir(path.dirname(file));
15
+ const tmp = `${file}.tmp-${process.pid}-${Date.now().toString(36)}`;
16
+ await writeFile(tmp, content);
17
+ await rename(tmp, file);
18
+ return file;
19
+ }
20
+
21
+ export async function writeJson(file, value, { pretty = true } = {}) {
22
+ return writeFileAtomic(file, `${JSON.stringify(value, null, pretty ? 2 : 0)}\n`);
23
+ }
24
+
25
+ export async function readJson(file) {
26
+ return JSON.parse(await readFile(file, 'utf8'));
27
+ }
28
+
29
+ export async function readJsonIfExists(file, fallback = null) {
30
+ try {
31
+ return await readJson(file);
32
+ } catch (err) {
33
+ if (err.code === 'ENOENT') return fallback;
34
+ throw err;
35
+ }
36
+ }
37
+
38
+ export async function writeJsonl(file, rows) {
39
+ return writeFileAtomic(file, rows.map((r) => JSON.stringify(r)).join('\n') + '\n');
40
+ }
41
+
42
+ export async function appendJsonl(file, row) {
43
+ const { appendFile } = await import('node:fs/promises');
44
+ await ensureDir(path.dirname(file));
45
+ await appendFile(file, `${JSON.stringify(row)}\n`);
46
+ return file;
47
+ }
48
+
49
+ export async function readJsonl(file) {
50
+ const content = await readFile(file, 'utf8');
51
+ return content.split('\n').filter((l) => l.trim()).map((l) => JSON.parse(l));
52
+ }
53
+
54
+ export async function exists(target) {
55
+ try {
56
+ await access(target, constants.F_OK);
57
+ return true;
58
+ } catch {
59
+ return false;
60
+ }
61
+ }
62
+
63
+ export async function removeDir(dir) {
64
+ await rm(dir, { recursive: true, force: true });
65
+ }
@@ -0,0 +1,47 @@
1
+ import { createHash } from 'node:crypto';
2
+ import { createReadStream } from 'node:fs';
3
+ import { readdir, stat } from 'node:fs/promises';
4
+ import path from 'node:path';
5
+
6
+ export function sha256(data) {
7
+ return createHash('sha256').update(data).digest('hex');
8
+ }
9
+
10
+ export function sha256Json(value) {
11
+ return sha256(stableStringify(value));
12
+ }
13
+
14
+ // Stable key ordering so lineage digests do not drift with object literal order.
15
+ export function stableStringify(value) {
16
+ if (value === null || typeof value !== 'object') return JSON.stringify(value) ?? 'null';
17
+ if (Array.isArray(value)) return `[${value.map(stableStringify).join(',')}]`;
18
+ const keys = Object.keys(value).sort();
19
+ return `{${keys.map((k) => `${JSON.stringify(k)}:${stableStringify(value[k])}`).join(',')}}`;
20
+ }
21
+
22
+ export async function sha256File(file) {
23
+ const hash = createHash('sha256');
24
+ await new Promise((resolve, reject) => {
25
+ createReadStream(file).on('data', (c) => hash.update(c)).on('end', resolve).on('error', reject);
26
+ });
27
+ return hash.digest('hex');
28
+ }
29
+
30
+ // Checksum manifest for an exported bundle: every regular file, relative path, sorted.
31
+ export async function checksumTree(root) {
32
+ const entries = [];
33
+ async function walk(dir) {
34
+ const items = await readdir(dir, { withFileTypes: true });
35
+ for (const item of items.sort((a, b) => (a.name < b.name ? -1 : 1))) {
36
+ const full = path.join(dir, item.name);
37
+ if (item.isDirectory()) await walk(full);
38
+ else if (item.isFile()) {
39
+ const info = await stat(full);
40
+ entries.push({ path: path.relative(root, full), bytes: info.size, sha256: await sha256File(full) });
41
+ }
42
+ }
43
+ }
44
+ await walk(root);
45
+ entries.sort((a, b) => (a.path < b.path ? -1 : 1));
46
+ return entries;
47
+ }
@@ -0,0 +1,70 @@
1
+ // Deterministic, seedable PRNG. Every stochastic step in the foundry draws from
2
+ // one of these so that a (seed, config) pair reproduces a run bit-for-bit.
3
+
4
+ const MASK = 0xffffffff;
5
+
6
+ export function hashSeed(value) {
7
+ // FNV-1a over the string form; keeps string seeds usable in configs.
8
+ let h = 0x811c9dc5;
9
+ const s = String(value);
10
+ for (let i = 0; i < s.length; i += 1) {
11
+ h ^= s.charCodeAt(i);
12
+ h = Math.imul(h, 0x01000193) & MASK;
13
+ }
14
+ return h >>> 0;
15
+ }
16
+
17
+ export class Rng {
18
+ constructor(seed = 1) {
19
+ const s = typeof seed === 'number' && Number.isFinite(seed) ? seed >>> 0 : hashSeed(seed);
20
+ // mulberry32 state; 0 is a degenerate state so bump it.
21
+ this.state = (s || 0x9e3779b9) >>> 0;
22
+ this.seed = s;
23
+ }
24
+
25
+ next() {
26
+ this.state = (this.state + 0x6d2b79f5) >>> 0;
27
+ let t = this.state;
28
+ t = Math.imul(t ^ (t >>> 15), t | 1);
29
+ t ^= t + Math.imul(t ^ (t >>> 7), t | 61);
30
+ return ((t ^ (t >>> 14)) >>> 0) / 4294967296;
31
+ }
32
+
33
+ int(maxExclusive) {
34
+ return Math.floor(this.next() * maxExclusive);
35
+ }
36
+
37
+ pick(list) {
38
+ return list[this.int(list.length)];
39
+ }
40
+
41
+ // Box-Muller; cached second draw keeps the stream aligned.
42
+ normal(mean = 0, std = 1) {
43
+ if (this._spare !== undefined) {
44
+ const v = this._spare;
45
+ this._spare = undefined;
46
+ return mean + std * v;
47
+ }
48
+ let u = 0;
49
+ let v = 0;
50
+ while (u === 0) u = this.next();
51
+ while (v === 0) v = this.next();
52
+ const r = Math.sqrt(-2 * Math.log(u));
53
+ const theta = 2 * Math.PI * v;
54
+ this._spare = r * Math.sin(theta);
55
+ return mean + std * r * Math.cos(theta);
56
+ }
57
+
58
+ shuffled(list) {
59
+ const out = list.slice();
60
+ for (let i = out.length - 1; i > 0; i -= 1) {
61
+ const j = this.int(i + 1);
62
+ [out[i], out[j]] = [out[j], out[i]];
63
+ }
64
+ return out;
65
+ }
66
+
67
+ fork(label) {
68
+ return new Rng(hashSeed(`${this.seed}:${label}`));
69
+ }
70
+ }