feat(cli): neural wsp — optional ruv-FANN weight-space tooling (ADR-528)

Adds three exact-pinned optional dependencies of @claude-flow/cli:
ruv-fann-wsp@0.2.0, ruv-fann-wsp-invariants@0.1.0 and
ruv-fann-wsp-lifecycle@0.1.0. They reuse the ruv-fann@0.1.2 core and
ruv-fann-wasm@0.1.2 runtime that agentdb and darwin already install:
three new packages, no install scripts, no native code. The ruv-fann
0.3.0 facade is not used; it adds 60 packages including esbuild's
install script and a native RVF binding.

`neural wsp` subcommands (read-only evidence; nothing promotes or
reroutes):
- status: installed versions and limits
- inspect: fingerprint/shape (default: the centroid router)
- check: invariants; built-in self-routing suite for the centroid router
- gate: bounded-patch regression gate on user files
- export-centroid: centroid router as a ruv-fann dense model

Packages load by dynamic import inside those subcommands only; when
missing, each exits 2 with the reason. Input files must be regular
files of at most 2 MiB. Cold start and hooks route unchanged.

Co-Authored-By: RuFlo <ruv@ruv.net>
This commit is contained in:
randRuFlo committed 2026-11-12 15:58:34 -05:00
1 parent cee502244b
commit 2abaebc4f4
7 files changed
+811 -2

No files matched your search

