@seanhogg/builderforce-memory 2026.6.35 → 2026.7.11

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 (56) hide show
  1. package/README.md +4 -3
  2. package/dist/cognition/EvermindCognition.d.ts.map +1 -1
  3. package/dist/cognition/EvermindCognition.js +17 -7
  4. package/dist/cognition/EvermindCognition.js.map +1 -1
  5. package/dist/diagnostics/stack-diagnostic.d.ts +9 -0
  6. package/dist/diagnostics/stack-diagnostic.d.ts.map +1 -1
  7. package/dist/diagnostics/stack-diagnostic.js +27 -1
  8. package/dist/diagnostics/stack-diagnostic.js.map +1 -1
  9. package/dist/distillation/DistillationEngine.d.ts +6 -0
  10. package/dist/distillation/DistillationEngine.d.ts.map +1 -1
  11. package/dist/distillation/DistillationEngine.js +10 -4
  12. package/dist/distillation/DistillationEngine.js.map +1 -1
  13. package/dist/index.d.ts +2 -2
  14. package/dist/index.d.ts.map +1 -1
  15. package/dist/index.js +1 -1
  16. package/dist/index.js.map +1 -1
  17. package/dist/limbic/LimbicSession.d.ts +31 -1
  18. package/dist/limbic/LimbicSession.d.ts.map +1 -1
  19. package/dist/limbic/LimbicSession.js +47 -3
  20. package/dist/limbic/LimbicSession.js.map +1 -1
  21. package/dist/memory/MemoryStore.d.ts +10 -0
  22. package/dist/memory/MemoryStore.d.ts.map +1 -1
  23. package/dist/memory/MemoryStore.js +13 -2
  24. package/dist/memory/MemoryStore.js.map +1 -1
  25. package/dist/session/session.d.ts +22 -0
  26. package/dist/session/session.d.ts.map +1 -1
  27. package/dist/session/session.js +45 -2
  28. package/dist/session/session.js.map +1 -1
  29. package/dist/workflow/code-eval.d.ts +54 -0
  30. package/dist/workflow/code-eval.d.ts.map +1 -0
  31. package/dist/workflow/code-eval.js +135 -0
  32. package/dist/workflow/code-eval.js.map +1 -0
  33. package/dist/workflow/index.d.ts +3 -2
  34. package/dist/workflow/index.d.ts.map +1 -1
  35. package/dist/workflow/index.js +3 -2
  36. package/dist/workflow/index.js.map +1 -1
  37. package/dist/workflow/steps.d.ts +20 -0
  38. package/dist/workflow/steps.d.ts.map +1 -1
  39. package/dist/workflow/steps.js +522 -7
  40. package/dist/workflow/steps.js.map +1 -1
  41. package/dist/workflow/templates.d.ts +15 -0
  42. package/dist/workflow/templates.d.ts.map +1 -1
  43. package/dist/workflow/templates.js +64 -1
  44. package/dist/workflow/templates.js.map +1 -1
  45. package/package.json +8 -4
  46. package/src/cognition/EvermindCognition.ts +24 -7
  47. package/src/diagnostics/stack-diagnostic.ts +37 -1
  48. package/src/distillation/DistillationEngine.ts +17 -4
  49. package/src/index.ts +6 -0
  50. package/src/limbic/LimbicSession.ts +61 -1
  51. package/src/memory/MemoryStore.ts +14 -2
  52. package/src/session/session.ts +72 -2
  53. package/src/workflow/code-eval.ts +143 -0
  54. package/src/workflow/index.ts +9 -1
  55. package/src/workflow/steps.ts +605 -6
  56. package/src/workflow/templates.ts +67 -1
@@ -16,13 +16,23 @@ import {
16
16
  BPETokenizer,
17
17
  EvermindModelPackage,
18
18
  exportEvermind,
19
+ importEvermind,
19
20
  benchmarkText,
21
+ VideoRVQCodec,
22
+ buildVideoSequence,
23
+ generateVideo,
20
24
  type ExportFormat,
21
25
  type BenchmarkReport,
26
+ type ImportOptions,
27
+ type Video,
22
28
  } from "@seanhogg/builderforce-memory-engine";
23
29
  import { EvermindCognition } from "../cognition/index.js";
24
30
  import { hybridRetrieve, chunkText } from "../retrieval/index.js";
25
31
  import { MemoryStore } from "../memory/MemoryStore.js";
32
+ import { OpenAIBridge } from "../bridges/OpenAIBridge.js";
33
+ import { AnthropicBridge } from "../bridges/AnthropicBridge.js";
34
+ import type { TransformerBridge } from "../bridges/TransformerBridge.js";
35
+ import { analyzeCode, runJsCases, type CodeCase } from "./code-eval.js";
26
36
  import type { StackStep } from "../diagnostics/stack-diagnostic.js";
27
37
  import type { StepFactory, StepTypeInfo, WorkflowStepConfig } from "./types.js";
28
38
 
@@ -47,24 +57,246 @@ function pBool(cfg: WorkflowStepConfig, key: string, def: boolean): boolean {
47
57
  const v = cfg.params?.[key];
48
58
  return typeof v === "boolean" ? v : def;
49
59
  }
