π The original agent harness. Deploy intelligent multi-player swarms, coordinate autonomous workflows, and build conversational AI systems. Features adaptive memory, self-learning intelligence, federation, vector RAG integration, and native Claude Code / Codex / Hermes and many more Integrated
TypeScript agentic-aiagentic-frameworkagentic-workflowagentsai-agentsai-assistantai-skillsautonomous-agentsclaudecodexdsh-pluginharnessmcp-servermulti-agentmulti-agent-systemsnpmskillsswarmswarm-intelligencetypescript
feat(neural): training flywheel + @ruvector/ruvllm 2.6.0 (resume, val-split, checkpoint auto-load) (#2557)
rUv66ba80925044
diff --git a/package-lock.json b/package-lock.jsonindex a778399ee4..70c0315263 100644--- a/package-lock.json+++ b/package-lock.json@@ -3038,9 +3038,9 @@}},"node_modules/@ruvector/ruvllm": {- "version": "2.5.7",- "resolved": "https://registry.npmjs.org/@ruvector/ruvllm/-/ruvllm-2.5.7.tgz",- "integrity": "sha512-XxvUsPZaiIfK5/n1/Vgv3Gz9+cgBbvHbN/4OKHrLcpbw0eY9b9+BsQmvmYGfBwiVumQcgn8wmFiqRTqBrTa3BA==",+ "version": "2.6.0",+ "resolved": "https://registry.npmjs.org/@ruvector/ruvllm/-/ruvllm-2.6.0.tgz",+ "integrity": "sha512-aXAIYTtjtsxINagNY9451/9+lbLO24yAKqLqRxad/FlkgJcR3uicMQCwayH/pFP0PbgGI5bQAL0PvkDC4Zz0lA==","license": "MIT OR Apache-2.0","optional": true,"dependencies": {diff --git a/package.json b/package.jsonindex 6d736b4643..234d4ad844 100644--- a/package.json+++ b/package.json@@ -117,7 +117,7 @@"@grpc/grpc-js": ">=1.14.4","form-data": ">=4.0.6","http-proxy-middleware": ">=3.0.7",- "@ruvector/ruvllm": ">=2.5.7"+ "@ruvector/ruvllm": ">=2.6.0"},"devDependencies": {"@openai/codex": "^0.98.0",diff --git a/ruflo/package.json b/ruflo/package.jsonindex 702a4f726a..375c3e1e96 100644--- a/ruflo/package.json+++ b/ruflo/package.json@@ -80,7 +80,7 @@"@opentelemetry/otlp-transformer": ">=0.220.0","agentdb": ">=3.0.0-alpha.17","agentic-flow": ">=2.0.14",- "@ruvector/ruvllm": ">=2.5.7"+ "@ruvector/ruvllm": ">=2.6.0"},"engines": {"node": ">=20.0.0"diff --git a/v3/@claude-flow/cli/__tests__/neural-status-training-backend-2549.test.ts b/v3/@claude-flow/cli/__tests__/neural-status-training-backend-2549.test.tsindex 03365fb904..68b08af141 100644--- a/v3/@claude-flow/cli/__tests__/neural-status-training-backend-2549.test.ts+++ b/v3/@claude-flow/cli/__tests__/neural-status-training-backend-2549.test.ts@@ -115,3 +115,128 @@ describe('#2549 follow-up β native training routing', () => {expect(await runNativeTraining({ embeddings: [new Float32Array(8)], epochs: 1, batchSize: 2, learningRate: 0.01, dim: 8 })).toBeNull();});});++describe('training flywheel β validation split (--val-split)', () => {+ it('validationSplit>0 surfaces a non-null bestValLoss when there are enough batches', async () => {+ const { runNativeTraining, nativeTrainingAvailable } = await import('../src/services/native-training.js');+ const embeddings = Array.from({ length: 16 }, (_, s) =>+ Float32Array.from({ length: 8 }, (_, i) => Math.sin(s + i)));+ if (!nativeTrainingAvailable()) {+ // No native pipeline β no validation possible; runNativeTraining stays null.+ expect(await runNativeTraining({ embeddings, epochs: 3, batchSize: 2, learningRate: 0.05, dim: 8, validationSplit: 0.25 })).toBeNull();+ return;+ }+ const r = await runNativeTraining({+ embeddings, epochs: 3, batchSize: 2, learningRate: 0.05, dim: 8, validationSplit: 0.25,+ });+ expect(r).not.toBeNull();+ expect(r!.bestValLoss).not.toBeNull();+ expect(typeof r!.bestValLoss).toBe('number');+ expect(typeof r!.earlyStopped).toBe('boolean');+ });++ it('validationSplit=0 (disabled) leaves bestValLoss null', async () => {+ const { runNativeTraining, nativeTrainingAvailable } = await import('../src/services/native-training.js');+ if (!nativeTrainingAvailable()) return;+ const embeddings = Array.from({ length: 12 }, (_, s) =>+ Float32Array.from({ length: 8 }, (_, i) => Math.cos(s + i)));+ const r = await runNativeTraining({ embeddings, epochs: 2, batchSize: 2, learningRate: 0.05, dim: 8, validationSplit: 0 });+ expect(r).not.toBeNull();+ expect(r!.bestValLoss).toBeNull();+ });+});++describe('training flywheel β resume (--resume)', () => {+ it('a missing --resume checkpoint fails loudly (throws), never silently fresh-trains', async () => {+ const { runNativeTraining, nativeTrainingAvailable, ResumeFailedError } = await import('../src/services/native-training.js');+ const embeddings = Array.from({ length: 6 }, (_, s) =>+ Float32Array.from({ length: 8 }, (_, i) => Math.sin(s + i)));+ const missing = '/definitely/does/not/exist/lora-checkpoint-0.json';+ if (!nativeTrainingAvailable()) {+ // Without the native module the whole path degrades to null (the+ // resume check lives past module construction) β nothing to assert loudly.+ expect(await runNativeTraining({ embeddings, epochs: 1, batchSize: 2, learningRate: 0.01, dim: 8, resumeFrom: missing })).toBeNull();+ return;+ }+ await expect(+ runNativeTraining({ embeddings, epochs: 1, batchSize: 2, learningRate: 0.01, dim: 8, resumeFrom: missing }),+ ).rejects.toBeInstanceOf(ResumeFailedError);+ });++ it('resuming from a real checkpoint succeeds and records the resume mode', async () => {+ const { runNativeTraining, nativeTrainingAvailable } = await import('../src/services/native-training.js');+ if (!nativeTrainingAvailable()) return;+ const { mkdtempSync, existsSync, rmSync } = await import('node:fs');+ const { join } = await import('node:path');+ const { tmpdir } = await import('node:os');+ const dir = mkdtempSync(join(tmpdir(), 'resume-train-'));+ try {+ const embeddings = Array.from({ length: 8 }, (_, s) =>+ Float32Array.from({ length: 8 }, (_, i) => Math.sin(s + i)));+ const cp = join(dir, 'ckpt.json');+ const first = await runNativeTraining({ embeddings, epochs: 2, batchSize: 2, learningRate: 0.02, dim: 8, checkpointPath: cp });+ expect(first).not.toBeNull();+ expect(existsSync(cp)).toBe(true);+ const second = await runNativeTraining({ embeddings, epochs: 2, batchSize: 2, learningRate: 0.02, dim: 8, resumeFrom: cp });+ expect(second).not.toBeNull();+ expect(second!.resumed).toBe(true);+ // 2.5.7 has no resumeFrom() β weights-only loadCheckpoint fallback.+ expect(['resumeFrom', 'loadCheckpoint']).toContain(second!.resumeMode);+ } finally {+ rmSync(dir, { recursive: true, force: true });+ }+ });+});++describe('training flywheel β checkpoint auto-load (loadLatestCheckpoint)', () => {+ it('latestCheckpointInfo picks the newest lora-checkpoint-*.json by timestamp', async () => {+ const { latestCheckpointInfo } = await import('../src/ruvector/lora-adapter.js');+ const { mkdtempSync, mkdirSync, writeFileSync, rmSync } = await import('node:fs');+ const { join } = await import('node:path');+ const { tmpdir } = await import('node:os');+ const root = mkdtempSync(join(tmpdir(), 'cp-newest-'));+ const cwd = process.cwd();+ try {+ const neuralDir = join(root, '.claude-flow', 'neural');+ mkdirSync(neuralDir, { recursive: true });+ const older = 1000000000000;+ const newer = 2000000000000;+ writeFileSync(join(neuralDir, `lora-checkpoint-${older}.json`), JSON.stringify({ A: [0], B: [0], scaling: 1 }));+ writeFileSync(join(neuralDir, `lora-checkpoint-${newer}.json`), JSON.stringify({ A: [0], B: [0], scaling: 1 }));+ writeFileSync(join(neuralDir, 'not-a-checkpoint.json'), '{}');+ process.chdir(root);+ const info = latestCheckpointInfo();+ expect(info).not.toBeNull();+ expect(info!.filename).toBe(`lora-checkpoint-${newer}.json`);+ expect(typeof info!.ageLabel).toBe('string');+ } finally {+ process.chdir(cwd);+ rmSync(root, { recursive: true, force: true });+ }+ });++ it('respects the CLAUDE_FLOW_NO_CHECKPOINT_AUTOLOAD kill-switch', async () => {+ const { loadLatestCheckpoint, LoRAAdapter } = await import('../src/ruvector/lora-adapter.js');+ const { mkdtempSync, mkdirSync, writeFileSync, rmSync } = await import('node:fs');+ const { join } = await import('node:path');+ const { tmpdir } = await import('node:os');+ const root = mkdtempSync(join(tmpdir(), 'cp-killswitch-'));+ const cwd = process.cwd();+ const prev = process.env.CLAUDE_FLOW_NO_CHECKPOINT_AUTOLOAD;+ try {+ const neuralDir = join(root, '.claude-flow', 'neural');+ mkdirSync(neuralDir, { recursive: true });+ writeFileSync(join(neuralDir, 'lora-checkpoint-3000000000000.json'), JSON.stringify({ A: [0], B: [0], scaling: 1 }));+ process.chdir(root);+ process.env.CLAUDE_FLOW_NO_CHECKPOINT_AUTOLOAD = '1';+ const res = await loadLatestCheckpoint(new LoRAAdapter());+ expect(res.loaded).toBe(false);+ expect(res.path).toBeUndefined();+ } finally {+ if (prev === undefined) delete process.env.CLAUDE_FLOW_NO_CHECKPOINT_AUTOLOAD;+ else process.env.CLAUDE_FLOW_NO_CHECKPOINT_AUTOLOAD = prev;+ process.chdir(cwd);+ rmSync(root, { recursive: true, force: true });+ }+ });+});diff --git a/v3/@claude-flow/cli/src/commands/neural.ts b/v3/@claude-flow/cli/src/commands/neural.tsindex f31eba02f5..b1a7a4ab8f 100644--- a/v3/@claude-flow/cli/src/commands/neural.ts+++ b/v3/@claude-flow/cli/src/commands/neural.ts@@ -27,6 +27,8 @@ const trainCommand: Command = {{ name: 'contrastive', type: 'boolean', description: 'Use contrastive learning (InfoNCE)', default: 'true' },{ name: 'curriculum', type: 'boolean', description: 'Enable curriculum learning', default: 'false' },{ name: 'backend', type: 'string', description: 'Training backend: auto (native when available), native (@ruvector/ruvllm TrainingPipeline, disk checkpoints), wasm (RuVector MicroLoRA/InfoNCE)', default: 'auto' },+ { name: 'val-split', type: 'number', description: 'Validation holdout fraction 0..1 (native backend). >0 reports Best Val Loss + early stopping; 0 disables', default: '0.1' },+ { name: 'resume', type: 'string', description: 'Resume native training from a checkpoint path (weights on 2.5.7; epoch position on >=2.6.0). Native backend only', default: '' },],examples: [{ command: 'claude-flow neural train -p coordination -e 100', description: 'Train coordination patterns' },@@ -44,6 +46,17 @@ const trainCommand: Command = {// 'wasm' = RuVector MicroLoRA/InfoNCE (pre-3.19 behavior),// 'auto' = native when the module resolves, else wasm.const backendFlag = String(ctx.flags.backend || 'auto');+ // Feature: validation split + resume (native TrainingPipeline leg).+ const valSplitRaw = parseFloat((ctx.flags['val-split'] as string) ?? '0.1');+ const valSplit = Number.isFinite(valSplitRaw) ? Math.max(0, Math.min(1, valSplitRaw)) : 0.1;+ const resumePath = ctx.flags.resume ? String(ctx.flags.resume) : undefined;+ // --resume is a native-only capability; refuse the WASM combination up+ // front so the user gets a clear error rather than a silently-ignored flag.+ if (resumePath && backendFlag === 'wasm') {+ output.writeln();+ output.writeln(output.error('--resume is only supported by the native backend; drop --backend wasm.'));+ return { success: false, exitCode: 1 };+ }const useWasm = ctx.flags.wasm !== false;const useFlash = ctx.flags.flash !== false;const useMoE = ctx.flags.moe === true;@@ -218,18 +231,33 @@ const trainCommand: Command = {const nativeTraining = await import('../services/native-training.js');const useNative = backendFlag === 'native'|| (backendFlag === 'auto' && nativeTraining.nativeTrainingAvailable());+ // --resume only works on the native pipeline; if native is unavailable+ // (module absent), fail loudly rather than silently fresh-train.+ if (resumePath && !useNative) {+ spinner.fail('--resume requires the native @ruvector/ruvllm backend, which is not available');+ return { success: false, exitCode: 1 };+ }let nativeResult: import('../services/native-training.js').NativeTrainingResult | null = null;if (useNative) {spinner.setText(`Training ${patternType} on native @ruvector/ruvllm pipeline...`);const path = await import('path');- nativeResult = await nativeTraining.runNativeTraining({- embeddings,- epochs,- batchSize,- learningRate,- dim,- checkpointPath: path.join(process.cwd(), '.claude-flow', 'neural', `lora-checkpoint-${Date.now()}.json`),- });+ try {+ nativeResult = await nativeTraining.runNativeTraining({+ embeddings,+ epochs,+ batchSize,+ learningRate,+ dim,+ validationSplit: valSplit,+ resumeFrom: resumePath,+ checkpointPath: path.join(process.cwd(), '.claude-flow', 'neural', `lora-checkpoint-${Date.now()}.json`),+ });+ } catch (err) {+ // ResumeFailedError β an explicit --resume that could not load is a+ // loud, exit-1 failure, never a silent fall-through to fresh training.+ spinner.fail(`Resume failed: ${(err as Error).message}`);+ return { success: false, exitCode: 1 };+ }if (!nativeResult && backendFlag === 'native') {spinner.fail('Native backend requested (--backend native) but @ruvector/ruvllm training failed');return { success: false, exitCode: 1 };@@ -374,8 +402,23 @@ const trainCommand: Command = {{ metric: 'Backend', value: 'native (@ruvector/ruvllm TrainingPipeline)' },{ metric: 'Native Steps', value: String(nativeResult.steps) },{ metric: 'Final Loss', value: nativeResult.finalLoss.toExponential(3) },- { metric: 'Early Stopped', value: nativeResult.earlyStopped ? 'yes' : 'no' },);+ // Validation metrics only surface when a holdout actually ran+ // (bestValLoss is non-null); Early Stopped is only meaningful then.+ if (nativeResult.bestValLoss !== null && nativeResult.bestValLoss !== undefined) {+ tableData.push(+ { metric: 'Best Val Loss', value: nativeResult.bestValLoss.toExponential(3) },+ { metric: 'Early Stopped', value: nativeResult.earlyStopped ? 'yes' : 'no' },+ );+ }+ if (nativeResult.resumed) {+ tableData.push({+ metric: 'Resumed',+ value: nativeResult.resumeMode === 'resumeFrom'+ ? `${resumePath} (epoch position restored)`+ : `${resumePath} (weights only β epoch-position resume needs @ruvector/ruvllm >=2.6.0)`,+ });+ }if (nativeResult.checkpointPath) {tableData.push({metric: 'Checkpoint',@@ -604,10 +647,14 @@ const statusCommand: Command = {details: stats._trainingBackend === 'ruvllm'? await (async () => {try {- const { nativeCheckpointsSupported } = await import('../ruvector/lora-adapter.js');- return nativeCheckpointsSupported()+ const { nativeCheckpointsSupported, latestCheckpointInfo } = await import('../ruvector/lora-adapter.js');+ // Most important info first (truncation-friendly): backend+ // capability, then the newest checkpoint + age when one exists.+ const base = nativeCheckpointsSupported()? 'native @ruvector/ruvllm pipeline + disk checkpoints': 'native @ruvector/ruvllm pipeline (checkpoints need >=2.5.7)';+ const cp = latestCheckpointInfo();+ return cp ? `${base} Β· latest: ${cp.filename} (${cp.ageLabel})` : base;} catch {return 'native @ruvector/ruvllm pipeline';}diff --git a/v3/@claude-flow/cli/src/ruvector/index.ts b/v3/@claude-flow/cli/src/ruvector/index.tsindex a501473d13..b2c190800f 100644--- a/v3/@claude-flow/cli/src/ruvector/index.ts+++ b/v3/@claude-flow/cli/src/ruvector/index.ts@@ -102,6 +102,9 @@ export {adaptEmbedding,trainLoRA,getLoRAStats,+ loadLatestCheckpoint,+ latestCheckpointInfo,+ formatCheckpointAge,DEFAULT_RANK,DEFAULT_ALPHA,INPUT_DIM as LORA_INPUT_DIM,@@ -110,6 +113,7 @@ export {type LoRAWeights,type AdaptationResult,type LoRAStats,+ type CheckpointInfo,} from './lora-adapter.js';export {ModelRouter,diff --git a/v3/@claude-flow/cli/src/ruvector/lora-adapter.ts b/v3/@claude-flow/cli/src/ruvector/lora-adapter.tsindex 172e2d07cb..f4700d4e50 100644--- a/v3/@claude-flow/cli/src/ruvector/lora-adapter.ts+++ b/v3/@claude-flow/cli/src/ruvector/lora-adapter.ts@@ -18,7 +18,7 @@* @module lora-adapter*/-import { existsSync, mkdirSync, readFileSync, writeFileSync } from 'fs';+import { existsSync, mkdirSync, readdirSync, readFileSync, writeFileSync } from 'fs';import { dirname, join } from 'path';import { createRequire } from 'module';@@ -654,6 +654,114 @@ export class LoRAAdapter {}}+// ============================================================================+// Checkpoint auto-load (the training flywheel)+// ============================================================================++/**+ * Info about the newest on-disk training checkpoint.+ */+export interface CheckpointInfo {+ /** Absolute path to the checkpoint file */+ path: string;+ /** Basename, e.g. lora-checkpoint-1712345678901.json */+ filename: string;+ /** Age in ms derived from the filename timestamp (falls back to mtime) */+ ageMs: number;+ /** Human-friendly age, e.g. "2h ago" */+ ageLabel: string;+}++/**+ * Directories `neural train` writes checkpoints to. It only ever writes to+ * `<cwd>/.claude-flow/neural` (see commands/neural.ts + services/native-training.ts),+ * so that is the single source of truth β kept in a helper so the discovery+ * and status surfaces stay consistent.+ */+function checkpointDirs(): string[] {+ return [join(process.cwd(), '.claude-flow', 'neural')];+}++/** Compact relative-age label. Most-significant unit only. */+export function formatCheckpointAge(ms: number): string {+ const s = Math.floor(ms / 1000);+ if (s < 60) return `${s}s ago`;+ const m = Math.floor(s / 60);+ if (m < 60) return `${m}m ago`;+ const h = Math.floor(m / 60);+ if (h < 24) return `${h}h ago`;+ const d = Math.floor(h / 24);+ return `${d}d ago`;+}++/**+ * Find the newest `lora-checkpoint-<ts>.json` without loading it. Pure disk+ * scan β safe to call from read-only status surfaces. Returns null when no+ * checkpoint exists or the directory is unreadable.+ */+export function latestCheckpointInfo(): CheckpointInfo | null {+ try {+ let best: { path: string; filename: string; ts: number } | null = null;+ for (const dir of checkpointDirs()) {+ if (!existsSync(dir)) continue;+ for (const f of readdirSync(dir)) {+ const match = /^lora-checkpoint-(\d+)\.json$/.exec(f);+ if (!match) continue;+ const ts = Number(match[1]);+ if (!Number.isFinite(ts)) continue;+ if (!best || ts > best.ts) best = { path: join(dir, f), filename: f, ts };+ }+ }+ if (!best) return null;+ const ageMs = Math.max(0, Date.now() - best.ts);+ return { path: best.path, filename: best.filename, ageMs, ageLabel: formatCheckpointAge(ageMs) };+ } catch {+ return null;+ }+}++/**+ * Validate a file looks like a ruvllm training checkpoint before loading it,+ * so a stray/corrupt JSON in the neural dir can't poison routing weights.+ * Accepts both the JS-fallback envelope ({A,B,scaling}) and native ruvllm+ * checkpoint shapes (weights/adapter/epoch/step/loss/version/index markers).+ */+function isCheckpointEnvelope(path: string): boolean {+ try {+ const data = JSON.parse(readFileSync(path, 'utf-8'));+ if (!data || typeof data !== 'object') return false;+ const obj = data as Record<string, unknown>;+ if (Array.isArray(obj.A) && Array.isArray(obj.B)) return true;+ return ['weights', 'adapter', 'epoch', 'step', 'loss', 'version', 'index'].some((k) => k in obj);+ } catch {+ return false;+ }+}++/**+ * Flywheel entry point: locate the newest trained checkpoint and load it into+ * `adapter` via the adapter's existing loadCheckpoint path, so routing /+ * adaptation benefits from prior `neural train` runs.+ *+ * Contract: lazy (call on first adaptation use, never at CLI startup),+ * non-fatal on any failure, and kill-switchable via+ * CLAUDE_FLOW_NO_CHECKPOINT_AUTOLOAD=1.+ */+export async function loadLatestCheckpoint(+ adapter: LoRAAdapter,+): Promise<{ loaded: boolean; path?: string; ageMs?: number }> {+ if (process.env.CLAUDE_FLOW_NO_CHECKPOINT_AUTOLOAD === '1') return { loaded: false };+ try {+ const info = latestCheckpointInfo();+ if (!info) return { loaded: false };+ if (!isCheckpointEnvelope(info.path)) return { loaded: false, path: info.path, ageMs: info.ageMs };+ const loaded = await adapter.loadCheckpoint(info.path);+ return { loaded, path: info.path, ageMs: info.ageMs };+ } catch {+ return { loaded: false };+ }+}+// ============================================================================// Singleton & Factory Functions// ============================================================================@@ -676,6 +784,13 @@ export async function getLoRAAdapter(): Promise<LoRAAdapter> {initPromise = (async () => {const adapter = new LoRAAdapter();await adapter.initialize();+ // Flywheel: fold in the newest trained checkpoint so routing/adaptation+ // benefits from prior `neural train` runs. This singleton is constructed+ // lazily on first adaptation use (NOT at CLI startup), so the checkpoint+ // scan + ruvllm load stay off the hot `--help` path. Non-fatal.+ try {+ await loadLatestCheckpoint(adapter);+ } catch { /* auto-load is best-effort β never block adaptation */ }loraInstance = adapter;return adapter;})();diff --git a/v3/@claude-flow/cli/src/services/native-training.ts b/v3/@claude-flow/cli/src/services/native-training.tsindex 24d4053867..987fcf9864 100644--- a/v3/@claude-flow/cli/src/services/native-training.ts+++ b/v3/@claude-flow/cli/src/services/native-training.ts@@ -30,6 +30,14 @@ export interface NativeTrainingResult {earlyStopped: boolean;checkpointPath?: string;checkpointBytes?: number;+ /** True when training resumed from a --resume checkpoint. */+ resumed?: boolean;+ /**+ * How the resume happened: 'resumeFrom' (ruvllm >=2.6.0 β restores epoch+ * position + optimizer state) or 'loadCheckpoint' (2.5.7 fallback β+ * weights only, training restarts from epoch 0).+ */+ resumeMode?: 'resumeFrom' | 'loadCheckpoint';}export interface NativeTrainingOptions {@@ -38,10 +46,34 @@ export interface NativeTrainingOptions {batchSize: number;learningRate: number;dim: number;+ /**+ * Validation holdout fraction (0..1). >0 makes the pipeline report+ * bestValLoss + early-stopping; 0 (or omitted) disables validation.+ * validationSplit exists in ruvllm 2.5.7 β no version gate needed.+ */+ validationSplit?: number;+ /**+ * Resume weights (and, on >=2.6.0, epoch position) from this checkpoint+ * BEFORE training. A missing/invalid path throws ResumeFailedError β an+ * explicit --resume must fail loudly, never silently fresh-train.+ */+ resumeFrom?: string;/** When set, the TRAINED pipeline checkpoints here (ruvllm >=2.5.7). */checkpointPath?: string;}+/**+ * Thrown when an explicit --resume checkpoint cannot be found or loaded.+ * Distinct from the generic "native unavailable β null" degradation so the+ * caller can surface a loud, exit-1 failure rather than fresh training.+ */+export class ResumeFailedError extends Error {+ constructor(message: string) {+ super(message);+ this.name = 'ResumeFailedError';+ }+}+export function nativeTrainingAvailable(): boolean {try {createRequire(import.meta.url).resolve('@ruvector/ruvllm');@@ -54,19 +86,52 @@ export function nativeTrainingAvailable(): boolean {export async function runNativeTraining(opts: NativeTrainingOptions,): Promise<NativeTrainingResult | null> {- const { embeddings, epochs, batchSize, learningRate, dim, checkpointPath } = opts;+ const { embeddings, epochs, batchSize, learningRate, dim, validationSplit, resumeFrom, checkpointPath } = opts;if (embeddings.length < 2) return null;try {const req = createRequire(import.meta.url);const ruvllm = req('@ruvector/ruvllm');- const pipeline = new ruvllm.TrainingPipeline({+ const pipelineConfig: Record<string, unknown> = {learningRate,batchSize,epochs,inputDim: dim,outputDim: dim,- });+ };+ // 0 (or omitted) disables validation; only pass a real holdout through.+ if (typeof validationSplit === 'number' && validationSplit > 0) {+ pipelineConfig.validationSplit = validationSplit;+ }+ const pipeline = new ruvllm.TrainingPipeline(pipelineConfig);++ // Resume BEFORE training. Prefer resumeFrom() (2.6.0 β epoch position ++ // optimizer state); fall back to loadCheckpoint() (2.5.7 β weights only).+ // Any failure with an explicit --resume is loud (ResumeFailedError),+ // never silent fresh training.+ let resumed = false;+ let resumeMode: 'resumeFrom' | 'loadCheckpoint' | undefined;+ if (resumeFrom) {+ if (!existsSync(resumeFrom)) {+ throw new ResumeFailedError(`--resume checkpoint not found: ${resumeFrom}`);+ }+ try {+ if (typeof pipeline.resumeFrom === 'function') {+ pipeline.resumeFrom(resumeFrom);+ resumeMode = 'resumeFrom';+ } else {+ const ok = pipeline.loadCheckpoint(resumeFrom);+ if (ok === false) throw new Error('loadCheckpoint returned false');+ resumeMode = 'loadCheckpoint';+ }+ resumed = true;+ } catch (e) {+ if (e instanceof ResumeFailedError) throw e;+ throw new ResumeFailedError(+ `--resume failed to load checkpoint ${resumeFrom}: ${(e as Error).message}`,+ );+ }+ }// Pattern-alignment pairs, chunked into pipeline batches.const inputs: number[][] = [];@@ -86,13 +151,21 @@ export async function runNativeTraining(}const r = pipeline.train();+ // When validation is disabled the pipeline reports Infinity for+ // bestValLoss β normalize any non-finite value to null so downstream+ // "bestValLoss !== null β validation ran" holds for the results table.+ const bestValLoss = typeof r.bestValLoss === 'number' && Number.isFinite(r.bestValLoss)+ ? r.bestValLoss+ : null;const result: NativeTrainingResult = {epochs: r.epochs,steps: r.steps,finalLoss: r.finalLoss,- bestValLoss: r.bestValLoss ?? null,+ bestValLoss,durationMs: r.durationMs,earlyStopped: !!r.earlyStopped,+ resumed,+ resumeMode,};if (checkpointPath) {@@ -108,7 +181,10 @@ export async function runNativeTraining(}return result;- } catch {+ } catch (err) {+ // An explicit --resume failure must propagate as a loud error; every+ // other failure degrades to null so callers fall back to the WASM path.+ if (err instanceof ResumeFailedError) throw err;return null;}}diff --git a/v3/package.json b/v3/package.jsonindex fbf45c8640..0873b39058 100644--- a/v3/package.json+++ b/v3/package.json@@ -69,7 +69,7 @@"@vitest/coverage-v8": ">=4.1.0","handlebars": ">=4.7.9","protobufjs": ">=8.6.0",- "@ruvector/ruvllm": ">=2.5.7"+ "@ruvector/ruvllm": ">=2.6.0"}}}diff --git a/v3/pnpm-lock.yaml b/v3/pnpm-lock.yamlindex 667a7c4951..e40726d0ad 100644--- a/v3/pnpm-lock.yaml+++ b/v3/pnpm-lock.yaml@@ -14,7 +14,7 @@ overrides:'@vitest/coverage-v8': '>=4.1.0'handlebars: '>=4.7.9'protobufjs: '>=8.6.0'- '@ruvector/ruvllm': '>=2.5.7'+ '@ruvector/ruvllm': '>=2.6.0'importers:@@ -525,8 +525,8 @@ importers:'@claude-flow/providers':dependencies:'@ruvector/ruvllm':- specifier: '>=2.5.7'- version: 2.5.7+ specifier: '>=2.6.0'+ version: 2.6.0events:specifier: ^3.3.0version: 3.3.0@@ -5631,8 +5631,8 @@ packages:requiresBuild: trueoptional: true- /@ruvector/[email protected]:- resolution: {integrity: sha512-XxvUsPZaiIfK5/n1/Vgv3Gz9+cgBbvHbN/4OKHrLcpbw0eY9b9+BsQmvmYGfBwiVumQcgn8wmFiqRTqBrTa3BA==}+ /@ruvector/[email protected]:+ resolution: {integrity: sha512-aXAIYTtjtsxINagNY9451/9+lbLO24yAKqLqRxad/FlkgJcR3uicMQCwayH/pFP0PbgGI5bQAL0PvkDC4Zz0lA==}engines: {node: '>= 18'}hasBin: truedependencies:@@ -6871,7 +6871,7 @@ packages:'@ruvector/gnn': 0.1.25'@ruvector/graph-node': 0.1.26'@ruvector/router': 0.1.26- '@ruvector/ruvllm': 2.5.7+ '@ruvector/ruvllm': 2.6.0'@ruvector/sona': 0.1.5ajv: 8.17.1chalk: 5.6.2@@ -6932,7 +6932,7 @@ packages:'@ruvector/gnn': 0.1.25'@ruvector/graph-node': 0.1.26'@ruvector/router': 0.1.30- '@ruvector/ruvllm': 2.5.7+ '@ruvector/ruvllm': 2.6.0'@ruvector/sona': 0.1.7ajv: 8.18.0chalk: 5.6.2@@ -6997,7 +6997,7 @@ packages:'@ruvector/gnn': 0.1.25'@ruvector/graph-node': 2.0.3'@ruvector/router': 0.1.30- '@ruvector/ruvllm': 2.5.7+ '@ruvector/ruvllm': 2.6.0'@ruvector/rvf': 0.1.9'@ruvector/rvf-node': 0.1.8'@ruvector/rvf-solver': 0.1.8@@ -7153,7 +7153,7 @@ packages:'@ruvector/core': 0.1.30'@ruvector/edge-full': 0.1.0'@ruvector/router': 0.1.30- '@ruvector/ruvllm': 2.5.7+ '@ruvector/ruvllm': 2.6.0'@ruvector/tiny-dancer': 0.1.22'@supabase/supabase-js': 2.89.0'@xenova/transformers': 2.17.2@@ -7209,7 +7209,7 @@ packages:'@ruvector/core': 0.1.30'@ruvector/edge-full': 0.1.0'@ruvector/router': 0.1.30- '@ruvector/ruvllm': 2.5.7+ '@ruvector/ruvllm': 2.6.0'@ruvector/tiny-dancer': 0.1.18'@supabase/supabase-js': 2.89.0axios: 1.13.2@@ -7266,7 +7266,7 @@ packages:'@ruvector/core': 0.1.30'@ruvector/edge-full': 0.1.0'@ruvector/router': 0.1.26- '@ruvector/ruvllm': 2.5.7+ '@ruvector/ruvllm': 2.6.0'@ruvector/tiny-dancer': 0.1.22'@supabase/supabase-js': 2.89.0'@xenova/transformers': 2.17.2@@ -10414,7 +10414,7 @@ packages:kolorist: 1.8.0prompts: 2.4.2optionalDependencies:- '@ruvector/ruvllm': 2.5.7+ '@ruvector/ruvllm': 2.6.0dev: falseoptional: true@@ -11944,7 +11944,7 @@ packages:'@ruvector/diskann': '>=0.1.0''@ruvector/pi-brain': '>=0.1.0''@ruvector/router': '>=0.1.0'- '@ruvector/ruvllm': '>=2.5.7'+ '@ruvector/ruvllm': '>=2.6.0'peerDependenciesMeta:'@ruvector/diskann':optional: true