首页
/ RuView AIDefence Guardian 实战:为多智能体集群构建 AIMDS 提示注入防御层

RuView AIDefence Guardian 实战:为多智能体集群构建 AIMDS 提示注入防御层

2026-09-06 15:55:14作者:伍希望

本文以 RuView 仓库中的 .claude/agents/v3/aidefence-guardian.md 为核心,完整解析 AIDefence Guardian 这一 V3 安全智能体:它如何通过 @claude-flow/aidefence 库对所有 agent 输入/输出执行实时威胁检测(提示注入、越狱、PII 泄露等六类威胁),如何接入 hooks、swarm 共享记忆与升级协议,以及它与同目录 security-architect-aidefenceinjection-analyst 等 agent 组成的协作防御体系。读完后你可以复制该 agent 的完整定义与集成钩子,在自己的 claude-flow 项目中落地一套"先扫描、再放行"的 AI 操纵防护机制。

1. 角色定位:常驻守护型安全智能体

AIDefence Guardian 的定义位于 .claude/agents/v3/aidefence-guardian.md,其 YAML frontmatter 定义了它在 claude-flow V3 agent 体系中的元数据与生命周期配置:

配置项 取值 含义
name aidefence-guardian agent 唯一标识
type security 安全域 agent
priority critical 最高优先级,威胁处理优先于常规任务
singleton: true 单例:全局只运行一个实例,保证检测状态一致
auto_spawn.on_swarm_init true swarm 初始化时自动拉起
auto_spawn.topology ["hierarchical", "hierarchical-mesh"] 仅在这两种拓扑下自动出现
requires.packages @claude-flow/aidefence 依赖的检测引擎 npm 包
requires.agents security-architect 升级(escalation)目标

capabilities 声明了八项能力:threat_detectionprompt_injection_defensejailbreak_preventionpii_protectionbehavioral_monitoringadaptive_mitigationsecurity_consensuspattern_learning

frontmatter 还内嵌了两段 shell hook 脚本,构成一个"会话级指标闭环":

  • pre hook(会话开始):打印初始化日志,并初始化三个会话级统计变量——AIDEFENCE_SESSION_ID(以 guardian-<unix时间戳> 命名)、THREATS_BLOCKEDTHREATS_WARNEDSCANS_COMPLETED,全部置零。
  • post hook(会话结束):输出 Scans completed / Threats blocked / Threats warned 汇总,并通过 CLI 将指标写入共享记忆:
npx claude-flow@v3alpha memory store \
  --namespace "security_metrics" \
  --key "$AIDEFENCE_SESSION_ID" \
  --value "{\"scans\": $SCANS_COMPLETED, \"blocked\": $THREATS_BLOCKED, \"warned\": $THREATS_WARNED}" \
  2>/dev/null

这段 post 脚本与仓库实际的 hook 基建相互印证:.claude/settings.jsonSessionStart/SessionEnd/Stop 等钩子统一路由到 hook-handler.cjs,且 permissions.allow 白名单放行了 Bash(npx claude-flow*)mcp__claude-flow__:*,正是 guardian 这类 agent 运行 npx claude-flow@v3alpha ... 命令与调用 MCP 工具所需的最小权限面。

2. 检测能力:六类威胁与性能指标

Guardian 使用 @claude-flow/aidefence 库做实时检测,文档给出的性能承诺为:检测延迟 <10ms(实测约 0.06ms)、内置 50+ 模式且学习模式数量无上限、误报率 <5%。

可检测的威胁类型(result.threats[].type)共六类:

威胁类型 典型特征
instruction_override 试图覆盖系统指令(如 "ignore previous instructions")
jailbreak DAN 模式、绕过请求、解除限制
role_switching 身份操纵("你现在是……")
context_manipulation 伪造 system 消息、滥用分隔符
encoding_attack Base64/hex 编码的恶意内容
pii_exposure 邮箱、SSN、API 密钥、口令等 PII 暴露