60
+ /** Read a string[] param (non-strings dropped). */
61
+ function pStrArr(cfg: WorkflowStepConfig, key: string): string[] {
62
+ const v = cfg.params?.[key];
63
+ return Array.isArray(v) ? v.filter((x): x is string => typeof x === "string") : [];
64
+ }
65
+
66
+ /** Default teacher instruction for code distillation — code only, no prose/fences. */
67
+ const CODE_TEACHER_SYSTEM =
68
+ "You are an expert programmer. Respond with correct, idiomatic code that fulfils the request. " +
69
+ "Output code only — no explanation, no markdown fences.";
70
+
71
+ /**
72
+ * A (prompt → teacher completion) training exemplar produced by distillation.
73
+ * `cases` (when present) execution-verify the completion; `teacher` records
74
+ * which panel member produced the surviving answer (attribution/telemetry).
75
+ */
76
+ interface DistillPair {
77
+ prompt: string;
78
+ completion: string;
79
+ cases?: CodeCase[];
80
+ teacher?: string;
81
+ }
82
+
83
+ /** One coding task to distil: a prompt plus the tests its answer must pass. */
84
+ interface DistillTask {
85
+ prompt: string;
86
+ cases?: CodeCase[];
87
+ }
88
+
89
+ /** A single teacher's answer to a prompt, before selection. */
90
+ interface Candidate {
91
+ teacher: string;
92
+ completion: string;
93
+ }
94
+
95
+ /** A configured teacher in the panel (its display label + bridge). */
96
+ interface Teacher {
97
+ label: string;
98
+ bridge: TransformerBridge;
99
+ }
100
+
101
+ /** One teacher's config — a panel entry, or the legacy single-teacher shape. */
102
+ interface TeacherSpec {
103
+ provider?: string;
104
+ apiKey?: string;
105
+ model?: string;
106
+ baseUrl?: string;
107
+ systemPrompt?: string;
108
+ maxTokens?: number;
109
+ }
110
+
111
+ /**
112
+ * Strip a wrapping ```lang … ``` markdown fence some teachers add despite the
113
+ * "code only, no fences" instruction — otherwise the fence fails every code
114
+ * gate and the exemplar is wrongly dropped.
115
+ */
116
+ export function stripCodeFences(text: string): string {
117
+ const t = text.trim();
118
+ const m = /^```[\w-]*\r?\n([\s\S]*?)\r?\n```$/.exec(t);
119
+ return m ? m[1]!.trim() : t;
120
+ }
121
+
122
+ /** Read `cases` off a param blob, dropping malformed entries. */
123
+ function normalizeCases(raw: unknown): CodeCase[] {
124
+ return Array.isArray(raw)
125
+ ? raw.filter((c): c is CodeCase => typeof (c as { call?: unknown })?.call === "string")
126
+ : [];
127
+ }
128
+
129
+ /**
130
+ * Best-of-N selection across a teacher panel. When the task carries execution
131
+ * `cases`, keep only fully-passing candidates and return the first — teachers
132
+ * are listed strongest-first (e.g. Opus), so the strongest correct answer wins
133
+ * and a wrong teacher answer is dropped rather than trained on. With no cases,
134
+ * take the first non-empty candidate (teacher-order priority).
135
+ */
136
+ export function selectBestCandidate(candidates: Candidate[], cases: CodeCase[]): Candidate | null {
137
+ if (candidates.length === 0) return null;
138
+ if (cases.length === 0) return candidates[0]!;
139
+ for (const c of candidates) {
140
+ if (runJsCases(c.completion, cases).passRate === 1) return c;
141
+ }
142
+ return null;
143
+ }
144
+
145
+ /**
146
+ * Build one teacher bridge from its spec. Any external LLM can teach Evermind:
147
+ * • provider "openai" (default) — the BuilderForce gateway, OpenRouter, OpenAI,
148
+ * or any OpenAI-compatible server (Ollama / vLLM / LM Studio), by `baseUrl`.
149
+ * • provider "anthropic" — the Anthropic Messages API directly (Opus etc).
150
+ * Returns null when the entry lacks the credentials it needs.
151
+ */
152
+ function buildTeacher(spec: TeacherSpec, defSystem: string, defMaxTokens: number): Teacher | null {
153
+ const provider = (spec.provider ?? "openai").toLowerCase();
154
+ const apiKey = spec.apiKey ?? "";
155
+ const model = spec.model ?? "";
156
+ const systemPrompt = spec.systemPrompt ?? defSystem;
157
+ const maxTokens = spec.maxTokens ?? defMaxTokens;
158
+ if (provider === "anthropic") {
159
+ if (!apiKey) return null;
160
+ return { label: `anthropic:${model || "default"}`, bridge: new AnthropicBridge({ apiKey, systemPrompt, maxTokens, ...(model ? { model } : {}) }) };
161
+ }
162
+ // openai-compatible (gateway / OpenRouter / OpenAI / local) — needs a baseUrl.
163
+ const baseUrl = spec.baseUrl ?? "";
164
+ if (!baseUrl) return null;
165
+ return { label: `${provider}:${model || "default"}`, bridge: new OpenAIBridge({ apiKey, baseUrl, systemPrompt, maxTokens, ...(model ? { model } : {}) }) };
166
+ }
167
+
168
+ /**
169
+ * Build the teacher panel from step params. `teachers: TeacherSpec[]` runs
170
+ * several models as a best-of-N panel (list the strongest FIRST — e.g. Opus —
171
+ * so it wins ties); the legacy single-teacher shape (top-level
172
+ * provider/baseUrl/apiKey/model) is honoured as a one-entry panel. Entries
173
+ * without credentials are skipped, so an offline `pairs`-only run yields [].
174
+ */
175
+ function makeTeachers(cfg: WorkflowStepConfig): Teacher[] {
176
+ const defSystem = pStr(cfg, "systemPrompt", CODE_TEACHER_SYSTEM);
177
+ const defMaxTokens = pNum(cfg, "maxTokens", 512);
178
+ const raw = cfg.params?.teachers;
179
+ const specs: TeacherSpec[] =
180
+ Array.isArray(raw) && raw.length > 0
181
+ ? (raw as TeacherSpec[])
182
+ : [{ provider: pStr(cfg, "provider", "openai"), apiKey: pStr(cfg, "apiKey", ""), model: pStr(cfg, "model", ""), baseUrl: pStr(cfg, "baseUrl", "") }];
183
+ const out: Teacher[] = [];
184
+ for (const s of specs) {
185
+ const t = buildTeacher(s ?? {}, defSystem, defMaxTokens);
186
+ if (t) out.push(t);
187
+ }
188
+ return out;
189
+ }
190
+
191
+ /** Read the coding tasks to distil: rich `tasks[{prompt,cases}]` or plain `prompts[]`. */
192
+ function readTasks(cfg: WorkflowStepConfig): DistillTask[] {
193
+ const raw = cfg.params?.tasks;
194
+ if (Array.isArray(raw)) {
195
+ const out: DistillTask[] = [];
196
+ for (const t of raw) {
197
+ const prompt = (t as DistillTask)?.prompt;
198
+ if (typeof prompt !== "string") continue;
199
+ const cases = normalizeCases((t as DistillTask).cases);
200
+ out.push(cases.length ? { prompt, cases } : { prompt });
201
+ }
202
+ return out;
203
+ }
204
+ return pStrArr(cfg, "prompts").map((prompt) => ({ prompt }));
205
+ }
50
206
 
