关于 apex-dev
面向 APEX 生态系统开发的工程技能,为 LLM 提供功能开发、排错、性能、安全、测试和部署方面的实践流程。它以 APEX 模块约定、架构模式和验证清单为核心,帮助生成并检查代码改动。
主要功能
- 01APEX 模块开发约定
- 02系统化故障定位与修复
- 03性能优化模式
- 04安全与风险分级指导
- 05ARMAGEDDON 测试流程
- 06部署及架构检查清单
适用场景
- 01为 APEX 应用实现新功能
- 02排查 APEX 项目的代码问题
- 03检查安全、测试和部署准备情况
安装
复制下面的命令,在终端中运行。
$
npx skills add https:/ / github.com/ apexbusiness-systems/ apex-omnihub --skill apex-dev安装后在 Claude Code 中输入/apex-dev确认已加载。
包含的文件
除 SKILL.md 外,安装时一起下载的参考资料和脚本。
architecture-deep-dive.mddrift-check.pyLICENSEREADME.mdsecurity-protocols.mdtesting-patterns.mdverify-build.sh详细介绍
APEX-DEV:全知开发技能
使命:使任何 LLM 都能为 APEX 生态系统编写企业级、零偏差、一次通过的代码。
理念:“智能设计”——每项输出都具备确定性、安全性、可移植性,并可用于生产环境。
输入/输出约定
输入:引用 APEX 生态系统(OmniHub、TradeLine、aSpiral、OmniDash 等)的任务描述 输出:可用于生产环境的代码、架构决策或修复方案,并附带验证步骤 成功标准:代码通过 lint、类型检查和相关的 ARMAGEDDON 测试套件
合成记忆锚点
在执行任何操作之前,先将以下不变量牢记于心:
┌─────────────────────────────────────────────────────────────────────┐
│ APEX ECOSYSTEM TRUTH TABLE (Load into working memory) │
├─────────────────────────────────────────────────────────────────────┤
│ Platform: APEX OmniHub ("Intelligence Designed") │
│ Domain: apexomnihub.icu │
│ Core Value: Universal Orchestration (Web2 ↔ Web3 Semantic Bridge)│
│ Stack: React 18 + Vite + TypeScript + Tailwind + shadcn UI │
│ Backend: Supabase (Auth, Storage, Edge Functions, Postgres) │
│ Orchestrator: Temporal.io (Event Sourcing + Saga Pattern) │
│ Security: Guardian/Triforce + MAN Mode + Zero-Trust + RLS │
│ Test Suite: ARMAGEDDON (265 tests, 100% pass, Level 6 Adaptive) │
│ Non-Negotiable: No vendor lock-in, no drift, no loops, no secrets │
└─────────────────────────────────────────────────────────────────────┘
防止偏差:每调用 3 次工具或切换上下文后,重新阅读此锚点。
决策树(入口)
你正在做什么?
Building new feature? → Section A: FEATURE DEVELOPMENT
Fixing a bug? → Section B: BUG RESOLUTION PROTOCOL
Optimizing performance? → Section C: PERFORMANCE ENGINEERING
Security hardening? → Section D: SECURITY POSTURE
Writing tests? → Section E: ARMAGEDDON TEST PROTOCOL
Deploying/DevOps? → Section F: DEPLOYMENT & OPS
Architecture decision? → Section G: ARCHITECTURE PATTERNS
Working on specific app? → Section H: APP-SPECIFIC PATTERNS
A 节:功能开发
A1. 开发前检查清单
编写任何代码之前:
□ Identify target module (OmniDash | OmniConnect | OmniLink | Guardian | Edge)
□ Check existing patterns in that module (don't reinvent)
□ Verify abstraction layer exists (no direct provider calls)
□ Confirm test strategy (unit + integration + chaos)
□ Load relevant type definitions
A2. 文件放置决策树
UI Component?
├─ Shared across apps → src/components/
├─ Page-specific → src/pages/{PageName}/components/
└─ shadcn primitive → src/components/ui/
Business Logic?
├─ API calls → src/lib/api/
├─ State management → src/contexts/ or src/stores/
├─ Utilities → src/lib/utils/
└─ Security → src/security/
Backend?
├─ Edge Function → supabase/functions/{name}/
├─ Workflow → orchestrator/workflows/
├─ Activity → orchestrator/activities/
└─ Migration → supabase/migrations/
Test?
├─ Unit → tests/{module}/
├─ E2E → tests/e2e/
├─ Chaos → tests/chaos/
└─ Security → tests/prompt-defense/
A3. 组件模板(React + TypeScript)
// src/components/{ComponentName}.tsx
import { FC, memo } from 'react';
import { cn } from '@/lib/utils';
interface {ComponentName}Props {
/** Required: Describe purpose */
requiredProp: string;
/** Optional: Describe default behavior */
optionalProp?: boolean;
className?: string;
}
/**
* {ComponentName} - One-line description
* @example <{ComponentName} requiredProp="value" />
*/
export const {ComponentName}: FC<{ComponentName}Props> = memo(({
requiredProp,
optionalProp = false,
className,
}) => {
return (
<div className={cn('base-styles', className)}>
{/* Implementation */}
</div>
);
});
{ComponentName}.displayName = '{ComponentName}';
A4. Hook 模板
// src/hooks/use{HookName}.ts
import { useState, useCallback, useEffect } from 'react';
interface Use{HookName}Options {
initialValue?: string;
}
interface Use{HookName}Return {
value: string;
setValue: (v: string) => void;
isLoading: boolean;
error: Error | null;
}
export function use{HookName}(options: Use{HookName}Options = {}): Use{HookName}Return {
const [value, setValue] = useState(options.initialValue ?? '');
const [isLoading, setIsLoading] = useState(false);
const [error, setError] = useState<Error | null>(null);
// Cleanup on unmount (prevent memory leaks)
useEffect(() => {
return () => {
// Cleanup timers, subscriptions, etc.
};
}, []);
return { value, setValue, isLoading, error };
}
B 节:Bug 解决流程
B1. 根本原因分析(必做步骤)
1. REPRODUCE → Get exact steps, inputs, expected vs actual
2. ISOLATE → Identify smallest code path that triggers bug
3. TRACE → Follow data flow from input to failure point
4. IDENTIFY → Name the root cause (not symptoms)
5. FIX → Patch at root, not at symptom
6. VERIFY → Regression test + add to ARMAGEDDON suite
7. DOCUMENT → Update CHANGELOG, add test case comment
B2. 常见 APEX Bug 模式(预先处理)
| 现象 | 根本原因 | 修复模式 |
|---|---|---|
| “Cannot read property of undefined” | Supabase 响应缺少空值检查 | data?.property ?? fallback |
| 无限重新渲染 | useEffect 缺少依赖项 | 添加依赖项或使用 useCallback |
| 变更后数据过时 | React Query 缓存未失效 | queryClient.invalidateQueries(['key']) |
| Auth 令牌已过期 | 未触发会话刷新 | 检查 AuthContext 刷新逻辑 |
| Edge Function 中的类型错误 | Deno 与 Node 类型不匹配 | 使用 Supabase Edge Function 类型 |
| RLS 策略阻止访问 | 策略条件错误 | 检查 auth.uid() 与 user_id |
| Guardian 心跳过时 | 循环未启动 | 验证 npm run guardian:status |
B3. 调试命令序列
# 1. Check build health
npm run build 2>&1 | head -50
# 2. Run type check
npm run typecheck
# 3. Run relevant test battery
npm test -- --grep "{module}"
# 4. Check Guardian status
npm run guardian:status
# 5. Verify security posture
npm run security:audit
# 6. Check for console errors in dev
npm run dev 2>&1 | grep -i error
C 节:性能工程
C1. 性能目标(经 ARMAGEDDON 验证)
| 指标 | 目标 | 当前值 |
|---|---|---|
| API 响应(p95) | <100ms | <10ms ✓ |
| DB 查询(p95) | <500ms | <20ms ✓ |
| 状态更新 | <100ms | <5ms ✓ |
| 并发用户数 | 100+ | 100+ ✓ |
| WebSocket 消息/秒 | 1000+ | 1000+ ✓ |
C2. 优化决策树
Slow API call?
├─ Add React Query caching → staleTime: 5 * 60 * 1000
├─ Check N+1 queries → Use Supabase .select('*, relation(*)')
└─ Add index → supabase/migrations/
Slow render?
├─ Add memo() to component
├─ Use useMemo/useCallback for expensive computations
└─ Lazy load with React.lazy + Suspense
Memory leak?
├─ Check useEffect cleanup
├─ Verify event listener removal
└─ Check timer/interval cleanup
C3. React Query 模式(标准)
// src/lib/api/{resource}.ts
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query';
import { supabase } from '@/lib/supabase';
const STALE_TIME = 5 * 60 * 1000; // 5 minutes
export function use{Resource}s() {
return useQuery({
queryKey: ['{resource}s'],
queryFn: async () => {
const { data, error } = await supabase
.from('{resource}s')
.select('*')
.order('created_at', { ascending: false });
if (error) throw error;
return data;
},
staleTime: STALE_TIME,
});
}
export function useCreate{Resource}() {
const queryClient = useQueryClient();
return useMutation({
mutationFn: async (payload: Create{Resource}Payload) => {
const { data, error } = await supabase
.from('{resource}s')
.insert(payload)
.select()
.single();
if (error) throw error;
return data;
},
onSuccess: () => {
queryClient.invalidateQueries({ queryKey: ['{resource}s'] });
},
});
}
D 节:安全态势
D1. 安全不变量(绝不违反)
❌ NEVER commit secrets (API keys, tokens, passwords)
❌ NEVER trust user input without validation
❌ NEVER bypass RLS policies
❌ NEVER execute raw SQL from user input
❌ NEVER disable CSRF protection
❌ NEVER log PII to console in production
✅ ALWAYS use parameterized queries
✅ ALWAYS validate with Zod schemas
✅ ALWAYS use RLS for row-level access
✅ ALWAYS audit log security events
✅ ALWAYS use Guardian heartbeat for critical loops
D2. MAN 模式(人工审批节点)集成
Agent 操作的风险分类:
| 通道 | 行为 | 工具示例 |
|---|---|---|
| GREEN | 自动执行 | search_database、read_record、get_config |
| YELLOW | 执行并记录审计日志 | 未知工具、单个高风险参数 |
| RED | 隔离并请求人工审批 | delete_record、transfer_funds、send_email |
| BLOCKED | 永不执行 | execute_sql_raw、shell_execute |
// Use MAN Mode for high-risk actions
import { riskTriage } from '@/orchestrator/policies/man_policy';
const result = riskTriage({
tool: 'delete_record',
params: { id: recordId },
context: { userId, sessionId }
});
if (result.lane === 'RED') {
// Isolate and await human approval
await createManTask(result);
return { status: 'isolated', awaiting_approval: true };
}
D3. 提示词注入防御
// src/security/promptDefense.ts
import { evaluatePrompt } from './promptDefenseConfig';
// Always sanitize LLM inputs
function sanitizeUserInput(input: string): string {
const result = evaluatePrompt(input);
if (result.blocked) {
auditLog.record({
actionType: 'PROMPT_INJECTION_BLOCKED',
metadata: { pattern: result.matchedPattern }
});
throw new SecurityError('Invalid input detected');
}
return result.sanitized;
}
D4. 零信任设备注册表
// Verify device on every sensitive operation
import { deviceRegistry } from '@/zero-trust/deviceRegistry';
async function sensitiveOperation(userId: string, deviceId: string) {
const device = await deviceRegistry.verify(userId, deviceId);
if (device.status !== 'trusted') {
throw new SecurityError('Device not trusted');
}
// Proceed with operation
}
E 节:ARMAGEDDON 测试协议
E1. 测试套件结构
tests/
├── chaos/ # Chaos engineering tests
│ ├── battery.spec.ts # Core chaos battery (21 tests)
│ ├── memory-stress.spec.ts # Memory leak detection (7 tests)
│ └── integration-stress.spec.ts # Integration stress (9 tests)
├── e2e/ # End-to-end tests
│ ├── enterprise-workflows.spec.ts # Business flows (20 tests)
│ ├── errorHandling.spec.ts # Error scenarios (8 tests)
│ └── security.spec.ts # Security tests (13 tests)
├── prompt-defense/ # Prompt injection tests
│ └── real-injection.spec.ts # Real-world attacks
└── {module}/ # Unit tests per module
E2. 测试模板(Vitest)
// tests/{module}/{feature}.spec.ts
import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest';
describe('{Feature}', () => {
beforeEach(() => {
vi.clearAllMocks();
});
afterEach(() => {
vi.restoreAllMocks();
});
it('should {expected behavior} when {condition}', async () => {
// Arrange
const input = { /* test data */ };
// Act
const result = await featureUnderTest(input);
// Assert
expect(result).toMatchObject({ /* expected */ });
});
it('should handle error when {error condition}', async () => {
// Arrange
vi.spyOn(dependency, 'method').mockRejectedValue(new Error('fail'));
// Act & Assert
await expect(featureUnderTest({})).rejects.toThrow('fail');
});
});
E3. 测试命令
# Run all tests
npm test
# Run specific battery
npm test -- --grep "chaos"
# Run prompt defense tests
npm run test:prompt-defense
# Run chaos simulation (CI-safe dry run)
npm run sim:dry
# Run E2E (requires server)
npm run test:e2e
# Full ARMAGEDDON suite
npm run armageddon
F 节:部署与运维
F1. 部署检查清单
□ Build passes: npm run build
□ Type check passes: npm run typecheck
□ All tests pass: npm test
□ Security audit clean: npm run security:audit
□ No console.log in production code
□ Environment variables documented
□ Rollback plan documented
F2. 环境变量(必需)
# .env.example (NEVER commit actual values)
VITE_SUPABASE_URL=https://xxx.supabase.co
VITE_SUPABASE_PUBLISHABLE_KEY=eyJ...
# Optional
VITE_SENTRY_DSN=https://[email protected]/xxx
F3. 回滚流程
# 1. Identify failing deployment
vercel ls --prod
# 2. Rollback to previous
vercel rollback <deployment-url>
# 3. Verify rollback
curl -I https://apexomnihub.icu/health
# 4. Post-mortem within 24h
G 节:架构模式
G1. 核心架构层
┌─────────────────────────────────────────────────────────────────────┐
│ PRESENTATION LAYER (React + shadcn UI) │
│ - OmniDash (Navigation UI) │
│ - Pages (Route-level components) │
│ - Components (Reusable UI) │
└────────────────────────┬────────────────────────────────────────────┘
│
┌────────────────────────▼────────────────────────────────────────────┐
│ APPLICATION LAYER (Hooks + Context + React Query) │
│ - AuthContext (Session management) │
│ - useQuery/useMutation (Data fetching) │
│ - Business logic hooks │
└────────────────────────┬────────────────────────────────────────────┘
│
┌────────────────────────▼────────────────────────────────────────────┐
│ INTEGRATION LAYER (Adapters - Single Port Rule) │
│ - Supabase adapter (auth, db, storage) │
│ - OmniLink adapter (cross-app orchestration) │
│ - Web3 adapter (wallet, contracts) │
└────────────────────────┬────────────────────────────────────────────┘
│
┌────────────────────────▼────────────────────────────────────────────┐
│ ORCHESTRATION LAYER (Temporal.io) │
│ - Event Sourcing (Canonical Data Model) │
│ - Saga Pattern (LIFO Compensation) │
│ - Semantic Caching (70% cost reduction) │
│ - MAN Mode (Human-in-the-loop for RED lane) │
└────────────────────────┬────────────────────────────────────────────┘
│
┌────────────────────────▼────────────────────────────────────────────┐
│ SECURITY LAYER (Guardian/Triforce) │
│ - Guardian heartbeats │
│ - Zero-trust device registry │
│ - Prompt injection defense │
│ - RLS policies │
│ - Audit logging │
└─────────────────────────────────────────────────────────────────────┘
G2. 可移植性原则
// ❌ BAD: Direct provider coupling
import { createClient } from '@supabase/supabase-js';
const data = await supabase.from('users').select('*');
// ✅ GOOD: Abstraction layer
// src/lib/database/interface.ts
interface Database {
query<T>(table: string, options: QueryOptions): Promise<T[]>;
}
// src/lib/database/supabase.ts
export const supabaseDatabase: Database = {
async query(table, options) {
const { data } = await supabase.from(table).select(options.select);
return data;
}
};
// src/lib/database/index.ts
import { supabaseDatabase } from './supabase';
export const database: Database = supabaseDatabase; // Swap here for migration
G3. 单一集成端口规则
所有外部系统调用都通过一个适配器模块:
src/lib/
├── supabase/ # Single port for Supabase
│ ├── index.ts # Re-exports
│ ├── auth.ts # Auth methods
│ ├── database.ts # Query methods
│ └── storage.ts # Storage methods
├── web3/ # Single port for Web3
│ ├── index.ts
│ ├── wallet.ts
│ └── contracts.ts
└── omnilink/ # Single port for OmniLink orchestration
├── index.ts
└── events.ts
H 节:应用专属模式
H1. OmniDash(导航 UI)
// Revolutionary icon-based navigation
// Location: src/components/OmniDashNavIconButton.tsx
// Pattern: Zero-overlap flexbox layout
<nav className="flex items-center justify-between">
<OmniDashNavIconButton icon={Home} label="Dashboard" to="/" />
<OmniDashNavIconButton icon={Settings} label="Settings" to="/settings" />
</nav>
// Mobile: Bottom tabs
// Desktop: Side navigation with tooltips
H2. Guardian/Triforce(安全)
// Guardian heartbeat pattern
// Location: src/guardian/heartbeat.ts
import { startHeartbeat, getStatus } from '@/guardian/heartbeat';
// Start on app mount
useEffect(() => {
const cleanup = startHeartbeat('main-loop', 30000); // 30s interval
return cleanup;
}, []);
// Check status
const status = getStatus('main-loop');
// { loopName: 'main-loop', lastSeen: Date, ageMs: number, status: 'healthy' | 'stale' }
H3. Temporal 工作流模式
# orchestrator/workflows/agent_saga.py
@workflow.defn
class AgentSagaWorkflow:
@workflow.run
async def run(self, goal: Goal) -> GoalResult:
compensation_stack: List[CompensationStep] = []
try:
# Execute steps with compensation tracking
for step in plan.steps:
result = await workflow.execute_activity(
execute_tool,
step,
start_to_close_timeout=timedelta(seconds=30),
)
compensation_stack.append(step.compensation)
return GoalResult(status="completed", events=events)
except Exception as e:
# LIFO compensation (rollback)
for comp in reversed(compensation_stack):
await workflow.execute_activity(compensate, comp)
raise
防偏差协议
每调用 3 次工具后,进行验证:
□ Am I still solving the ORIGINAL task?
□ Have I introduced any provider lock-in?
□ Does this code have a test?
□ Is security considered (RLS, validation, audit)?
□ Would this pass ARMAGEDDON Level 6?
循环检测(触发时中止):
IF same error appears 3x → STOP, re-read Section B (Bug Protocol)
IF same code pattern rewritten 3x → STOP, extract to utility
IF task scope expanded 2x → STOP, confirm with user
IF file touched 5x without progress → STOP, architectural issue
失败预防(常见错误)
| 错误 | 预防措施 |
|---|---|
| 从错误的路径导入 | 使用 @/ 别名,并在 tsconfig 中验证 |
列表中缺少 key 属性 | 始终使用唯一且稳定的 ID,切勿使用索引 |
| 在 useEffect 中使用 async/await | 使用 IIFE 包装,或单独创建异步函数 |
| 直接修改状态 | 始终使用展开运算符:setState(prev => ({ ...prev, field: value })) |
| 缺少错误边界 | 包装路由级组件 |
| 在生产环境中使用 Console.log | 使用条件判断:import.meta.env.DEV && console.log() |
| URL 硬编码 | 使用环境变量:import.meta.env.VITE_API_URL |
| useEffect 中缺少清理逻辑 | 订阅或计时器始终要返回清理函数 |
命令参考(快速访问)
# Development
npm run dev # Start dev server
npm run build # Production build
npm run preview # Preview production build
# Quality
npm run typecheck # TypeScript check
npm run lint # ESLint
npm run lint:fix # Auto-fix lint issues
npm test # Run all tests
npm run test:watch # Watch mode
# Security
npm run security:audit # Dependency audit
npm run test:prompt-defense # Prompt injection tests
# Operations
npm run guardian:status # Check guardian loops
npm run zero-trust:baseline # Generate baseline metrics
npm run dr:test # Disaster recovery test (dry-run)
# Simulation
npm run sim:dry # Chaos simulation (safe)
npm run armageddon # Full test suite
成功标准
每项任务均在满足以下条件时完成:
✅ Code compiles: npm run build passes
✅ Types valid: npm run typecheck passes
✅ Tests pass: npm test passes
✅ Security clean: npm run security:audit clean
✅ No drift: Original task accomplished
✅ Documented: CHANGELOG updated if applicable
✅ Portable: No new vendor lock-in introduced
技能版本:1.0.0 上次更新:2026-01-20 维护方:APEX Business Systems Engineering 许可证:专有 — APEX Business Systems Ltd. Edmonton, AB, Canada
评论
支持 Markdown