Files
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

332 lines
9.9 KiB
TypeScript

/**
* Agentic QE v3 - Progressive Context Loader Unit Tests
* ADR-062 Action 5: HNSW-predicted context loading on agent spawn
*/
import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest';
import { ProgressiveContextLoader } from '../../../src/kernel/agent-coordinator';
import type { FileRequestRecord } from '../../../src/kernel/interfaces';
// Sample file list used across tests
const SAMPLE_FILES = [
'src/auth/auth-service.ts',
'src/auth/auth-controller.ts',
'src/auth/auth-middleware.ts',
'src/user/user-service.ts',
'src/user/user-repository.ts',
'src/payment/payment-service.ts',
'src/payment/stripe-adapter.ts',
'src/kernel/kernel.ts',
'src/kernel/event-bus.ts',
'src/shared/types.ts',
'src/shared/utils.ts',
'src/config/database.ts',
'tests/auth/auth-service.test.ts',
'tests/user/user-service.test.ts',
'tests/payment/payment-service.test.ts',
];
describe('ProgressiveContextLoader', () => {
const originalEnv = process.env.AQE_PROGRESSIVE_CONTEXT_ENABLED;
beforeEach(() => {
// Enable feature flag for most tests
process.env.AQE_PROGRESSIVE_CONTEXT_ENABLED = 'true';
});
afterEach(() => {
// Restore original env
if (originalEnv === undefined) {
delete process.env.AQE_PROGRESSIVE_CONTEXT_ENABLED;
} else {
process.env.AQE_PROGRESSIVE_CONTEXT_ENABLED = originalEnv;
}
});
describe('predictFilesForTask', () => {
it('should return at most maxInitialFiles files', () => {
const loader = new ProgressiveContextLoader({
strategy: 'predictive',
maxInitialFiles: 5,
predictionThreshold: 0.7,
trackFileRequests: true,
});
const result = loader.predictFilesForTask(
'Fix authentication token validation in the auth service',
SAMPLE_FILES,
);
expect(result.length).toBeLessThanOrEqual(5);
expect(result.length).toBeGreaterThan(0);
});
it('should rank relevant files higher based on task keywords', () => {
const loader = new ProgressiveContextLoader({
strategy: 'predictive',
maxInitialFiles: 5,
predictionThreshold: 0.7,
trackFileRequests: true,
});
const result = loader.predictFilesForTask(
'Fix authentication service and auth middleware',
SAMPLE_FILES,
);
// Auth-related files should be ranked first
const authFiles = result.filter(f => f.includes('auth'));
expect(authFiles.length).toBeGreaterThan(0);
// The first result should be auth-related
expect(result[0]).toContain('auth');
});
it('should return all files when feature flag is disabled', () => {
process.env.AQE_PROGRESSIVE_CONTEXT_ENABLED = 'false';
const loader = new ProgressiveContextLoader({
strategy: 'predictive',
maxInitialFiles: 3,
predictionThreshold: 0.7,
trackFileRequests: true,
});
const result = loader.predictFilesForTask(
'Fix authentication service',
SAMPLE_FILES,
);
// Should return ALL files, not limited by maxInitialFiles
expect(result).toHaveLength(SAMPLE_FILES.length);
expect(result).toEqual(SAMPLE_FILES);
});
it('should return all files when strategy is full', () => {
const loader = new ProgressiveContextLoader({
strategy: 'full',
maxInitialFiles: 3,
predictionThreshold: 0.7,
trackFileRequests: true,
});
const result = loader.predictFilesForTask(
'Fix authentication service',
SAMPLE_FILES,
);
expect(result).toHaveLength(SAMPLE_FILES.length);
});
it('should return first N files when task description is empty', () => {
const loader = new ProgressiveContextLoader({
strategy: 'predictive',
maxInitialFiles: 4,
predictionThreshold: 0.7,
trackFileRequests: true,
});
const result = loader.predictFilesForTask('', SAMPLE_FILES);
expect(result).toHaveLength(4);
expect(result).toEqual(SAMPLE_FILES.slice(0, 4));
});
it('should return empty array when file list is empty', () => {
const loader = new ProgressiveContextLoader({
strategy: 'predictive',
maxInitialFiles: 10,
predictionThreshold: 0.7,
trackFileRequests: true,
});
const result = loader.predictFilesForTask(
'Fix authentication service',
[],
);
expect(result).toHaveLength(0);
});
});
describe('recordFileRequest', () => {
it('should record file requests correctly', () => {
const loader = new ProgressiveContextLoader({
strategy: 'predictive',
maxInitialFiles: 5,
predictionThreshold: 0.7,
trackFileRequests: true,
});
const record: FileRequestRecord = {
filePath: 'src/auth/auth-service.ts',
requestedAt: Date.now(),
wasPreloaded: true,
agentId: 'agent-1',
taskDescription: 'Fix auth service',
};
loader.recordFileRequest(record);
const history = loader.getFileRequestHistory();
expect(history).toHaveLength(1);
expect(history[0]).toEqual(record);
});
it('should not record when trackFileRequests is false', () => {
const loader = new ProgressiveContextLoader({
strategy: 'predictive',
maxInitialFiles: 5,
predictionThreshold: 0.7,
trackFileRequests: false,
});
const record: FileRequestRecord = {
filePath: 'src/auth/auth-service.ts',
requestedAt: Date.now(),
wasPreloaded: true,
agentId: 'agent-1',
taskDescription: 'Fix auth service',
};
loader.recordFileRequest(record);
const history = loader.getFileRequestHistory();
expect(history).toHaveLength(0);
});
});
describe('getPredictionAccuracy', () => {
it('should calculate prediction accuracy correctly', () => {
const loader = new ProgressiveContextLoader({
strategy: 'predictive',
maxInitialFiles: 5,
predictionThreshold: 0.7,
trackFileRequests: true,
});
// First, predict files to populate preloadedFiles set
loader.predictFilesForTask(
'Fix authentication service and auth middleware',
SAMPLE_FILES,
);
// Record requests for files that were preloaded (hits)
loader.recordFileRequest({
filePath: 'src/auth/auth-service.ts',
requestedAt: Date.now(),
wasPreloaded: true,
agentId: 'agent-1',
taskDescription: 'Fix auth',
});
// Record a request for a file that was NOT preloaded (miss)
loader.recordFileRequest({
filePath: 'src/config/database.ts',
requestedAt: Date.now(),
wasPreloaded: false,
agentId: 'agent-1',
taskDescription: 'Fix auth',
});
const accuracy = loader.getPredictionAccuracy();
expect(accuracy.predicted).toBeGreaterThan(0);
expect(accuracy.actuallyUsed).toBe(1); // one wasPreloaded=true
expect(accuracy.hitRate).toBeGreaterThan(0);
expect(accuracy.hitRate).toBeLessThanOrEqual(1);
});
it('should return hit rate 0 when no predictions match', () => {
const loader = new ProgressiveContextLoader({
strategy: 'predictive',
maxInitialFiles: 2,
predictionThreshold: 0.7,
trackFileRequests: true,
});
// Predict auth files
loader.predictFilesForTask('Fix authentication', SAMPLE_FILES);
// But agent only requests payment files
loader.recordFileRequest({
filePath: 'src/payment/payment-service.ts',
requestedAt: Date.now(),
wasPreloaded: false,
agentId: 'agent-1',
taskDescription: 'Fix payment',
});
loader.recordFileRequest({
filePath: 'src/payment/stripe-adapter.ts',
requestedAt: Date.now(),
wasPreloaded: false,
agentId: 'agent-1',
taskDescription: 'Fix payment',
});
const accuracy = loader.getPredictionAccuracy();
// The preloaded set has auth files; requests are for payment files → no overlap
expect(accuracy.hitRate).toBe(0);
});
});
describe('getFileRequestHistory', () => {
it('should track multiple agents separately', () => {
const loader = new ProgressiveContextLoader({
strategy: 'predictive',
maxInitialFiles: 5,
predictionThreshold: 0.7,
trackFileRequests: true,
});
loader.recordFileRequest({
filePath: 'src/auth/auth-service.ts',
requestedAt: Date.now(),
wasPreloaded: true,
agentId: 'agent-1',
taskDescription: 'Fix auth',
});
loader.recordFileRequest({
filePath: 'src/payment/payment-service.ts',
requestedAt: Date.now(),
wasPreloaded: false,
agentId: 'agent-2',
taskDescription: 'Fix payment',
});
loader.recordFileRequest({
filePath: 'src/auth/auth-middleware.ts',
requestedAt: Date.now(),
wasPreloaded: true,
agentId: 'agent-1',
taskDescription: 'Fix auth',
});
// Filter by agent-1
const agent1History = loader.getFileRequestHistory('agent-1');
expect(agent1History).toHaveLength(2);
expect(agent1History.every(r => r.agentId === 'agent-1')).toBe(true);
// Filter by agent-2
const agent2History = loader.getFileRequestHistory('agent-2');
expect(agent2History).toHaveLength(1);
expect(agent2History[0].agentId).toBe('agent-2');
// No filter → all records
const allHistory = loader.getFileRequestHistory();
expect(allHistory).toHaveLength(3);
});
});
describe('defaults', () => {
it('should use default config when constructed without arguments', () => {
const loader = new ProgressiveContextLoader();
// Default strategy is 'full', so even when enabled, full returns all files
const result = loader.predictFilesForTask('Fix auth', SAMPLE_FILES);
expect(result).toHaveLength(SAMPLE_FILES.length);
});
});
});