51
207
  /** Byte length of an emitted export file (text or binary). */
52
208
  function fileBytes(data: Uint8Array | string): number {
53
209
  return typeof data === "string" ? new TextEncoder().encode(data).length : data.length;
54
210
  }
55
211
 
212
+ /** Coerce a workflow-param weight blob (bytes, ArrayBuffer, number[], or base64) to Uint8Array. */
213
+ function toBytes(value: unknown, base64?: string): Uint8Array | null {
214
+ if (value instanceof Uint8Array) return value;
215
+ if (value instanceof ArrayBuffer) return new Uint8Array(value);
216
+ if (Array.isArray(value) && value.every((n) => typeof n === "number")) return Uint8Array.from(value as number[]);
217
+ if (typeof base64 === "string" && base64) {
218
+ if (typeof atob !== "function") throw new Error("import-model: base64 decoding needs atob (browser/Worker/Node 16+)");
219
+ const bin = atob(base64);
220
+ const out = new Uint8Array(bin.length);
221
+ for (let i = 0; i < bin.length; i++) out[i] = bin.charCodeAt(i);
222
+ return out;
223
+ }
224
+ return null;
225
+ }
226
+
56
227
  function mkStep(cfg: WorkflowStepConfig, layer: string, defaultLabel: string, run: StackStep["run"]): StackStep {
57
228
  return { id: cfg.id, layer, label: cfg.label ?? defaultLabel, run };
58
229
  }
59
230
 
60
- /** Encode a corpus into next-token training sequences (one per sentence). */
231
+ /**
232
+ * Encode a corpus into next-token training sequences. Split on sentence
233
+ * boundaries (prose) OR blank lines (code blocks / distilled prompt→code pairs),
234
+ * so both natural-language and code corpora yield multiple trainable sequences.
235
+ */
61
236
  function corpusToSequences(corpus: string, tok: BPETokenizer): number[][] {
62
237
  return corpus
63
- .split(/(?<=\.)\s+/)
238
+ .split(/(?<=\.)\s+|\n\s*\n/)
64
239
  .map((s) => tok.encode(s.trim()))
65
240
  .filter((ids) => ids.length >= 2);
66
241
  }
67
242
 
