Files
ruflo/v3/@claude-flow/cli/__tests__/ecosystem-integrations.test.ts
T
rUvandr 29b327ee5f feat(cli,codex): ecosystem integrations + skills; darwin ^0.13.0, ruvllm ^4.1.0; release 3.72.1 (#4838)
* feat(cli,codex): wire ecosystem packages into real code paths + ecosystem skills

Every integration here has a reachable path (optional dep or lazy import,
graceful fallback) and a test that drives the real package.

- @ruvector/learning-wasm 0.1.29 (new optional dep): it was imported by
  ruvector-training.ts, neural.ts and ruvector/index.ts but never declared,
  so MicroLoRA always ran on the JS fallback. Now initializeTraining()
  reports backend 'wasm'; `neural benchmark` measures ~2 us/adaptation at
  256-dim. The benchmark's attention section (broken against
  @ruvector/attention 2.x) no longer aborts the MicroLoRA numbers.
- ruvector ^0.2.27 -> ^0.3.11. ruvector 0.3 ships @ruvector/mincut-wasm and
  its DynamicMinCut wrapper. New ruvector/mincut-bridge.ts folds duplicate and
  reversed edges (the solver rejects them) and backs:
  - agentdb_graph-pathfinder `dynamic-mincut`, previously a k-hop stub: exact
    min cut of the seed's depth-hop neighbourhood, returns the seed's side
    plus cut metadata (cutValue, cutEdges, backend). JS Stoer-Wagner
    fallback for neighbourhoods <= 300 nodes.
  - graph-analyzer loadRuVector(), which probed a nonexistent
    ruvector.hooks_graph_mincut and @ruvector/wasm GraphAnalyzer. Measured
    187 ms vs 6 s (JS) at 1,000 nodes, same cut value.
  spectral-sparsify / connected-component-churn stay k-hop approximations
  and now say so in the response (`implementation`).
- @ruvector/rabitq-wasm 0.1.0 -> 0.1.2: ruvector 0.3.11 declares an optional
  peer >=0.1.1, and npm raises ERESOLVE against an exact 0.1.0 pin. Same API.
- agent-booster ^0.2.2 (new optional dep) backs a new hooks_fast-apply MCP
  tool: merges a code snippet into a file or string (~ms, no LLM), with
  project-root and symlink containment, dryRun and minConfidence. ADR-143
  is respected: it is an applier for caller-supplied snippets, not a Tier-1
  intent engine. The appliance bridge's tier-1 hint, labelled
  'agent-booster' while being two regexes, is now labelled 'codemod' and
  points at hooks_codemod. Path-containment helpers move from hooks-tools.ts
  to realpath-containment.ts so both tools share them.
- ast-analyzer / diff-classifier / coverage-router imported @ruvector/ast,
  @ruvector/diff, @ruvector/coverage, which were never published (npm 404).
  ruvector 0.3's ASTParser needs native tree-sitter and is async-only;
  parseDiff / parseIstanbulCoverage are plain JS equivalent to the local
  parsers. The phantom imports are removed rather than swapped for a no-op hop.
- Skills: six new Claude Code skills (vector-quantization, graph-mincut,
  sublinear-solver, injection-defense, fast-code-edits, lora-learning) in a
  new SKILLS_MAP.ecosystem group, installed by default `ruflo init`
  (`init skills --ecosystem`), and the Codex equivalents bundled in
  @claude-flow/codex .agents/skills (built-in, installed by --full).
  @claude-flow/codex 3.0.5 -> 3.0.6.
- no-cli-optdep-bloat-2561 guard: CLI_MAX 13 -> 17 and learning-wasm off the
  FORBIDDEN list, with cold-install measurements (learning-wasm 0.38 s / 1
  pkg / 104K; agent-booster 0.98 s / 67 pkgs / 5.8M).

