Files
proffesor-for-testing__agen…/tests/unit/learning/meta-learning-cycle.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

396 lines
15 KiB
TypeScript

/**
* ADR-062 Tier 3 Action 6 — Meta-Learning Cycle Tests
*
* Validates:
* - UnifiedMetricsSnapshot collection
* - MetaLearningEngine trend detection (token-waste, quality-plateau,
* learning-stall, performance-regression)
* - Feature-flag gating (AQE_META_LEARNING_ENABLED)
* - shouldAutoApply confidence threshold
* - Edge cases (empty snapshots, insufficient data)
*/
import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest';
import type { UnifiedMetricsSnapshot } from '../../../src/learning/metrics-tracker.js';
import {
MetaLearningEngine,
DEFAULT_META_LEARNING_CONFIG,
type MetaLearningConfig,
type MetaInsight,
} from '../../../src/learning/aqe-learning-engine.js';
// ============================================================================
// Helpers
// ============================================================================
/** Build a snapshot with sensible defaults; overrides merged shallowly. */
function makeSnapshot(
overrides: Partial<{
timestamp: number;
tokenMetrics: Partial<UnifiedMetricsSnapshot['tokenMetrics']>;
qualityMetrics: Partial<UnifiedMetricsSnapshot['qualityMetrics']>;
learningMetrics: Partial<UnifiedMetricsSnapshot['learningMetrics']>;
performanceMetrics: Partial<UnifiedMetricsSnapshot['performanceMetrics']>;
}> = {},
): UnifiedMetricsSnapshot {
return {
timestamp: overrides.timestamp ?? Date.now(),
tokenMetrics: {
totalTokens: 1000,
costUsd: 0.05,
savingsUsd: 0.01,
cacheHitRate: 0.3,
...overrides.tokenMetrics,
},
qualityMetrics: {
gatePassRate: 0.85,
averageScore: 0.8,
ratchetLevel: 1,
...overrides.qualityMetrics,
},
learningMetrics: {
patternCount: 50,
averageConfidence: 0.7,
quarantinedCount: 2,
transferSuccessRate: 0.6,
...overrides.learningMetrics,
},
performanceMetrics: {
avgLatencyMs: 100,
p95LatencyMs: 250,
errorRate: 0.02,
...overrides.performanceMetrics,
},
};
}
/** Generate N healthy (stable) snapshots spaced 5 min apart. */
function healthySnapshots(n: number): UnifiedMetricsSnapshot[] {
const base = Date.now() - n * 300_000;
return Array.from({ length: n }, (_, i) =>
makeSnapshot({ timestamp: base + i * 300_000 }),
);
}
// ============================================================================
// Tests
// ============================================================================
describe('MetaLearningEngine (ADR-062 Tier 3 Action 6)', () => {
const enabledConfig: Partial<MetaLearningConfig> = { enabled: true };
let originalEnv: string | undefined;
beforeEach(() => {
originalEnv = process.env.AQE_META_LEARNING_ENABLED;
process.env.AQE_META_LEARNING_ENABLED = 'true';
});
afterEach(() => {
if (originalEnv === undefined) {
delete process.env.AQE_META_LEARNING_ENABLED;
} else {
process.env.AQE_META_LEARNING_ENABLED = originalEnv;
}
});
// --------------------------------------------------------------------------
// 1. collectUnifiedSnapshot returns valid structure
// --------------------------------------------------------------------------
it('collectUnifiedSnapshot returns valid structure with all fields', () => {
// This tests the interface shape — we construct one with makeSnapshot and
// verify every top-level and nested key is present.
const snap = makeSnapshot();
expect(snap.timestamp).toBeTypeOf('number');
expect(snap.tokenMetrics).toBeDefined();
expect(snap.tokenMetrics.totalTokens).toBeTypeOf('number');
expect(snap.tokenMetrics.costUsd).toBeTypeOf('number');
expect(snap.tokenMetrics.savingsUsd).toBeTypeOf('number');
expect(snap.tokenMetrics.cacheHitRate).toBeTypeOf('number');
expect(snap.qualityMetrics).toBeDefined();
expect(snap.qualityMetrics.gatePassRate).toBeTypeOf('number');
expect(snap.qualityMetrics.averageScore).toBeTypeOf('number');
expect(snap.qualityMetrics.ratchetLevel).toBeTypeOf('number');
expect(snap.learningMetrics).toBeDefined();
expect(snap.learningMetrics.patternCount).toBeTypeOf('number');
expect(snap.learningMetrics.averageConfidence).toBeTypeOf('number');
expect(snap.learningMetrics.quarantinedCount).toBeTypeOf('number');
expect(snap.learningMetrics.transferSuccessRate).toBeTypeOf('number');
expect(snap.performanceMetrics).toBeDefined();
expect(snap.performanceMetrics.avgLatencyMs).toBeTypeOf('number');
expect(snap.performanceMetrics.p95LatencyMs).toBeTypeOf('number');
expect(snap.performanceMetrics.errorRate).toBeTypeOf('number');
});
// --------------------------------------------------------------------------
// 2. Detects token-waste pattern
// --------------------------------------------------------------------------
it('runMetaLearningCycle detects token-waste pattern', () => {
const engine = new MetaLearningEngine(enabledConfig);
// First 3 snapshots: low cost
const first = Array.from({ length: 3 }, (_, i) =>
makeSnapshot({
timestamp: i * 300_000,
tokenMetrics: { costUsd: 0.05, savingsUsd: 0.01 },
}),
);
// Last 3 snapshots: cost jumped, savings flat
const second = Array.from({ length: 3 }, (_, i) =>
makeSnapshot({
timestamp: (i + 3) * 300_000,
tokenMetrics: { costUsd: 0.15, savingsUsd: 0.01 },
}),
);
const insights = engine.runMetaLearningCycle([...first, ...second]);
const tokenWaste = insights.filter(i => i.type === 'token-waste');
expect(tokenWaste.length).toBeGreaterThanOrEqual(1);
expect(tokenWaste[0].suggestedAction).toBeDefined();
expect(tokenWaste[0].confidence).toBeGreaterThan(0);
expect(tokenWaste[0].confidence).toBeLessThanOrEqual(1);
});
// --------------------------------------------------------------------------
// 3. Detects quality-plateau pattern
// --------------------------------------------------------------------------
it('runMetaLearningCycle detects quality-plateau pattern', () => {
const engine = new MetaLearningEngine(enabledConfig);
// All snapshots have identical gatePassRate
const snaps = Array.from({ length: 6 }, (_, i) =>
makeSnapshot({
timestamp: i * 300_000,
qualityMetrics: { gatePassRate: 0.82 },
}),
);
const insights = engine.runMetaLearningCycle(snaps);
const plateaus = insights.filter(i => i.type === 'quality-plateau');
expect(plateaus.length).toBeGreaterThanOrEqual(1);
expect(plateaus[0].description).toContain('flat');
});
// --------------------------------------------------------------------------
// 4. Detects learning-stall pattern
// --------------------------------------------------------------------------
it('runMetaLearningCycle detects learning-stall pattern', () => {
const engine = new MetaLearningEngine(enabledConfig);
const snaps = Array.from({ length: 6 }, (_, i) =>
makeSnapshot({
timestamp: i * 300_000,
learningMetrics: { patternCount: 42, averageConfidence: 0.65 },
}),
);
const insights = engine.runMetaLearningCycle(snaps);
const stalls = insights.filter(i => i.type === 'learning-stall');
expect(stalls.length).toBeGreaterThanOrEqual(1);
expect(stalls[0].suggestedAction).toContain('domain');
});
// --------------------------------------------------------------------------
// 5. Detects performance-regression pattern
// --------------------------------------------------------------------------
it('runMetaLearningCycle detects performance-regression pattern', () => {
const engine = new MetaLearningEngine(enabledConfig);
const first = Array.from({ length: 3 }, (_, i) =>
makeSnapshot({
timestamp: i * 300_000,
performanceMetrics: { p95LatencyMs: 200 },
}),
);
const second = Array.from({ length: 3 }, (_, i) =>
makeSnapshot({
timestamp: (i + 3) * 300_000,
performanceMetrics: { p95LatencyMs: 500 },
}),
);
const insights = engine.runMetaLearningCycle([...first, ...second]);
const regressions = insights.filter(i => i.type === 'performance-regression');
expect(regressions.length).toBeGreaterThanOrEqual(1);
expect(regressions[0].description).toContain('latency');
});
// --------------------------------------------------------------------------
// 6. No insights for healthy metrics
// --------------------------------------------------------------------------
it('returns no insights for healthy, improving metrics', () => {
const engine = new MetaLearningEngine(enabledConfig);
// Gradually improving across all dimensions
const snaps = Array.from({ length: 6 }, (_, i) =>
makeSnapshot({
timestamp: i * 300_000,
tokenMetrics: { costUsd: 0.05 - i * 0.005, savingsUsd: 0.01 + i * 0.005 },
qualityMetrics: { gatePassRate: 0.80 + i * 0.02 },
learningMetrics: { patternCount: 40 + i * 3, averageConfidence: 0.6 + i * 0.04 },
performanceMetrics: { p95LatencyMs: 300 - i * 20 },
}),
);
const insights = engine.runMetaLearningCycle(snaps);
expect(insights.length).toBe(0);
});
// --------------------------------------------------------------------------
// 7. minSnapshotsForAnalysis respected
// --------------------------------------------------------------------------
it('returns no insights when fewer snapshots than minSnapshotsForAnalysis', () => {
const engine = new MetaLearningEngine({ enabled: true, minSnapshotsForAnalysis: 10 });
// Only 4 snapshots with clear token-waste — should still be skipped
const snaps = Array.from({ length: 4 }, (_, i) =>
makeSnapshot({
timestamp: i * 300_000,
tokenMetrics: { costUsd: 0.05 + i * 0.1 },
}),
);
const insights = engine.runMetaLearningCycle(snaps);
expect(insights.length).toBe(0);
});
// --------------------------------------------------------------------------
// 8. shouldAutoApply respects confidence threshold
// --------------------------------------------------------------------------
it('shouldAutoApply respects confidence threshold', () => {
const engine = new MetaLearningEngine(enabledConfig);
const highConfidence: MetaInsight = {
id: 'test-1',
type: 'token-waste',
description: 'test',
confidence: 0.9,
suggestedAction: 'do something',
detectedAt: Date.now(),
};
const lowConfidence: MetaInsight = {
id: 'test-2',
type: 'token-waste',
description: 'test',
confidence: 0.5,
suggestedAction: 'do something',
detectedAt: Date.now(),
};
expect(engine.shouldAutoApply(highConfidence)).toBe(true);
expect(engine.shouldAutoApply(lowConfidence)).toBe(false);
// With custom config threshold
const strictConfig: MetaLearningConfig = {
...DEFAULT_META_LEARNING_CONFIG,
enabled: true,
autoApplyThreshold: 0.95,
};
expect(engine.shouldAutoApply(highConfidence, strictConfig)).toBe(false);
});
// --------------------------------------------------------------------------
// 9. Feature flag disabled returns empty insights
// --------------------------------------------------------------------------
it('feature flag disabled returns empty insights', () => {
delete process.env.AQE_META_LEARNING_ENABLED;
const engine = new MetaLearningEngine(enabledConfig);
// Create snapshots that would normally trigger token-waste
const first = Array.from({ length: 3 }, (_, i) =>
makeSnapshot({
timestamp: i * 300_000,
tokenMetrics: { costUsd: 0.05 },
}),
);
const second = Array.from({ length: 3 }, (_, i) =>
makeSnapshot({
timestamp: (i + 3) * 300_000,
tokenMetrics: { costUsd: 0.50 },
}),
);
const insights = engine.runMetaLearningCycle([...first, ...second]);
expect(insights.length).toBe(0);
});
// --------------------------------------------------------------------------
// 10. Multiple insights can be detected simultaneously
// --------------------------------------------------------------------------
it('detects multiple insights simultaneously', () => {
const engine = new MetaLearningEngine(enabledConfig);
// First half: low cost, low latency
const first = Array.from({ length: 3 }, (_, i) =>
makeSnapshot({
timestamp: i * 300_000,
tokenMetrics: { costUsd: 0.02, savingsUsd: 0.01 },
performanceMetrics: { p95LatencyMs: 100 },
learningMetrics: { patternCount: 50, averageConfidence: 0.7 },
qualityMetrics: { gatePassRate: 0.85 },
}),
);
// Second half: high cost, high latency, same patterns/quality
const second = Array.from({ length: 3 }, (_, i) =>
makeSnapshot({
timestamp: (i + 3) * 300_000,
tokenMetrics: { costUsd: 0.20, savingsUsd: 0.01 },
performanceMetrics: { p95LatencyMs: 500 },
learningMetrics: { patternCount: 50, averageConfidence: 0.7 },
qualityMetrics: { gatePassRate: 0.85 },
}),
);
const insights = engine.runMetaLearningCycle([...first, ...second]);
const types = new Set(insights.map(i => i.type));
expect(types.has('token-waste')).toBe(true);
expect(types.has('performance-regression')).toBe(true);
expect(insights.length).toBeGreaterThanOrEqual(2);
});
// --------------------------------------------------------------------------
// 11. Edge case: empty snapshots
// --------------------------------------------------------------------------
it('returns no insights for empty snapshots array', () => {
const engine = new MetaLearningEngine(enabledConfig);
const insights = engine.runMetaLearningCycle([]);
expect(insights.length).toBe(0);
});
// --------------------------------------------------------------------------
// 12. Snapshot timestamps are used for trend detection (ordering matters)
// --------------------------------------------------------------------------
it('uses snapshot ordering for trend detection', () => {
const engine = new MetaLearningEngine(enabledConfig);
// Ordered oldest-to-newest: cost rises over time
const rising = Array.from({ length: 6 }, (_, i) =>
makeSnapshot({
timestamp: 1000 + i * 300_000,
tokenMetrics: { costUsd: 0.02 + i * 0.04, savingsUsd: 0.01 },
}),
);
const insightsRising = engine.runMetaLearningCycle(rising);
const hasTokenWaste = insightsRising.some(i => i.type === 'token-waste');
expect(hasTokenWaste).toBe(true);
// Same snapshots reversed: cost *falls* over time — no token-waste
const falling = [...rising].reverse();
const insightsFalling = engine.runMetaLearningCycle(falling);
const hasTokenWasteFalling = insightsFalling.some(i => i.type === 'token-waste');
expect(hasTokenWasteFalling).toBe(false);
});
});