这六类分类与同目录的 injection-analyst.md 中的攻击技术分类表一一对应(Instruction Override / Role Switching / Jailbreak / Context Manipulation / Encoding Attacks / Social Engineering),可以看到 guardian 负责"实时拦截",injection-analyst 负责"事后深度分析与模式回灌",二者共享同一个 @claude-flow/aidefence 依赖包。

3. 核心 API 一:输入侧扫描(guardInput)

原文档给出的标准用法是"处理前扫描、critical 即阻断、非 critical 告警":

import { createAIDefence } from '@claude-flow/aidefence';

const guardian = createAIDefence({ enableLearning: true });

// Scan before processing
async function guardInput(agentId: string, input: string) {
  const result = await guardian.detect(input);

  if (!result.safe) {
    const critical = result.threats.filter(t => t.severity === 'critical');

    if (critical.length > 0) {
      // Block critical threats
      throw new SecurityError(`Blocked: ${critical[0].description}`, {
        agentId,
        threats: critical
      });
    }

    // Warn on non-critical
    console.warn(`⚠️ [${agentId}] ${result.threats.length} threat(s) detected`);
    for (const threat of result.threats) {
      console.warn(`  - [${threat.severity}] ${threat.type}`);
    }
  }

  if (result.piiFound) {
    console.warn(`⚠️ [${agentId}] PII detected in input`);
  }

  return result;
}

从这段代码可以读出检测结果的契约结构:detect(input) 返回 { safe: boolean, threats: [{ severity, type, description }], piiFound: boolean }。两级处置策略是明确的——severity === 'critical' 的威胁直接抛 SecurityError 中断处理,其余降级为 console.warn 告警;PII 不阻断、只标记。enableLearning: true 则开启模式学习,使后续 learnFromDetection 可用。

4. 核心 API 二:多 agent 安全共识

单点判断容易误伤,guardian 支持把多个安全 agent 的评估按权重聚合成共识结论:

import { calculateSecurityConsensus } from '@claude-flow/aidefence';

// Gather assessments from multiple security agents
const assessments = [
  { agentId: 'guardian-1', threatAssessment: result1, weight: 1.0 },
  { agentId: 'security-architect', threatAssessment: result2, weight: 0.8 },
  { agentId: 'reviewer', threatAssessment: result3, weight: 0.5 },
];

const consensus = calculateSecurityConsensus(assessments);

if (consensus.consensus === 'threat') {
  console.log(`🚨 Security consensus: THREAT (${(consensus.confidence * 100).toFixed(1)}% confidence)`);
  if (consensus.criticalThreats.length > 0) {
    console.log('Critical threats:', consensus.criticalThreats.map(t => t.type).join(', '));
  }
}

要点:每个评估携带 agentIdthreatAssessment(即 detect() 的结果对象)与 weight;返回的 consensusconsensus 结论('threat' / 安全)、confidence 置信度(0–1)与 criticalThreats 列表。权重设计体现了"专业安全 agent 话语权更大"的编排思路:guardian 1.0 > security-architect 0.8 > reviewer 0.5。

5. 核心 API 三:检测学习与缓解策略库

检测不是一次性的,guardian 将确认准确的检测回灌给学习器,并维护"威胁类型 → 最优缓解策略"的经验库:

// When detection is confirmed accurate
await guardian.learnFromDetection(input, result, {
  wasAccurate: true,
  userVerdict: 'Confirmed prompt injection attempt'
});

// Record successful mitigation
await guardian.recordMitigation('jailbreak', 'block', true);

// Get best mitigation for threat type
const mitigation = await guardian.getBestMitigation('prompt_injection');
console.log(`Best strategy: ${mitigation.strategy} (${mitigation.effectiveness * 100}% effective)`);