Evaluated and not wired: sublinear-time-solver as a PPR accelerator (its
computePageRank took 1.2 s at 500 nodes and 68 s at 2,000, vs ms for the
built-in power iteration; 184 deps / 123 MB), strange-loops (pulls the same
tree), @ruvector/kge, @ruvector/cnn, @ruvector/rvlite, @ruvector/graph-wasm,
@ruvector/emergent-time, agentic-jujutsu, @ruvector/pi-brain (no existing
caller doing the job badly); @ruvector/diskann (see the memory PR).

Co-Authored-By: claude-flow <ruv@ruv.net>

* fix(deps): bound @ruvector/ruvllm away from the broken 4.0.x; ruvector override to ^0.3.11

@ruvector/ruvllm 4.0.0/4.0.1 were published from the wrong repository: an
ESM-only GPU-loop harness with no main entry and none of SonaCoordinator,
ContrastiveTrainer, TrainingPipeline or LoraAdapter. The open `>=2.6.0`
ranges in the root and ruflo overrides and the v3 pnpm.overrides let it
resolve, and every createRequire('@ruvector/ruvllm') caller (intelligence.ts,
sona-optimizer.ts, native-training.ts) then fell back to JS silently.

- root/ruflo overrides, v3 pnpm.overrides, providers peer:
  `>=2.6.0 <4.0.0 || ^4.1.0` (2.6-3.x all export the four classes; 4.1.0 is
  the restored runtime). Narrow to ^4.1.0 once it is on the registry.
- root/ruflo overrides: ruvector ^0.2.41 -> ^0.3.11. agentdb 3.3.0 itself
  depends on ruvector ^0.3.5 and the CLI now on ^0.3.11, so the old override
  forced both below their own ranges inside this repo's tree.
- ruflo overrides: agentdb `>=3.3.0` -> `^3.3.0`, agentic-flow `>=2.0.14` ->
  `^2.0.14 || ^3.0.0` (no open-ended ecosystem ranges).
- providers/src/__tests__/ruvllm-runtime-contract.test.ts loads the installed
  package through createRequire, asserts the four classes, constructs a
  SonaCoordinator the way the CLI does, and checks the resolved version is in
  range. Against 4.0.1, require() itself fails (no CJS entry).

Co-Authored-By: claude-flow <ruv@ruv.net>

* test: run ecosystem and ruvllm contract tests where the packages are installed

ci.yml's repo-root npm layout does not install the CLI's optional
dependencies, so those blocks skip there; the pnpm workspace that Test V3
Packages uses installs every one of them, so they run. The probe walks
node_modules only up to the repository root. A @ruvector/ruvllm that is
installed but does not load through require() still fails, and says which
copy and why.

Co-Authored-By: claude-flow <ruv@ruv.net>

* fix(umbrella): claude-flow carries the CLI's new optional deps; rabitq-wasm 0.1.2

The claude-flow umbrella ships the CLI dist with its own dependency list.
With @ruvector/rabitq-wasm pinned at 0.1.0, npm could not hoist ruvector 0.3
(optional peer rabitq-wasm >=0.1.1) and nested it under agentdb/agentic-flow,
so the umbrella's copy of the CLI could not import('ruvector') and the mincut
path was dead there. rabitq-wasm -> 0.1.2 (same API) puts ruvector back at
the top level; ruvector ^0.3.11, @ruvector/learning-wasm 0.1.29 and
agent-booster ^0.2.2 join the umbrella's optionalDependencies so the WASM
MicroLoRA, min-cut and fast-apply paths are reachable from npx claude-flow too.

Co-Authored-By: claude-flow <ruv@ruv.net>

* fix(security): @metaharness/darwin ^0.13.0 (GHSA-mjwg-5fm3-fx2p), metaharness ^0.4.20

@metaharness/darwin 0.13.0 fixes a high-severity sandbox bypass
(GHSA-mjwg-5fm3-fx2p); the CLI's `~0.12.0` could never resolve it.

- cli optionalDependencies @metaharness/darwin ~0.12.0 -> ^0.13.0; peer
  metaharness ^0.4.1 -> ^0.4.20