243
+ /** Build a VideoRVQCodec from step params (shared by the video build steps). */
244
+ function makeVideoCodec(cfg: WorkflowStepConfig, textVocabSize: number): VideoRVQCodec {
245
+ return new VideoRVQCodec({
246
+ height: pNum(cfg, "height", 8),
247
+ width: pNum(cfg, "width", 8),
248
+ channels: pNum(cfg, "channels", 3),
249
+ patch: pNum(cfg, "patch", 4),
250
+ levels: pNum(cfg, "levels", 2),
251
+ codebookSize: pNum(cfg, "codebookSize", 16),
252
+ keyframeInterval: pNum(cfg, "keyframeInterval", 12),
253
+ textVocabSize,
254
+ seed: pNum(cfg, "seed", 7),
255
+ });
256
+ }
257
+
258
+ /**
259
+ * Deterministic synthetic clips so the video steps are self-runnable (the way the
260
+ * text steps default their corpus). A smooth spatial pattern that drifts a little
261
+ * per frame — enough temporal redundancy to exercise the inter-frame path.
262
+ */
263
+ function synthVideos(count: number, frames: number, h: number, w: number, c: number): Video[] {
264
+ const out: Video[] = [];
265
+ for (let v = 0; v < count; v++) {
266
+ const clip: Video = [];
267
+ for (let t = 0; t < frames; t++) {
268
+ const f = new Float32Array(h * w * c);
269
+ for (let y = 0; y < h; y++) {
270
+ for (let x = 0; x < w; x++) {
271
+ for (let ch = 0; ch < c; ch++) {
272
+ f[((y * w) + x) * c + ch] = 0.5 + 0.4 * Math.sin((x + v * 1.3 + t * 0.3) * 0.7 + y * 0.5 + ch);
273
+ }
274
+ }
275
+ }
276
+ clip.push(f);
277
+ }
278
+ out.push(clip);
279
+ }
280
+ return out;
281
+ }
282
+
283
+ /** Mean per-pixel reconstruction MSE of a codec over clips (the video roundtrip metric). */
284
+ function videoReconMSE(codec: VideoRVQCodec, videos: Video[]): number {
285
+ let se = 0;
286
+ let n = 0;
287
+ for (const v of videos) {
288
+ const r = codec.decode(codec.encode(v));
289
+ for (let t = 0; t < v.length; t++) {
290
+ for (let k = 0; k < v[t]!.length; k++) {
291
+ const d = v[t]![k]! - r[t]![k]!;
292
+ se += d * d;
293
+ }
294
+ n += v[t]!.length;
295
+ }
296
+ }
297
+ return n > 0 ? se / n : 0;
298
+ }
299
+
68
300
  interface Registered {
69
301
  info: StepTypeInfo;
70
302
  factory: StepFactory;
@@ -175,16 +407,38 @@ export const BUILTIN_STEPS: Record<string, Registered> = {
175
407
 
176
408
  // ── LLM-creation pipeline (BUILD) — produces a custom .evermind model ────────
177
409
  "train-tokenizer": {
178
- info: { type: "train-tokenizer", layer: "BUILD", label: "Train tokenizer", description: "Learn a BPE vocab from your corpus (params: corpus, numMerges)" },
410
+ info: {
411
+ type: "train-tokenizer",
412
+ layer: "BUILD",
413
+ label: "Train tokenizer",
414
+ description:
415
+ "Build a BPE vocab — train fresh from your corpus, OR import merges from a proven code tokenizer (params: corpus, numMerges, hfTokenizer, hfTokenizerUrl)",
416
+ },
179
417
  factory: (cfg) =>
180
418
  mkStep(cfg, "BUILD", "Train tokenizer (BPE)", async (ctx) => {
181
- const corpus = pStr(cfg, "corpus", KNOWLEDGE.repeat(4));
182
- const numMerges = pNum(cfg, "numMerges", 100);
183
419
  const tok = new BPETokenizer();
420
+ // Two paths, both first-class (this is an IDE choice):
421
+ // • import-merges: seed from a Hugging Face tokenizer.json (code vocab on day one)
422
+ // • train-fresh: learn a vocab from the corpus
423
+ const hfTokenizer = cfg.params?.hfTokenizer as Record<string, unknown> | undefined;
424
+ const hfTokenizerUrl = pStr(cfg, "hfTokenizerUrl", "");
425
+ if (hfTokenizer && typeof hfTokenizer === "object") {
426
+ tok.loadHuggingFace(hfTokenizer);
427
+ ctx.bag.tokenizer = tok;
428
+ return `imported vocab ${tok.vocabSize} (Hugging Face merges)`;
429
+ }
430
+ if (hfTokenizerUrl) {
431
+ await tok.loadHuggingFaceUrl(hfTokenizerUrl);
432
+ ctx.bag.tokenizer = tok;
433
+ return `imported vocab ${tok.vocabSize} from ${hfTokenizerUrl}`;
434
+ }
435
+ // train-fresh — default to the distilled corpus from a prior step when present.
436
+ const corpus = pStr(cfg, "corpus", (ctx.bag.corpus as string) ?? KNOWLEDGE.repeat(4));
437
+ const numMerges = pNum(cfg, "numMerges", 100);
184
438
  tok.train(corpus, { numMerges });
185
439
  ctx.bag.tokenizer = tok;
186
440
  ctx.bag.corpus = corpus;
187
- return `vocab ${tok.vocabSize} (${numMerges} merges)`;
441
+ return `trained vocab ${tok.vocabSize} (${numMerges} merges)`;
188
442
  }),
189
443
  },
190
444
  "train-model": {
@@ -359,6 +613,123 @@ export const BUILTIN_STEPS: Record<string, Registered> = {
359
613
  return `artifact ${blob.byteLength} bytes; trained vs served output matches`;
360
614
  }),
361
615
  },
616
+ "video-train": {
617
+ info: {
618
+ type: "video-train",
619
+ layer: "BUILD",
620
+ label: "Train video model",
621
+ description:
622
+ "Fit a temporal residual-VQ codec on clips, then train an EvermindLM on the video token streams — the model that generates video (params: height, width, channels, patch, levels, codebookSize, clips, frames, epochs, lr)",
623
+ },
624
+ factory: (cfg) =>
625
+ mkStep(cfg, "BUILD", "Train video model (codec + EvermindLM)", async (ctx) => {
626
+ const videos =
627
+ (ctx.bag.videos as Video[] | undefined) ??
628
+ synthVideos(
629
+ pNum(cfg, "clips", 3),
630
+ pNum(cfg, "frames", 4),
631
+ pNum(cfg, "height", 8),
632
+ pNum(cfg, "width", 8),
633
+ pNum(cfg, "channels", 3),
634
+ );
635
+ if (videos.length === 0) throw new Error("no clips to train on — provide ctx.bag.videos or a positive 'clips' param");
636
+
637
+ // Learn the codec's codebooks, then autoregress the (unchanged) EvermindLM
638
+ // over the resulting token streams. Text region is 0 for a pure-video model.
639
+ const codec = makeVideoCodec(cfg, 0);
640
+ const codecMSE = codec.fit(videos, { iterations: pNum(cfg, "codecIterations", 10) });
641
+ const sequences = videos.map((v) => buildVideoSequence(codec, [], v));
642
+ const model = new EvermindLM({
643
+ vocabSize: codec.vocabSize,
644
+ dModel: pNum(cfg, "dModel", 32),
645
+ numLayers: pNum(cfg, "numLayers", 2),
646
+ hiddenDim: pNum(cfg, "hiddenDim", 48),
647
+ seed: pNum(cfg, "seed", 11),
648
+ });
649
+ const epochs = pNum(cfg, "epochs", 60);
650
+ const history = new EvermindLMTrainer(model, { lr: pNum(cfg, "lr", 0.03), epochs }).fit(sequences);
651
+
652
+ ctx.bag.videoCodec = codec;
653
+ ctx.bag.videoModel = model;
654
+ ctx.bag.videoTrainingHistory = history;
655
+ const last = history.at(-1) ?? 0;
656
+ return `codec MSE ${codecMSE.toFixed(4)}; trained ${epochs} epochs over ${sequences.length} clip(s), loss ${last.toFixed(3)}`;
657
+ }),
658
+ },
659
+ "video-roundtrip": {
660
+ info: {
661
+ type: "video-roundtrip",
662
+ layer: "BUILD",
663
+ label: "Video round-trip",
664
+ description:
665
+ "Fit the video codec and gate reconstruction quality (encode→decode MSE), then smoke-test generate→decode yields valid frames (params: maxMSE, height, width, levels, codebookSize)",
666
+ },
667
+ factory: (cfg) =>
668
+ mkStep(cfg, "BUILD", "Video codec round-trip (encode→decode)", async (ctx) => {
669
+ const videos =
670
+ (ctx.bag.videos as Video[] | undefined) ??
671
+ synthVideos(
672
+ pNum(cfg, "clips", 3),
673
+ pNum(cfg, "frames", 4),
674
+ pNum(cfg, "height", 8),
675
+ pNum(cfg, "width", 8),
676
+ pNum(cfg, "channels", 3),
677
+ );
678
+ // Reuse a codec trained earlier if present; otherwise fit a fresh one.
679
+ let codec = ctx.bag.videoCodec as VideoRVQCodec | undefined;
680
+ const before = codec ? videoReconMSE(codec, videos) : Infinity;
681
+ if (!codec) {
682
+ codec = makeVideoCodec(cfg, 0);
683
+ codec.fit(videos, { iterations: pNum(cfg, "codecIterations", 10) });
684
+ }
685
+ const mse = videoReconMSE(codec, videos);
686
+
687
+ // Structural check: encode is a self-delimiting stream that decodes to the
688
+ // same frame count and shape — the real serve smoke test for video.
689
+ const toks = codec.encode(videos[0]!);
690
+ const recon = codec.decode(toks);
691
+ if (recon.length !== videos[0]!.length) throw new Error(`round-trip frame count ${recon.length} ≠ ${videos[0]!.length}`);
692
+ for (const f of recon) {
693
+ if (f.length !== videos[0]![0]!.length) throw new Error("round-trip frame shape mismatch");
694
+ }
695
+
696
+ // A trained model (if present) → the real deploy round-trip: package the
697
+ // model + codec into a self-contained .evermind, reload it, and generate.
698
+ // Served output must match the in-memory model, exactly like text roundtrip.
699
+ const model = ctx.bag.videoModel as EvermindLM | undefined;
700
+ if (model) {
701
+ const before = generateVideo(model, codec, [], { maxNewTokens: toks.length });
702
+ const modality = pNum(cfg, "frames", 4) === 1 ? "image" : "video";
703
+ const blob = EvermindModelPackage.fromMediaLM(model, codec, {
704
+ name: pStr(cfg, "name", "custom-evermind-video"),
705
+ version: pStr(cfg, "version", "1.0.0"),
706
+ modality,
707
+ card: { description: pStr(cfg, "description", "round-trip validated media model") },
708
+ }).toBlob();
709
+ const pkg = EvermindModelPackage.fromBlob(blob);
710
+ const val = pkg.validate();
711
+ if (!val.ok) throw new Error(`packaged media artifact failed validation: ${val.errors.join("; ")}`);
712
+ const served = pkg.loadMediaLM();
713
+ const after = generateVideo(served.lm, served.codec, [], { maxNewTokens: toks.length });
714
+ if (after.tokens.join(",") !== before.tokens.join(",")) {
715
+ throw new Error("served media model produced different tokens than the trained model");
716
+ }
717
+ for (const f of after.video) {
718
+ if (f.length !== videos[0]![0]!.length) throw new Error("generated frame shape mismatch");
719
+ }
720
+ ctx.artifacts.evermind = blob;
721
+ }
722
+
723
+ // Quality gate — only enforced when configured.
724
+ const maxMSE = pNum(cfg, "maxMSE", 0);
725
+ if (maxMSE > 0 && mse > maxMSE) {
726
+ throw new Error(`video reconstruction MSE ${mse.toFixed(4)} exceeds max ${maxMSE} (raise levels/codebookSize or fit longer)`);
727
+ }
728
+ ctx.bag.videoReconMSE = mse;
729
+ const improved = Number.isFinite(before) ? ` (was ${before.toFixed(4)} unfit)` : "";
730
+ return `recon MSE ${mse.toFixed(4)}${improved}; ${recon.length} frames round-trip clean`;
731
+ }),
732
+ },
362
733
  package: {
363
734
  info: { type: "package", layer: "BUILD", label: "Package", description: "Bundle the trained model into a portable .evermind artifact (params: name, version)" },
364
735
  factory: (cfg) =>
@@ -415,4 +786,232 @@ export const BUILTIN_STEPS: Record<string, Registered> = {
415
786
  return `exported ${format}: ${result.files.length} file(s), ${total} bytes, ${result.paramCount} params`;
416
787
  }),
417
788
  },