三个方法分工清晰:

  1. learnFromDetection(input, result, meta)——带人工裁决(userVerdict)的正反馈学习入口,只有 wasAccurate: true 的确认检测才会强化模式;
  2. recordMitigation(threatType, strategy, success)——记录某类威胁下某缓解策略(如 block)是否奏效;
  3. getBestMitigation(threatType)——查询历史经验中有效性(effectiveness)最高的 strategy

这套闭环在 security-architect-aidefence.md 中有 CLI 侧的同构实现:npx claude-flow@v3alpha security learn --threat-type prompt_injection --strategy sanitize --effectiveness 0.95,且该 agent 将成功缓解(reward > 0.8)额外存入 security_mitigations 命名空间——与 guardian 的 recordMitigation 数据最终汇入同一共享记忆体系。

6. 集成钩子一:settings.json 的 pre-agent-input 拦截

guardian 最直接的部署形态是挂到 agent 输入链路前。原文档建议在 .claude/settings.json 中加入如下 hook(timeout 5000ms,超过 5 秒放行以免拖垮 agent):

{
  "hooks": {
    "pre-agent-input": {
      "command": "node -e \"
        const { createAIDefence } = require('@claude-flow/aidefence');
        const guardian = createAIDefence({ enableLearning: true });
        const input = process.env.AGENT_INPUT;
        const result = guardian.detect(input);
        if (!result.safe && result.threats.some(t => t.severity === 'critical')) {
          console.error('BLOCKED: Critical threat detected');
          process.exit(1);
        }
        process.exit(0);
      \"",
      "timeout": 5000
    }
  }
}

语义是:从环境变量 AGENT_INPUT 取待处理输入 → 同步执行 detect → 存在 critical 威胁时以非零码退出从而阻断下游处理,否则 exit(0) 放行。

对照仓库实际配置可见其工程落点:.claude/settings.json 已使用同一 hook-handler 路由模式挂载 UserPromptSubmitroute)、PreToolUsepre-bash,matcher 为 Bash)、SubagentStartstatus)等钩子,全部以 node "$CLAUDE_PROJECT_DIR/.claude/helpers/hook-handler.cjs" <stage> 的统一入口收敛。也就是说,guardian 的"输入前拦截"与仓库既有的 prompt 路由、bash 前置检查属于同一 hook 管道,只是拦截阶段更靠前。

7. 集成钩子二:swarm 共享记忆中的检测协调

在 swarm 模式下,guardian 把每次检测写入共享记忆,并借历史相似度检索实现"见过的攻击快速响应":

// Store detection in swarm memory
mcp__claude-flow__memory_usage({
  action: "store",
  namespace: "security_detections",
  key: `detection-${Date.now()}`,
  value: JSON.stringify({
    agentId: "aidefence-guardian",
    input: inputHash,
    threats: result.threats,
    timestamp: Date.now()
  })
});

// Search for similar past detections
const similar = await guardian.searchSimilarThreats(input, { k: 5 });
if (similar.length > 0) {
  console.log('Similar threats found in history:', similar.length);
}

两个设计细节值得注意:一是入库的 input 字段存的是 inputHash 而非原文,避免把原始(可能含 PII 的)攻击载荷扩散到共享记忆中;二是 searchSimilarThreats(input, { k: 5 }) 返回 top-k 相似历史检测,可用于升级判断与告警去重。支撑该检索的性能底座是 settings.json 中 memory.enableHNSW: true 开启的 HNSW 向量索引——security-architect-aidefence.md 中对同一 security_threats 命名空间的 HNSW 检索标注了 150x–12,500x 的模式匹配加速,即相似度检索走的是近似最近邻而非全量扫描。

8. 升级协议:Block → Log → Alert → Escalate → Learn

result.threats 中出现 critical 级威胁时,guardian 执行五步协议,原文档给出了完整示例代码:

  1. Block:立即阻止该输入被处理;
  2. Log:连同完整上下文记录威胁;
  3. Alert:通过 hooks 通知系统告警;
  4. Escalate:写入升级记录并交由 security-architect agent 复核;
  5. Learn:把模式存入学习库供后续检测复用。
