apex-dev
Compare original and translation side by side
🇺🇸
Original
English🇨🇳
Translation
ChineseAPEX-DEV: Omniscient Development Skill
APEX-DEV: 全知型开发技能
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.
使命: 让任何大语言模型(LLM)都能为APEX生态系统生成企业级、零偏差、一次性成功的代码。
理念: "智能设计" —— 所有输出均具备确定性、安全性、可移植性,且可直接投入生产。
INPUT/OUTPUT CONTRACT
输入/输出契约
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
输入: 涉及APEX生态系统(OmniHub、TradeLine、aSpiral、OmniDash等)的任务描述
输出: 可投入生产的代码、架构决策或修复方案,附带验证步骤
成功标准: 代码通过语法检查、类型校验及相关ARMAGEDDON测试套件
SYNTHETIC MEMORY ANCHOR
合成内存锚点
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.
执行任何操作前,请先内化以下不变规则:
┌─────────────────────────────────────────────────────────────────────┐
│ 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次工具或切换上下文后,重新阅读此锚点。
DECISION TREE (Entry Point)
决策树(入口点)
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你当前要执行的操作是?
构建新功能? → 章节A:功能开发
修复Bug? → 章节B:Bug修复流程
性能优化? → 章节C:性能工程
安全加固? → 章节D:安全防护
编写测试? → 章节E:ARMAGEDDON测试流程
部署/DevOps? → 章节F:部署与运维
架构决策? → 章节G:架构模式
针对特定应用开发? → 章节H:应用专属模式SECTION A: FEATURE DEVELOPMENT
章节A:功能开发
A1. Pre-Flight Checklist
A1. 前置检查清单
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编写任何代码前,请完成以下检查:
□ 确定目标模块(OmniDash | OmniConnect | OmniLink | Guardian | Edge)
□ 查看该模块现有实现模式(避免重复造轮子)
□ 确认抽象层已存在(禁止直接调用供应商接口)
□ 确定测试策略(单元测试 + 集成测试 + 混沌测试)
□ 加载相关类型定义A2. File Placement Decision Tree
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/UI组件?
├─ 跨应用共享 → src/components/
├─ 页面专属 → src/pages/{PageName}/components/
└─ shadcn基础组件 → src/components/ui/
业务逻辑?
├─ API调用 → src/lib/api/
├─ 状态管理 → src/contexts/ 或 src/stores/
├─ 工具函数 → src/lib/utils/
└─ 安全相关 → src/security/
后端代码?
├─ Edge函数 → supabase/functions/{name}/
├─ 工作流 → orchestrator/workflows/
├─ 活动 → orchestrator/activities/
└─ 数据库迁移 → supabase/migrations/
测试代码?
├─ 单元测试 → tests/{module}/
├─ 端到端测试 → tests/e2e/
├─ 混沌测试 → tests/chaos/
└─ 安全测试 → tests/prompt-defense/A3. Component Template (React + TypeScript)
A3. 组件模板(React + TypeScript)
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}';typescript
// 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}';A4. Hook Template
A4. Hook模板
typescript
// 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 };
}typescript
// 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 };
}SECTION B: BUG RESOLUTION PROTOCOL
章节B:Bug修复流程
B1. Root Cause Analysis (Mandatory Steps)
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 comment1. 复现问题 → 获取精确步骤、输入、预期结果与实际结果
2. 隔离问题 → 定位触发Bug的最小代码路径
3. 追踪数据流 → 从输入到故障点的完整数据流
4. 确定根因 → 明确根本原因(而非表面症状)
5. 修复问题 → 从根因处修复,而非针对症状
6. 验证修复 → 回归测试并加入ARMAGEDDON测试套件
7. 文档更新 → 更新CHANGELOG,添加测试用例注释B2. Common APEX Bug Patterns (Pre-empted)
B2. 常见APEX Bug模式(预定义)
| Symptom | Root Cause | Fix Pattern |
|---|---|---|
| "Cannot read property of undefined" | Missing null check on Supabase response | |
| Infinite re-render | Missing dependency in useEffect | Add dep or use useCallback |
| Stale data after mutation | React Query cache not invalidated | |
| 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 |
| Guardian heartbeat stale | Loop not started | Verify |
| 症状 | 根因 | 修复模式 |
|---|---|---|
| "Cannot read property of undefined" | Supabase响应未做空值检查 | |
| 无限重渲染 | useEffect依赖项缺失 | 添加依赖项或使用useCallback |
| 数据变更后数据陈旧 | React Query缓存未失效 | |
| 认证令牌过期 | 未触发会话刷新 | 检查AuthContext刷新逻辑 |
| Edge函数类型错误 | Deno与Node类型不匹配 | 使用Supabase Edge Function类型定义 |
| RLS策略拦截 | 策略条件错误 | 检查 |
| Guardian心跳停滞 | 未启动循环 | 验证 |
B3. Debug Command Sequence
B3. 调试命令序列
bash
undefinedbash
undefined1. Check build health
1. 检查构建健康状态
npm run build 2>&1 | head -50
npm run build 2>&1 | head -50
2. Run type check
2. 执行类型检查
npm run typecheck
npm run typecheck
3. Run relevant test battery
3. 运行相关测试套件
npm test -- --grep "{module}"
npm test -- --grep "{module}"
4. Check Guardian status
4. 检查Guardian状态
npm run guardian:status
npm run guardian:status
5. Verify security posture
5. 验证安全状态
npm run security:audit
npm run security:audit
6. Check for console errors in dev
6. 检查开发环境控制台错误
npm run dev 2>&1 | grep -i error
---npm run dev 2>&1 | grep -i error
---SECTION C: PERFORMANCE ENGINEERING
章节C:性能工程
C1. Performance Targets (ARMAGEDDON-Verified)
C1. 性能指标(已通过ARMAGEDDON验证)
| 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+ ✓ |
| 指标 | 目标值 | 当前值 |
|---|---|---|
| API响应时间(p95) | <100ms | <10ms ✓ |
| 数据库查询时间(p95) | <500ms | <20ms ✓ |
| 状态更新时间 | <100ms | <5ms ✓ |
| 并发用户数 | 100+ | 100+ ✓ |
| WebSocket消息数/秒 | 1000+ | 1000+ ✓ |
C2. Optimization Decision Tree
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 cleanupAPI调用缓慢?
├─ 添加React Query缓存 → staleTime: 5 * 60 * 1000
├─ 检查N+1查询问题 → 使用Supabase .select('*, relation(*)')
└─ 添加数据库索引 → supabase/migrations/
渲染缓慢?
├─ 为组件添加memo()
├─ 对复杂计算使用useMemo/useCallback
└─ 使用React.lazy + Suspense实现懒加载
内存泄漏?
├─ 检查useEffect清理逻辑
├─ 验证事件监听器是否移除
└─ 检查定时器/循环是否清理C3. React Query Pattern (Standard)
C3. React Query标准模式
typescript
// 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'] });
},
});
}typescript
// 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'] });
},
});
}SECTION D: SECURITY POSTURE
章节D:安全防护
D1. Security Invariants (NEVER Violate)
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❌ 绝对禁止提交敏感信息(API密钥、令牌、密码)
❌ 绝对禁止信任未验证的用户输入
❌ 绝对禁止绕过RLS策略
❌ 绝对禁止执行来自用户输入的原生SQL
❌ 绝对禁止关闭CSRF保护
❌ 绝对禁止在生产环境日志中记录个人可识别信息(PII)
✅ 始终使用参数化查询
✅ 始终使用Zod schema进行验证
✅ 始终使用RLS实现行级访问控制
✅ 始终记录安全事件审计日志
✅ 始终为关键循环使用Guardian心跳D2. MAN Mode (Manual Approval Node) Integration
D2. MAN模式(人工审批节点)集成
Risk classification for agent actions:
| Lane | Behavior | Tool Examples |
|---|---|---|
| GREEN | Auto-execute | |
| YELLOW | Execute + Audit Log | Unknown tools, single high-risk param |
| RED | Isolate + Human Approval | |
| BLOCKED | Never Execute | |
typescript
// 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 };
}代理操作的风险分类:
| 等级 | 行为 | 工具示例 |
|---|---|---|
| 绿色 | 自动执行 | |
| 黄色 | 执行并记录审计日志 | 未知工具、单一高风险参数 |
| 红色 | 隔离并等待人工审批 | |
| 阻塞 | 绝对禁止执行 | |
typescript
// 对高风险操作使用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 };
}D3. Prompt Injection Defense
D3. 提示注入防御
typescript
// 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;
}typescript
// 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;
}D4. Zero-Trust Device Registry
D4. 零信任设备注册表
typescript
// 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
}typescript
// 在每次敏感操作时验证设备
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('设备未被信任');
}
// 继续执行操作
}SECTION E: ARMAGEDDON TEST PROTOCOL
章节E:ARMAGEDDON测试流程
E1. Test Battery Structure
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 moduletests/
├── 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}/ # 按模块划分的单元测试E2. Test Template (Vitest)
E2. 测试模板(Vitest)
typescript
// 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');
});
});typescript
// tests/{module}/{feature}.spec.ts
import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest';
describe('{Feature}', () => {
beforeEach(() => {
vi.clearAllMocks();
});
afterEach(() => {
vi.restoreAllMocks();
});
it('当{条件}时,应{预期行为}', async () => {
// 准备测试数据
const input = { /* 测试数据 */ };
// 执行测试
const result = await featureUnderTest(input);
// 断言结果
expect(result).toMatchObject({ /* 预期结果 */ });
});
it('当{错误条件}时,应处理错误', async () => {
// 准备测试数据
vi.spyOn(dependency, 'method').mockRejectedValue(new Error('fail'));
// 执行测试并断言
await expect(featureUnderTest({})).rejects.toThrow('fail');
});
});E3. Test Commands
E3. 测试命令
bash
undefinedbash
undefinedRun all tests
运行所有测试
npm test
npm test
Run specific battery
运行指定测试套件
npm test -- --grep "chaos"
npm test -- --grep "chaos"
Run prompt defense tests
运行提示注入防御测试
npm run test:prompt-defense
npm run test:prompt-defense
Run chaos simulation (CI-safe dry run)
运行混沌模拟(CI安全空跑)
npm run sim:dry
npm run sim:dry
Run E2E (requires server)
运行端到端测试(需要启动服务器)
npm run test:e2e
npm run test:e2e
Full ARMAGEDDON suite
运行完整ARMAGEDDON测试套件
npm run armageddon
---npm run armageddon
---SECTION F: DEPLOYMENT & OPS
章节F:部署与运维
F1. Deployment Checklist
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□ 构建通过:npm run build
□ 类型检查通过:npm run typecheck
□ 所有测试通过:npm test
□ 安全审计无问题:npm run security:audit
□ 生产代码中无console.log
□ 环境变量已文档化
□ 回滚计划已文档化F2. Environment Variables (Required)
F2. 环境变量(必填)
bash
undefinedbash
undefined.env.example (NEVER commit actual values)
.env.example(绝对禁止提交实际值)
VITE_SUPABASE_URL=https://xxx.supabase.co
VITE_SUPABASE_PUBLISHABLE_KEY=eyJ...
VITE_SUPABASE_URL=https://xxx.supabase.co
VITE_SUPABASE_PUBLISHABLE_KEY=eyJ...
Optional
可选
VITE_SENTRY_DSN=https://xxx@sentry.io/xxx
undefinedVITE_SENTRY_DSN=https://xxx@sentry.io/xxx
undefinedF3. Rollback Protocol
F3. 回滚流程
bash
undefinedbash
undefined1. Identify failing deployment
1. 定位失败的部署
vercel ls --prod
vercel ls --prod
2. Rollback to previous
2. 回滚到上一版本
vercel rollback <deployment-url>
vercel rollback <deployment-url>
3. Verify rollback
3. 验证回滚结果
curl -I https://apexomnihub.icu/health
curl -I https://apexomnihub.icu/health
4. Post-mortem within 24h
4. 24小时内完成事后分析
---
---SECTION G: ARCHITECTURE PATTERNS
章节G:架构模式
G1. Core Architecture Layers
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 │
└─────────────────────────────────────────────────────────────────────┘┌─────────────────────────────────────────────────────────────────────┐
│ 表现层(React + shadcn UI) │
│ - OmniDash(导航UI) │
│ - 页面(路由级组件) │
│ - 组件(可复用UI) │
└────────────────────────┬────────────────────────────────────────────┘
│
┌────────────────────────▼────────────────────────────────────────────┐
│ 应用层(Hooks + Context + React Query) │
│ - AuthContext(会话管理) │
│ - useQuery/useMutation(数据获取) │
│ - 业务逻辑Hooks │
└────────────────────────┬────────────────────────────────────────────┘
│
┌────────────────────────▼────────────────────────────────────────────┐
│ 集成层(适配器 - 单一端口规则) │
│ - Supabase适配器(认证、数据库、存储) │
│ - OmniLink适配器(跨应用编排) │
│ - Web3适配器(钱包、合约) │
└────────────────────────┬────────────────────────────────────────────┘
│
┌────────────────────────▼────────────────────────────────────────────┐
│ 编排层(Temporal.io) │
│ - 事件溯源(规范数据模型) │
│ - Saga模式(后进先出补偿) │
│ - 语义缓存(降低70%成本) │
│ - MAN模式(红色操作需人工介入) │
└────────────────────────┬────────────────────────────────────────────┘
│
┌────────────────────────▼────────────────────────────────────────────┐
│ 安全层(Guardian/Triforce) │
│ - Guardian心跳 │
│ - 零信任设备注册表 │
│ - 提示注入防御 │
│ - RLS策略 │
│ - 审计日志 │
└─────────────────────────────────────────────────────────────────────┘G2. Portability Principle
G2. 可移植性原则
typescript
// ❌ 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 migrationtypescript
// ❌ 不良实践:直接耦合供应商
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; // 迁移时仅需替换此处G3. Single Integration Port Rule
G3. 单一集成端口规则
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所有外部系统调用必须通过唯一的适配器模块:
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.tsSECTION H: APP-SPECIFIC PATTERNS
章节H:应用专属模式
H1. OmniDash (Navigation UI)
H1. OmniDash(导航UI)
typescript
// 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 tooltipstypescript
// 革命性的图标式导航
// 位置:src/components/OmniDashNavIconButton.tsx
// 模式:无重叠弹性布局
<nav className="flex items-center justify-between">
<OmniDashNavIconButton icon={Home} label="仪表盘" to="/" />
<OmniDashNavIconButton icon={Settings} label="设置" to="/settings" />
</nav>
// 移动端:底部标签栏
// 桌面端:带提示的侧边导航H2. Guardian/Triforce (Security)
H2. Guardian/Triforce(安全)
typescript
// 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' }typescript
// 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' }H3. Temporal Workflow Pattern
H3. Temporal工作流模式
python
undefinedpython
undefinedorchestrator/workflows/agent_saga.py
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
---@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:
# 后进先出补偿(回滚)
for comp in reversed(compensation_stack):
await workflow.execute_activity(compensate, comp)
raise
---ANTI-DRIFT PROTOCOL
防偏差协议
Every 3 Tool Calls, Verify:
每调用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?□ 我是否仍在解决最初的任务?
□ 是否引入了供应商锁定?
□ 代码是否有对应的测试用例?
□ 是否考虑了安全因素(RLS、验证、审计)?
□ 是否能通过ARMAGEDDON Level 6测试?Loop Detection (ABORT if triggered):
循环检测(触发则终止):
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若同一错误出现3次 → 停止操作,重新阅读章节B(Bug修复流程)
若同一代码模式重写3次 → 停止操作,提取为工具函数
若任务范围扩大2次 → 停止操作,与用户确认
若同一文件修改5次仍无进展 → 停止操作,排查架构问题FAILURE PRE-EMPTION (Common Mistakes)
故障预排查(常见错误)
| Mistake | Prevention |
|---|---|
| Importing from wrong path | Use |
Missing | Always use unique stable ID, never index |
| Async/await in useEffect | Wrap in IIFE or use separate async function |
| Direct state mutation | Always spread: |
| Missing error boundary | Wrap route-level components |
| Console.log in production | Use conditional: |
| Hardcoded URLs | Use env variables: |
| Missing cleanup in useEffect | Always return cleanup function for subscriptions/timers |
| 错误 | 预防措施 |
|---|---|
| 导入路径错误 | 使用 |
列表中缺少 | 始终使用唯一稳定ID,禁止使用索引 |
| useEffect中使用async/await | 包裹在立即执行函数中或使用单独的异步函数 |
| 直接修改状态 | 始终使用扩展运算符: |
| 缺少错误边界 | 包裹路由级组件 |
| 生产代码中存在console.log | 使用条件判断: |
| 硬编码URL | 使用环境变量: |
| useEffect中未清理 | 始终返回清理函数以处理订阅/定时器 |
COMMAND REFERENCE (Quick Access)
命令参考(快速访问)
bash
undefinedbash
undefinedDevelopment
开发相关
npm run dev # Start dev server
npm run build # Production build
npm run preview # Preview production build
npm run dev # 启动开发服务器
npm run build # 生产构建
npm run preview # 预览生产构建结果
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
npm run typecheck # TypeScript类型检查
npm run lint # ESLint检查
npm run lint:fix # 自动修复ESLint问题
npm test # 运行所有测试
npm run test:watch # 监听模式运行测试
Security
安全相关
npm run security:audit # Dependency audit
npm run test:prompt-defense # Prompt injection tests
npm run security:audit # 依赖安全审计
npm run test:prompt-defense # 提示注入防御测试
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)
npm run guardian:status # 检查Guardian循环状态
npm run zero-trust:baseline # 生成零信任基准指标
npm run dr:test # 灾难恢复测试(空跑)
Simulation
模拟相关
npm run sim:dry # Chaos simulation (safe)
npm run armageddon # Full test suite
---npm run sim:dry # 混沌模拟(安全模式)
npm run armageddon # 运行完整测试套件
---SUCCESS CRITERIA
成功标准
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 introducedSkill Version: 1.0.0
Last Updated: 2026-01-20
Maintained By: APEX Business Systems Engineering
License: Proprietary - APEX Business Systems Ltd. Edmonton, AB, Canada
任务完成的标志:
✅ 代码编译通过: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