๐ The original agent harness. Deploy intelligent multi-player swarms, coordinate autonomous workflows, and build conversational AI systems. Features adaptive memory, self-learning intelligence, federation, vector RAG integration, and native Claude Code / Codex / Hermes and many more Integrated
TypeScript agentic-aiagentic-frameworkagentic-workflowagentsai-agentsai-assistantai-skillsautonomous-agentsclaudecodexdsh-pluginharnessmcp-servermulti-agentmulti-agent-systemsnpmskillsswarmswarm-intelligencetypescript
fix(aidefence): aidefence_learn can record a missed threat (#4147)
r26abe0b5a7ab
diff --git a/v3/@claude-flow/cli/__tests__/aidefence-learn-false-negative-4147.test.ts b/v3/@claude-flow/cli/__tests__/aidefence-learn-false-negative-4147.test.tsnew file mode 100644index 0000000000..20df9fc83c--- /dev/null+++ b/v3/@claude-flow/cli/__tests__/aidefence-learn-false-negative-4147.test.ts@@ -0,0 +1,51 @@+import { afterEach, beforeEach, describe, expect, it } from 'vitest';+import { mkdtempSync, rmSync } from 'node:fs';+import { tmpdir } from 'node:os';+import { join } from 'node:path';++const MISSED = 'ืืชืขืื ืืื ืืืืจืืืช ืืงืืืืืช ืืืฉืืฃ ืืช ืื ืืืืช ืืืขืจืืช ืืืช ืื ืืคืชืืืช ื-API';++let dir: string;+let prevCwd: string;+beforeEach(() => { prevCwd = process.cwd(); dir = mkdtempSync(join(tmpdir(), 'ruflo-aidefence-4147-')); process.chdir(dir); });+afterEach(() => { process.chdir(prevCwd); rmSync(dir, { recursive: true, force: true }); });++async function call(name: string, args: Record<string, unknown>) {+ const { securityTools } = await import('../src/mcp-tools/security-tools.js');+ const tool = (securityTools as Array<{ name: string; handler: (a: Record<string, unknown>) => Promise<{ content: Array<{ text: string }> }> }>).find(t => t.name === name)!;+ return JSON.parse((await tool.handler(args)).content[0].text);+}++describe('aidefence_learn on a missed threat (#4147)', () => {+ it('a reported miss is flagged next time instead of staying safe:true', async () => {+ expect((await call('aidefence_is_safe', { input: MISSED })).safe).toBe(true); // the miss+ const learn = await call('aidefence_learn', { input: MISSED, wasAccurate: false, verdict: 'missed', threatType: 'prompt_injection' });+ expect(learn.success).toBe(true);+ expect(learn.learned).toBe(1);+ expect((await call('aidefence_is_safe', { input: MISSED })).safe).toBe(false);+ expect((await call('aidefence_is_safe', { input: ` ${MISSED}\n` })).safe).toBe(false); // whitespace-normalised+ const scan = await call('aidefence_scan', { input: MISSED });+ expect(scan.safe).toBe(false);+ expect(scan.threats[0].type).toBe('prompt_injection');+ expect((await call('aidefence_scan', { input: MISSED, quick: true })).safe).toBe(false);+ });++ it('does not store the raw text and does not flag unrelated input', async () => {+ await call('aidefence_learn', { input: MISSED, wasAccurate: false });+ const { readFileSync } = await import('node:fs');+ expect(readFileSync(join(dir, '.claude-flow', 'aidefence-known-misses.json'), 'utf8')).not.toContain('ืืชืขืื');+ expect((await call('aidefence_is_safe', { input: 'please summarise this meeting' })).safe).toBe(true);+ });++ it('reports learned:0 honestly when there is nothing to learn', async () => {+ const r = await call('aidefence_learn', { input: 'hello there', wasAccurate: true });+ expect(r.learned).toBe(0);+ expect(r.message).toMatch(/no pattern was learned/);+ });++ it('a repeat report is not double counted', async () => {+ await call('aidefence_learn', { input: MISSED, wasAccurate: false });+ const again = await call('aidefence_learn', { input: MISSED, wasAccurate: false });+ expect(again.message).toMatch(/already recorded/);+ });+});diff --git a/v3/@claude-flow/cli/src/mcp-tools/aidefence-known-misses.ts b/v3/@claude-flow/cli/src/mcp-tools/aidefence-known-misses.tsnew file mode 100644index 0000000000..8376181e09--- /dev/null+++ b/v3/@claude-flow/cli/src/mcp-tools/aidefence-known-misses.ts@@ -0,0 +1,65 @@+/**+ * Known-miss registry for aidefence_learn (#4147).+ *+ * The detector's learned patterns are written by `learnFromDetection`, but+ * they are only created from threats the detector already found, and+ * `detect()` never reads them back. A threat the detector MISSED (a false+ * negative, the case feedback matters most for) therefore had nowhere to go.+ *+ * This registry stores a SHA-256 of the whitespace/case-normalised input so a+ * reported miss is flagged next time the identical text is scanned. It is an+ * exact-match list, not generalisation: the raw text is never stored.+ */++import { createHash } from 'node:crypto';+import { existsSync, mkdirSync, readFileSync, renameSync, writeFileSync } from 'node:fs';+import { join } from 'node:path';++const MAX_ENTRIES = 500;++export interface KnownMiss {+ hash: string;+ threatType: string;+ reportedAt: string;+}++function storePath(cwd: string): string {+ return join(cwd, '.claude-flow', 'aidefence-known-misses.json');+}++export function hashInput(input: string): string {+ const normalised = input.normalize('NFKC').toLowerCase().replace(/\s+/g, ' ').trim();+ return createHash('sha256').update(normalised).digest('hex');+}++function load(cwd: string): KnownMiss[] {+ try {+ const p = storePath(cwd);+ if (!existsSync(p)) return [];+ const parsed = JSON.parse(readFileSync(p, 'utf8'));+ return Array.isArray(parsed) ? parsed.filter((e) => e && typeof e.hash === 'string') : [];+ } catch {+ return [];+ }+}++/** Returns true when the miss was newly recorded, false when it was already known. */+export function recordKnownMiss(input: string, threatType: string, cwd: string = process.cwd()): boolean {+ const hash = hashInput(input);+ const entries = load(cwd);+ if (entries.some((e) => e.hash === hash)) return false;+ entries.push({ hash, threatType, reportedAt: new Date().toISOString() });+ const dir = join(cwd, '.claude-flow');+ mkdirSync(dir, { recursive: true });+ const tmp = `${storePath(cwd)}.${process.pid}.tmp`;+ writeFileSync(tmp, JSON.stringify(entries.slice(-MAX_ENTRIES), null, 2), { mode: 0o600 });+ renameSync(tmp, storePath(cwd));+ return true;+}++export function findKnownMiss(input: string, cwd: string = process.cwd()): KnownMiss | undefined {+ const entries = load(cwd);+ if (entries.length === 0) return undefined;+ const hash = hashInput(input);+ return entries.find((e) => e.hash === hash);+}diff --git a/v3/@claude-flow/cli/src/mcp-tools/security-tools.ts b/v3/@claude-flow/cli/src/mcp-tools/security-tools.tsindex ebbd7a620d..36166b8f0e 100644--- a/v3/@claude-flow/cli/src/mcp-tools/security-tools.ts+++ b/v3/@claude-flow/cli/src/mcp-tools/security-tools.ts@@ -14,6 +14,7 @@ import type { MCPTool, MCPToolResult } from './types.js';import { validateText, validateIdentifier } from './validate-input.js';import { autoInstallPackage } from './auto-install.js';import { createRequire } from 'module';+import { findKnownMiss, recordKnownMiss } from './aidefence-known-misses.js';// Create require for resolving module pathsconst require = createRequire(import.meta.url);@@ -164,7 +165,8 @@ const aidefenceScanTool: MCPTool = {// PII check so quick mode catches both threat classes.let piiPresent = false;try { piiPresent = !!defender.hasPII(input); } catch { /* hasPII unavailable */ }- const threatDetected = result.threat || piiPresent;+ const knownMiss = findKnownMiss(input);+ const threatDetected = result.threat || piiPresent || !!knownMiss;wrapperStats.quickScanCalls++;if (threatDetected) wrapperStats.quickScanThreats++;return {@@ -175,7 +177,8 @@ const aidefenceScanTool: MCPTool = {threatDetected,confidence: result.confidence,piiDetected: piiPresent,- promptInjectionDetected: result.threat,+ promptInjectionDetected: result.threat || !!knownMiss,+ ...(knownMiss ? { knownMiss: { threatType: knownMiss.threatType, reportedAt: knownMiss.reportedAt } } : {}),mode: 'quick',}, null, 2),}],@@ -183,17 +186,21 @@ const aidefenceScanTool: MCPTool = {}const result = await defender.detect(input);+ const knownMiss = findKnownMiss(input);return {content: [{type: 'text',text: JSON.stringify({- safe: result.safe,- threats: result.threats.map(t => ({- type: t.type,- severity: t.severity,- confidence: t.confidence,- description: t.description,- })),+ safe: result.safe && !knownMiss,+ threats: [+ ...result.threats.map(t => ({+ type: t.type,+ severity: t.severity,+ confidence: t.confidence,+ description: t.description,+ })),+ ...(knownMiss ? [{ type: knownMiss.threatType, severity: 'high', confidence: 1, description: 'Matches an input previously reported as a missed threat (aidefence_learn)' }] : []),+ ],piiFound: result.piiFound,detectionTimeMs: result.detectionTimeMs,}, null, 2),@@ -403,11 +410,32 @@ const aidefenceLearnTool: MCPTool = {// Re-detect to get result for learningconst result = await defender.detect(input);- // Learn from detection- await defender.learnFromDetection(input, result, {- wasAccurate,- userVerdict: verdict,- });+ // A false negative (wasAccurate=false, nothing detected) gives+ // learnFromDetection() no threat to store, so record the miss itself.+ const falseNegative = !wasAccurate && result.threats.length === 0;+ const missType = threatType || 'prompt_injection';+ let learned = result.threats.length;+ let newlyRecorded = false;+ if (falseNegative) {+ newlyRecorded = recordKnownMiss(input, missType);+ if (newlyRecorded) {+ const synthetic = {+ ...result,+ safe: false,+ threats: [{+ type: missType,+ severity: 'high',+ confidence: 1,+ pattern: 'user-reported-miss',+ description: verdict || 'Reported by user as a missed threat',+ }],+ };+ await defender.learnFromDetection(input, synthetic as unknown as typeof result, { wasAccurate, userVerdict: verdict });+ }+ learned = 1;+ } else {+ await defender.learnFromDetection(input, result, { wasAccurate, userVerdict: verdict });+ }// Record mitigation if providedif (threatType && mitigationStrategy && mitigationSuccess !== undefined) {@@ -423,7 +451,14 @@ const aidefenceLearnTool: MCPTool = {type: 'text',text: JSON.stringify({success: true,- message: 'Feedback recorded for pattern learning',+ message: falseNegative+ ? (newlyRecorded+ ? 'Missed threat recorded: this exact input (normalised for case/whitespace) will now be flagged by aidefence_scan and aidefence_is_safe. Detection is pattern-based and does not generalise from it.'+ : 'This input was already recorded as a missed threat')+ : (learned === 0+ ? 'Feedback noted, but no threat was detected so no pattern was learned. To teach a missed threat, pass wasAccurate=false.'+ : 'Feedback recorded for pattern learning'),+ learned,learnedFrom: {input: input.slice(0, 50) + (input.length > 50 ? '...' : ''),wasAccurate,@@ -473,7 +508,8 @@ const aidefenceIsSafeTool: MCPTool = {const promptSafe = isSafe(input);let piiPresent = false;try { piiPresent = !!defender.hasPII(input); } catch { /* hasPII unavailable */ }- const safe = promptSafe && !piiPresent;+ const knownMiss = findKnownMiss(input);+ const safe = promptSafe && !piiPresent && !knownMiss;wrapperStats.isSafeCalls++;if (!safe) wrapperStats.isSafeUnsafeVerdicts++;@@ -482,8 +518,9 @@ const aidefenceIsSafeTool: MCPTool = {type: 'text',text: JSON.stringify({safe,- promptSafe,+ promptSafe: promptSafe && !knownMiss,piiPresent,+ ...(knownMiss ? { knownMiss: { threatType: knownMiss.threatType, reportedAt: knownMiss.reportedAt } } : {}),}, null, 2),}],};