Files
ruvnet__ruflo/v3/@claude-flow/cli/__tests__/sona-embeddings-validation.test.ts
rUv e111bfbd7f fix(memory,tests): restore memory search recall and green the CLI suite (69 → 0) (#3252)
* fix(memory,tests): restore `memory search` recall and green the CLI suite (69 → 0)

The CLI suite had 69 failing tests across 50 files. Root-causing each rather
than adjusting expectations turned up one real product regression, two real
bugs, and a set of tests asserting things about the machine instead of the code.

PRODUCT REGRESSION — `memory search` recalled nothing (re-break of #2558)

`memory search` returned zero results for content that matched word for word,
while store/list/retrieve worked. Bisected to the threshold default:

  * 2026-07-04 #2558 restored recall, designed around a 0.3 threshold. Its
    fusion scores a full-coverage keyword hit as
    0.6*max(0,semantic) + 0.4*lexical, so with a non-positive cosine — routine
    for a one-word query — a PERFECT keyword match tops out at exactly 0.40.
  * 2026-07-26 #2790 set the CLI default to 0.7. Above 0.4, keyword recall is
    mathematically unreachable, so #2558 silently regressed.

Instrumented the live path to confirm before changing anything:
  key=note/alpha terms=["connectivity"] cov=1 bm25=0.029 sem=-0.883
  lex=1.000 score=0.400 thr=0.7      → dropped
Default restored to 0.3 at both sites, with the ceiling documented so it is not
raised past 0.4 again. Verified end to end: a shared keyword recalls all three
entries, a unique keyword recalls only its own. This was broken on main too.

REAL BUG — anchor containment rejected any project under a symlink

containedPath() compared a realpath'd root against a NON-realpath'd candidate,
so on macOS (/tmp → /private/tmp) every project looked like an escape. Now
compares like with like. Both guarantees re-verified by probe: ../ traversal,
deep traversal, absolute-outside and symlink-escape all still rejected;
symlinked-root spelling now accepted.

REAL BUG — a test that could not fail

funnel.test.ts asserted `elapsed < 100ms` as a proxy for "no network call" —
its own comment conceded a future fetch() would still pass. It also failed
intermittently (118ms) under full-suite CPU contention. Replaced with an
actual assertion on fetch/http.request/https.request, patched via the CJS
copies (ESM namespaces are non-writable). Negative-controlled: the technique
observes a real call and restores cleanly.

TESTS THAT MEASURED THE MACHINE, NOT THE CODE

  * 51 wasm tests asserted `available === true` for optional packages that were
    simply not installed, gated only on `process.env.CI`. Now also gated on real
    availability. The 7 tests in those files that need no WASM were lifted into
    their own blocks so they keep running rather than being skipped along with
    the rest — no coverage traded away for a green tick.
  * 4 agenticow tests lacked the `skipIf(!havePkg)` guard their 4 siblings had;
    in degraded mode the verb is inert and returns before validation.
  * policy-runtime hashed the raw tmpdir path while the source hashes the
    CANONICAL one, so it looked for a trust anchor that is never written there —
    and its cleanup was deleting a nonexistent path, leaking real anchors into
    ~/.config on every run.
  * sona's provider allowlist predated the ruvector / wasm-embedder /
    @claude-flow/embeddings backends.
  * ruvector/index asserted vi.mock satisfies a *dynamic* import() of a bare
    specifier. It does not under vitest 4 — the specifier is rewritten to
    '/@id/@ruvector/core' and fails with ERR_MODULE_NOT_FOUND. Now pins the
    contract the try/catch actually provides: unloadable → false, never throws.

TIMEOUTS — the "flakiness" was a fixed 5s budget

Six memory/intelligence files failed with "Test timed out in 5000ms", never an
assertion. They initialise a real ONNX embedder and SQLite; alone they are
fast, but the full suite saturates every core (~440% CPU). Because it depended
on scheduling, a different file failed each run. Raised testTimeout/hookTimeout
to 30s. (Process-level isolation was tried first and ruled out — forks changed
nothing, which is what identified the cause as time, not shared state.)

Verified: 3 consecutive full runs at 0 failed / 3572 passed on the feature
base, and 0 failed / 3537 passed on this branch's base.

Co-Authored-By: RuFlo <ruv@ruv.net>
Claude-Session: https://claude.ai/code/session_013u4pmL9ZUAXb6usVQgNo67

* fix(tests): make ruvector availability assertion environment-independent

CI caught what my first pass missed. The rewritten test asserted
`isRuvectorAvailable()` resolves to `false`, but whether the dynamic
`import('@ruvector/core')` resolves is environment-dependent:

  - under vitest's module runner a bare-specifier dynamic import is
    rewritten to '/@id/@ruvector/core' and fails (ERR_MODULE_NOT_FOUND)
    → false → my `toBe(false)` passed locally
  - a normal install where the package resolves → true → `toBe(false)`
    fails, which is exactly what the CI test-ratchet flagged

The prior `toBe(true)` had the same defect in the other direction. Pin
the invariant that holds in BOTH environments instead — the only thing
the try/catch actually promises: it resolves to a boolean and never
throws. No specific resolution outcome is asserted.

Verified 33/33 locally; the sibling "should return boolean" test already
covers the type, so this now documents the no-throw contract distinctly.

Co-Authored-By: RuFlo <ruv@ruv.net>
Claude-Session: https://claude.ai/code/session_013u4pmL9ZUAXb6usVQgNo67
2026-09-09 23:07:32 +00:00

111 lines
5.3 KiB
TypeScript

/**
* Deep validation: SONA optimizer, embeddings transparency, neural tools
*/
import { describe, it, expect, beforeEach } from 'vitest';
import { SONAOptimizer, resetSONAOptimizer } from '../src/memory/sona-optimizer.js';
import { generateEmbedding } from '../src/ruvector/vector-db.js';
// ---------- SONA Optimizer ----------
describe('SONA Optimizer', () => {
let sona: SONAOptimizer;
beforeEach(() => {
resetSONAOptimizer();
sona = new SONAOptimizer({ persistencePath: '/tmp/sona-test-' + Date.now() + '.json' });
});
it('1: getRoutingSuggestion() is async and returns a result with source field', async () => {
const result = await sona.getRoutingSuggestion('implement a login page');
expect(result).toBeDefined();
expect(typeof result.source).toBe('string');
});
it('2: source field is one of the allowed values', async () => {
const allowed = ['sona-native', 'sona-pattern', 'q-learning', 'sona-keyword', 'default'];
const result = await sona.getRoutingSuggestion('write unit tests for the api');
expect(allowed).toContain(result.source);
});
it('3: keyword routing maps "implement authentication" to coder or security-architect', async () => {
const result = await sona.getRoutingSuggestion('implement authentication');
// "implement" is a coder keyword, "authentication" is security-architect
expect(['coder', 'security-architect']).toContain(result.agent);
expect(result.source).toMatch(/sona-keyword|default/);
});
it('4: loadSonaEngine() gracefully handles missing @ruvector/sona', async () => {
// With no @ruvector/sona installed, should still return a result via keyword/default
const result = await sona.getRoutingSuggestion('design a database schema');
expect(['sona-keyword', 'default', 'sona-pattern']).toContain(result.source);
expect(result.agent).toBeDefined();
});
it('5: return type has agentType-equivalent, confidence, source, reasoning-equivalent fields', async () => {
const result = await sona.getRoutingSuggestion('optimize performance of the cache layer');
// RoutingSuggestion uses `agent` (not `agentType`) and `alternatives` (not `reasoning`)
expect(typeof result.agent).toBe('string');
expect(typeof result.confidence).toBe('number');
expect(typeof result.source).toBe('string');
expect(Array.isArray(result.alternatives)).toBe(true);
expect(typeof result.usedQLearning).toBe('boolean');
});
});
// ---------- Embeddings Transparency ----------
describe('Embeddings Transparency (vector-db)', () => {
it('6: generateHashEmbedding via generateEmbedding returns Float32Array of length 384', () => {
// generateEmbedding defaults to 768, but we request 384
const emb = generateEmbedding('hello world', 384);
expect(emb).toBeInstanceOf(Float32Array);
expect(emb.length).toBe(384);
});
it('7: hash embedding is deterministic (same input -> same output)', () => {
const a = generateEmbedding('deterministic test input', 384);
const b = generateEmbedding('deterministic test input', 384);
expect(Array.from(a)).toEqual(Array.from(b));
});
it('8: hash embedding has _warning property (non-enumerable) on fallback', () => {
const emb = generateEmbedding('test transparency', 384);
// _warning is defined as non-enumerable
const descriptor = Object.getOwnPropertyDescriptor(emb, '_warning');
expect(descriptor).toBeDefined();
expect(descriptor!.enumerable).toBe(false);
expect(typeof descriptor!.value).toBe('string');
expect(descriptor!.value).toContain('hash-based');
});
});
// ---------- Neural Tools ----------
describe('Neural Tools (neural-tools)', () => {
it('9: generateEmbedding function exists in neural-tools and is callable', async () => {
// neural-tools has a module-scoped generateEmbedding; we test it indirectly
// by importing the neuralTools array and calling the neural_predict handler
const { neuralTools } = await import('../src/mcp-tools/neural-tools.js');
const predictTool = neuralTools.find(t => t.name === 'neural_predict');
expect(predictTool).toBeDefined();
// Call it — should succeed without real embeddings
const result = await predictTool!.handler({ input: 'test embedding generation' });
expect(result).toHaveProperty('embeddingDims', 384);
});
it('10: embeddingServiceName reflects active provider (real or hash-fallback)', async () => {
const { neuralTools } = await import('../src/mcp-tools/neural-tools.js');
const statusTool = neuralTools.find(t => t.name === 'neural_status');
expect(statusTool).toBeDefined();
const result = await statusTool!.handler({});
const provider = (result as any).embeddingProvider as string;
// Must be a non-empty string indicating which embedding backend is active
expect(typeof provider).toBe('string');
expect(provider.length).toBeGreaterThan(0);
// Must match one of the known provider tiers or fallback
// Every backend neural-tools can actually report. The three added here
// (ruvector, wasm-embedder, @claude-flow/embeddings) are real provider
// strings the allowlist predated — see neural-tools.ts:115/141/1073.
const knownProviders =
/agentic-flow|onnx|mock|hash|fallback|reasoningbank|none|ruvector|wasm-embedder|@claude-flow\/embeddings/i;
expect(provider).toMatch(knownProviders);
});
});