- distill-oracle MH_DARWIN_PIN 0.12.0 -> 0.13.0 (npx tier-1 oracle calls)
- ruflo-metaharness helper pins: _darwin.mjs ~0.12.0 -> ~0.13.0,
  _harness.mjs ~0.4.1 -> ~0.4.20 (tilde, as check-metaharness-pins requires);
  plugin 0.4.0 -> 0.4.1

Checked against 0.13.0 before bumping (0.x minor): same exports
(., ./contrastive, ./gepa), same metaharness-darwin verbs ruflo surfaces
(evolve, evolve-numeric, bench create|verify, security bench), and the gepa
library calls (loadCand6Genome, validateGenome, buildSystemFromGenome)
return identical results to 0.12.0. Tier-2 evolution now runs in an isolated
child process upstream; ruflo already drives darwin as a subprocess. Note:
0.13.0 adds one runtime dependency (@babel/parser), where 0.12 had none.
check-metaharness-pins, metaharness-clean-install-test and the CLI's
metaharness/distill/darwin tests (80) pass.

Co-Authored-By: claude-flow <ruv@ruv.net>

* fix(deps): @ruvector/ruvllm ^4.1.0 now that the restored runtime is published

4.1.0 is the dual CJS/ESM runtime again. Root and ruflo overrides, v3
pnpm.overrides and the providers peer move from `>=2.6.0 <4.0.0 || ^4.1.0`
to `^4.1.0`; both lockfiles now resolve 4.1.0. The contract test requires
>=4.1 <5 and passed against 4.1.0 (SonaCoordinator, ContrastiveTrainer,
TrainingPipeline, LoraAdapter, DEFAULT_SONA_CONFIG; SonaCoordinator
constructs), as did the CLI's neural-status/trajectory/learning tests.

Co-Authored-By: claude-flow <ruv@ruv.net>

* release: 3.72.1

@claude-flow/cli, claude-flow and ruflo 3.72.1 (ruflo pins cli 3.72.1),
carrying the ecosystem integrations, @claude-flow/memory 3.2.3, codex 3.0.6,
@ruvector/ruvllm ^4.1.0 and @metaharness/darwin ^0.13.0.

Co-Authored-By: claude-flow <ruv@ruv.net>

* fix(metaharness): tilde-pin darwin ~0.13.0; smoke expects plugin 0.4.1