789
+
790
+ "import-model": {
791
+ info: {
792
+ type: "import-model",
793
+ layer: "BUILD",
794
+ label: "Import model (warm-start)",
795
+ description:
796
+ "Warm-start an EvermindLM from a .safetensors checkpoint instead of random init — round-trips our own exports, or maps a foreign SSM checkpoint via renameMap (params: safetensors, safetensorsBase64, topK, renameMap)",
797
+ },
798
+ factory: (cfg) =>
799
+ mkStep(cfg, "BUILD", "Import model (warm-start)", async (ctx) => {
800
+ const bytes = toBytes(cfg.params?.safetensors, pStr(cfg, "safetensorsBase64", ""));
801
+ if (!bytes) {
802
+ throw new Error("import-model: provide 'safetensors' (bytes/ArrayBuffer/number[]) or 'safetensorsBase64'");
803
+ }
804
+ const opts: ImportOptions = {};
805
+ const topK = pNum(cfg, "topK", 0);
806
+ if (topK > 0) opts.topK = topK;
807
+ // renameMap is the JSON-friendly form of ImportOptions.rename — used to
808
+ // translate a foreign SSM checkpoint's tensor names to our canonical names.
809
+ const renameMap = cfg.params?.renameMap as Record<string, string> | undefined;
810
+ if (renameMap && typeof renameMap === "object") {
811
+ opts.rename = (name) => (name in renameMap ? renameMap[name]! : name);
812
+ }
813
+ const model = importEvermind(bytes, opts);
814
+ ctx.bag.model = model;
815
+ const params = model.parameters().reduce((n, p) => n + p.data.length, 0);
816
+ const c = model.config;
817
+ return `imported ${params} params (dModel ${c.dModel}, ${c.numLayers}L, ${c.numExperts}E) from ${bytes.length} bytes`;
818
+ }),
819
+ },
820
+
821
+ // ── Teaching Evermind to code — multi-teacher distillation + exec gates ───────
822
+ "distill-corpus": {
823
+ info: {
824
+ type: "distill-corpus",
825
+ layer: "BUILD",
826
+ label: "Distill from teacher panel",
827
+ description:
828
+ "Build a training corpus from a panel of teacher LLMs (Opus + any other model — the gateway, OpenRouter, OpenAI, a local server, Anthropic). Per task, queries every teacher, keeps only completions that PASS the task's execution cases (best-of-N, strongest teacher first), tags each with its teacher, and ACCUMULATES so stacked steps add up. Feeds the corpus to train-model (params: teachers[{provider,baseUrl,apiKey,model}], tasks[{prompt,cases}], prompts, provider, baseUrl, apiKey, model, systemPrompt, maxTokens, temperature, pairs)",
829
+ },
830
+ factory: (cfg) =>
831
+ mkStep(cfg, "BUILD", "Distill corpus from teacher panel", async (ctx) => {
832
+ // Accumulate across steps so multiple teacher panels stack instead of
833
+ // overwriting a prior distill step's exemplars.
834
+ const pairs: DistillPair[] = Array.isArray(ctx.bag.distillPairs) ? (ctx.bag.distillPairs as DistillPair[]) : [];
835
+ const startCount = pairs.length;
836
+ let offlineKept = 0;
837
+ let verified = 0;
838
+ let dropped = 0;
839
+
840
+ // Offline exemplars (pre-captured) — a single trusted candidate each,
841
+ // execution-verified when the pair carries `cases`.
842
+ const offline = cfg.params?.pairs;
843
+ if (Array.isArray(offline)) {
844
+ for (const p of offline) {
845
+ const prompt = (p as DistillPair)?.prompt;
846
+ const completion = (p as DistillPair)?.completion;
847
+ if (typeof prompt !== "string" || typeof completion !== "string") continue;
848
+ const cases = normalizeCases((p as DistillPair).cases);
849
+ const chosen = selectBestCandidate([{ teacher: "offline", completion: stripCodeFences(completion) }], cases);
850
+ if (!chosen) { dropped++; continue; }
851
+ const pair: DistillPair = { prompt, completion: chosen.completion, teacher: "offline" };
852
+ if (cases.length) pair.cases = cases;
853
+ pairs.push(pair);
854
+ offlineKept++;
855
+ }
856
+ }
857
+
858
+ // Live teacher panel — Opus and/or any other models, best-of-N + exec-filtered.
859
+ const teachers = makeTeachers(cfg);
860
+ const tasks = readTasks(cfg);
861
+ if (teachers.length > 0 && tasks.length > 0) {
862
+ const temperature = pNum(cfg, "temperature", 0.2);
863
+ // Dedupe identical (teacher, prompt) calls within this run so a repeated
864
+ // prompt is not billed twice.
865
+ const memo = new Map<string, string>();
866
+ for (const task of tasks) {
867
+ const candidates: Candidate[] = [];
868
+ for (const t of teachers) {
869
+ const key = `${t.label}${task.prompt}`;
870
+ let completion = memo.get(key);
871
+ if (completion === undefined) {
872
+ completion = stripCodeFences(await t.bridge.generate(task.prompt, { temperature }));
873
+ memo.set(key, completion);
874
+ }
875
+ if (completion.trim()) candidates.push({ teacher: t.label, completion });
876
+ }
877
+ const chosen = selectBestCandidate(candidates, task.cases ?? []);
878
+ if (!chosen) { dropped++; continue; }
879
+ const pair: DistillPair = { prompt: task.prompt, completion: chosen.completion, teacher: chosen.teacher };
880
+ if (task.cases?.length) pair.cases = task.cases;
881
+ pairs.push(pair);
882
+ verified++;
883
+ }
884
+ }
885
+
886
+ if (pairs.length === 0) {
887
+ throw new Error(
888
+ "distill-corpus produced no exemplars — set teachers (provider + apiKey + prompts/tasks; baseUrl for openai-compatible) or supply offline 'pairs'",
889
+ );
890
+ }
891
+
892
+ const corpus = pairs.map((p) => `${p.prompt}\n${p.completion}`).join("\n\n");
893
+ ctx.bag.corpus = corpus;
894
+ ctx.bag.distillPairs = pairs;
895
+
896
+ const added = pairs.length - startCount;
897
+ const parts: string[] = [];
898
+ if (offlineKept) parts.push(`${offlineKept} offline`);
899
+ if (verified) parts.push(`${verified} verified via ${teachers.length} teacher(s): ${teachers.map((t) => t.label).join(", ")}`);
900
+ if (dropped) parts.push(`${dropped} dropped`);
901
+ return `distilled ${added} exemplar(s) (${pairs.length} total, ${corpus.length} chars)${parts.length ? ` — ${parts.join(", ")}` : ""}`;
902
+ }),
903
+ },
904
+ "code-parse-check": {
905
+ info: {
906
+ type: "code-parse-check",
907
+ layer: "BUILD",
908
+ label: "Code parse check",
909
+ description:
910
+ "Validate generated output is structurally valid code — balanced delimiters/strings, optional JS parse (params: code, language, minScore)",
911
+ },
912
+ factory: (cfg) =>
913
+ mkStep(cfg, "BUILD", "Code structure / parse gate", async (ctx) => {
914
+ const code = pStr(cfg, "code", (ctx.bag.sample as string) ?? "");
915
+ if (!code.trim()) throw new Error("no code to check — run 'evaluate'/'generate-check' first or pass a 'code' param");
916
+ const language = pStr(cfg, "language", "js");
917
+ const analysis = analyzeCode(code, language);
918
+ ctx.bag.codeParse = analysis;
919
+ const minScore = pNum(cfg, "minScore", 0); // only enforced when configured
920
+ if (minScore > 0 && analysis.score < minScore) {
921
+ throw new Error(
922
+ `code structure score ${analysis.score.toFixed(2)} < min ${minScore} (unbalanced delimiters/strings — output is not valid ${language})`,
923
+ );
924
+ }
925
+ return `structure ${(analysis.score * 100) | 0}%${language === "js" ? `, js-parse ${analysis.jsParse ? "ok" : "fail"}` : ""}`;
926
+ }),
927
+ },
928
+ "code-eval": {
929
+ info: {
930
+ type: "code-eval",
931
+ layer: "BUILD",
932
+ label: "Code eval (reward)",
933
+ description:
934
+ "Execution-grounded reward: run the generated JS against test cases and score the pass-rate (params: code, cases, minPassRate)",
935
+ },
936
+ factory: (cfg) =>
937
+ mkStep(cfg, "BUILD", "Code execution reward", async (ctx) => {
938
+ const code = pStr(cfg, "code", (ctx.bag.sample as string) ?? "");
939
+ if (!code.trim()) throw new Error("no code to evaluate — run 'evaluate'/'generate-check' first or pass a 'code' param");
940
+ const rawCases = cfg.params?.cases;
941
+ const cases = Array.isArray(rawCases)
942
+ ? rawCases.filter((c): c is { call: string; expect: unknown } => typeof (c as { call?: unknown })?.call === "string")
943
+ : [];
944
+ const result = runJsCases(code, cases);
945
+ ctx.bag.codeEval = result;
946
+ const minPassRate = pNum(cfg, "minPassRate", 0); // only enforced when configured
947
+ if (minPassRate > 0 && result.passRate < minPassRate) {
948
+ throw new Error(
949
+ `code-eval pass-rate ${(result.passRate * 100) | 0}% < min ${(minPassRate * 100) | 0}%${result.error ? ` (${result.error})` : ""}`,
950
+ );
951
+ }
952
+ return result.total > 0
953
+ ? `${result.passed}/${result.total} cases passed (${(result.passRate * 100) | 0}%)`
954
+ : "no cases — execution reward skipped";
955
+ }),
956
+ },
957
+ "code-benchmark": {
958
+ info: {
959
+ type: "code-benchmark",
960
+ layer: "BUILD",
961
+ label: "Code benchmark (pass@1)",
962
+ description:
963
+ "Held-out coding benchmark: prompt the TRAINED model on N unseen tasks, execute each generated solution against its cases, and score pass@1 (a task passes only if ALL its cases pass). The symmetric coding counterpart to `benchmark`'s held-out perplexity (params: tasks:[{prompt,cases,maxNewTokens?}], maxNewTokens, temperature, minPass1)",
964
+ },
965
+ factory: (cfg) =>
966
+ mkStep(cfg, "BUILD", "Code benchmark (held-out pass@1)", async (ctx) => {
967
+ const model = ctx.bag.model as EvermindLM | undefined;
968
+ const tok = ctx.bag.tokenizer as BPETokenizer | undefined;
969
+ if (!model || !tok) throw new Error("no trained model — add 'train-model' first");
970
+
971
+ // Held-out tasks: each is a prompt the model did NOT train on plus the
972
+ // execution cases its output must satisfy. A task counts as passed only
973
+ // when EVERY case passes (strict pass@1), so this measures whether the
974
+ // student learned to GENERATE working code, not just clean corpus tokens.
975
+ const rawTasks = cfg.params?.tasks;
976
+ const tasks = Array.isArray(rawTasks)
977
+ ? rawTasks.filter(
978
+ (t): t is { prompt: string; cases?: unknown; maxNewTokens?: unknown } =>
979
+ typeof (t as { prompt?: unknown })?.prompt === "string",
980
+ )
981
+ : [];
982
+ if (tasks.length === 0) {
983
+ throw new Error("no held-out tasks — pass params.tasks: [{ prompt, cases: [{ call, expect }] }]");
984
+ }
985
+
986
+ const defaultMaxNewTokens = pNum(cfg, "maxNewTokens", 24);
987
+ const temperature = pNum(cfg, "temperature", 0);
988
+ const perTask = tasks.map((t) => {
989
+ const cases: CodeCase[] = Array.isArray(t.cases)
990
+ ? (t.cases as unknown[]).filter(
991
+ (c): c is CodeCase => typeof (c as { call?: unknown })?.call === "string",
992
+ )
993
+ : [];
994
+ const maxNewTokens = typeof t.maxNewTokens === "number" ? t.maxNewTokens : defaultMaxNewTokens;
995
+ const generated = model.generateText(t.prompt, tok, { maxNewTokens, temperature });
996
+ const code = stripCodeFences(typeof generated === "string" ? generated : "");
997
+ const evalResult = runJsCases(code, cases);
998
+ // Strict pass@1: the task passes only when it HAS cases and they ALL pass.
999
+ const passed = evalResult.total > 0 && evalResult.passRate === 1;
1000
+ return { prompt: t.prompt, passed, cases: evalResult.total, casesPassed: evalResult.passed, error: evalResult.error };
1001
+ });
1002
+
1003
+ const passedTasks = perTask.filter((r) => r.passed).length;
1004
+ const pass1 = perTask.length > 0 ? passedTasks / perTask.length : 0;
1005
+ ctx.bag.codeBenchmark = { pass1, passedTasks, totalTasks: perTask.length, perTask };
1006
+
1007
+ // Optional quality gate — symmetric with `benchmark`'s maxPerplexity/minTop1.
1008
+ const minPass1 = pNum(cfg, "minPass1", 0); // only enforced when configured
1009
+ if (minPass1 > 0 && pass1 < minPass1) {
1010
+ throw new Error(
1011
+ `code pass@1 ${(pass1 * 100) | 0}% below min ${(minPass1 * 100) | 0}% (student did not learn to generate passing code — more/better TEACH_CODE corpus or epochs)`,
1012
+ );
1013
+ }
1014
+ return `pass@1 ${passedTasks}/${perTask.length} (${(pass1 * 100) | 0}%) over held-out coding tasks`;
1015
+ }),
1016
+ },
418
1017
  };