重要前提
安装AI Skills的关键前提是:必须科学上网,且开启TUN模式,这一点至关重要,直接决定安装能否顺利完成,在此郑重提醒三遍:科学上网,科学上网,科学上网。查看完整安装教程 →
apex-dev by apexbusiness-systems/apex-omnihub
npx skills add https://github.com/apexbusiness-systems/apex-omnihub --skill apex-dev使命:使任何大型语言模型都能为 APEX 生态系统生成企业级、零漂移、一次成功的代码。
理念:"智能设计" —— 每个输出都是确定性的、安全的、可移植的且可直接用于生产环境的。
输入:引用 APEX 生态系统(OmniHub、TradeLine、aSpiral、OmniDash 等)的任务描述 输出:可直接用于生产环境的代码、架构决策或附带验证步骤的修复方案 成功标准:代码通过代码检查、类型检查以及相关的 ARMAGEDDON 测试套件
在执行任何操作之前,请内化以下不变式:
┌─────────────────────────────────────────────────────────────────────┐
│ APEX 生态系统真值表(加载到工作内存中) │
├─────────────────────────────────────────────────────────────────────┤
│ 平台: APEX OmniHub ("Intelligence Designed") │
│ 域名: apexomnihub.icu │
│ 核心价值: 通用编排(Web2 ↔ Web3 语义桥接) │
│ 技术栈: React 18 + Vite + TypeScript + Tailwind + shadcn UI │
│ 后端: Supabase(认证、存储、边缘函数、Postgres) │
│ 编排器: Temporal.io(事件溯源 + Saga 模式) │
│ 安全: Guardian/Triforce + MAN 模式 + 零信任 + RLS │
│ 测试套件: ARMAGEDDON(265 项测试,100% 通过,第 6 级自适应) │
│ 不可协商: 无供应商锁定、无漂移、无循环、无密钥泄露 │
└─────────────────────────────────────────────────────────────────────┘
广告位招租
在这里展示您的产品或服务
触达数万 AI 开发者,精准高效
漂移预防:每进行 3 次工具调用或上下文切换后,重新阅读此锚点。
您正在做什么?
构建新功能? → 章节 A:功能开发
修复错误? → 章节 B:错误解决协议
优化性能? → 章节 C:性能工程
安全加固? → 章节 D:安全态势
编写测试? → 章节 E:ARMAGEDDON 测试协议
部署/运维? → 章节 F:部署与运维
架构决策? → 章节 G:架构模式
处理特定应用? → 章节 H:应用特定模式
在编写任何代码之前:
□ 确定目标模块(OmniDash | OmniConnect | OmniLink | Guardian | Edge)
□ 检查该模块中的现有模式(不要重新发明轮子)
□ 验证抽象层是否存在(不直接调用供应商接口)
□ 确认测试策略(单元 + 集成 + 混沌)
□ 加载相关的类型定义
UI 组件?
├─ 跨应用共享 → src/components/
├─ 页面特定 → src/pages/{PageName}/components/
└─ shadcn 基础组件 → src/components/ui/
业务逻辑?
├─ API 调用 → src/lib/api/
├─ 状态管理 → src/contexts/ 或 src/stores/
├─ 工具函数 → src/lib/utils/
└─ 安全相关 → src/security/
后端?
├─ 边缘函数 → supabase/functions/{name}/
├─ 工作流 → orchestrator/workflows/
├─ 活动 → orchestrator/activities/
└─ 数据库迁移 → supabase/migrations/
测试?
├─ 单元测试 → tests/{module}/
├─ 端到端测试 → tests/e2e/
├─ 混沌测试 → tests/chaos/
└─ 安全测试 → tests/prompt-defense/
// src/components/{ComponentName}.tsx
import { FC, memo } from 'react';
import { cn } from '@/lib/utils';
interface {ComponentName}Props {
/** 必需:描述用途 */
requiredProp: string;
/** 可选:描述默认行为 */
optionalProp?: boolean;
className?: string;
}
/**
* {ComponentName} - 单行描述
* @example <{ComponentName} requiredProp="value" />
*/
export const {ComponentName}: FC<{ComponentName}Props> = memo(({
requiredProp,
optionalProp = false,
className,
}) => {
return (
<div className={cn('base-styles', className)}>
{/* 实现 */}
</div>
);
});
{ComponentName}.displayName = '{ComponentName}';
// 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);
// 在组件卸载时清理(防止内存泄漏)
useEffect(() => {
return () => {
// 清理定时器、订阅等
};
}, []);
return { value, setValue, isLoading, error };
}
1. 复现 → 获取确切的步骤、输入、预期与实际结果
2. 隔离 → 识别触发错误的最小代码路径
3. 追踪 → 从输入到失败点跟踪数据流
4. 识别 → 命名根本原因(而非症状)
5. 修复 → 在根源处修补,而非症状处
6. 验证 → 回归测试 + 添加到 ARMAGEDDON 套件
7. 记录 → 更新 CHANGELOG,添加测试用例注释
| 症状 | 根本原因 | 修复模式 |
|---|---|---|
| "无法读取未定义的属性" | Supabase 响应缺少空值检查 | data?.property ?? fallback |
| 无限重新渲染 | useEffect 中缺少依赖项 | 添加依赖项或使用 useCallback |
| 变更后数据陈旧 | React Query 缓存未失效 | queryClient.invalidateQueries(['key']) |
| 认证令牌过期 | 会话刷新未触发 | 检查 AuthContext 刷新逻辑 |
| 边缘函数中的类型错误 | Deno 与 Node 类型不匹配 | 使用 Supabase 边缘函数类型 |
| RLS 策略阻止 | 策略条件错误 | 检查 auth.uid() 与 user_id |
| Guardian 心跳陈旧 | 循环未启动 | 验证 npm run guardian:status |
# 1. 检查构建健康状况
npm run build 2>&1 | head -50
# 2. 运行类型检查
npm run typecheck
# 3. 运行相关测试套件
npm test -- --grep "{module}"
# 4. 检查 Guardian 状态
npm run guardian:status
# 5. 验证安全态势
npm run security:audit
# 6. 在开发环境中检查控制台错误
npm run dev 2>&1 | grep -i error
| 指标 | 目标 | 当前 |
|---|---|---|
| API 响应(p95) | <100ms | <10ms ✓ |
| 数据库查询(p95) | <500ms | <20ms ✓ |
| 状态更新 | <100ms | <5ms ✓ |
| 并发用户数 | 100+ | 100+ ✓ |
| WebSocket 消息数/秒 | 1000+ | 1000+ ✓ |
API 调用慢?
├─ 添加 React Query 缓存 → staleTime: 5 * 60 * 1000
├─ 检查 N+1 查询 → 使用 Supabase .select('*, relation(*)')
└─ 添加索引 → supabase/migrations/
渲染慢?
├─ 为组件添加 memo()
├─ 对昂贵计算使用 useMemo/useCallback
└─ 使用 React.lazy + Suspense 进行懒加载
内存泄漏?
├─ 检查 useEffect 清理
├─ 验证事件监听器移除
└─ 检查定时器/间隔清理
// 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 分钟
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'] });
},
});
}
❌ 永不提交密钥(API 密钥、令牌、密码)
❌ 永不未经验证就信任用户输入
❌ 永不绕过 RLS 策略
❌ 永不执行来自用户输入的原始 SQL
❌ 永不禁用 CSRF 保护
❌ 永不在生产环境中将 PII 记录到控制台
✅ 始终使用参数化查询
✅ 始终使用 Zod 模式进行验证
✅ 始终使用 RLS 进行行级访问控制
✅ 始终审计记录安全事件
✅ 始终对关键循环使用 Guardian 心跳
代理操作的风险分类:
| 通道 | 行为 | 工具示例 |
|---|---|---|
| 绿色 | 自动执行 | search_database, read_record, get_config |
| 黄色 | 执行 + 审计日志 | 未知工具,单个高风险参数 |
| 红色 | 隔离 + 人工审批 | delete_record, transfer_funds, send_email |
| 阻止 | 永不执行 | execute_sql_raw, shell_execute |
// 对高风险操作使用 MAN 模式
import { riskTriage } from '@/orchestrator/policies/man_policy';
const result = riskTriage({
tool: 'delete_record',
params: { id: recordId },
context: { userId, sessionId }
});
if (result.lane === 'RED') {
// 隔离并等待人工审批
await createManTask(result);
return { status: 'isolated', awaiting_approval: true };
}
// src/security/promptDefense.ts
import { evaluatePrompt } from './promptDefenseConfig';
// 始终清理 LLM 输入
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('检测到无效输入');
}
return result.sanitized;
}
// 在每次敏感操作时验证设备
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('设备不受信任');
}
// 继续执行操作
}
tests/
├── chaos/ # 混沌工程测试
│ ├── battery.spec.ts # 核心混沌测试套件(21 项测试)
│ ├── memory-stress.spec.ts # 内存泄漏检测(7 项测试)
│ └── integration-stress.spec.ts # 集成压力测试(9 项测试)
├── e2e/ # 端到端测试
│ ├── enterprise-workflows.spec.ts # 业务流程(20 项测试)
│ ├── errorHandling.spec.ts # 错误场景(8 项测试)
│ └── security.spec.ts # 安全测试(13 项测试)
├── prompt-defense/ # 提示注入测试
│ └── real-injection.spec.ts # 真实世界攻击
└── {module}/ # 每个模块的单元测试
// tests/{module}/{feature}.spec.ts
import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest';
describe('{Feature}', () => {
beforeEach(() => {
vi.clearAllMocks();
});
afterEach(() => {
vi.restoreAllMocks();
});
it('当 {condition} 时,应该 {expected behavior}', async () => {
// 准备
const input = { /* 测试数据 */ };
// 执行
const result = await featureUnderTest(input);
// 断言
expect(result).toMatchObject({ /* 预期结果 */ });
});
it('当 {error condition} 时,应该处理错误', async () => {
// 准备
vi.spyOn(dependency, 'method').mockRejectedValue(new Error('fail'));
// 执行 & 断言
await expect(featureUnderTest({})).rejects.toThrow('fail');
});
});
# 运行所有测试
npm test
# 运行特定测试套件
npm test -- --grep "chaos"
# 运行提示注入防御测试
npm run test:prompt-defense
# 运行混沌模拟(CI 安全的干运行)
npm run sim:dry
# 运行端到端测试(需要服务器)
npm run test:e2e
# 完整的 ARMAGEDDON 套件
npm run armageddon
□ 构建通过:npm run build
□ 类型检查通过:npm run typecheck
□ 所有测试通过:npm test
□ 安全审计干净:npm run security:audit
□ 生产代码中没有 console.log
□ 环境变量已记录
□ 回滚计划已记录
# .env.example(永不提交实际值)
VITE_SUPABASE_URL=https://xxx.supabase.co
VITE_SUPABASE_PUBLISHABLE_KEY=eyJ...
# 可选
VITE_SENTRY_DSN=https://xxx@sentry.io/xxx
# 1. 识别失败的部署
vercel ls --prod
# 2. 回滚到上一个版本
vercel rollback <deployment-url>
# 3. 验证回滚
curl -I https://apexomnihub.icu/health
# 4. 24 小时内进行事后分析
┌─────────────────────────────────────────────────────────────────────┐
│ 表示层(React + shadcn UI) │
│ - OmniDash(导航 UI) │
│ - 页面(路由级组件) │
│ - 组件(可复用的 UI) │
└────────────────────────┬────────────────────────────────────────────┘
│
┌────────────────────────▼────────────────────────────────────────────┐
│ 应用层(Hooks + Context + React Query) │
│ - AuthContext(会话管理) │
│ - useQuery/useMutation(数据获取) │
│ - 业务逻辑钩子 │
└────────────────────────┬────────────────────────────────────────────┘
│
┌────────────────────────▼────────────────────────────────────────────┐
│ 集成层(适配器 - 单一端口规则) │
│ - Supabase 适配器(认证、数据库、存储) │
│ - OmniLink 适配器(跨应用编排) │
│ - Web3 适配器(钱包、合约) │
└────────────────────────┬────────────────────────────────────────────┘
│
┌────────────────────────▼────────────────────────────────────────────┐
│ 编排层(Temporal.io) │
│ - 事件溯源(规范数据模型) │
│ - Saga 模式(LIFO 补偿) │
│ - 语义缓存(70% 成本降低) │
│ - MAN 模式(红色通道的人工介入) │
└────────────────────────┬────────────────────────────────────────────┘
│
┌────────────────────────▼────────────────────────────────────────────┐
│ 安全层(Guardian/Triforce) │
│ - Guardian 心跳 │
│ - 零信任设备注册表 │
│ - 提示注入防御 │
│ - RLS 策略 │
│ - 审计日志记录 │
└─────────────────────────────────────────────────────────────────────┘
// ❌ 错误:直接耦合供应商
import { createClient } from '@supabase/supabase-js';
const data = await supabase.from('users').select('*');
// ✅ 正确:抽象层
// 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; // 在此处切换以进行迁移
所有外部系统调用都通过一个适配器模块:
src/lib/
├── supabase/ # Supabase 的单一端口
│ ├── index.ts # 重新导出
│ ├── auth.ts # 认证方法
│ ├── database.ts # 查询方法
│ └── storage.ts # 存储方法
├── web3/ # Web3 的单一端口
│ ├── index.ts
│ ├── wallet.ts
│ └── contracts.ts
└── omnilink/ # OmniLink 编排的单一端口
├── index.ts
└── events.ts
// 革命性的基于图标的导航
// 位置:src/components/OmniDashNavIconButton.tsx
// 模式:零重叠的 flexbox 布局
<nav className="flex items-center justify-between">
<OmniDashNavIconButton icon={Home} label="仪表板" to="/" />
<OmniDashNavIconButton icon={Settings} label="设置" to="/settings" />
</nav>
// 移动端:底部标签栏
// 桌面端:带工具提示的侧边导航
// Guardian 心跳模式
// 位置:src/guardian/heartbeat.ts
import { startHeartbeat, getStatus } from '@/guardian/heartbeat';
// 在应用挂载时启动
useEffect(() => {
const cleanup = startHeartbeat('main-loop', 30000); // 30 秒间隔
return cleanup;
}, []);
// 检查状态
const status = getStatus('main-loop');
// { loopName: 'main-loop', lastSeen: Date, ageMs: number, status: 'healthy' | 'stale' }
# orchestrator/workflows/agent_saga.py
@workflow.defn
class AgentSagaWorkflow:
@workflow.run
async def run(self, goal: Goal) -> GoalResult:
compensation_stack: List[CompensationStep] = []
try:
# 执行步骤并跟踪补偿
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 补偿(回滚)
for comp in reversed(compensation_stack):
await workflow.execute_activity(compensate, comp)
raise
□ 我是否仍在解决**原始**任务?
□ 我是否引入了任何供应商锁定?
□ 这段代码有测试吗?
□ 是否考虑了安全性(RLS、验证、审计)?
□ 这能通过 ARMAGEDDON 第 6 级测试吗?
如果同一错误出现 3 次 → 停止,重新阅读章节 B(错误协议)
如果同一代码模式重写 3 次 → 停止,提取到工具函数
如果任务范围扩展 2 次 → 停止,向用户确认
如果文件被修改 5 次而无进展 → 停止,存在架构问题
| 错误 | 预防措施 |
|---|---|
| 从错误路径导入 | 使用 @/ 别名,在 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 中缺少清理 | 始终为订阅/定时器返回清理函数 |
# 开发
npm run dev # 启动开发服务器
npm run build # 生产构建
npm run preview # 预览生产构建
# 质量
npm run typecheck # TypeScript 检查
npm run lint # ESLint
npm run lint:fix # 自动修复代码检查问题
npm test # 运行所有测试
npm run test:watch # 监视模式
# 安全
npm run security:audit # 依赖项审计
npm run test:prompt-defense # 提示注入防御测试
# 运维
npm run guardian:status # 检查 guardian 循环
npm run zero-trust:baseline # 生成基线指标
npm run dr:test # 灾难恢复测试(干运行)
# 模拟
npm run sim:dry # 混沌模拟(安全)
npm run armageddon # 完整测试套件
每个任务在以下情况下完成:
✅ 代码编译:npm run build 通过
✅ 类型有效:npm run typecheck 通过
✅ 测试通过:npm test 通过
✅ 安全干净:npm run security:audit 干净
✅ 无漂移:原始任务已完成
✅ 已记录:如果适用,已更新 CHANGELOG
✅ 可移植:未引入新的供应商锁定
技能版本 : 1.0.0 最后更新 : 2026-01-20 维护者 : APEX Business Systems Engineering 许可证 : 专有 - APEX Business Systems Ltd. Edmonton, AB, Canada
每周安装次数
45
代码仓库
GitHub 星标数
1
首次出现
2026年2月3日
安全审计
安装于
gemini-cli45
codex45
kimi-cli45
opencode44
antigravity44
claude-code44
Mission : Enable any LLM to produce enterprise-grade, zero-drift, first-pass success code for the APEX ecosystem.
Philosophy : "Intelligence Designed" — Every output is deterministic, secure, portable, and production-ready.
Input : Task description referencing APEX ecosystem (OmniHub, TradeLine, aSpiral, OmniDash, etc.) Output : Production-ready code, architecture decisions, or fixes with verification steps Success : Code passes lint, type-check, and relevant ARMAGEDDON test battery
Before ANY action, internalize these invariants:
┌─────────────────────────────────────────────────────────────────────┐
│ 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 │
└─────────────────────────────────────────────────────────────────────┘
DRIFT PREVENTION : Re-read this anchor every 3 tool calls or context switches.
What are you doing?
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
Before writing ANY code:
□ 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
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/
// 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}';
// 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 };
}
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
| Symptom | Root Cause | Fix Pattern |
|---|---|---|
| "Cannot read property of undefined" | Missing null check on Supabase response | data?.property ?? fallback |
| Infinite re-render | Missing dependency in useEffect | Add dep or use useCallback |
| Stale data after mutation | React Query cache not invalidated | queryClient.invalidateQueries(['key']) |
| Auth token expired | Session refresh not triggered | Check AuthContext refresh logic |
| Type error in Edge Function | Deno vs Node type mismatch | Use Supabase Edge Function types |
| RLS policy blocking | Policy condition wrong | Check auth.uid() vs |
# 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
| Metric | Target | Current |
|---|---|---|
| API Response (p95) | <100ms | <10ms ✓ |
| DB Query (p95) | <500ms | <20ms ✓ |
| State Update | <100ms | <5ms ✓ |
| Concurrent Users | 100+ | 100+ ✓ |
| WebSocket Messages/s | 1000+ | 1000+ ✓ |
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
// 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'] });
},
});
}
❌ 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
Risk classification for agent actions:
| Lane | Behavior | Tool Examples |
|---|---|---|
| GREEN | Auto-execute | search_database, read_record, get_config |
| YELLOW | Execute + Audit Log | Unknown tools, single high-risk param |
| RED | Isolate + Human Approval | delete_record, transfer_funds, send_email |
| BLOCKED | Never 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 };
}
// 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;
}
// 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
}
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
// 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');
});
});
# 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
□ 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
# .env.example (NEVER commit actual values)
VITE_SUPABASE_URL=https://xxx.supabase.co
VITE_SUPABASE_PUBLISHABLE_KEY=eyJ...
# Optional
VITE_SENTRY_DSN=https://xxx@sentry.io/xxx
# 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
┌─────────────────────────────────────────────────────────────────────┐
│ 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 │
└─────────────────────────────────────────────────────────────────────┘
// ❌ 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
All external system calls go through ONE adapter module:
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
// 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
// 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' }
# 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
□ 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
| Mistake | Prevention |
|---|---|
| Importing from wrong path | Use @/ alias, verify in tsconfig |
Missing key prop in lists | Always use unique stable ID, never index |
| Async/await in useEffect | Wrap in IIFE or use separate async function |
| Direct state mutation | Always spread: setState(prev => ({ ...prev, field: value })) |
| Missing error boundary | Wrap route-level components |
| Console.log in production | Use conditional: import.meta.env.DEV && console.log() |
| Hardcoded URLs | Use env variables: import.meta.env.VITE_API_URL |
# 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
Every task is complete when:
✅ 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
Skill Version : 1.0.0 Last Updated : 2026-01-20 Maintained By : APEX Business Systems Engineering License : Proprietary - APEX Business Systems Ltd. Edmonton, AB, Canada
Weekly Installs
45
Repository
GitHub Stars
1
First Seen
Feb 3, 2026
Security Audits
Gen Agent Trust HubPassSocketPassSnykWarn
Installed on
gemini-cli45
codex45
kimi-cli45
opencode44
antigravity44
claude-code44
Go 错误处理最佳实践:提升代码可靠性与可维护性
901 周安装
Marp幻灯片制作工具:7款专业主题模板,快速创建精美演示文稿
211 周安装
cc-skill-continuous-learning:Claude代码模板持续学习技能,提升开发效率与代码质量
211 周安装
World Labs:AI 驱动 3D 环境生成器,文本/图像一键创建逼真游戏世界
209 周安装
Instagram Graph API 使用指南:读取与发布内容,获取媒体和话题标签数据
208 周安装
Nansen Trading 命令行工具:Solana 和 Base 链上代币交易与报价执行指南
209 周安装
uni-app原生App打包指南:Android/iOS离线打包、签名配置与原生插件集成
45 周安装
user_id| Guardian heartbeat stale | Loop not started | Verify npm run guardian:status |
execute_sql_raw, shell_execute |
| Missing cleanup in useEffect | Always return cleanup function for subscriptions/timers |