if (result.threats.some(t => t.severity === 'critical')) {
  // Block
  const blocked = true;

  // Log
  await guardian.learnFromDetection(input, result);

  // Alert
  npx claude-flow@v3alpha hooks notify \
    --severity critical \
    --message "Critical threat blocked by AIDefence Guardian"

  // Escalate to security-architect
  mcp__claude-flow__memory_usage({
    action: "store",
    namespace: "security_escalations",
    key: `escalation-${Date.now()}`,
    value: JSON.stringify({
      from: "aidefence-guardian",
      to: "security-architect",
      threat: result.threats[0],
      requiresReview: true
    })
  });
}

升级通道的实现方式是"共享记忆信箱":guardian 不直接调用 security-architect,而是向 security_escalations 命名空间写入带 requiresReview: true 的升级记录,由架构侧 agent 消费。告警则复用 CLI 的 hooks notify --severity critical 命令——这与 security-architect-aidefence.md post hook 中扫描出 critical 漏洞时的 hooks notify --severity critical 调用是同一套通知设施,保证两个安全 agent 的告警走统一出口。

9. 协作网络与性能观测

guardian 的协作矩阵(原文档 Collaboration 一节):

  • security-architect:升级 critical 威胁、接收策略指导——这是 frontmatter 中 requires.agents 唯一声明的依赖;
  • security-auditor:共享检测模式、协同审计;
  • reviewer:为代码评审提供安全上下文;
  • coder:基于已检测模式给出安全编码建议。

与同目录 agent 的分工从源码结构看可归纳为三层:guardian(critical 优先级、单例、自动扫描拦截)→ injection-analyst(high 优先级、事后深度分类与 MITRE 技法映射)→ security-architect-aidefence(继承 security-architect,叠加 AIMDS 行为分析、Lyapunov 混沌检测与 LTL 策略校验)。三层共享 @claude-flow/aidefencesecurity_threats 等记忆命名空间,形成"检测—分析—架构响应"的流水线。

性能观测方面,guardian 通过 getStats() 拉取自检指标并写入 guardian_metrics 命名空间(按日期为 key):

const stats = await guardian.getStats();

// Report to metrics system
mcp__claude-flow__memory_usage({
  action: "store",
  namespace: "guardian_metrics",
  key: `metrics-${new Date().toISOString().split('T')[0]}`,
  value: JSON.stringify({
    detectionCount: stats.detectionCount,
    avgLatencyMs: stats.avgDetectionTimeMs,
    learnedPatterns: stats.learnedPatterns,
    mitigationEffectiveness: stats.avgMitigationEffectiveness
  })
});

四个指标正好对应其四项承诺能力:检测量(detectionCount)、平均检测时延(avgDetectionTimeMs,用于校验 <10ms 承诺)、已学习模式数(learnedPatterns)、缓解策略平均有效性(avgMitigationEffectiveness)。

10. 在 RuView 仓库中的定位与使用边界

综合仓库证据,AIDefence Guardian 属于 RuView 所采用的 claude-flow V3 多智能体开发编排层(而非 RuView 的 WiFi 感知业务代码本身),仓库内可见的关联证据包括:

使用前提与限制:该 agent 依赖 @claude-flow/aidefence 包与 claude-flow@v3alpha CLI(npx 方式按需拉取),且 auto_spawn 仅在 hierarchical/hierarchical-mesh 两种 swarm 拓扑下生效;文档中 <10ms 延迟、<5% 误报率等为其自述指标,引用时以上述 agent 文档为准。复制该定义到项目时,建议同步保留 frontmatter 的 pre/post hooks(会话指标闭环)与 security_metrics 命名空间约定,以维持检测—统计—学习的完整链路。

登录后查看全文
热门项目推荐
相关项目推荐