Files
proffesor-for-testing__agen…/tests/benchmarks/rvf-pattern-store.test.ts
Dragan Spiridonov a6202c39a3 chore(release): v3.9.1 (#395)
* feat: implement ADR-062 (StrongDM all 3 tiers) and ADR-087 (RuVector 14/14 capabilities)

ADR-062 StrongDM Software Factory — all 6 actions across 3 tiers:
- Tier 1: Loop detection wired to MCP protocol-server (blocks on strike 3+),
  token dashboard (pre-existing)
- Tier 2: Holdout testing (10% FNV-1a selection, filtered in test-execution),
  gate ratcheting (monotonic 5-pass/2%/95% cap, persisted to MemoryBackend)
- Tier 3: Progressive context (TF-IDF prediction, reduces availableFiles on spawn),
  meta-learning cycle (4 insight types, stored + published as domain events)

ADR-087 RuVector Advanced Capabilities — milestones 1-5:
- EWC++ recordOutcome + backgroundConsolidate wired to 3 domain coordinators
- R1: HDC fingerprinting (10K-bit hypervectors, wired to PatternStore.store())
- R3: Delta event sourcing (sparse encoding, wired to PatternStore.store())
- R13: Cognitive routing (predictive compression, wired to mailbox.send/receive)
- R14: Hyperbolic HNSW (Poincare ball, auto-indexed in PatternStore.store())

Also updates ADR statuses: 059, 060, 061 → Implemented (were already done),
062 → Implemented, 086 → In Progress, 087 → Implemented.

223 new tests across 11 test files, all passing. Zero regressions.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>

* feat: implement RVF cluster (ADR-065/066/067/071) with native benchmarks

Implements the RVF persistence cluster for persistent HNSW vector storage,
agent memory branching, and HNSW unification foundation.

Key changes:
- RvfPatternStore: IPatternStore backed by @ruvector/rvf-node native HNSW
  (1.2ms cold-start, 0.19ms search p50, verified with real native binary)
- AgentMemoryBranch: per-agent COW isolation via derive(), ingest-log merge,
  wired into Kernel.initialize() + DefaultAgentCoordinator
- HnswLegacyBridge: adapts old IHNSWIndex to unified IHnswIndexProvider,
  wired into PatternStore when useUnifiedHnsw flag enabled
- Factory routing: createPatternStore() returns RvfPatternStore when flag
  enabled + native available + data directory exists
- Dream engine: accepts external RVF adapter (no duplicate file handles),
  RVCOWBranchManager enhanced with recall validation check
- @ruvector/gnn bumped 0.1.19→0.1.25, 3 new feature flags added
- IPatternStore interface extracted for polymorphic pattern store usage
- 50 new tests (16 RvfPatternStore + 17 AgentMemoryBranch + 12 bridge + 5 benchmarks)
- 1188 tests pass, 0 regressions

ADR status: 066 Implemented, 067 Implemented, 065 Implemented,
069/071 In Progress (honest assessment after brutal-honesty review)

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>

* fix(init): resolve skills/agents paths from package root, not relative to bundle depth

esbuild code-splitting puts installer code into dist/cli/chunks/ (3 levels
deep) instead of dist/init/ (2 levels deep), so the old ../../ traversals
landed at dist/ instead of the package root — causing "Source directory not
found" errors for all global installs.

Replace brittle relative-path resolution in all 4 installers with a shared
findPackageRoot() that walks up to the nearest package.json with
name=agentic-qe. Prioritise assets/ paths (canonical npm source) over
.claude/ paths.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>

* feat: complete RVF cluster Phases 2-3 (ADR-067/069/071/072) with devil's advocate fixes

Phase 2A (ADR-067): Agent memory branching enabled — useAgentMemoryBranching=true,
BRANCH_DISCARD witness action, recordIngest callback exposed to agents via config.

Phase 2B (ADR-069): Dream RVF COW — useRvfFork driven by isRVFPatternStoreEnabled(),
child adapter stored + temp files cleaned up on merge/discard, 13 tests.

Phase 2C (ADR-071): HNSW unification — useUnifiedHnsw=true, HNSWEmbeddingIndex routes
through HnswAdapter, UnifiedMemory vectorIndex uses UnifiedHnswIndex, HnswLegacyBridge
delegates to adapter string-ID APIs (no duplicate ID maps), addEmbeddingsBatch routed
correctly, saveIndex/loadIndex safe under unified mode.

Phase 3 (ADR-072): RVF primary migration scaffolding — RvfMigrationAdapter (5-stage
routing with write latency tracking), RvfConsistencyValidator (rolling divergence +
compaction), RvfStageGate (go/no-go with witness chain), rvfMigrationStage=1 default,
wired into shared-rvf-dual-writer at stage >= 2, 32 tests.

Cross-cutting fixes from devil's advocate review:
- Shared RVF adapter singleton eliminates dual file handles (kernel + dream engine)
- RvfPatternStore reports honest nativeAvailable=false + rvfInitError on failure
- ESM-safe dynamic import() replaces require() in dream-engine and branch-manager
- quality_assess defaults to src/ instead of cwd to prevent full-project scan hang
- discoverSourceFiles skips .agentic-qe/.claude/.cache dirs, adds maxFiles=5000 cap

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>

* feat: complete RVF cluster plan — Phase 2C decommission, Phase 3 integration, fix 7 pre-existing test failures

Phase 2C (ADR-071) — HNSW decommission:
- Remove RuvectorFlatIndex fallback from unified-memory.ts; always use UnifiedHnswIndex
- Hardcode isUnifiedHnswActive()=true in HNSWEmbeddingIndex (hnswlib-node legacy path is dead code)
- Create HnswShadowValidator for brute-force vs HnswAdapter divergence validation
- Benchmark alias (rvf-pattern-store.bench.ts) for plan compliance

Phase 3 (ADR-072) — RVF Primary Migration integration:
- RvfMigrationCoordinator: wires adapter + validator + gate with real SQLite/RVF handles
- MCP tools: migration_status, migration_check, migration_promote (persistence category)
- Kernel boot wiring: coordinator initializes when rvfMigrationStage >= 2
- RvfMigrationAdapter.setStage(): propagate promotions to routing logic
- Promote default rvfMigrationStage from 1 (hybrid) to 2 (dual-write-sqlite-primary)
- Integration test: 13 tests covering full lifecycle (stage 1→2→3→4), write/read routing,
  consistency checks, gate enforcement, fallback, metrics

Test fixes (7 pre-existing failures → 1 remaining):
- code-intelligence-metrics-wiring: spy console.info not console.log (logger routes to console.info)
- mcp-integration: disable ADR-062 loop detection (repeated identical calls are by design)
- dream-cycle-tool (2 tests): RvfPatternStore empty-query branch returns all patterns from SQLite
- coherence-integration (4 tests): RvfPatternStore vector search fallback computes brute-force
  cosine over SQLite embeddings when RVF adapter unavailable; getStats() falls back to SQLite count;
  auto-attach SQLitePatternStore in initialize() when not explicitly wired

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>

* chore(release): bump version to v3.9.1

- Version bump in package.json and skills-manifest.json
- Fix "Dynamic require of X is not supported" in ESM bundles by adding
  createRequire banner to both CLI and MCP build scripts — every chunk
  now has a working require() for Node.js builtins
- Add CHANGELOG.md entry and release notes for v3.9.1

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>

* fix(ci): regenerate package-lock.json for npm ci compatibility

The lock file was out of sync with package.json — new transitive
dependencies added on main were missing. All 15 CI checks failed
at `npm ci` with "Missing from lock file" errors.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>

* fix(ci): pin Node to 24.13.0 and restore working lock file

Node 24.14.1 ships npm 11.11.0 which enforces stricter lock file
validation than 11.6.x (what 24.13.0 ships). The existing lock file
passes under 11.6.x but fails under 11.11.0 with "Missing from lock
file" for transitive dependencies of private-registry packages.

Pin all 5 workflow files to node-version: '24.13.0' and restore the
lock file from commit f9b76968 (last CI-passing state) with only the
version bump to 3.9.1.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>

* fix(ci): regenerate package-lock.json with npm 10 for stable npm ci

npm 11 (Node 24) produces internally inconsistent lock files that npm ci
rejects — each npm install resolves transitive deps differently. Generated
with npm 10 (Node 22 LTS) which produces stable lock files compatible with
both npm 10 and npm 11.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-05 18:51:49 +02:00

227 lines
7.5 KiB
TypeScript

/**
* Benchmark: RvfPatternStore with REAL @ruvector/rvf-node native backend
*
* Measures actual user-facing performance with disk-backed HNSW:
* 1. Cold-start time (open .rvf file + index ready)
* 2. Ingest throughput (patterns/second to native HNSW)
* 3. Search latency p50/p95 (native SIMD-accelerated queries)
* 4. Correctness (self-search returns stored pattern)
*
* Run: npx vitest run tests/benchmarks/rvf-pattern-store.test.ts
*/
import { describe, it, expect, afterAll } from 'vitest';
import { existsSync, unlinkSync, mkdirSync } from 'fs';
import { join } from 'path';
import { RvfPatternStore } from '../../src/learning/rvf-pattern-store.js';
import {
createRvfStore,
isRvfNativeAvailable,
} from '../../src/integrations/ruvector/rvf-native-adapter.js';
import type { QEPattern } from '../../src/learning/qe-patterns.js';
// ============================================================================
// Helpers
// ============================================================================
const BENCH_DIR = join(process.cwd(), '.agentic-qe', 'bench-tmp');
const RVF_PATH = join(BENCH_DIR, 'bench-patterns.rvf');
const DIM = 384;
function cleanupBenchFiles(): void {
for (const ext of ['', '.idmap.json']) {
const p = `${RVF_PATH}${ext}`;
if (existsSync(p)) unlinkSync(p);
}
}
function randomEmbedding(): number[] {
return Array.from({ length: DIM }, () => Math.random() - 0.5);
}
function makePattern(idx: number): QEPattern {
return {
id: `bench-${idx}`,
patternType: 'test-template',
qeDomain: 'test-generation',
domain: 'test-generation',
name: `Bench Pattern ${idx}`,
description: `Benchmark pattern number ${idx} for performance testing`,
confidence: 0.5 + Math.random() * 0.5,
usageCount: Math.floor(Math.random() * 20),
successRate: 0.7 + Math.random() * 0.3,
qualityScore: 0.6 + Math.random() * 0.3,
context: { tags: ['bench'] },
template: { type: 'code', content: 'bench()', variables: [] },
embedding: randomEmbedding(),
tier: 'short-term',
createdAt: new Date(),
lastUsedAt: new Date(),
successfulUses: 3,
reusable: false,
reuseCount: 0,
averageTokenSavings: 0,
} as QEPattern;
}
// ============================================================================
// Real Native Benchmarks
// ============================================================================
describe('RvfPatternStore — Real Native Benchmarks', () => {
const nativeAvailable = isRvfNativeAvailable();
afterAll(() => {
cleanupBenchFiles();
});
it('should have @ruvector/rvf-node native binary available', () => {
expect(nativeAvailable).toBe(true);
});
it.runIf(nativeAvailable)('cold-start: open/create .rvf file', async () => {
cleanupBenchFiles();
if (!existsSync(BENCH_DIR)) mkdirSync(BENCH_DIR, { recursive: true });
const start = performance.now();
const store = new RvfPatternStore(
(path, dim) => createRvfStore(path, dim),
{ rvfPath: RVF_PATH, base: undefined as any },
);
await store.initialize();
const coldStartMs = performance.now() - start;
await store.dispose();
console.log(`[REAL BENCH] Cold-start (create new .rvf): ${coldStartMs.toFixed(2)}ms`);
// Creating a new .rvf file should be fast (no index to rebuild)
expect(coldStartMs).toBeLessThan(500);
});
it.runIf(nativeAvailable)('ingest 1000 patterns into native HNSW', async () => {
cleanupBenchFiles();
if (!existsSync(BENCH_DIR)) mkdirSync(BENCH_DIR, { recursive: true });
const store = new RvfPatternStore(
(path, dim) => createRvfStore(path, dim),
{ rvfPath: RVF_PATH, base: undefined as any },
);
await store.initialize();
const PATTERN_COUNT = 1000;
const patterns = Array.from({ length: PATTERN_COUNT }, (_, i) => makePattern(i));
const start = performance.now();
for (const p of patterns) {
await store.store(p);
}
const ingestMs = performance.now() - start;
const throughput = PATTERN_COUNT / (ingestMs / 1000);
console.log(
`[REAL BENCH] Ingest ${PATTERN_COUNT} patterns: ${ingestMs.toFixed(2)}ms ` +
`(${throughput.toFixed(0)} patterns/sec)`,
);
const stats = await store.getStats();
console.log(`[REAL BENCH] RVF status: ${stats.totalPatterns} vectors, ${stats.hnswStats.indexSizeBytes} bytes`);
expect(stats.totalPatterns).toBe(PATTERN_COUNT);
expect(ingestMs).toBeLessThan(10000); // generous limit for CI
await store.dispose();
});
it.runIf(nativeAvailable)('ingest + search latency with 1000 patterns in same session', async () => {
cleanupBenchFiles();
if (!existsSync(BENCH_DIR)) mkdirSync(BENCH_DIR, { recursive: true });
const store = new RvfPatternStore(
(path, dim) => createRvfStore(path, dim),
{ rvfPath: join(BENCH_DIR, 'search-bench.rvf'), base: undefined as any },
);
await store.initialize();
// Ingest 1000 patterns
const PATTERN_COUNT = 1000;
const patternMap = new Map<string, QEPattern>();
for (let i = 0; i < PATTERN_COUNT; i++) {
const p = makePattern(i);
patternMap.set(p.id, p);
await store.store(p);
}
// Attach mock sqlite for metadata resolution
(store as any).sqliteStore = {
getPattern: (id: string) => patternMap.get(id) ?? null,
};
// Run 100 search queries and measure latency
const latencies: number[] = [];
for (let i = 0; i < 100; i++) {
const query = randomEmbedding();
const start = performance.now();
const result = await store.search(query, { limit: 10 });
latencies.push(performance.now() - start);
if (i === 0 && result.success) {
console.log(`[REAL BENCH] First search returned ${result.value.length} results`);
}
}
latencies.sort((a, b) => a - b);
const p50 = latencies[Math.floor(latencies.length * 0.5)];
const p95 = latencies[Math.floor(latencies.length * 0.95)];
const avg = latencies.reduce((s, l) => s + l, 0) / latencies.length;
console.log(
`[REAL BENCH] Search (${PATTERN_COUNT} patterns): avg=${avg.toFixed(2)}ms ` +
`p50=${p50.toFixed(2)}ms p95=${p95.toFixed(2)}ms`,
);
expect(p95).toBeLessThan(50);
await store.dispose();
// Cleanup
for (const ext of ['', '.idmap.json']) {
const p = join(BENCH_DIR, `search-bench.rvf${ext}`);
if (existsSync(p)) unlinkSync(p);
}
});
it.runIf(nativeAvailable)('correctness: self-search finds stored pattern', async () => {
cleanupBenchFiles();
if (!existsSync(BENCH_DIR)) mkdirSync(BENCH_DIR, { recursive: true });
const store = new RvfPatternStore(
(path, dim) => createRvfStore(path, dim),
{ rvfPath: RVF_PATH, base: undefined as any },
);
await store.initialize();
const pattern = makePattern(42);
await store.store(pattern);
// Attach mock sqlite for metadata resolution
(store as any).sqliteStore = {
getPattern: (id: string) => id === pattern.id ? pattern : null,
};
// Search with the same embedding — should find it
const result = await store.search(pattern.embedding!, { limit: 5 });
expect(result.success).toBe(true);
if (result.success) {
expect(result.value.length).toBeGreaterThan(0);
expect(result.value[0].pattern.id).toBe(pattern.id);
expect(result.value[0].score).toBeGreaterThan(0.95);
console.log(
`[REAL BENCH] Self-search score: ${result.value[0].score.toFixed(4)} ` +
`(expected ~1.0)`,
);
}
await store.dispose();
cleanupBenchFiles();
});
});