ruflo production-validator 技能详解:从 Mock 扫描到负载压测的生产就绪验证体系
ruflo(agent meta-harness)通过 .agents/skills/ 目录为 Codex CLI / Claude Code 等智能体加载技能包,其中 production-validator 是 "Testing & Validation" 类别下与 tdd-london-swarm 并列的验证类智能体技能。本文以 SKILL.md 为主体,完整解析该技能的前置/后置钩子、五大验证策略与四类检查清单,帮助读者掌握一套"确保生产环境零 Mock、零假数据"的端到端验证方法论,并能在自己的项目中复制这套检查流程。
技能在 ruflo 中的定位与加载方式
ruflo 的智能体技能统一存放于 .agents/skills/<技能目录>/SKILL.md,.agents/README.md 中给出了标准目录结构:
.agents/
config.toml # 主配置文件
skills/ # 技能定义
skill-name/
SKILL.md # 技能说明
scripts/ # 可选脚本
docs/ # 可选文档
技能通过 $skill-name 语法调用,每个技能包含 YAML frontmatter 元数据、触发与跳过条件、命令与示例。在本仓库中,生产验证技能注册在 agent-production-validator 目录下,frontmatter 中声明了 name: agent-production-validator 与调用提示 invoke with $agent-production-validator。项目根目录的 CLAUDE.md 将 production-validator 归入 "Testing & Validation" 类别,与 tdd-london-swarm 并列;init 执行器 在生成项目文档时同样把这两个技能写入智能体路由清单。此外,.agents/config.toml 展示了技能启用的通用方式——通过 [[skills.config]] 表逐项指定技能路径并设置 enabled = true:
[[skills.config]]
path = ".agents/skills/security-audit"
enabled = true
技能 Frontmatter:类型、能力与钩子
技能文件的第二段 frontmatter 定义了该智能体的元数据,是理解其行为的关键:
name: production-validator
type: validator
color: "#4CAF50"
description: Production validation specialist ensuring applications are fully implemented and deployment-ready
capabilities:
- production_validation
- implementation_verification
- end_to_end_testing
- deployment_readiness
- real_world_simulation
priority: critical
hooks:
pre: |
echo "🔍 Production Validator starting: $TASK"
# Verify no mock implementations remain
echo "🚫 Scanning for mock$fake implementations..."
grep -r "mock\|fake\|stub\|TODO\|FIXME" src/ || echo "✅ No mock implementations found"
post: |
echo "✅ Production validation complete"
# Run full test suite against real implementations
if [ -f "package.json" ]; then
npm run test:production --if-present
npm run test:e2e --if-present
fi
可以把它拆解为三层含义:
- 身份声明:
type: validator与priority: critical表明这是一个高优先级的验证器角色——在智能体编排中,它不是执行者而是守门人。五项capabilities覆盖了生产验证(production_validation)、实现核验(implementation_verification)、端到端测试(end_to_end_testing)、部署就绪(deployment_readiness)与真实世界模拟(real_world_simulation)的完整谱系。 - pre 钩子(前置扫描):任务启动时先对
src/执行grep -r "mock\|fake\|stub\|TODO\|FIXME",一旦命中即暴露遗留的占位实现;若无命中则回显 "No mock implementations found"。这一步把"代码里没有残留 Mock"作为验证工作的前置门禁。 - post 钩子(后置回归):任务结束后,若项目存在
package.json,则依次尝试执行npm run test:production与npm run test:e2e,并使用--if-present保证脚本不存在时不报错。也就是说,该技能对项目的硬性要求是:把"生产级测试"与"E2E 测试"固化为 package.json 中的两个 script,钩子会自动驱动它们。
从技能结构设计上看,pre 钩子负责"静态证据"(源码扫描),post 钩子负责"动态证据"(真实测试套件),两者构成一次完整的验证闭环。
职责定义:五项核心职责
技能正文将角色职责归纳为五条,这也是整篇文章后续展开的主线:
- Implementation Verification:确保所有组件均为真实实现,而非 Mock;
- Production Readiness:验证应用能与真实数据库、API 与服务协同工作;
- End-to-End Testing:针对真实系统集成执行全面测试;
- Deployment Validation:验证应用在类生产环境中行为正确;
- Performance Validation:确认真实负载下的性能达标。
验证策略一:实现完整性扫描(Mock/Fake/Stub 模式匹配)
这是技能的第一道技术防线:用一组正则模式扫描整个代码库,定位"看起来实现了、实际是占位"的代码。技能文档给出的参考实现如下:
// Scan for incomplete implementations
const validateImplementation = async (codebase: string[]) => {
const violations = [];
// Check for mock implementations in production code
const mockPatterns = [
/^mock[A-Z]\w+$/g, // mockService, mockRepository
/^fake[A-Z]\w+$/g, // fakeDatabase, fakeAPI
/^stub[A-Z]\w+$/g, // stubMethod, stubService
/TODO.*implementation/gi, // TODO: implement this
/FIXME.*mock/gi, // FIXME: replace mock
/throw new Error\(['"]not implemented/gi
];
for (const file of codebase) {
for (const pattern of mockPatterns) {
if (pattern.test(file.content)) {
violations.push({
file: file.path,
issue: 'Mock/fake implementation found',
pattern: pattern.source
});
}
}
}
return violations;
};
六个模式分别针对六类典型残留:
| 模式 | 目标 | 典型示例 |
|---|---|---|
/^mock[A-Z]\w+$/ |
标识符级 Mock 命名 | mockService、mockRepository |
/^fake[A-Z]\w+$/ |
Fake 替身 | fakeDatabase、fakeAPI |
/^stub[A-Z]\w+$/ |
Stub 桩方法 | stubMethod、stubService |
/TODO.*implementation/i |
未完成的实现占位 | // TODO: implement this |
/FIXME.*mock/i |
待替换的 Mock 标注 | // FIXME: replace mock |
throw new Error('not implemented') |
显式未实现抛错 | 骨架方法直接抛错 |
函数返回结构化的 violations 列表(文件路径 + 问题描述 + 命中的正则源码),便于接入 CI 报告或智能体决策。这里体现的技能设计思想是:命名本身即证据——只要生产代码中出现 Mock/Fake/Stub 前缀的标识符,就应视为待办缺陷而非测试资产(因此配套的 grep 命令都会排除测试目录,见下文检查清单)。
验证策略二:真实数据库集成测试
第二项策略反对"用内存数据库冒充集成测试"的做法。技能文档给出的示例直连 TEST_DB_HOST / TEST_DB_NAME 指定的真实测试库,并完整走一遍 CRUD 生命周期:
// Validate against actual database
describe('Database Integration Validation', () => {
let realDatabase: Database;
beforeAll(async () => {
// Connect to actual test database (not in-memory)
realDatabase = await DatabaseConnection.connect({
host: process.env.TEST_DB_HOST,
database: process.env.TEST_DB_NAME,
// Real connection parameters
});
});
it('should perform CRUD operations on real database', async () => {
const userRepository = new UserRepository(realDatabase);
// Create real record
const user = await userRepository.create({
email: 'test@example.com',
name: 'Test User'
});
expect(user.id).toBeDefined();
expect(user.createdAt).toBeInstanceOf(Date);
// Verify persistence
const retrieved = await userRepository.findById(user.id);
expect(retrieved).toEqual(user);
// Update operation
const updated = await userRepository.update(user.id, { name: 'Updated User' });
expect(updated.name).toBe('Updated User');
// Delete operation
await userRepository.delete(user.id);
const deleted = await userRepository.findById(user.id);
expect(deleted).toBeNull();
});
});
这段用例的验证要点在于四个环节环环相扣:create 后断言 id 与 createdAt 已由数据库侧生成,证明走的是真实持久化路径;findById 回读做相等断言验证持久化;update 验证写回;delete 后回读应为 null。任何一个环节用内存替代品(如 :memory: 的 SQLite)都测不出真实连接池、真实 SQL 方言、真实隔离级别的问题——这正是技能"Real Data Usage / Infrastructure Testing"最佳实践的要求。
验证策略三:外部 API 集成验证
第三项策略验证与外部服务的真实集成,示例以支付服务为对象(使用真实测试密钥而非硬编码假响应):
// Validate against real external services
describe('External API Validation', () => {
it('should integrate with real payment service', async () => {
const paymentService = new PaymentService({
apiKey: process.env.STRIPE_TEST_KEY, // Real test API
baseUrl: 'https://api.stripe.com/v1'
});
// Test actual API call
const paymentIntent = await paymentService.createPaymentIntent({
amount: 1000,
currency: 'usd',
customer: 'cus_test_customer'
});
expect(paymentIntent.id).toMatch(/^pi_/);
expect(paymentIntent.status).toBe('requires_payment_method');
expect(paymentIntent.amount).toBe(1000);
});
it('should handle real API errors gracefully', async () => {
const paymentService = new PaymentService({
apiKey: 'invalid_key',
baseUrl: 'https://api.stripe.com/v1'
});
await expect(paymentService.createPaymentIntent({
amount: 1000,
currency: 'usd'
})).rejects.toThrow('Invalid API key');
});
});
用例设计上有两个值得注意的点:其一,正向用例对响应做"结构指纹"断言(pi_ 前缀、requires_payment_method 状态),能区分"真实接口返回"与"本地伪造响应";其二,负向用例刻意传入无效密钥并断言抛出 Invalid API key,验证错误处理链路在真实网络错误下依然优雅。密钥一律来自环境变量(process.env.STRIPE_TEST_KEY),与技能后文"环境验证"一节形成呼应。
验证策略四:基础设施验证(缓存与邮件)
第四项策略针对真实基础设施组件,文档给出了 Redis 缓存与 SMTP 邮件两个代表性用例:
// Validate real infrastructure components
describe('Infrastructure Validation', () => {
it('should connect to real Redis cache', async () => {
const cache = new RedisCache({
host: process.env.REDIS_HOST,
port: parseInt(process.env.REDIS_PORT),
password: process.env.REDIS_PASSWORD
});
await cache.connect();
// Test cache operations
await cache.set('test-key', 'test-value', 300);
const value = await cache.get('test-key');
expect(value).toBe('test-value');
await cache.delete('test-key');
const deleted = await cache.get('test-key');
expect(deleted).toBeNull();
await cache.disconnect();
});
it('should send real emails via SMTP', async () => {
const emailService = new EmailService({
host: process.env.SMTP_HOST,
port: parseInt(process.env.SMTP_PORT),
auth: {
user: process.env.SMTP_USER,
pass: process.env.SMTP_PASS
}
});
const result = await emailService.send({
to: 'test@example.com',
subject: 'Production Validation Test',
body: 'This is a real email sent during validation'
});
expect(result.messageId).toBeDefined();
expect(result.accepted).toContain('test@example.com');
});
});
Redis 用例覆盖了连接、写入(带 300 秒 TTL)、读取、删除、断开的完整生命周期;SMTP 用例则断言服务端回执(messageId 与收件人列表 accepted)。这两类依赖都是典型的"单机跑通、上云就翻车"组件——认证方式、网络策略、超时行为只有在真实环境中才会暴露,这也对应技能最佳实践中"Test failure scenarios with real service outages"的要求。
验证策略五:真实负载下的性能验证
第五项策略用两种负载模型验证性能承诺:瞬时并发与持续吞吐。
// Validate performance with real load
describe('Performance Validation', () => {
it('should handle concurrent requests', async () => {
const apiClient = new APIClient(process.env.API_BASE_URL);
const concurrentRequests = 100;
const startTime = Date.now();
// Simulate real concurrent load
const promises = Array.from({ length: concurrentRequests }, () =>
apiClient.get('/health')
);
const results = await Promise.all(promises);
const endTime = Date.now();
const duration = endTime - startTime;
// Validate all requests succeeded
expect(results.every(r => r.status === 200)).toBe(true);
// Validate performance requirements
expect(duration).toBeLessThan(5000); // 5 seconds for 100 requests
const avgResponseTime = duration / concurrentRequests;
expect(avgResponseTime).toBeLessThan(50); // 50ms average
});
it('should maintain performance under sustained load', async () => {
const apiClient = new APIClient(process.env.API_BASE_URL);
const duration = 60000; // 1 minute
const requestsPerSecond = 10;
const startTime = Date.now();
let totalRequests = 0;
let successfulRequests = 0;
while (Date.now() - startTime < duration) {
const batchStart = Date.now();
const batch = Array.from({ length: requestsPerSecond }, () =>
apiClient.get('/api/users').catch(() => null)
);
const results = await Promise.all(batch);
totalRequests += requestsPerSecond;
successfulRequests += results.filter(r => r?.status === 200).length;
// Wait for next second
const elapsed = Date.now() - batchStart;
if (elapsed < 1000) {
await new Promise(resolve => setTimeout(resolve, 1000 - elapsed));
}
}
const successRate = successfulRequests / totalRequests;
expect(successRate).toBeGreaterThan(0.95); // 95% success rate
});
});
两个用例的量化阈值都写死在断言里,可直接作为验收标准引用:
- 瞬时并发:100 个并发
/health请求,全部 200;总耗时 < 5000ms,平均响应 < 50ms; - 持续负载:持续 60 秒、10 req/s,按秒分批发送并记录成功数,最终成功率 > 95%。注意持续用例中每个请求都挂了
.catch(() => null)——在压测场景下单次失败不应中断整个批次,失败被计入成功率分母,这比"失败即抛错"更接近生产监控口径。
验证清单一:代码质量 grep 检查
技能文档的 Checklist 部分首先给出一组可直接复制到 CI 的静态检查命令(与 pre 钩子的轻量版互补,这里排除了测试目录):
# No mock implementations in production code
grep -r "mock\|fake\|stub" src/ --exclude-dir=__tests__ --exclude="*.test.*" --exclude="*.spec.*"
# No TODO/FIXME in critical paths
grep -r "TODO\|FIXME" src/ --exclude-dir=__tests__
# No hardcoded test data
grep -r "test@\|example\|localhost" src/ --exclude-dir=__tests__
# No console.log statements
grep -r "console\." src/ --exclude-dir=__tests__
四条命令分别守住四类生产隐患:测试替身混入生产代码、关键路径上的未完成标注、硬编码测试数据(如 test@、example、localhost)、遗留调试输出。--exclude-dir=__tests__ 与 --exclude 通配符保证 Mock 只被允许存在于测试资产中——这与策略一的"命名即证据"原则一致。
验证清单二:环境变量完备性校验
部署失败的高频原因是"本地有、线上没有"的环境变量。技能文档给出了启动期强制校验的参考实现:
// Validate environment configuration
const validateEnvironment = () => {
const required = [
'DATABASE_URL',
'REDIS_URL',
'API_KEY',
'SMTP_HOST',
'JWT_SECRET'
];
const missing = required.filter(key => !process.env[key]);
if (missing.length > 0) {
throw new Error(`Missing required environment variables: ${missing.join(', ')}`);
}
};
必填清单 DATABASE_URL、REDIS_URL、API_KEY、SMTP_HOST、JWT_SECRET 恰好与前文数据库、Redis、外部 API、SMTP 各验证用例使用的环境变量一一对应,形成自洽的依赖闭环:任何一项缺失都在启动时以明确报错终止,而不是在某个请求路径上静默降级。
验证清单三:安全验证用例
// Validate security measures
describe('Security Validation', () => {
it('should enforce authentication', async () => {
const response = await request(app)
.get('/api/protected')
.expect(401);
expect(response.body.error).toBe('Authentication required');
});
it('should validate input sanitization', async () => {
const maliciousInput = '<script>alert("xss")</script>';
const response = await request(app)
.post('/api/users')
.send({ name: maliciousInput })
.set('Authorization', `Bearer ${validToken}`)
.expect(400);
expect(response.body.error).toContain('Invalid input');
});
it('should use HTTPS in production', () => {
if (process.env.NODE_ENV === 'production') {
expect(process.env.FORCE_HTTPS).toBe('true');
}
});
});
三个用例分别覆盖认证强制(无凭据访问受保护端点必须 401 且错误信息明确)、输入净化(XSS payload 应被 400 拒绝)、传输层约束(NODE_ENV=production 时强制 FORCE_HTTPS=true)。其中 HTTPS 用例采用"条件断言"写法——只在生产环境断言,使同一套测试在非生产环境也可运行而不误报。
验证清单四:部署就绪验证
// Validate deployment configuration
describe('Deployment Validation', () => {
it('should have proper health check endpoint', async () => {
const response = await request(app)
.get('/health')
.expect(200);
expect(response.body).toMatchObject({
status: 'healthy',
timestamp: expect.any(String),
uptime: expect.any(Number),
dependencies: {
database: 'connected',
cache: 'connected',
external_api: 'reachable'
}
});
});
it('should handle graceful shutdown', async () => {
const server = app.listen(0);
// Simulate shutdown signal
process.emit('SIGTERM');
// Verify server closes gracefully
await new Promise(resolve => {
server.close(resolve);
});
});
});
健康检查用例对 /health 的响应结构做了完整断言:顶层 status/timestamp/uptime 之外,dependencies 必须逐一报告 database: connected、cache: connected、external_api: reachable——这与前面"依赖数据库、缓存、外部 API 都要真实可达"的验证策略首尾呼应,说明健康端点是所有依赖状态的汇总出口。优雅停机用例通过 process.emit('SIGTERM') 模拟容器平台的终止信号,验证 server.close() 能被正常触发,对应容器编排场景下的滚动发布需求。
最佳实践:文档给出的四条原则
技能文档以 Best Practices 收束,四类原则可视为验证工作的"价值观":
- Real Data Usage:使用接近生产的测试数据而非占位值;用真实文件上传而非 Mock 文件;用真实用户场景与边界情况做验证。
- Infrastructure Testing:对真实数据库而非内存替代品做测试;验证网络连通性与超时行为;用真实服务中断演练失败场景。
- Performance Validation:在真实负载下测量响应时间;以真实数据量测内存占用;以生产规模数据集验证扩展行为。
- Security Testing:用真实身份提供方测认证;用真实证书验证加密;用真实用户角色与权限测授权。
总结:一条贯穿始终的验证哲学
把 frontmatter 钩子、五项验证策略与四类清单串起来看,production-validator 技能的逻辑链条非常清晰:pre 钩子做静态 Mock 扫描 → 实现完整性检查用正则定位占位代码 → 数据库/API/基础设施三组集成测试把"真实依赖"逐一点亮 → 双模型压测验证性能承诺 → 环境变量、安全、健康检查与优雅停机四张清单兜住部署细节 → post 钩子以 test:production 与 test:e2e 两个 script 完成最终回归。技能文档的结语也点明了目标:"确保应用到达生产环境时,表现与测试时完全一致——没有惊喜、没有 Mock 实现、没有对假数据的依赖。"在 ruflo 的多智能体工作流中,该技能正是"Testing & Validation"环节里承担上线前最后一道门禁的角色,配合 CLAUDE.md 中的智能体路由与 .agents/config.toml 的技能开关,可以在任何接入 Codex CLI 的项目中复用这套验证体系。
atomcodeClaude Code 的开源替代方案。连接任意大模型,编辑代码,运行命令,自动验证 — 全自动执行。用 Rust 构建,极致性能。 | An open-source alternative to Claude Code. Connect any LLM, edit code, run commands, and verify changes — autonomously. Built in Rust for speed. Get StartedRust0622
Hy4-previewHy4 preview 是由腾讯混元团队研发的新一代混合专家(MoE)旗舰模型。模型总参数量 770B,每个 token 激活 49B,主干共包含78层,第一层采用标准 FFN,其余 77 层均为 MoE 结构,每层包含 256 个路由专家与 1 个共享专家,每个 token 激活 top-8 路由专家及共享专家。主干之外原生内置 1 层 MTP(总参数量 10B,激活 0.7B)以支持投机解码。Python00
GLM-5.3GLM-5.3 与 GLM-5.2 使用相同的基座模型——所有提升均来自后训练。与 GLM-5.2 相比,它在复杂编程和长程任务上的表现显著提升。Jinja00
GLM-5.3-FlashGLM-5.3-Flash (320B-A18B),是GLM-5系列的首个原生多模态模型。320B总参数,能力超过GLM-5.2Jinja00
Spark-X2.5-4BSpark-X2.5-4B 旨在让强大的 AI 更实用、更高效、更易获得。在广泛日常任务中表现强劲,涵盖对话、写作、翻译、推理、编码、工具调用以及智能体工作流,并在同等规模的开源模型中取得领先成绩。Spark-X2.5 将面向效率的架构与最高 1M tokens 的原生上下文窗口相结合,并支持 200 多种语言。Python00
Spark-X2.5-1.7BSpark-X2.5-1.7B 旨在让强大的 AI 更加实用、高效且易于获取。这些模型在广泛的日常任务中表现出色,涵盖对话、写作、翻译、推理、编程、工具调用和智能体工作流,并在同等规模的开源模型中取得领先结果。Spark-X2.5 将面向效率的架构与最高 1M tokens 的原生上下文窗口相结合,并支持 200 多种语言。Python00