ruflo-metaharness smoke step 17z73 enforces tilde pins for @metaharness/*
(ADR-150 review: tilde stays on one minor). ~0.13.0 admits the same versions
as ^0.13.0 on a 0.x line and still resolves the GHSA-mjwg-5fm3-fx2p fix.
Smoke step 1 hard-codes the plugin version; it moves to 0.4.1 with the bump
that plugin-version-bump requires. smoke.sh: 128/128 locally.

Co-Authored-By: claude-flow <ruv@ruv.net>

---------

Co-authored-by: r <r@x>
2026-11-05 20:50:18 -06:00

257 lines
12 KiB
TypeScript

/**
* Ecosystem integrations: each optional package must be reachable through a
* real code path, not only declared. These tests import the real packages
* (no mocks) — @ruvector/learning-wasm, ruvector (+ @ruvector/mincut-wasm),
* agent-booster — and assert the accelerated path is the one that ran.
*
* Each block runs when its package is installed for the CLI (the pnpm
* workspace that "Test V3 Packages" uses installs all of them) and is skipped
* otherwise (the repo-root npm layout of ci.yml does not install the CLI's
* optional dependencies). The probe stops at the repository root so a stray
* node_modules above the checkout cannot make a skipped block run.
*/
import { afterEach, beforeAll, beforeEach, describe, expect, it } from 'vitest';
import { createRequire } from 'node:module';
import { existsSync, mkdtempSync, mkdirSync, readFileSync, rmSync, writeFileSync } from 'node:fs';
import { dirname, join, resolve } from 'node:path';
import { spawnSync } from 'node:child_process';
import { pathToFileURL } from 'node:url';
import { tmpdir } from 'node:os';
import { loadWasmMinCut, wasmMinCut, seedLocalMinCut } from '../src/ruvector/mincut-bridge.js';
import { analyzeMinCutBoundaries, fallbackMinCut, getMinCutBackend } from '../src/ruvector/graph-analyzer.js';
import { fastApply } from '../src/ruvector/fast-apply.js';
import { hooksFastApply } from '../src/mcp-tools/fast-apply-tools.js';
import { agentdbGraphPathfinder } from '../src/mcp-tools/agentdb-tools.js';
import { _resetMemoryRootCache } from '../src/memory/memory-initializer.js';
import { _resetBridgeDb } from '../src/memory/graph-edge-writer.js';
const REPO_ROOT = resolve(__dirname, '..', '..', '..', '..');
/** True when `pkg` is installed in a node_modules between the CLI and the repo root. */
function installedForCli(pkg: string): boolean {
let dir = resolve(__dirname, '..');
for (;;) {
if (existsSync(join(dir, 'node_modules', ...pkg.split('/'), 'package.json'))) return true;
if (dir === REPO_ROOT || dirname(dir) === dir) return false;
dir = dirname(dir);
}
}
const HAS_LEARNING_WASM = installedForCli('@ruvector/learning-wasm');
const HAS_RUVECTOR = installedForCli('ruvector');
const HAS_AGENT_BOOSTER = installedForCli('agent-booster');
type Edge = [string, string, number];
/** Two 4-cliques joined by one light bridge: min cut = 0.5, sides {a*} / {b*}. */
function twoClusters(): { nodes: string[]; edges: Edge[] } {
const a = ['a1', 'a2', 'a3', 'a4'];
const b = ['b1', 'b2', 'b3', 'b4'];
const edges: Edge[] = [];
for (const group of [a, b]) {
for (let i = 0; i < group.length; i++) {
for (let j = i + 1; j < group.length; j++) edges.push([group[i], group[j], 2]);
}
}
edges.push(['a1', 'b1', 0.5]);
return { nodes: [...a, ...b], edges };
}
// vitest externalizes `@ruvector/*` to a context that cannot see the pnpm
// symlinks, so (as in ruvector-training-attention-api-4610.test.ts) the
// learning-wasm path runs in a child process under tsx — the production loader.
const CLI_DIR = resolve(__dirname, '..');
function probeTraining(): Record<string, any> {
const src = (p: string) => JSON.stringify(pathToFileURL(join(CLI_DIR, 'src', p)).href);
const script = `
const rt = await import(${src('services/ruvector-training.ts')});
const idx = await import(${src('ruvector/index.ts')});
const init = await rt.initializeTraining({ dim: 64 });
const out = rt.forward(new Float32Array(64).fill(0.1));
console.log('RESULT=' + JSON.stringify({ init, active: rt.getActiveBackend(),
available: await idx.isWasmBackendAvailable(), outLen: out.length, isF32: out instanceof Float32Array }));
process.exit(0);`;
const child = spawnSync(process.execPath, ['--import', 'tsx', '--input-type=module', '-e', script], { cwd: CLI_DIR, encoding: 'utf8', timeout: 120_000 });
const line = child.stdout.split('\n').find(l => l.startsWith('RESULT='));
if (!line) throw new Error(`probe produced no result: ${child.stderr.slice(-800)}`);
return JSON.parse(line.slice('RESULT='.length));
}
describe.skipIf(!HAS_LEARNING_WASM)('@ruvector/learning-wasm activates the WASM MicroLoRA backend', () => {
it('initializeTraining() selects the wasm backend, not the JS fallback', () => {
const r = probeTraining();
expect(r.available).toBe(true);
expect(r.init.backend).toBe('wasm');
expect(r.active).toBe('wasm');
expect(r.init.features.some((f: string) => f.startsWith('MicroLoRA/WASM'))).toBe(true);
expect(r.isF32).toBe(true);
expect(r.outLen).toBe(64);
});
});
describe.skipIf(!HAS_RUVECTOR)('ruvector DynamicMinCut (@ruvector/mincut-wasm) backs graph min-cut', () => {
it('loads the wasm solver through ruvector', async () => {
expect(await loadWasmMinCut()).not.toBeNull();
expect(await getMinCutBackend()).toBe('mincut-wasm');
});
it('finds the bridge cut and folds duplicate / reversed edges', async () => {
const { nodes, edges } = twoClusters();
// Duplicates in both directions would make the raw solver throw "Edge already exists".
const noisy: Edge[] = [...edges, ['a2', 'a1', 2], ['a3', 'a3', 9]];
const cut = await wasmMinCut(nodes, noisy);
expect(cut).not.toBeNull();
expect(cut!.cutValue).toBeCloseTo(0.5, 6);
const sides = [cut!.partition1, cut!.partition2].map(s => [...s].sort().join(','));
expect(sides.sort()).toEqual(['a1,a2,a3,a4', 'b1,b2,b3,b4']);
expect(cut!.cutEdges).toEqual([['a1', 'b1']]);
});
it('agrees with the JS Stoer-Wagner fallback on a random graph', async () => {
let seed = 7;
const rand = () => ((seed = (seed * 1103515245 + 12345) % 2 ** 31) / 2 ** 31);
const nodes = Array.from({ length: 40 }, (_, i) => `n${i}`);
const edges: Edge[] = [];
for (let i = 0; i < nodes.length; i++) edges.push([nodes[i], nodes[(i + 1) % nodes.length], 1 + Math.floor(rand() * 4)]);
for (let k = 0; k < 60; k++) {
const u = Math.floor(rand() * 40), v = Math.floor(rand() * 40);
if (u !== v) edges.push([nodes[u], nodes[v], 1 + Math.floor(rand() * 4)]);
}
const wasm = await wasmMinCut(nodes, edges);
const js = fallbackMinCut(nodes, edges);
expect(wasm).not.toBeNull();
expect(wasm!.cutValue).toBeCloseTo(js.cutValue, 6);
});
it('analyzeMinCutBoundaries uses the wasm result', async () => {
const { nodes, edges } = twoClusters();
const graph = {
nodes: new Map(nodes.map(n => [n, { id: n, path: n, name: n, type: 'file' as const, imports: [], exports: [], size: 1, complexity: 1 }])),
edges: edges.map(([s, t, w]) => ({ source: s, target: t, type: 'import' as const, weight: w })),
};
const [b] = await analyzeMinCutBoundaries(graph as never, 2);
expect(b.cutValue).toBeCloseTo(0.5, 6);
});
it('seedLocalMinCut returns the seed side of the weakest boundary', async () => {
const { edges } = twoClusters();
const r = await seedLocalMinCut('a2', edges, 3, 1000, fallbackMinCut);
expect(r).not.toBeNull();
expect(r!.backend).toBe('mincut-wasm');
expect(r!.cutValue).toBeCloseTo(0.5, 6);
expect(r!.seedSide.map(n => n.nodeId).sort()).toEqual(['a1', 'a3', 'a4']);
expect([...r!.otherSide].sort()).toEqual(['b1', 'b2', 'b3', 'b4']);
});
});
describe.skipIf(!HAS_RUVECTOR)('agentdb_graph-pathfinder dynamic-mincut runs the real min cut', () => {
const req = createRequire(import.meta.url);
let Database: any;
let native = true;
let root: string;
const saved: Record<string, string | undefined> = {};
beforeAll(() => {
try {
Database = req('better-sqlite3');
new Database(':memory:').close();
} catch {
native = false;
}
});
beforeEach(() => {
saved.CLAUDE_FLOW_MEMORY_PATH = process.env.CLAUDE_FLOW_MEMORY_PATH;
saved.CLAUDE_FLOW_DB_PATH = process.env.CLAUDE_FLOW_DB_PATH;
root = mkdtempSync(join(tmpdir(), 'ruflo-mincut-'));
mkdirSync(join(root, '.swarm'), { recursive: true });
process.env.CLAUDE_FLOW_MEMORY_PATH = join(root, '.swarm');
delete process.env.CLAUDE_FLOW_DB_PATH;
_resetMemoryRootCache();
_resetBridgeDb();
});
afterEach(() => {
for (const [k, v] of Object.entries(saved)) {
if (v === undefined) delete process.env[k];
else process.env[k] = v;
}
_resetMemoryRootCache();
_resetBridgeDb();
rmSync(root, { recursive: true, force: true });
});
it('returns the seed partition and cut metadata', async () => {
if (!native) return;
const db = new Database(join(root, '.swarm', 'memory.db'));
db.exec(`CREATE TABLE graph_edges (
id TEXT PRIMARY KEY, source_id TEXT NOT NULL, target_id TEXT NOT NULL, relation TEXT NOT NULL,
weight REAL DEFAULT 1.0, confidence REAL DEFAULT 1.0, decay_rate REAL DEFAULT 0.0,
last_reinforced TEXT, witness_id TEXT, embedding_ref TEXT, metadata TEXT, created_at TEXT NOT NULL)`);
const ins = db.prepare('INSERT INTO graph_edges (id, source_id, target_id, relation, weight, created_at) VALUES (?, ?, ?, ?, ?, ?)');
twoClusters().edges.forEach(([s, t, w], i) => ins.run(`e${i}`, `entity:${s}`, `entity:${t}`, 'related', w, new Date().toISOString()));
db.close();
const r = await agentdbGraphPathfinder.handler({
seedNodeId: 'entity:a2', query: 'boundary', algorithm: 'dynamic-mincut', threshold: 0,
complexityBudget: { maxMillis: 5000 },
}) as any;
expect(r.success).toBe(true);
expect(r.mincut.backend).toBe('mincut-wasm');
expect(r.mincut.cutValue).toBeCloseTo(0.5, 6);
expect(r.paths.map((p: any) => p.nodeId).sort()).toEqual(['entity:a1', 'entity:a3', 'entity:a4']);
});
});
describe.skipIf(!HAS_AGENT_BOOSTER)('agent-booster backs hooks_fast-apply', () => {
const code = 'function add(a, b) {\n return a + b;\n}\n\nfunction sub(a, b) {\n return a - b;\n}\n';
const snippet = 'function add(a: number, b: number): number {\n return a + b;\n}';
it('merges a code snippet with the real engine', async () => {
const r = await fastApply({ code, edit: snippet, language: 'typescript' });
expect(r.backend).toBe('agent-booster');
expect(r.success).toBe(true);
expect(r.output).toContain('function add(a: number, b: number): number');
expect(r.output).toContain('function sub(a, b)');
});
it('refuses a natural-language instruction (it is an applier, not a generator)', async () => {
const r = await fastApply({ code, edit: 'Convert all var declarations to const', language: 'javascript' });
expect(r.backend).toBe('agent-booster');
expect(r.success).toBe(false);
expect(r.output).toBe(code);
});
describe('file mode', () => {
let dir: string;
let prev: string | undefined;
beforeEach(() => {
dir = mkdtempSync(join(tmpdir(), 'ruflo-fastapply-'));
prev = process.env.CLAUDE_FLOW_CWD;
process.env.CLAUDE_FLOW_CWD = dir;
});
afterEach(() => {
if (prev === undefined) delete process.env.CLAUDE_FLOW_CWD;
else process.env.CLAUDE_FLOW_CWD = prev;
rmSync(dir, { recursive: true, force: true });
});
it('patches a file in place and honours dryRun', async () => {
writeFileSync(join(dir, 'math.ts'), code);
const dry = await hooksFastApply.handler({ file: 'math.ts', edit: snippet, dryRun: true }) as any;
expect(dry.success).toBe(true);
expect(dry.written).toBe(false);
expect(readFileSync(join(dir, 'math.ts'), 'utf-8')).toBe(code);
const real = await hooksFastApply.handler({ file: 'math.ts', edit: snippet }) as any;
expect(real.written).toBe(true);
expect(readFileSync(join(dir, 'math.ts'), 'utf-8')).toContain('a: number, b: number');
});
it('rejects a path outside the project root', async () => {
const r = await hooksFastApply.handler({ file: '../outside.ts', edit: snippet }) as any;
expect(r.success).toBe(false);
});
});
});