@@ -0,0 +1,179 @@
/**
* ADR-528 — optional ruv-FANN weight-space tooling.
*
* Runs against the real ruv-fann-wsp / invariants / lifecycle packages
* (optional dependencies, installed in the workspace) and against an
* importer that reports them missing.
*/
import { describe, it, expect, beforeEach } from 'vitest';
import { mkdtempSync, writeFileSync, symlinkSync, mkdirSync } from 'node:fs';
import { tmpdir } from 'node:os';
import { join } from 'node:path';
import {
loadWsp, __resetWspForTests, centroidToDenseModel, centroidSelfRoutingSuites, checkCentroidSelfRouting,
readJsonInput, assertDenseModel, wspVersions, MAX_CASES_PER_SUITE, type WspModules,
} from '../src/ruvector/ruv-fann-wsp.js';
import { loadCentroidArtifact, classify, type CentroidArtifact } from '../src/ruvector/centroid-router.js';
function artifact(centroids: number[][], labels = centroids.map((_, i) => `a${i}`)): CentroidArtifact {
return {
schema: 'ruflo.agent-centroids/1', embedder: 'minilm', model: 'all-MiniLM-L6-v2', dim: centroids[0].length,
margin: 0, corpusSha256: 'x', split: 'dev', labels, support: labels.map(() => 1), centroids,
};
}
function unit(v: number[]): number[] {
const n = Math.sqrt(v.reduce((s, x) => s + x * x, 0));
return v.map((x) => x / n);
}
async function mods(): Promise<WspModules> {
const l = await loadWsp();
if (!l.available) throw new Error(l.reason);
return l.modules;
}
beforeEach(() => __resetWspForTests());
describe('loadWsp', () => {
it('loads all three optional packages', async () => {
const l = await loadWsp();
expect(l.available).toBe(true);
});
it('reports a missing package instead of throwing', async () => {
const missing = async (s: string) => {
if (s === 'ruv-fann-wsp-lifecycle') throw Object.assign(new Error(`Cannot find package '${s}'`), { code: 'ERR_MODULE_NOT_FOUND' });
return import(s);
};
const l = await loadWsp(missing);
expect(l).toEqual({ available: false, reason: 'ruv-fann-wsp-lifecycle is not installed (optional dependency of @claude-flow/cli)' });
});
it('reports a package that fails to load for another reason', async () => {
const l = await loadWsp(async () => { throw new SyntaxError('bad token'); });
expect(l.available).toBe(false);
if (!l.available) expect(l.reason).toContain('failed to load: bad token');
});
it('resolves versions, including the shared ruv-fann core', () => {
const v = wspVersions();
expect(v['ruv-fann-wsp']).toBe('0.2.0');
expect(v['ruv-fann-wsp-invariants']).toBe('0.1.0');
expect(v['ruv-fann-wsp-lifecycle']).toBe('0.1.0');
expect(v['ruv-fann']).toMatch(/^0\.1\./);
});
});
describe('centroidToDenseModel', () => {
it('ranks labels exactly as the centroid router does', async () => {
const shipped = loadCentroidArtifact({});
expect(shipped.error).toBeNull();
const a = shipped.artifact!;
const m = await mods();
const model = centroidToDenseModel(a);
// Deterministic pseudo-random unit queries.
let seed = 7;
const rnd = () => ((seed = (seed * 1103515245 + 12345) % 2 ** 31) / 2 ** 31) - 0.5;
const queries = Array.from({ length: 25 }, () => unit(Array.from({ length: a.dim }, rnd)));
// One batched WASM pass through ruv-FANN: Linear layer, so outputs are the preactivations.
const trace = await m.wsp.traceWeightModel(model, { inputs: queries.flat(), rows: queries.length });
const outs: number[] = trace.layers[0].activations;
const n = a.labels.length;
for (let q = 0; q < queries.length; q++) {
const query = queries[q];
const out = outs.slice(q * n, (q + 1) * n);
const top = out.indexOf(Math.max(...out));
const d = classify(a, query, 'minilm', undefined, 0);
expect(d.status).toBe('decided');
if (d.status === 'decided') expect(a.labels[top]).toBe(d.label);
}
expect((await m.wsp.inspectWeightModel(model)).parameterCount).toBe(a.labels.length * (a.dim + 1));
});
});
describe('self-routing invariants', () => {
it('pass on the shipped centroid router', async () => {
const r = await checkCentroidSelfRouting(await mods(), loadCentroidArtifact({}).artifact!);
expect(r.accepted).toBe(true);
expect(r.violations).toEqual([]);
expect(r.checks).toBe(r.labels * r.labels * 2);
});
it('catch two near-duplicate labels', async () => {
const a = artifact([unit([1, 0, 0]), unit([0, 1, 0]), unit([0.99, 0.01, 0])], ['x', 'y', 'x-copy']);
const r = await checkCentroidSelfRouting(await mods(), a);
expect(r.accepted).toBe(false);
expect(r.violations.some((v) => v.output === 'x-copy' && v.constraint === 'maximum')).toBe(true);
});
it('catch a corrupt (non-unit) centroid', async () => {
const a = artifact([[2, 0, 0], unit([0, 1, 0]), unit([0, 0, 1])]);
const r = await checkCentroidSelfRouting(await mods(), a);
expect(r.accepted).toBe(false);
});
it('split more labels than one suite allows', () => {
const n = MAX_CASES_PER_SUITE + 3;
const a = artifact(Array.from({ length: n }, (_, i) => Array.from({ length: n }, (_, j) => (i === j ? 1 : 0))));
const suites = centroidSelfRoutingSuites(a);
expect(suites.map((s) => s.cases.length)).toEqual([MAX_CASES_PER_SUITE, 3]);
});
it('reject an out-of-range gap', () => {
const a = artifact([unit([1, 0]), unit([0, 1])]);
expect(() => centroidSelfRoutingSuites(a, { minGap: 0 })).toThrow(RangeError);
expect(() => centroidSelfRoutingSuites(a, { minGap: 1 })).toThrow(RangeError);
});
});
describe('regression gate', () => {
it('accepts a small bias edit and rejects a large one', async () => {
const m = await mods();
const a = loadCentroidArtifact({}).artifact!;
const model = centroidToDenseModel(a);
const n = a.labels.length;
const baseHash = await m.wsp.fingerprintModel(model);
const suites = [{
name: 'onehot',
dataset: { inputs: a.centroids.flat(), targets: Array.from({ length: n * n }, (_, k) => (Math.floor(k / n) === k % n ? 1 : 0)), rows: n },
policy: { maxMSE: 1, maxRegressionMSE: 0.001 },
}];
const edit = (value: number) => ({ schema: 'ruv-fann.weight-patch/1', baseHash, edits: [{ layer: 0, parameter: 'bias', index: 0, value }] });
expect((await m.lifecycle.runRegressionGate({ model, patch: edit(0.001), suites })).accepted).toBe(true);
expect((await m.lifecycle.runRegressionGate({ model, patch: edit(5), suites })).accepted).toBe(false);
});
});
describe('readJsonInput', () => {
const dir = mkdtempSync(join(tmpdir(), 'wsp-adr528-'));
it('reads a small JSON file', () => {
const p = join(dir, 'ok.json');
writeFileSync(p, '{"a":1}');
expect(readJsonInput(p, 'x')).toEqual({ a: 1 });
});
it('refuses directories, oversize files, bad JSON and NUL paths', () => {
mkdirSync(join(dir, 'd'), { recursive: true });
expect(() => readJsonInput(join(dir, 'd'), 'x')).toThrow(/not a regular file/);
const big = join(dir, 'big.json');
writeFileSync(big, ' '.repeat(64));
expect(() => readJsonInput(big, 'x', 32)).toThrow(/limit is 32/);
const bad = join(dir, 'bad.json');
writeFileSync(bad, '{');
expect(() => readJsonInput(bad, 'x')).toThrow(/not valid JSON/);
expect(() => readJsonInput('a\0b', 'x')).toThrow(/file path is required/);
});
it('checks the target of a symlink, not the link', () => {
const link = join(dir, 'link.json');
try { symlinkSync(join(dir, 'd'), link); } catch { return; }
expect(() => readJsonInput(link, 'x')).toThrow(/not a regular file/);
});
it('assertDenseModel rejects other shapes', () => {
expect(() => assertDenseModel({ schema: 'nope', layers: [] })).toThrow(/dense-layers/);
expect(() => assertDenseModel(null)).toThrow(/dense-layers/);
});
});
+4 -1
View File
@@ -149,7 +149,10 @@
"ruvector": "^0.3.13",
"nostr-tools": "^2.7.0",
"@ruvector/learning-wasm": "0.1.29",
"agent-booster": "^0.2.2"
"agent-booster": "^0.2.2",
"ruv-fann-wsp": "0.2.0",
"ruv-fann-wsp-invariants": "0.1.0",
"ruv-fann-wsp-lifecycle": "0.1.0"
},
"peerDependencies": {
"@metaharness/router": "^0.4.0",
@@ -0,0 +1,252 @@
/**
* `neural wsp` — ruv-FANN weight-space tooling (ADR-528).
*
* Read-only evidence over dense models: fingerprint, inspect, invariant
* checks and bounded-patch regression gates. Nothing here promotes a model,
* writes routing state or changes what `hooks route` does. The only write is
* `export-centroid`, which writes the file the user names.
*
* Backed by the optional dependencies ruv-fann-wsp, ruv-fann-wsp-invariants
* and ruv-fann-wsp-lifecycle; every subcommand reports cleanly when they are
* missing.
*/
import { existsSync, writeFileSync } from 'node:fs';
import { resolve as resolvePath } from 'node:path';
import type { Command, CommandContext, CommandResult } from '../types.js';
import { output } from '../output.js';
type Flags = CommandContext['flags'];
function str(flags: Flags, name: string): string | undefined {
const v = flags[name];
return typeof v === 'string' && v.length > 0 ? v : undefined;
}
function isJson(flags: Flags): boolean {
return str(flags, 'format') === 'json';
}
function fail(message: string, json: boolean, exitCode = 1): CommandResult {
if (json) output.writeln(JSON.stringify({ ok: false, error: message }, null, 2));
else output.printError(message);
return { success: false, exitCode, message };
}
async function requireWsp(json: boolean) {
const { loadWsp } = await import('../ruvector/ruv-fann-wsp.js');
const load = await loadWsp();
if (!load.available) return { error: fail(`ruv-FANN WSP unavailable: ${load.reason}`, json, 2) };
return { mods: load.modules };
}
/** The shipped (or CLAUDE_FLOW_ROUTER_CENTROID_PATH) centroid artifact. */
async function loadCentroid() {
const { loadCentroidArtifact } = await import('../ruvector/centroid-router.js');
return loadCentroidArtifact();
}
/** `--model <file>` when given, else the centroid router as a dense model. */
async function resolveModel(flags: Flags) {
const w = await import('../ruvector/ruv-fann-wsp.js');
const file = str(flags, 'model');
if (file) return { model: w.assertDenseModel(w.readJsonInput(file, 'model')), source: resolvePath(file), artifact: null };
const c = await loadCentroid();
if (!c.artifact) throw new Error(`centroid router artifact unavailable: ${c.error}`);
return { model: w.centroidToDenseModel(c.artifact), source: `centroid router (${c.path})`, artifact: c.artifact };
}
const formatOpt = { name: 'format', short: 'f', type: 'string' as const, description: 'Output format: table, json', default: 'table' };
const modelOpt = { name: 'model', short: 'm', type: 'string' as const, description: 'ruv-fann.dense-layers/1 JSON file (default: the centroid router)' };
const statusCommand: Command = {
name: 'status',
description: 'Show whether the ruv-FANN WSP packages are installed, their versions and limits',
options: [formatOpt],
action: async (ctx: CommandContext): Promise<CommandResult> => {
const json = isJson(ctx.flags);
const { loadWsp, wspVersions } = await import('../ruvector/ruv-fann-wsp.js');
const load = await loadWsp();
const versions = wspVersions();
const limits = load.available
? { wsp: load.modules.wsp.WSP_LIMITS, invariants: load.modules.invariants.INVARIANT_LIMITS, lifecycle: load.modules.lifecycle.LIFECYCLE_LIMITS }
: null;
const data = { available: load.available, reason: load.available ? null : load.reason, versions, limits };
if (json) output.writeln(JSON.stringify(data, null, 2));
else {
output.writeln(output.bold('ruv-FANN weight-space programming'));
output.writeln(` Available: ${load.available ? output.success('yes') : output.warning('no — ' + data.reason)}`);
for (const [k, v] of Object.entries(versions)) output.writeln(` ${k.padEnd(24)} ${v ?? output.dim('not installed')}`);
if (limits) output.writeln(output.dim(` Patch limit: ${limits.wsp.maxEdits} edits · rows ≤ ${limits.wsp.maxRows} · params ≤ ${limits.wsp.maxParameters} · invariant cases ≤ ${limits.invariants.maxCases}`));
}
return { success: true, data };
},
};
const inspectCommand: Command = {
name: 'inspect',
description: 'Fingerprint and describe a dense model (default: the centroid router)',
options: [modelOpt, formatOpt],
examples: [
{ command: 'claude-flow neural wsp inspect', description: 'Hash and shape of the shipped centroid router' },
{ command: 'claude-flow neural wsp inspect -m model.json -f json', description: 'Inspect your own ruv-FANN model' },
],
action: async (ctx: CommandContext): Promise<CommandResult> => {
const json = isJson(ctx.flags);
const w = await requireWsp(json);
if ('error' in w) return w.error!;
try {
const { model, source } = await resolveModel(ctx.flags);
const inspection = await w.mods.wsp.inspectWeightModel(model);
const data = { source, ...inspection };
if (json) output.writeln(JSON.stringify(data, null, 2));
else {
output.writeln(output.bold(`Model: ${source}`));
output.writeln(` Hash: ${inspection.baseHash}`);
output.writeln(` Shape: ${inspection.inputSize} → ${inspection.outputSize} (${inspection.parameterCount} parameters)`);
for (const l of inspection.layers) {
output.writeln(output.dim(` layer ${l.layer}: ${l.inputs}→${l.outputs} ${l.activation} (${l.parameterCount} params)`));
}
}
return { success: true, data };
} catch (err) {
return fail(err instanceof Error ? err.message : String(err), json);
}
},
};
const checkCommand: Command = {
name: 'check',
description: 'Run invariant checks: the built-in centroid self-routing suite, or --suite on --model',
options: [
modelOpt,
{ name: 'suite', short: 's', type: 'string', description: 'ruv-fann.invariants/1 JSON file (required with --model)' },
{ name: 'min-gap', type: 'number', description: 'Self-routing: required gap between a label and any other label on its own centroid', default: '0.05' },
formatOpt,
],
examples: [
{ command: 'claude-flow neural wsp check', description: 'Each centroid must route to its own label by a clear gap' },
{ command: 'claude-flow neural wsp check -m model.json -s invariants.json', description: 'Your own model and suite' },
],
action: async (ctx: CommandContext): Promise<CommandResult> => {
const json = isJson(ctx.flags);
const w = await requireWsp(json);
if ('error' in w) return w.error!;
const mod = await import('../ruvector/ruv-fann-wsp.js');
try {
const modelFile = str(ctx.flags, 'model');
const suiteFile = str(ctx.flags, 'suite');
let data: Record<string, unknown>, accepted: boolean;
if (!modelFile) {
if (suiteFile) return fail('--suite needs --model; without --model the built-in self-routing suite runs', json);
const c = await loadCentroid();
if (!c.artifact) return fail(`centroid router artifact unavailable: ${c.error}`, json);
const gapRaw = ctx.flags.minGap ?? ctx.flags['min-gap'];
const minGap = gapRaw === undefined ? undefined : Number(gapRaw);
if (minGap !== undefined && !(minGap > 0 && minGap < 1)) return fail('--min-gap must be in (0, 1)', json);
const r = await mod.checkCentroidSelfRouting(w.mods, c.artifact, { minGap });
accepted = r.accepted;
data = { suite: 'centroid-self-routing', source: c.path, ...r };
} else {
if (!suiteFile) return fail('--model needs --suite (a ruv-fann.invariants/1 file)', json);
const model = mod.assertDenseModel(mod.readJsonInput(modelFile, 'model'));
const suite = mod.readJsonInput(suiteFile, 'suite');
const r = await w.mods.invariants.checkModelInvariants(model, suite);
accepted = r.accepted === true;
data = { suite: resolvePath(suiteFile), source: resolvePath(modelFile), ...r };
}
if (json) output.writeln(JSON.stringify(data, null, 2));
else {
output.writeln(accepted ? output.success(`Invariants hold (${data.checks} checks, ${data.backend})`) : output.warning(`Invariants FAILED (${data.checks} checks)`));
const v = (data.violations as Array<Record<string, unknown>>) ?? [];
for (const x of v.slice(0, 20)) output.writeln(output.dim(` ${x.case}: output ${x.output} ${x.constraint} — actual ${x.actual}, bound ${x.bound}`));
if (v.length > 20) output.writeln(output.dim(` … ${v.length - 20} more`));
}
return { success: accepted, exitCode: accepted ? 0 : 1, data };
} catch (err) {
return fail(err instanceof Error ? err.message : String(err), json);
}
},
};
const gateCommand: Command = {
name: 'gate',
description: 'Regression-gate a bounded weight patch against one or more datasets (evidence only; never promotes)',
options: [
{ name: 'model', short: 'm', type: 'string', description: 'ruv-fann.dense-layers/1 JSON file', required: true },
{ name: 'patch', short: 'p', type: 'string', description: 'ruv-fann.weight-patch/1 JSON file (≤128 edits)', required: true },
{ name: 'suites', short: 's', type: 'string', description: 'JSON array of {name, dataset:{inputs,targets,rows}, policy:{maxMSE,maxRegressionMSE}}', required: true },
formatOpt,
],
examples: [
{ command: 'claude-flow neural wsp gate -m model.json -p patch.json -s suites.json', description: 'Accept or reject a patch on every suite' },
],
action: async (ctx: CommandContext): Promise<CommandResult> => {
const json = isJson(ctx.flags);
const w = await requireWsp(json);
if ('error' in w) return w.error!;
const mod = await import('../ruvector/ruv-fann-wsp.js');
try {
const m = str(ctx.flags, 'model'), p = str(ctx.flags, 'patch'), s = str(ctx.flags, 'suites');
if (!m || !p || !s) return fail('--model, --patch and --suites are all required', json);
const model = mod.assertDenseModel(mod.readJsonInput(m, 'model'));
const patch = mod.readJsonInput(p, 'patch');
const suites = mod.readJsonInput(s, 'suites');
if (!Array.isArray(suites)) return fail('suites: expected a JSON array', json);
const r = await w.mods.lifecycle.runRegressionGate({ model, patch, suites });
if (json) output.writeln(JSON.stringify(r, null, 2));
else {
output.writeln(r.accepted ? output.success('Patch ACCEPTED on every suite') : output.warning('Patch REJECTED'));
output.writeln(output.dim(` base ${r.baseHash.slice(0, 16)}… → candidate ${r.candidateHash.slice(0, 16)}…`));
for (const x of r.suites) {
const e = x.evaluation;
output.writeln(` ${x.name}: ${e.accepted ? 'pass' : 'fail'} mse ${e.baseline.mse.toFixed(6)} → ${e.candidate.mse.toFixed(6)}${e.reasons.length ? ' (' + e.reasons.join('; ') + ')' : ''}`);
}
output.writeln(output.dim(' Evidence only: nothing was promoted or written.'));
}
return { success: r.accepted, exitCode: r.accepted ? 0 : 1, data: r };
} catch (err) {
return fail(err instanceof Error ? err.message : String(err), json);
}
},
};
const exportCentroidCommand: Command = {
name: 'export-centroid',
description: 'Write the centroid router as a ruv-fann.dense-layers/1 model (one Linear layer)',
options: [
{ name: 'output', short: 'o', type: 'string', description: 'Destination JSON file', required: true },
{ name: 'force', type: 'boolean', description: 'Overwrite an existing file', default: 'false' },
],
examples: [
{ command: 'claude-flow neural wsp export-centroid -o centroid-router.json', description: 'Export for use with other ruv-FANN tooling' },
],
action: async (ctx: CommandContext): Promise<CommandResult> => {
const out = str(ctx.flags, 'output');
if (!out) return fail('--output is required', false);
const dest = resolvePath(out);
if (existsSync(dest) && ctx.flags.force !== true) return fail(`${dest} exists; pass --force to overwrite`, false);
const c = await loadCentroid();
if (!c.artifact) return fail(`centroid router artifact unavailable: ${c.error}`, false);
const { centroidToDenseModel } = await import('../ruvector/ruv-fann-wsp.js');
const model = centroidToDenseModel(c.artifact);
writeFileSync(dest, JSON.stringify(model) + '\n', { mode: 0o644 });
output.writeln(output.success(`Wrote ${dest}`));
output.writeln(output.dim(` ${c.artifact.labels.length} outputs (labels, in order): ${c.artifact.labels.join(', ')}`));
return { success: true, data: { path: dest, labels: c.artifact.labels } };
},
};
export const wspCommand: Command = {
name: 'wsp',
description: 'ruv-FANN weight-space tooling: inspect, invariant checks, regression gates (ADR-528)',
subcommands: [statusCommand, inspectCommand, checkCommand, gateCommand, exportCentroidCommand],
examples: [
{ command: 'claude-flow neural wsp status', description: 'Are the optional ruv-FANN packages installed?' },
{ command: 'claude-flow neural wsp check', description: 'Self-routing invariants on the shipped centroid router' },
],
action: async (): Promise<CommandResult> => {
output.writeln('Use a subcommand: status | inspect | check | gate | export-centroid');
return { success: true };
},
};
+2 -1
View File
@@ -8,6 +8,7 @@
import type { Command, CommandContext, CommandResult } from '../types.js';
import { output } from '../output.js';
import { getProjectRoot } from '../services/project-root.js';
import { wspCommand } from './neural-wsp.js';
// Train subcommand - REAL WASM training with RuVector
const trainCommand: Command = {
@@ -4694,7 +4695,7 @@ const distillCommand: Command = {
export const neuralCommand: Command = {
name: 'neural',
description: 'Neural pattern training, MoE, Flash Attention, pattern learning',
subcommands: [trainCommand, statusCommand, patternsCommand, predictCommand, optimizeCommand, benchmarkCommand, listCommand, exportCommand, importCommand, routerCommand, distillCommand],
subcommands: [trainCommand, statusCommand, patternsCommand, predictCommand, optimizeCommand, benchmarkCommand, listCommand, exportCommand, importCommand, routerCommand, distillCommand, wspCommand],
examples: [
{ command: 'claude-flow neural status', description: 'Check neural system status' },
{ command: 'claude-flow neural train -p coordination', description: 'Train coordination patterns' },
@@ -0,0 +1,275 @@
/**
* ruv-fann-wsp.ts — optional ruv-FANN weight-space tooling (ADR-528).
*
* Wraps three exact-pinned optional dependencies:
* - `ruv-fann-wsp` fingerprint, inspect, sensitivity
* - `ruv-fann-wsp-invariants` finite-domain output-bound checks
* - `ruv-fann-wsp-lifecycle` bounded-patch regression gates
*
* They share the `ruv-fann` core and `ruv-fann-wasm` runtime that agentdb and
* @metaharness/darwin already install, so they add no native code and no
* install scripts. The `ruv-fann` 0.3.0 facade is deliberately NOT used: it
* pulls esbuild (an install script) and a native RVF binding into every
* install for capabilities ruflo does not call.
*
* Every entry point loads the packages lazily. When they are absent the
* caller gets `{ available: false, reason }`; nothing else in the CLI
* imports this module, so cold start and routing are unchanged.
*
* Results are hash-bound evidence, not authority: nothing here promotes,
* writes or reroutes on its own.
*
* @module ruv-fann-wsp
*/
import { lstatSync, readFileSync, realpathSync } from 'node:fs';
import { dirname, resolve as resolvePath } from 'node:path';
import { fileURLToPath } from 'node:url';
import type { CentroidArtifact } from './centroid-router.js';
export const WSP_PACKAGES = ['ruv-fann-wsp', 'ruv-fann-wsp-invariants', 'ruv-fann-wsp-lifecycle'] as const;
export type WspPackage = (typeof WSP_PACKAGES)[number];
/** Upper bound for any JSON file this module reads (models, suites, patches). */
export const MAX_INPUT_BYTES = 2 * 1024 * 1024;
/** INVARIANT_LIMITS.maxCases in ruv-fann-wsp-invariants 0.1.0. */
export const MAX_CASES_PER_SUITE = 16;
/** Centroids are stored rounded, so a centroid scores slightly below 1 against itself. */
export const SELF_SCORE_TOLERANCE = 1e-5;
export interface DenseLayer {
inputs: number;
outputs: number;
/** Row-major [outputs, inputs]. */
weights: number[];
bias?: number[] | null;
activation: string;
steepness: number;
}
export interface DenseModel {
schema: 'ruv-fann.dense-layers/1';
layers: DenseLayer[];
}
export interface InvariantCase {
name: string;
inputs: number[];
rows: number;
minimum?: number[];
maximum?: number[];
expected?: number[];
tolerance?: number;
}
export interface InvariantSuite {
schema: 'ruv-fann.invariants/1';
cases: InvariantCase[];
}
export interface WspModules {
wsp: Record<string, any>;
invariants: Record<string, any>;
lifecycle: Record<string, any>;
}
export type WspLoad = { available: true; modules: WspModules } | { available: false; reason: string };
export type Importer = (specifier: string) => Promise<Record<string, any>>;
// A non-literal specifier keeps tsc from resolving the optional packages at
// build time; they are ESM-only, so `require` cannot load them.
const defaultImporter: Importer = (specifier) => import(specifier);
let _load: Promise<WspLoad> | null = null;
function isMissingModule(err: unknown): boolean {
const code = (err as { code?: string } | null)?.code;
return code === 'ERR_MODULE_NOT_FOUND' || code === 'MODULE_NOT_FOUND';
}
/** Load all three packages once. Never throws. */
export function loadWsp(importer: Importer = defaultImporter): Promise<WspLoad> {
if (importer !== defaultImporter) return doLoad(importer);
if (!_load) _load = doLoad(importer);
return _load;
}
async function doLoad(importer: Importer): Promise<WspLoad> {
const mods: Partial<Record<WspPackage, Record<string, any>>> = {};
for (const name of WSP_PACKAGES) {
try {
mods[name] = await importer(name);
} catch (err) {
const why = isMissingModule(err) ? 'is not installed' : `failed to load: ${err instanceof Error ? err.message : String(err)}`;
return { available: false, reason: `${name} ${why} (optional dependency of @claude-flow/cli)` };
}
}
return {
available: true,
modules: { wsp: mods['ruv-fann-wsp']!, invariants: mods['ruv-fann-wsp-invariants']!, lifecycle: mods['ruv-fann-wsp-lifecycle']! },
};
}
/** Package root of `name` at or above `dir`, or null. */
function packageRootAbove(dir: string, name: string): { root: string; version: string } | null {
for (let i = 0; i < 4; i++) {
try {
const pkg = JSON.parse(readFileSync(resolvePath(dir, 'package.json'), 'utf8'));
if (pkg && pkg.name === name && typeof pkg.version === 'string') return { root: dir, version: pkg.version };
} catch { /* keep walking */ }
dir = dirname(dir);
}
return null;
}
/**
* Installed version of each package, or null. `ruv-fann` is not a direct
* dependency, so it is looked up where ruv-fann-wsp resolves it: nested
* under it (pnpm, npm conflicts) or beside it (flat npm).
*/
export function wspVersions(): Record<WspPackage | 'ruv-fann', string | null> {
const out = {} as Record<WspPackage | 'ruv-fann', string | null>;
let wspRoot: string | null = null;
for (const name of WSP_PACKAGES) {
out[name] = null;
try {
const found = packageRootAbove(dirname(fileURLToPath(import.meta.resolve(name))), name);
if (found) {
out[name] = found.version;
if (name === 'ruv-fann-wsp') wspRoot = found.root;
}
} catch { /* not installed */ }
}
out['ruv-fann'] = null;
if (wspRoot) {
for (const dir of [resolvePath(wspRoot, 'node_modules', 'ruv-fann'), resolvePath(wspRoot, '..', 'ruv-fann')]) {
const found = packageRootAbove(dir, 'ruv-fann');
if (found && found.root === dir) { out['ruv-fann'] = found.version; break; }
}
}
return out;
}
/**
* The centroid router as a one-layer Linear ruv-FANN model. Output k is the
* dot product with centroid k, which is the router's cosine score for a
* unit-length query, so the model ranks labels exactly as `classify` does.
*/
export function centroidToDenseModel(artifact: CentroidArtifact): DenseModel {
const weights: number[] = [];
for (const c of artifact.centroids) for (const v of c) weights.push(v);
return {
schema: 'ruv-fann.dense-layers/1',
layers: [{
inputs: artifact.dim,
outputs: artifact.labels.length,
weights,
bias: new Array(artifact.labels.length).fill(0),
activation: 'Linear',
steepness: 1,
}],
};
}
function caseName(prefix: string, label: string, i: number): string {
const safe = label.replace(/[^A-Za-z0-9_.-]/g, '_');
return `${prefix}${i}-${safe}`.slice(0, 64);
}
/**
* Self-routing invariants: fed its own centroid, each label must score
* 1 ± tolerance and every other label at most `1 - minGap`. A failure means
* two labels are (near-)duplicates or the artifact is corrupt — the router
* could not separate them even on their own means.
*
* Returned as several suites when there are more labels than one suite allows.
*/
export function centroidSelfRoutingSuites(
artifact: CentroidArtifact,
opts: { tolerance?: number; minGap?: number } = {},
): InvariantSuite[] {
const tol = opts.tolerance ?? SELF_SCORE_TOLERANCE;
const minGap = opts.minGap ?? 0.05;
if (!(tol >= 0 && tol < 0.5)) throw new RangeError('tolerance must be in [0, 0.5)');
if (!(minGap > 0 && minGap < 1)) throw new RangeError('minGap must be in (0, 1)');
const n = artifact.labels.length;
const cases: InvariantCase[] = artifact.centroids.map((c, i) => ({
name: caseName('self-', artifact.labels[i], i),
inputs: c.slice(),
rows: 1,
// Unit vectors: every score is within [-1, 1]; pad by tol for rounding.
minimum: Array.from({ length: n }, (_, j) => (j === i ? 1 - tol : -1 - tol)),
maximum: Array.from({ length: n }, (_, j) => (j === i ? 1 + tol : 1 - minGap)),
}));
const suites: InvariantSuite[] = [];
for (let i = 0; i < cases.length; i += MAX_CASES_PER_SUITE) {
suites.push({ schema: 'ruv-fann.invariants/1', cases: cases.slice(i, i + MAX_CASES_PER_SUITE) });
}
return suites;
}
/**
* Read a JSON file the user named. Refuses non-regular files (FIFOs, devices,
* directories), symlinks that leave nothing to read, and anything larger
* than MAX_INPUT_BYTES, before reading it into memory.
*/
export function readJsonInput(path: string, what: string, maxBytes = MAX_INPUT_BYTES): unknown {
if (typeof path !== 'string' || path.length === 0 || path.includes('\0')) {
throw new Error(`${what}: a file path is required`);
}
const real = realpathSync(resolvePath(path));
const st = lstatSync(real);
if (!st.isFile()) throw new Error(`${what}: ${path} is not a regular file`);
if (st.size > maxBytes) throw new Error(`${what}: ${path} is ${st.size} bytes; limit is ${maxBytes}`);
const text = readFileSync(real, 'utf8');
try {
return JSON.parse(text);
} catch (err) {
throw new Error(`${what}: ${path} is not valid JSON (${err instanceof Error ? err.message : String(err)})`);
}
}
/** Shape check before handing a user model to WSP (which validates fully). */
export function assertDenseModel(x: unknown, what = 'model'): DenseModel {
const m = x as Partial<DenseModel> | null;
if (!m || typeof m !== 'object' || m.schema !== 'ruv-fann.dense-layers/1' || !Array.isArray(m.layers) || m.layers.length === 0) {
throw new Error(`${what}: expected a ruv-fann.dense-layers/1 model with at least one layer`);
}
return m as DenseModel;
}
export interface SelfRoutingResult {
accepted: boolean;
modelHash: string;
labels: number;
suites: number;
checks: number;
violations: Array<{ case: string; output: string; constraint: string; actual: number; bound: number }>;
backend: string;
ms: number;
}
/** Run the self-routing invariants against a centroid artifact. */
export async function checkCentroidSelfRouting(
mods: WspModules,
artifact: CentroidArtifact,
opts: { tolerance?: number; minGap?: number } = {},
): Promise<SelfRoutingResult> {
const t0 = performance.now();
const model = centroidToDenseModel(artifact);
const suites = centroidSelfRoutingSuites(artifact, opts);
let accepted = true, checks = 0, backend = '', modelHash = '';
const violations: SelfRoutingResult['violations'] = [];
for (const suite of suites) {
const r = await mods.invariants.checkModelInvariants(model, suite);
accepted &&= r.accepted === true;
checks += r.checks;
backend = r.backend;
modelHash = r.modelHash;
for (const v of r.violations) {
violations.push({ case: v.case, output: artifact.labels[v.output] ?? String(v.output), constraint: v.constraint, actual: v.actual, bound: v.bound });
}
}
return { accepted, modelHash, labels: artifact.labels.length, suites: suites.length, checks, violations, backend, ms: Math.round(performance.now() - t0) };
}
/** Test hook. */
export function __resetWspForTests(): void {
_load = null;
}
@@ -0,0 +1,62 @@
# ADR-528: ruv-FANN weight-space tooling as optional dependencies (`neural wsp`)
- **Status:** Accepted
- **Date:** 2026-11-11
- **Related:** [ADR-527](ADR-527-centroid-agent-router.md) (centroid router; ruv-fann routing deferred), ADR-150 (optional-integration constraints)
- **Surfaces:** `neural wsp {status,inspect,check,gate,export-centroid}`, `src/commands/neural-wsp.ts`, `src/ruvector/ruv-fann-wsp.ts`
## Context
ruv-FANN 0.3.0 (2026-11-11) is a facade over fifteen capability packages. Its
neural core is unchanged from 0.1.2, the version agentdb 3.10.0 and
@metaharness/darwin 0.14.0 already pin, so it does not change ADR-527's result
(training did not beat the nearest-centroid router). What is new is the
weight-space programming (WSP) toolkit: hash-bound inspection, finite-domain
invariant checks and bounded-patch regression gates.
Installing the facade into `ruflo@3.76.0` adds 60 packages, including
`esbuild` (an install script, via `ruv-fann-wsp-cloudflare`) and a native RVF
binding, for capabilities ruflo does not call (Cloudflare workers, Hugging Face
fetches, worker-thread evolution loops with promotion authority).
The WSP regression gate is not a fit for gating centroid rebuilds: a rebuild
changes ~4,224 weights and a patch is capped at 128 edits, and the gate's
policy is MSE-only, not argmax accuracy.
## Decision
1. Add three exact-pinned **optional** dependencies to `@claude-flow/cli`:
`ruv-fann-wsp@0.2.0`, `ruv-fann-wsp-invariants@0.1.0`,
`ruv-fann-wsp-lifecycle@0.1.0`. They reuse the `ruv-fann@0.1.2` core and
`ruv-fann-wasm@0.1.2` runtime already in the tree: three new packages, no
install scripts, no native code. `ruv-fann-wsp@0.2.0` (not 0.2.1) matches
what lifecycle and invariants pin, so one copy is installed.
2. Do **not** depend on the `ruv-fann` 0.3.0 facade, `cloudflare`,
`huggingface`, `loop`, `swarm`, `ruos` or `agenticow` subpackages.
3. Expose them as `neural wsp`, read-only evidence that never promotes a model
or changes routing:
- `status` — installed versions and limits;
- `inspect` — fingerprint and shape of a model (default: the centroid router);
- `check` — invariants; with no `--model`, a built-in **self-routing suite**
for the centroid router: fed its own centroid, each label must score
1 ± 1e-5 and every other label at most `1 − minGap` (default 0.05). A
failure means near-duplicate labels or a corrupt artifact;
- `gate` — `runRegressionGate` on a user model, ≤128-edit patch and suites;
- `export-centroid` — the centroid router as a one-layer Linear
`ruv-fann.dense-layers/1` model (refuses to overwrite without `--force`).
4. The packages are loaded with a dynamic `import()` only inside those
subcommands. When any is missing, each subcommand exits 2 with the reason;
nothing else in the CLI imports them.
5. User-supplied files must be regular files (after resolving symlinks) of at
most 2 MiB; WSP itself rejects unknown fields, non-plain objects and
out-of-limit models.
## Consequences
- Cold start and `hooks route` are unchanged (measured equal to 3.76.0).
- The shipped centroid router passes self-routing at the default gap; its
closest pair (coder/researcher/tester) sits at cosine 0.41–0.47, which
`check --min-gap 0.6` surfaces.
- Picking up `ruv-fann-wsp@0.2.1` or `ruv-fann-wasm@0.1.3` waits for upstream
to repin lifecycle and invariants.
- No routing-accuracy claim is made for this change.
+37
View File
@@ -253,6 +253,15 @@ importers:
nostr-tools:
specifier: ^2.7.0
version: 2.25.2(typescript@5.9.3)
ruv-fann-wsp:
specifier: 0.2.0
version: 0.2.0
ruv-fann-wsp-invariants:
specifier: 0.1.0
version: 0.1.0
ruv-fann-wsp-lifecycle:
specifier: 0.1.0
version: 0.1.0
ruvector:
specifier: ^0.3.13
version: 0.3.13(@ruvector/router@0.1.30)(@ruvector/ruvllm@4.1.0)(zod@3.25.76)
@@ -8684,12 +8693,40 @@ packages:
resolution: {integrity: sha512-wV0xT+yMoidjs6ndeTkTO0rNUiDAZ4H7aP6slbVbdM1vG3xS6iCS1/jDwknNBo+m37GBXN4kgFXHZ0yRmMP7oQ==}
engines: {node: '>=20.9.0'}
/ruv-fann-wsp-invariants@0.1.0:
resolution: {integrity: sha512-qDWrl2WENx0bIwdYVl82GcuJobYd9hhscmg2Xvf5cO9mzGrq3z2wqwdEqjJbTGABRaT0EYdxH2i0cFsz6tSZ/A==}
engines: {node: '>=20.9.0'}
requiresBuild: true
dependencies:
ruv-fann: 0.1.2
ruv-fann-wsp: 0.2.0
dev: false
optional: true
/ruv-fann-wsp-lifecycle@0.1.0:
resolution: {integrity: sha512-VLQJ70hPwS+S9dUVGF3/3S0bp7AdiC0CiCN2hc5aQDsh+GCpzJzAUzWIyENUsD865ja+elC/En/GBuwF6wzu7Q==}
engines: {node: '>=20.9.0'}
requiresBuild: true
dependencies:
ruv-fann-wsp: 0.2.0
dev: false
optional: true
/ruv-fann-wsp@0.1.0:
resolution: {integrity: sha512-nFnbETlTYq3QmvobCWfIVbuuEDKuVK89FBrsv9+yhX4baabzLsfib5g2fLkShhZ1GLyA84KKKn+uALSp/F1Rww==}
engines: {node: '>=20.9.0'}
dependencies:
ruv-fann: 0.1.2
/ruv-fann-wsp@0.2.0:
resolution: {integrity: sha512-vCHGNiMUuxvCycd58gIOdlXTy1e2Tw6J1MD3FV9ri2ljkS534sk90c3h2mS4bBJozpebQu/fB6iDwKvdp09xIQ==}
engines: {node: '>=20.9.0'}
requiresBuild: true
dependencies:
ruv-fann: 0.1.2
dev: false
optional: true
/ruv-fann@0.1.2:
resolution: {integrity: sha512-gdHjT8EUz4tSPpBYkCjbpISwW7bcB5XvtDPeRqZps8M9DcDF+I3deiIBt9aw6hxqKphrnbzQSltiFYLUYc0vjQ==}
engines: {node: '>=20.9.0'}