mcpField
A
apex-dev

apex-dev

github.com/apexbusiness-systems開発564 回インストール14 週間前に更新
リポジトリ

apex-dev について

APEXエコシステムの開発向けスキルで、機能開発、デバッグ、性能改善、セキュリティ、テスト、デプロイの手順を提供します。APEXのモジュール規約や設計パターン、検証チェックリストを軸にしています。

主な機能

  1. 01APEXモジュールの開発規約
  2. 02体系的なデバッグと原因修正
  3. 03性能最適化パターン
  4. 04セキュリティとリスク分類の指針
  5. 05ARMAGEDDONテスト手順
  6. 06デプロイと設計のチェックリスト

活用シーン

  1. 01APEXアプリケーションの機能実装
  2. 02APEXプロジェクトのコード問題の調査
  3. 03セキュリティ、テスト、デプロイ準備の確認

インストール

コマンドをコピーしてターミナルで実行します。

$npx skills add https://github.com/apexbusiness-systems/apex-omnihub --skill apex-dev

インストール後、Claude Code で/apex-devを入力して読み込まれたか確認します。

同梱ファイル

SKILL.md と一緒にインストールされる参考資料やスクリプト。

architecture-deep-dive.md
drift-check.py
LICENSE
README.md
security-protocols.md
testing-patterns.md
verify-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. フックのテンプレート
// 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:バグ解決プロトコル

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 のバグパターン(事前対策済み)
症状根本原因修正パターン
「undefined のプロパティを読み取れません」Supabase のレスポンスに null チェックがないdata?.property ?? fallback
無限の再レンダリングuseEffect に依存関係が不足している依存関係を追加するか、useCallback を使用する
ミューテーション後にデータが古いままReact Query のキャッシュが無効化されていないqueryClient.invalidateQueries(['key'])
認証トークンの有効期限切れセッションの更新がトリガーされていない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 モード(手動承認ノード)の統合

エージェントのアクションのリスク分類:

レーン動作ツールの例
GREEN自動実行search_database、read_record、get_config
YELLOW実行 + 監査ログ不明なツール、リスクの高いパラメーターが1つ
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. 単一統合ポートのルール

すべての外部システム呼び出しは、1つのアダプターモジュールを経由します。

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 でラップするか、別の非同期関数を使用します
state を直接変更する必ずスプレッド構文を使用します: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

コメント