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

9.3 KiB

ADR-059: Ghost Intent Coverage Analysis

Field Value
Decision ID ADR-059
Status Implemented
Date 2026-02-06
Author Architecture Team
Review Cadence 6 months
Analysis Method Six Thinking Hats (AISP Integration Review)
Conceptual Inspiration AISP 5.1 Ghost Intent Search

WH(Y) Decision Statement

In the context of the coverage-analysis bounded context (ADR-003) which currently detects gaps by scanning what IS covered and finding what falls below thresholds,

facing the fundamental limitation that threshold-based gap detection only finds known unknowns (low coverage files) but cannot identify unknown unknowns (behaviors that SHOULD have tests but don't even have code paths),

we decided for implementing a Ghost Intent Coverage primitive that computes PhantomSurface = IdealTestSurface - ActualTestSurface using HNSW vector operations, inverting the coverage paradigm from "find what's poorly covered" to "find what's missing entirely",

and neglected (a) importing AISP as a dependency (rejected: notation overhead, token cost), (b) simple heuristic-based gap detection (rejected: only finds known coverage holes), (c) LLM-only approach without vector math (rejected: non-deterministic, expensive per invocation),

to achieve discovery of phantom test surfaces — missing error handlers, absent boundary validations, unprotected state transitions, and missing integration contracts that no existing coverage metric detects,

accepting that the "ideal test surface" is a learned approximation from ReasoningBank patterns (not ground truth), requiring sufficient pattern history to be accurate, and that the ghost vector computation adds ~50ms overhead to gap detection.


Context

Current coverage analysis (ADR-003) uses HNSW indexing for O(log n) gap detection, but it operates within a "scan what exists" paradigm. When detectGaps() runs, it finds files with low line/branch/function coverage. This is valuable but fundamentally limited: it can only find gaps in code that EXISTS. It cannot discover that an entire error handling path, integration boundary, or state machine transition is absent from the codebase.

AISP 5.1's Ghost Intent Search (psi_g = psi_* - psi_have) introduced a mathematically principled approach: compute the vector difference between a target state and current state to find the "ghost" — what's needed but not present. This concept maps directly to QE coverage analysis: if we can represent the "ideal test surface" for a codebase as a vector space, we can compute the phantom surface (what SHOULD be tested but isn't) via vector subtraction in HNSW space.

This ADR does NOT import AISP notation or packages. It implements the ghost intent concept natively in TypeScript, integrated with existing HNSW infrastructure (ADR-003, ADR-038) and ReasoningBank pattern learning (ADR-021).


Options Considered

Option 1: Native Ghost Intent via HNSW Vector Subtraction (Selected)

Implement GhostCoverageAnalyzer as a new service in the coverage-analysis domain. It uses ReasoningBank's learned patterns to construct an "ideal test surface" embedding, then computes the ghost vector against actual coverage embeddings in HNSW space. Returns PhantomGap[] — test gaps for code that doesn't exist yet.

Pros:

  • Discovers unknown unknowns (missing error handlers, absent integrations)
  • Builds on existing HNSW + ReasoningBank infrastructure
  • Improves over time as ReasoningBank accumulates more patterns
  • O(log n) complexity using existing HNSW index
  • Zero external dependencies

Cons:

  • Requires sufficient pattern history (~100+ patterns) for accurate ideal surface
  • Ghost vectors are approximations, not ground truth
  • Cold-start problem: new projects with no history produce noisy results

Option 2: Import AISP Library Directly (Rejected)

Use aisp-validator and aisp-converter npm packages to implement ghost intent search with AISP's full symbolic notation.

Why rejected: 8,817 tokens per compilation, 512-symbol vocabulary overhead, external dependency risk. The concept is valuable; the notation is not needed for QE.

Option 3: LLM-Based Gap Inference (Rejected)

Use an LLM to analyze code and suggest missing test scenarios without vector math.

Why rejected: Non-deterministic results, high per-invocation cost (Tier 3 routing required), no mathematical convergence guarantee. Better as a complement to ghost intent, not a replacement.


Technical Design

Core Interfaces

// New service in coverage-analysis domain
interface GhostCoverageAnalyzer {
  /** Compute phantom test surface — what SHOULD exist but DOESN'T */
  computePhantomSurface(request: PhantomSurfaceRequest): Promise<Result<PhantomSurface, Error>>;

  /** Get specific phantom gaps ranked by risk */
  detectPhantomGaps(request: PhantomGapRequest): Promise<Result<PhantomGap[], Error>>;

  /** Update ideal surface model from new patterns */
  updateIdealSurface(patterns: QEPattern[]): Promise<void>;
}

interface PhantomSurfaceRequest {
  /** Current coverage data */
  actualCoverage: CoverageData;
  /** Project context for ideal surface lookup */
  projectContext: ProjectContext;
  /** Minimum confidence threshold for phantom gaps */
  minConfidence?: number; // default 0.6
}

interface PhantomGap {
  /** Category of missing test surface */
  category: 'missing-error-handler' | 'absent-boundary-validation' |
            'unprotected-state-transition' | 'missing-integration-contract' |
            'absent-edge-case' | 'missing-security-check';
  /** Description of what should exist */
  description: string;
  /** File/module most likely to need this */
  suggestedLocation: string;
  /** Confidence that this gap is real (0-1) */
  confidence: number;
  /** Ghost vector distance from ideal surface */
  ghostDistance: number;
  /** Risk score if this phantom gap is exploited */
  riskScore: number;
}

interface PhantomSurface {
  /** Total phantom gaps discovered */
  totalGaps: number;
  /** Gaps by category */
  gapsByCategory: Map<string, PhantomGap[]>;
  /** Overall phantom surface area (0-1, lower is better) */
  phantomRatio: number;
  /** Ideal surface confidence (how reliable is the model) */
  idealSurfaceConfidence: number;
}

Ghost Vector Computation

// Core algorithm (conceptual, inspired by AISP psi_g = psi_* - psi_have)
async computeGhostVector(
  actualEmbedding: Float32Array,
  idealEmbedding: Float32Array
): Promise<Float32Array> {
  const ghost = new Float32Array(actualEmbedding.length);
  for (let i = 0; i < ghost.length; i++) {
    ghost[i] = idealEmbedding[i] - actualEmbedding[i];
  }
  // Normalize ghost vector
  const norm = Math.sqrt(ghost.reduce((sum, v) => sum + v * v, 0));
  if (norm > 0) {
    for (let i = 0; i < ghost.length; i++) ghost[i] /= norm;
  }
  return ghost;
}

Integration Points

Component Integration
hnsw-index.ts (ADR-003) Store ideal surface embeddings, query ghost vectors
coverage-embedder.ts (ADR-003) Embed actual coverage as vectors
real-qe-reasoning-bank.ts (ADR-021) Source learned patterns for ideal surface construction
sublinear-analyzer.ts (ADR-003) New findPhantomGaps() method
gap-detector.ts (existing) Extended with phantom gap category

Dependencies

Relationship ADR ID Title Notes
Depends On ADR-003 Sublinear Coverage Analysis HNSW index and coverage embedder
Depends On ADR-021 ReasoningBank Pattern Learning Ideal surface model from patterns
Depends On ADR-038 Memory System Unification AgentDB + HNSW backend
Relates To ADR-005 AI-First Test Generation Ghost gaps feed into test generation
Relates To ADR-030 Coherence-Gated Quality Gates Phantom ratio as quality gate metric
Relates To ADR-052 Coherence-Gated QE Lambda-coherence on phantom surface
Part Of MADR-001 V3 Implementation Initiative Phase 13 enhancement

Success Metrics

  • GhostCoverageAnalyzer service implemented in coverage-analysis domain
  • >80% of phantom gaps validated as genuine missing test surfaces (on 3+ reference projects)
  • <100ms ghost vector computation on codebases up to 10,000 files
  • Integration with test-generation domain: phantom gaps auto-generate test stubs
  • PhantomRatio metric added to quality gate evaluation
  • 40+ unit tests covering ghost vector math, ideal surface construction, cold-start behavior

References

Ref ID Title Type Location
EXT-001 AISP 5.1 Ghost Intent Search Conceptual Inspiration aisp-open-core
INT-001 Coverage Analysis Domain Existing Code v3/src/domains/coverage-analysis/
INT-002 ReasoningBank Existing Code v3/src/learning/real-qe-reasoning-bank.ts

Status History

Status Date Notes
Proposed 2026-02-06 Created from Six Thinking Hats AISP analysis. Concept from AISP ghost intent; native implementation.