* fix(security): ADR-165 Phase 1 — close all critical CVEs, refresh registry, add CI gate Closes ADR-165 Phase 1. Both workspaces pass `npm audit --audit-level=critical`. ## Before (2026-06-29) | Workspace | Critical | High | Moderate | Total | |-----------|----------|------|----------|-------| | Root | **1** | 6 | 31 | 38 | | v3 | **4** | 33 | 57 | 97 | ## After | Workspace | Critical | High | Moderate | Total | |-----------|----------|------|----------|-------| | Root | **0** | 0 | 31 | 31 | | v3 | **0** | 27 | 58 | 88 | All 5 critical advisories closed (vitest GHSA-5xrq, handlebars prototype-pollution, protobufjs constructor-pollution, plus 2 more in v3). 12 of 39 high advisories closed via overrides; the remaining 27 v3 highs are deeper transitive chains that would require breaking-change major bumps — flagged for ADR-165 Phase 2. ## Changes ### Root workspace overrides (package.json) - `vitest`: `^1.0.0` → `^3.2.6` (closes critical GHSA-5xrq CVSS 9.8) - `hono`: `>=4.11.4` → `>=4.12.25` (closes 6 hono advisories) - `undici`: `>=7.18.0` → `>=8.5.0` (closes 7 undici advisories — bumps the stale pin that ADR-165 flagged as still-in-vulnerable-range) - `vite`: `>=6.4.6` → `>=8.0.16` (closes 2 vite advisories) - NEW `@grpc/grpc-js`: `>=1.14.4` - NEW `form-data`: `>=4.0.6` - NEW `http-proxy-middleware`: `>=3.0.7` - `@hono/node-server`: `>=1.19.10` → `>=1.19.14` ### v3 workspace overrides (v3/package.json + pnpm.overrides) - `vitest`: `^4.0.16` → `^4.1.0` (and `@vitest/coverage-v8` matched) - Top-level + pnpm overrides: `handlebars: >=4.7.9`, `protobufjs: >=8.6.0` - 27 sub-package `package.json` updated to `vitest ^4.1.0` ### CVE registry refresh (v3/@claude-flow/security/src/CVE-REMEDIATION.ts) Rewritten from 5 stale Jan-2026 entries to 16 total: 15 fixed, 1 open (ADR165-OPEN-01 — PII pipeline wiring per ADR-164 §6.1 not yet on dispatch-layer). `SECURITY_SUMMARY` is now computed dynamically from the registry; `validateRemediation()` correctly returns `allFixed: false` with 1 issue. ADR-165 §5 flagged this as THE Phase 2 priority — now closed. ### New CI gate `.github/workflows/cve-audit.yml`: - `audit-root` — `npm audit --audit-level=critical` in root, blocking - `audit-v3` — same in v3, blocking - `audit-high-report` — warn-only summary on high-severity drift - Triggers: PR, push to main, daily cron ### ADR-165 §9 evidence ledger addendum Captures AFTER-remediation `npm audit --json` metadata for both workspaces. The diff between BEFORE (already in §9) and AFTER makes Phase 1 verifiable. Also CORRECTED one prior surprise in §9: the `validate-input.ts` in `mcp-tools/` is NOT a 9-line shim. It's 269 lines of real implementation. (That was an inaccurate findings note from the initial audit.) ### §7.3 research items resolved - `protobufjs` v3 chain confirmed gone after override pins - `handlebars` v3 chain confirmed not user-reachable on the workflow path (toolchain-only; override sufficient) - `validate-input.ts` confirmed real implementation, not a shim (registry entry corrected) - CORS surface check: no `cors()` / `app.use(cors` call sites — the hono CORS-wildcard advisory is not exploitable on the current server - ADR-164 §6.1 PII pipeline NOT wired in current agentbbs dispatch — recorded as ADR165-OPEN-01 (Phase 3 work) ## Gates (all PASS) - `npm audit --audit-level=critical` root: exit 0 (was non-zero) - `npm audit --audit-level=critical` v3: exit 0 (was non-zero) - vitest suites: 105/109 pass (4 skip-conditional — same as before) - ADR-112 audit: 352/352 tools with guidance - business-pods smoke: 11/11 PASS - agentbbs smoke: 8/8 PASS - agenticow smoke: 8/8 PASS - cli build: clean (tsc) ## Phase 2+ deferred The 27 v3 high-severity advisories that remain are transitive chains with no patched-in-range version. ADR-165 §6 Phase 2 picks these up after the `cve-watch.yml` automation in §6 lands (NEW PR — not in scope here). Co-Authored-By: RuFlo <ruv@ruv.net> Claude-Session: https://claude.ai/code/session_01WbBa4nccx5aGhXphoHxcni * chore(lock): regen v3/pnpm-lock.yaml after override updates (PR #2508 CI fix) PR #2508 added handlebars + protobufjs to v3 overrides + bumped vitest pin, but v3/pnpm-lock.yaml wasn't regenerated. CI surfaced ERR_PNPM_LOCKFILE_CONFIG_MISMATCH on every install step. Same pattern as the previous lockfile-drift fixes on PR #2500 and #2503. * fix(ci): cve-audit.yml jq-only + regen witness manifests for #1609 marker drift Two PR #2508 CI failures fixed: 1. Static-regression-guard tripped on cve-audit.yml line 52: the static YAML strict-parser sees `if high > 0:` inside the `run: |` block as a YAML block-mapping key indicator. Refactored all 3 inline-python blocks to use jq (preinstalled on ubuntu-latest) — no embedded `if x > 0:` lines, so the YAML guard passes. 2. Witness marker drift smoke flagged fix-marker #1609 — the Phase 1 vitest bump (4.0.16 → 4.1.0) drifted the cited marker string in v3/@claude-flow/aidefence/package.json. Updated `marker` field in all 3 platform manifests + `desc` to reference ADR-165 Phase 1, then re-signed via plugins/ruflo-core/scripts/witness/regen.mjs. Co-Authored-By: RuFlo <ruv@ruv.net>
@claude-flow/plugin-test-intelligence
A comprehensive test intelligence plugin combining reinforcement learning for optimal test selection with graph neural networks for code-to-test mapping. The plugin enables predictive test selection (run only tests likely to fail), flaky test detection, mutation testing optimization, and test coverage gap identification while integrating seamlessly with popular testing frameworks.
Features
- Predictive Test Selection: Select tests most likely to fail based on code changes using RL
- Flaky Test Detection: Identify and analyze flaky tests with root cause classification
- Coverage Gap Analysis: Identify test coverage gaps using code-test graph analysis
- Mutation Testing Optimization: Optimize mutation testing for efficiency within time budgets
- Test Generation Suggestions: Suggest test cases for uncovered code paths
Installation
npm
npm install @claude-flow/plugin-test-intelligence
CLI
npx claude-flow plugins install --name @claude-flow/plugin-test-intelligence
Quick Start
import { TestIntelligencePlugin } from '@claude-flow/plugin-test-intelligence';
// Initialize the plugin
const testIntel = new TestIntelligencePlugin({
historyPath: './data/test-history',
framework: 'vitest',
projectPath: './'
});
// Predictive test selection
const selectedTests = await testIntel.selectPredictive({
changes: {
files: ['src/auth/login.ts', 'src/utils/validation.ts'],
gitRef: 'HEAD'
},
strategy: 'balanced',
budget: { maxTests: 50, confidence: 0.95 }
});
// Detect flaky tests
const flakyTests = await testIntel.flakyDetect({
scope: { historyDepth: 100 },
analysis: ['intermittent_failures', 'timing_sensitive'],
threshold: 0.1
});
// Identify coverage gaps
const gaps = await testIntel.coverageGaps({
targetPaths: ['src/'],
coverageType: 'semantic',
prioritization: 'risk'
});
MCP Tools
1. test/select-predictive
Select tests most likely to fail based on code changes.
const result = await mcp.invoke('test/select-predictive', {
changes: {
files: ['src/services/UserService.ts', 'src/models/User.ts'],
gitDiff: '...diff content...',
gitRef: 'feature-branch'
},
strategy: 'fast_feedback',
budget: {
maxTests: 30,
maxDuration: 300, // 5 minutes
confidence: 0.95
}
});
// Returns:
// {
// selectedTests: [
// { name: 'UserService.createUser', file: 'tests/UserService.test.ts', priority: 1, failureProbability: 0.82 },
// { name: 'User.validate', file: 'tests/User.test.ts', priority: 2, failureProbability: 0.75 },
// ...
// ],
// estimatedDuration: 45,
// coverageEstimate: 0.89,
// skippedTests: 120,
// timeSaved: '4m 30s'
// }
2. test/flaky-detect
Identify and analyze flaky tests.
const result = await mcp.invoke('test/flaky-detect', {
scope: {
testSuite: 'integration',
historyDepth: 200
},
analysis: [
'intermittent_failures',
'timing_sensitive',
'order_dependent',
'resource_contention'
],
threshold: 0.1
});
// Returns:
// {
// flakyTests: [
// {
// name: 'API.rateLimit.test',
// flakinessScore: 0.23,
// failureRate: 0.15,
// rootCause: 'timing_sensitive',
// details: 'Relies on 100ms timeout that occasionally exceeds',
// recommendation: 'Use fake timers or increase timeout margin',
// lastFailed: '2024-01-14T10:30:00Z'
// },
// {
// name: 'Database.concurrent.test',
// flakinessScore: 0.18,
// failureRate: 0.08,
// rootCause: 'resource_contention',
// details: 'Competes for database connections with other tests',
// recommendation: 'Isolate test database or use connection pooling'
// }
// ],
// summary: {
// totalFlakyTests: 8,
// quarantineSuggested: 3,
// estimatedCITimeSaved: '12 minutes per run'
// }
// }
3. test/coverage-gaps
Identify test coverage gaps.
const result = await mcp.invoke('test/coverage-gaps', {
targetPaths: ['src/services/', 'src/controllers/'],
coverageType: 'semantic',
prioritization: 'risk',
minCoverage: 80
});
// Returns:
// {
// gaps: [
// {
// file: 'src/services/PaymentService.ts',
// function: 'processRefund',
// currentCoverage: 45,
// riskScore: 0.85,
// complexity: 'high',
// recommendation: 'Add tests for error handling paths',
// suggestedTestCases: [
// 'should handle partial refund',
// 'should reject refund exceeding original amount',
// 'should handle payment provider timeout'
// ]
// },
// ...
// ],
// summary: {
// averageCoverage: 72,
// highRiskUncovered: 5,
// estimatedTestsNeeded: 15
// }
// }
4. test/mutation-optimize
Optimize mutation testing for efficiency.
const result = await mcp.invoke('test/mutation-optimize', {
targetPath: 'src/utils/validation.ts',
budget: 100, // Max mutations to run
strategy: 'ml_guided',
mutationTypes: ['arithmetic', 'logical', 'boundary', 'null_check']
});
// Returns:
// {
// selectedMutations: [
// {
// location: { line: 45, column: 12 },
// type: 'boundary',
// original: 'age >= 18',
// mutated: 'age > 18',
// killedBy: ['validateAge.boundary.test'],
// priority: 1
// },
// ...
// ],
// mutationScore: 0.82,
// survivingMutants: 18,
// testGaps: [
// { mutation: 'null_check at line 67', reason: 'No test covers null input' }
// ],
// timeSpent: '45s',
// timeVsFullRun: '12x faster'
// }
5. test/generate-suggest
Suggest test cases for uncovered code.
const result = await mcp.invoke('test/generate-suggest', {
targetFunction: 'src/auth/validateToken.ts:validateJWT',
testStyle: 'unit',
framework: 'vitest',
edgeCases: true,
mockStrategy: 'minimal'
});
// Returns:
// {
// suggestedTests: [
// {
// name: 'should validate a valid JWT token',
// type: 'happy_path',
// code: `
// test('should validate a valid JWT token', () => {
// const token = createTestToken({ userId: '123', exp: Date.now() + 3600000 });
// const result = validateJWT(token);
// expect(result.valid).toBe(true);
// expect(result.payload.userId).toBe('123');
// });`
// },
// {
// name: 'should reject expired token',
// type: 'edge_case',
// code: `
// test('should reject expired token', () => {
// const token = createTestToken({ userId: '123', exp: Date.now() - 1000 });
// const result = validateJWT(token);
// expect(result.valid).toBe(false);
// expect(result.error).toBe('TOKEN_EXPIRED');
// });`
// },
// ...
// ],
// requiredMocks: ['jsonwebtoken.verify'],
// setupCode: '...'
// }
Configuration Options
interface TestIntelligenceConfig {
// Data paths
historyPath: string; // Path to test history storage
projectPath: string; // Project root path
// Framework
framework: 'jest' | 'vitest' | 'pytest' | 'junit' | 'mocha';
testPattern: string; // Glob pattern for test files
// Performance
maxMemoryMB: number; // WASM memory limit (default: 512)
maxCpuTimeSeconds: number; // Operation timeout (default: 60)
// Learning
learningEnabled: boolean; // Enable continuous learning (default: true)
minHistoryDepth: number; // Minimum runs before predictions (default: 50)
}
Framework Support
| Framework | Language | Support Level |
|---|---|---|
| Jest | JavaScript/TypeScript | Full |
| Vitest | JavaScript/TypeScript | Full |
| pytest | Python | Full |
| JUnit | Java | Partial |
| Mocha | JavaScript | Partial |
| RSpec | Ruby | Basic |
Security Considerations
Test Execution Safety
This plugin analyzes tests but does NOT execute them directly:
- Returns test selection lists only
- User runs tests via their own CI/CD pipeline
- No arbitrary code execution in WASM
WASM Security Constraints
| Constraint | Value | Rationale |
|---|---|---|
| Memory Limit | 512MB max | Sufficient for test analysis |
| CPU Time Limit | 60 seconds | Prevent runaway analysis |
| No Test Execution | Analysis only | Prevent arbitrary code execution |
| No Network Access | Enforced | Prevent data exfiltration |
| Sandboxed History | Per-project | Prevent cross-project leakage |
Input Validation
All inputs are validated using Zod schemas:
// All inputs validated:
- Git diffs: Maximum 1MB
- File lists: Maximum 1000 files
- History depth: 10-10000 runs
- Max duration: 1-86400 seconds (24 hours)
- Confidence level: 0.5-1.0
- Test names: Alphanumeric with standard punctuation, max 500 characters
- Framework: Enum validated against supported frameworks
Rate Limiting
const rateLimits = {
'test/select-predictive': { requestsPerMinute: 60, maxConcurrent: 5 },
'test/flaky-detect': { requestsPerMinute: 10, maxConcurrent: 2 },
'test/coverage-gaps': { requestsPerMinute: 30, maxConcurrent: 3 },
'test/mutation-optimize': { requestsPerMinute: 5, maxConcurrent: 1 },
'test/generate-suggest': { requestsPerMinute: 30, maxConcurrent: 3 }
};
Performance
| Metric | Target |
|---|---|
| Test selection | <1s for 10K tests |
| Flaky detection | <5s for 1000 test runs |
| Coverage gap analysis | <10s for 100K LOC |
| Mutation optimization | 80% mutation score in 20% time |
| CI time reduction | 60-80% |
Learning Pipeline
The plugin continuously learns from test execution history:
Execution History --> SONA Learning --> RL Policy
| | |
v v v
[fail rates] [pattern bank] [selection model]
[timings] [failure modes] [prioritization]
[coverage] [correlations] [budget allocation]
Dependencies
micro-hnsw-wasm: Fast code-to-test similarity matchingruvector-learning-wasm: RL-based test selection and prioritizationruvector-gnn-wasm: Code-test dependency graphs for impact analysisruvector-sparse-inference-wasm: Efficient flaky test pattern detectionsona: Continuous learning from test execution historyistanbul-lib-coverage: Coverage report parsing
Related Plugins
| Plugin | Description | Use Case |
|---|---|---|
| @claude-flow/plugin-code-intelligence | Code analysis | Impact analysis for test prioritization |
| @claude-flow/plugin-perf-optimizer | Performance optimization | Test performance profiling |
| @claude-flow/plugin-financial-risk | Risk analysis | Test risk scoring for critical paths |
License
MIT License
Copyright (c) 2026 Claude Flow
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.