MoAI Foundation Core Foundational principles and architectural patterns that power MoAI-ADK's AI-driven development workflow. Core Philosophy: Quality-first, domain-driven, modular, and efficient AI development through proven patterns and automated workflows. Quick Reference What is MoAI Foundation Core? Six essential principles that ensure quality, efficiency, and scalability in AI-powered development: 1. TRUST 5 Framework - Quality gate system (Tested, Readable, Unified, Secured, Trackable) 2. SPEC-First DDD - Specification-driven domain-driven development workflow 3. Delegation Patterns -…

)\nPASSWORD_MIN_LENGTH = 8\n\n@dataclass\nclass RegistrationResult:\n \"\"\"Result of user registration attempt.\"\"\"\n success: bool\n user: Optional[User]\n confirmation_sent: bool\n error: Optional[str] = None\n\ndef register_user(email: str, password: str) -> RegistrationResult:\n \"\"\"Register new user with email and password.\n\n Implements SPEC-001-REQ-01: User Registration (Ubiquitous)\n Behavior preserved from existing implementation.\n\n Args:\n email: User email adddess (must be valid format)\n password: User password (≥8 chars, mixed case, numbers, symbols)\n\n Returns:\n RegistrationResult with user data or error\n\n Raises:\n ValidationError: If email or password invalid\n \"\"\"\n if not EMAIL_REGEX.match(email):\n raise ValidationError(\"Invalid email format\")\n\n existing_user = User.query.filter_by(email=email).first()\n if existing_user:\n raise ValidationError(\"Email already registered\")\n\n if not _is_password_strong(password):\n raise ValidationError(\n \"Password must be ≥8 characters with mixed case, numbers, and symbols\"\n )\n\n password_hash = bcrypt.hashpw(\n password.encode('utf-8'),\n bcrypt.gensalt(rounds=12)\n ).decode('utf-8')\n\n user = User(email=email, password_hash=password_hash)\n db_session.add(user)\n db_session.commit()\n\n confirmation_sent = send_confirmation_email(user.email, user.id)\n\n return RegistrationResult(\n success=True,\n user=user,\n confirmation_sent=confirmation_sent\n )\n\ndef _is_password_strong(password: str) -> bool:\n \"\"\"Validate password strength.\"\"\"\n if len(password) \u003c PASSWORD_MIN_LENGTH:\n return False\n\n has_upper = any(c.isupper() for c in password)\n has_lower = any(c.islower() for c in password)\n has_digit = any(c.isdigit() for c in password)\n has_symbol = any(not c.isalnum() for c in password)\n\n return all([has_upper, has_lower, has_digit, has_symbol])\n```\n\n---\n\n## MFA Implementation Example\n\n```python\n# ANALYZE PHASE: Understand existing MFA behavior\ndef analyze_mfa_implementation():\n \"\"\"Document current MFA verification behavior for SPEC-002-REQ-03.\"\"\"\n # - Current code uses TOTP algorithm\n # - 30-second code window\n # - No rate limiting exists\n # - No expiry handling\n pass\n\n# PRESERVE PHASE: Create characterization tests\ndef test_mfa_verification_with_valid_code():\n \"\"\"SPEC-002-REQ-03: MFA verification happy path (characterization test).\"\"\"\n user = create_user_with_mfa_enabled()\n login_attempt = initiate_login(user.email, user.password)\n totp_code = get_pending_totp_code(user.id)\n\n result = verify_mfa(user.id, code=totp_code, timestamp=datetime.now())\n\n assert result.success is True\n assert result.token is not None\n assert result.mfa_verified is True\n\ndef test_mfa_verification_with_expired_code():\n \"\"\"SPEC-002-REQ-03: MFA code expiry (characterization test).\"\"\"\n user = create_user_with_mfa_enabled()\n totp_code = get_pending_totp_code(user.id)\n\n result = verify_mfa(\n user.id, code=totp_code,\n timestamp=datetime.now() + timedelta(minutes=6)\n )\n\n assert result.success is False\n assert result.error == \"Code expired\"\n\n# IMPROVE PHASE: Add rate limiting with behavior preservation\ndef test_mfa_rate_limiting():\n \"\"\"SPEC-002-REQ-03: Rate limiting after failed attempts (new requirement).\"\"\"\n user = create_user_with_mfa_enabled()\n\n for _ in range(3):\n verify_mfa(user.id, code=\"000000\")\n\n result = verify_mfa(user.id, code=\"123456\")\n\n assert result.success is False\n assert \"Too many failed attempts\" in result.error\n```\n\n---\n\n## Iterative SPEC Refinement\n\n```python\n# Initial SPEC (v1.0.0)\n# SPEC-003-REQ-01: File upload with size limit (10MB)\n\n# ANALYZE: Implementation reveals edge case\n# → User uploads 9.9MB file successfully\n# → But total storage exceeds user quota\n\n# Refined SPEC (v1.1.0)\n# SPEC-003-REQ-01: File upload with size and quota validation\n# - Single file limit: 10MB\n# - User quota limit: 100MB total\n# - Validation: Check both limits before accepting upload\n\n# PRESERVE: Characterization test for existing behavior\ndef test_file_upload_within_size_limit():\n \"\"\"SPEC-003-REQ-01: Existing behavior - size limit only.\"\"\"\n user = create_user(quota_limit_mb=100)\n result = upload_file(user, file_size_mb=9)\n assert result.success is True # Documents existing behavior\n\n# IMPROVE: Add quota validation while preserving existing checks\ndef test_file_upload_exceeds_quota():\n \"\"\"SPEC-003-REQ-01 v1.1.0: Quota validation (improvement).\"\"\"\n user = create_user(quota_limit_mb=100)\n upload_files(user, total_size_mb=95)\n\n result = upload_file(user, file_size_mb=8)\n\n assert result.success is False\n assert result.error == \"Upload would exceed storage quota\"\n```\n\n---\n\n## CI/CD Pipeline Integration\n\n```yaml\n# .github/workflows/spec-ddd-pipeline.yml\nname: SPEC-First DDD Pipeline\n\non:\n push:\n paths:\n - '.moai/specs/**'\n - 'src/**'\n - 'tests/**'\n\njobs:\n spec-validation:\n name: \"Phase 1: SPEC Validation\"\n runs-on: ubuntu-latest\n steps:\n - uses: actions/checkout@v4\n - name: Validate SPEC format\n run: python .moai/scripts/validate_spec.py\n - name: Check requirement traceability\n run: python .moai/scripts/check_traceability.py\n\n ddd-implementation:\n name: \"Phase 2: DDD Implementation\"\n needs: spec-validation\n runs-on: ubuntu-latest\n steps:\n - uses: actions/checkout@v4\n - name: Run characterization tests\n run: pytest tests/ -v --tb=short\n - name: Verify tests exist for all requirements\n run: python .moai/scripts/verify_test_coverage_mapping.py\n\n quality-gates:\n name: \"Phase 3: Quality Gates\"\n needs: ddd-implementation\n runs-on: ubuntu-latest\n steps:\n - uses: actions/checkout@v4\n - name: Run tests with coverage\n run: pytest --cov=src --cov-fail-under=85\n - name: Validate TRUST 5\n run: python .moai/scripts/validate_trust5.py\n```\n\n---\n\n## Works Well With\n\n- [spec-first-ddd.md](spec-first-ddd.md) - Main workflow overview\n- Canonical GEARS authoring guide: `.claude/skills/moai-workflow-spec/SKILL.md` § \"GEARS Format\" (current notation)\n- [spec-ears-format.md (legacy reference, deprecated — see GEARS Format guide)](spec-ears-format.md) - EARS patterns for legacy SPECs\n\n---\n\nVersion: 2.0.0\nLast Updated: 2026-01-17\n","content_type":"text/markdown; charset=utf-8","language":"markdown","size":9084,"content_sha256":"46ab0a7d108a8c6d57a2f9b712152fd1188706c14077463ae61b535395dd9a39"},{"filename":"modules/spec-ears-format.md","content":"# EARS Format Reference\n\nPurpose: Comprehensive guide to Easy Approach to Requirements Syntax (EARS) patterns for SPEC generation.\n\nVersion: 1.0.0\nLast Updated: 2026-01-06\nParent: [spec-first-ddd.md](spec-first-ddd.md)\n\n> **DEPRECATED in v3.0.0**: This document describes legacy EARS notation.\n>\n> For NEW SPECs, use GEARS notation per the [docs-site GEARS migration guide](https://adk.mo.ai.kr/en/workflow-commands/moai-plan/#gears-notation) (4-locale: en / ko / ja / zh).\n>\n> Backward-compatibility for legacy EARS REQs is supported for 6 months from v3.0.0 release. See `SPEC-V3R6-GEARS-MIGRATION-001` v0.2.0 (PR #1046) for the lint engine canonicalization that emits a `LegacyEARSKeyword` warning on residual `IF/THEN` modality in NEW SPECs.\n>\n> The canonical GEARS authoring guide lives in `.claude/skills/moai-workflow-spec/SKILL.md` \"GEARS Format\" section. This file is retained as legacy reference for the 6-month backward-compatibility window.\n\n---\n\n## EARS Pattern Overview\n\nEARS provides five requirement patterns for clear, unambiguous specifications:\n\n1. **Ubiquitous** - Always active requirements\n2. **Event-driven** - Triggered by specific events\n3. **State-driven** - Active during specific states\n4. **Unwanted** - Negative requirements (prevention)\n5. **Optional** - Nice-to-have features\n\n---\n\n## Pattern 1: Ubiquitous Requirements\n\nSyntax: `The system SHALL [action].`\n\nExample:\n```markdown\n### SPEC-001-REQ-01: User Registration (Ubiquitous)\nPattern: Ubiquitous\nStatement: The system SHALL register users with email and password validation.\n\nAcceptance Criteria:\n- Email format validated (RFC 5322)\n- Password strength: ≥8 chars, mixed case, numbers, symbols\n- Duplicate email rejected with clear error\n- Success returns user ID and confirmation email sent\n\nTest Coverage Target: ≥90%\n```\n\n---\n\n## Pattern 2: Event-Driven Requirements\n\nSyntax: `WHEN [event], the system SHALL [action].`\n\nExample:\n```markdown\n### SPEC-001-REQ-02: JWT Token Generation (Event-driven)\nPattern: Event-driven\nStatement: WHEN a user successfully authenticates, the system SHALL generate a JWT token with 1-hour expiry.\n\nAcceptance Criteria:\n- Token includes user ID, email, role claims\n- Token signed with RS256 algorithm\n- Expiry set to 1 hour from generation\n- Refresh token generated with 7-day expiry\n\nTest Coverage Target: ≥95%\n```\n\n---\n\n## Pattern 3: State-Driven Requirements\n\nSyntax: `WHILE [state], the system SHALL [action].`\n\nExample:\n```markdown\n### SPEC-001-REQ-03: Token Validation (State-driven)\nPattern: State-driven\nStatement: WHILE a request includes Authorization header, the system SHALL validate JWT token before processing.\n\nAcceptance Criteria:\n- Expired tokens rejected with 401 Unauthorized\n- Invalid signature rejected with 401 Unauthorized\n- Valid token extracts user claims successfully\n- Token blacklist checked (revoked tokens)\n\nTest Coverage Target: ≥95%\n```\n\n---\n\n## Pattern 4: Unwanted Requirements\n\nSyntax: `The system SHALL NOT [action].`\n\nExample:\n```markdown\n### SPEC-001-REQ-04: Weak Password Prevention (Unwanted)\nPattern: Unwanted\nStatement: The system SHALL NOT allow passwords from common password lists (top 10K).\n\nAcceptance Criteria:\n- Common passwords rejected (e.g., \"password123\")\n- Sequential patterns rejected (e.g., \"abc123\")\n- User-specific patterns rejected (e.g., email prefix)\n- Clear error message with improvement suggestions\n\nTest Coverage Target: ≥85%\n```\n\n---\n\n## Pattern 5: Optional Requirements\n\nSyntax: `WHERE [condition], the system SHOULD [action].`\n\nExample:\n```markdown\n### SPEC-001-REQ-05: OAuth2 Integration (Optional)\nPattern: Optional\nStatement: WHERE user chooses, the system SHOULD support OAuth2 authentication via Google and GitHub.\n\nAcceptance Criteria:\n- OAuth2 providers configurable\n- User can link multiple providers to one account\n- Provider-specific profile data merged\n- Graceful fallback if provider unavailable\n\nTest Coverage Target: ≥80%\n```\n\n---\n\n## Complex Requirement Example\n\nMulti-pattern requirements for complex scenarios:\n\n```markdown\n### SPEC-002-REQ-03: Multi-Factor Authentication (Event-driven + State-driven)\nPattern: Event-driven + State-driven\nStatement:\n- WHEN a user attempts login with MFA enabled (Event)\n- WHILE the MFA verification is pending (State)\n- The system SHALL send TOTP code and require verification within 5 minutes\n\nAcceptance Criteria:\n1. Event trigger: Login attempt detected\n2. State check: User has MFA enabled\n3. Action: Generate TOTP code (6 digits, 30s validity)\n4. Notification: Send code via SMS or email\n5. Verification: User submits code within 5 minutes\n6. Expiry: Code expires after 5 minutes\n7. Rate limiting: Max 3 failed attempts, then 15-minute lockout\n\nTest Scenarios:\n- Happy path: User submits valid code within time\n- Expired code: User submits code after 5 minutes\n- Invalid code: User submits incorrect code\n- Rate limit: User exceeds 3 failed attempts\n- Disabled MFA: User without MFA enabled\n```\n\n---\n\n## Complexity Analysis Template\n\n```yaml\n# .moai/specs/SPEC-001/complexity.yaml\ncomplexity_metrics:\n total_requirements: 5\n critical_requirements: 3\n\n complexity_breakdown:\n SPEC-001-REQ-01: Medium # Standard CRUD + validation\n SPEC-001-REQ-02: Medium # JWT library integration\n SPEC-001-REQ-03: High # Security validation logic\n SPEC-001-REQ-04: Low # Lookup validation\n SPEC-001-REQ-05: High # External API integration\n\n estimated_effort:\n development: 8 hours\n testing: 4 hours\n total: 12 hours\n\n risk_factors:\n - Security-critical functionality\n - External OAuth2 provider dependencies\n - Token expiry edge cases\n\n dependencies:\n - PyJWT library\n - bcrypt library\n - OAuth2 client libraries\n```\n\n---\n\n## Works Well With\n\n- [spec-first-ddd.md](spec-first-ddd.md) - Main workflow overview\n- [spec-ddd-implementation.md](spec-ddd-implementation.md) - DDD patterns\n\n---\n\nVersion: 1.0.0\nLast Updated: 2026-01-06\n","content_type":"text/markdown; charset=utf-8","language":"markdown","size":5934,"content_sha256":"3f29a915ca9fa7aefe18b8834d061a349dc9d90c74aa565a5da63fa9731ea670"},{"filename":"modules/spec-first-ddd.md","content":"# SPEC-First DDD - Specification-Driven Development\n\nPurpose: Specification-driven domain-driven development workflow ensuring clear requirements before implementation through GEARS format (current; EARS retained as legacy reference for 6-month backward-compat) and ANALYZE-PRESERVE-IMPROVE cycles.\n\nVersion: 3.0.0 (DDD Migration)\nLast Updated: 2026-01-17\n\n---\n\n## Quick Reference (30 seconds)\n\nSPEC-First DDD is MoAI-ADK's development methodology combining:\n\n1. SPEC Generation - GEARS format requirements (current; EARS as legacy reference) (/moai:1-plan)\n2. Domain-Driven Development - ANALYZE-PRESERVE-IMPROVE (/moai:2-run)\n3. Documentation Sync - Auto-generated docs (/moai:3-sync)\n\nThree-Phase Workflow:\n```\nPhase 1: SPEC → spec-builder → .moai/specs/SPEC-XXX/spec.md\nPhase 2: DDD → ddd-implementer → Code + Tests (≥85% coverage)\nPhase 3: Docs → docs-manager → API docs + diagrams\n```\n\nToken Budget: SPEC 30K | DDD 180K | Docs 40K | Total 250K\n\nKey Practice: Execute `/clear` after Phase 1 to save 45-50K tokens.\n\nGEARS Patterns (current notation):\n- Ubiquitous: The \u003csubject> shall \u003cbehavior>\n- Event-driven: When \u003cevent>, the \u003csubject> shall \u003cbehavior>\n- State-driven: While \u003cstate>, the \u003csubject> shall \u003cbehavior>\n- Where (capability gate): Where \u003ccapability or feature flag>, the \u003csubject> shall \u003cbehavior>\n- Event-detected (replaces the deprecated conditional modality): When \u003cundesired-condition-detected>, the \u003csubject> shall \u003cresponse>\n\nUnified compound clause: `[Where ...][While ...][When ...] The \u003csubject> shall \u003cbehavior>` — any subset of the three modifiers may chain. The `\u003csubject>` is generalized (any noun: system, component, service, agent, function, artifact).\n\nEARS Patterns (legacy reference, 6-month backward-compat — expires 2026-11-22):\n- Ubiquitous: System SHALL always...\n- Event-driven: WHEN \u003cevent>, system SHALL...\n- State-driven: WHILE \u003cstate>, system SHALL...\n- Unwanted: System SHALL NOT...\n- Optional: WHERE possible, system SHOULD...\n\nExtended Documentation:\n- Canonical GEARS authoring guide: `.claude/skills/moai-workflow-spec/SKILL.md` § \"GEARS Format\" (current)\n- [EARS Format Reference (legacy reference, deprecated — see GEARS Format guide)](spec-ears-format.md) - Detailed EARS patterns and examples for legacy SPECs\n- [DDD Implementation](spec-ddd-implementation.md) - ANALYZE-PRESERVE-IMPROVE workflows\n\n---\n\n## Implementation Guide (5 minutes)\n\n### Phase 1: SPEC Generation\n\nPurpose: Define clear, testable requirements in GEARS format (current; EARS legacy reference supported for the 6-month backward-compat window) before coding.\n\nWorkflow:\n```bash\n# 1. Generate SPEC\n/moai:1-plan \"Implement user authentication with JWT tokens\"\n\n# 2. spec-builder creates:\n.moai/specs/SPEC-001/\n spec.md # GEARS format requirements (current; EARS for legacy SPECs)\n acceptance.md # Acceptance criteria\n complexity.yaml # Complexity analysis\n\n# 3. Execute /clear (mandatory)\n/clear # Saves 45-50K tokens, prepares clean context\n```\n\nGEARS Format Structure (current; subject \"system\" shown for readability, but any noun is valid per generalized-subject rule):\n\n```markdown\n---\nspec_id: SPEC-001\ntitle: User Authentication System\nversion: 1.0.0\ncomplexity: Medium\nestimated_effort: 8-12 hours\n---\n\n## Requirements\n\n### SPEC-001-REQ-01: User Registration (Ubiquitous)\nPattern: Ubiquitous\nStatement: The system SHALL register users with email and password validation.\n\nAcceptance Criteria:\n- Email format validated (RFC 5322)\n- Password strength: ≥8 chars, mixed case, numbers, symbols\n- Duplicate email rejected with clear error\n- Success returns user ID and confirmation email sent\n\nTest Coverage Target: ≥90%\n```\n\n---\n\n### Phase 2: Domain-Driven Development\n\nANALYZE-PRESERVE-IMPROVE Cycle:\n\n```python\n# ANALYZE: Understand existing code and behavior\ndef analyze_existing_registration():\n \"\"\"Analyze current registration implementation.\n\n - Identify existing behavior patterns\n - Document current test coverage\n - Map dependencies and side effects\n \"\"\"\n pass\n\n# PRESERVE: Create characterization tests\ndef test_register_user_existing_behavior():\n \"\"\"Characterization test for existing behavior.\"\"\"\n result = register_user(\"[email protected]\", \"SecureP@ssw0rd\")\n assert result.success is True # Documents existing behavior\n\n# IMPROVE: Refactor with behavior preservation\ndef register_user(email: str, password: str) -> RegistrationResult:\n \"\"\"Register new user with email and password.\n\n Implements SPEC-001-REQ-01\n Behavior preserved from existing implementation.\n \"\"\"\n # Improved validation, hashing, database operations\n return RegistrationResult(success=True, user=user)\n```\n\nCoverage Validation:\n```bash\n# Run tests with coverage\npytest tests/auth/test_registration.py --cov=src/auth/registration --cov-report=html\n```\n\n---\n\n### Phase 3: Documentation Synchronization\n\nWorkflow:\n```bash\n# 1. Generate documentation\n/moai:3-sync SPEC-001\n\n# 2. docs-manager creates:\n.moai/specs/SPEC-001/\n docs/\n api.md # API reference\n architecture.md # Architecture diagram\n testing.md # Test report\n report.md # Implementation summary\n```\n\n---\n\n## Advanced Patterns\n\nFor comprehensive implementation patterns including MFA examples, iterative SPEC refinement, and CI/CD integration, see:\n\n- Canonical GEARS authoring guide: `.claude/skills/moai-workflow-spec/SKILL.md` § \"GEARS Format\" (current notation)\n- [EARS Format Reference (legacy reference, deprecated — see GEARS Format guide)](spec-ears-format.md) - All EARS patterns with examples for the 88 legacy SPECs\n- [DDD Implementation](spec-ddd-implementation.md) - Advanced DDD workflows\n\n---\n\n## Works Well With\n\nAgents:\n- spec-builder - GEARS format SPEC generation (current; EARS as legacy reference)\n- ddd-implementer - ANALYZE-PRESERVE-IMPROVE execution\n- quality-gate - TRUST 5 validation\n- docs-manager - Documentation generation\n\nSkills:\n- moai-workflow-testing - Test frameworks\n\nCommands:\n- /moai:1-plan - SPEC generation (Phase 1)\n- /moai:2-run - DDD implementation (Phase 2)\n- /moai:3-sync - Documentation sync (Phase 3)\n- /clear - Token optimization between phases\n\n---\n\nVersion: 3.0.0\nLast Updated: 2026-01-17\nStatus: Production Ready\n","content_type":"text/markdown; charset=utf-8","language":"markdown","size":6285,"content_sha256":"55df55ecb8e7fde410f69c00a723a7ab7cd134b3547ddbaff3b9b9aba182cba6"},{"filename":"modules/token-optimization.md","content":"# Token Optimization - Budget Management\n\nPurpose: Efficient 200K token budget management through strategic context loading, phase separation, and model selection for cost-effective AI development.\n\nVersion: 1.0.0\nLast Updated: 2025-11-25\n\n---\n\n## Quick Reference (30 seconds)\n\nToken Budget: 200K per feature (250K with overhead)\n\nPhase Allocation:\n- SPEC Generation: 30K tokens\n- DDD Implementation: 180K tokens\n- Documentation: 40K tokens\n\n/clear Execution Rules:\n1. Immediately after /moai:1-plan (saves 45-50K)\n2. When context > 150K tokens\n3. After 50+ conversation messages\n\nModel Selection:\n- Sonnet 4.5: Quality-critical (SPEC, security)\n- Haiku 4.5: Speed/cost (simple edits, tests)\n- Cost savings: 60-70% with strategic Haiku use\n\nContext Optimization:\n- Target: 20-30K tokens per agent\n- Maximum: 50K tokens\n- Load only necessary files for current task\n\n---\n\n## Implementation Guide (5 minutes)\n\n### Token Budget Allocation\n\nStandard Feature Budget (250K tokens):\n\n| Phase | Budget | Purpose | Breakdown |\n|-------|--------|---------|-----------|\n| Phase 1: SPEC | 30K | Requirements definition | GEARS format (current; EARS as legacy reference), acceptance criteria, complexity |\n| /clear | - | Context reset | Saves 45-50K tokens |\n| Phase 2: DDD | 180K | Implementation + tests | ANALYZE (40K) + PRESERVE (80K) + IMPROVE (60K) |\n| Phase 3: Docs | 40K | Documentation | API docs, architecture, reports |\n| Total | 250K | Complete feature | 60-70% efficiency vs manual |\n\nBudget Monitoring:\n\n```python\nclass TokenBudgetManager:\n \"\"\"Track and enforce token budget limits.\"\"\"\n \n PHASE_BUDGETS = {\n \"spec\": 30_000,\n \"ddd\": 180_000,\n \"docs\": 40_000\n }\n \n TOTAL_BUDGET = 250_000\n WARNING_THRESHOLD = 150_000\n \n def __init__(self):\n self.current_phase = None\n self.phase_usage = {\n \"spec\": 0,\n \"ddd\": 0,\n \"docs\": 0\n }\n \n def track_usage(self, phase: str, tokens_used: int):\n \"\"\"Track token usage for current phase.\"\"\"\n self.current_phase = phase\n self.phase_usage[phase] += tokens_used\n \n # Check budget\n if self.phase_usage[phase] > self.PHASE_BUDGETS[phase]:\n raise TokenBudgetExceededError(\n f\"Phase {phase} exceeded budget: \"\n f\"{self.phase_usage[phase]} > {self.PHASE_BUDGETS[phase]}\"\n )\n \n # Warn at threshold\n total = self.total_usage()\n if total > self.WARNING_THRESHOLD:\n suggest_clear()\n \n def total_usage(self) -> int:\n \"\"\"Calculate total token usage across all phases.\"\"\"\n return sum(self.phase_usage.values())\n \n def remaining_budget(self, phase: str) -> int:\n \"\"\"Calculate remaining budget for phase.\"\"\"\n return self.PHASE_BUDGETS[phase] - self.phase_usage[phase]\n \n def get_budget_report(self) -> dict:\n \"\"\"Generate budget usage report.\"\"\"\n return {\n \"total_budget\": self.TOTAL_BUDGET,\n \"total_used\": self.total_usage(),\n \"total_remaining\": self.TOTAL_BUDGET - self.total_usage(),\n \"phases\": {\n phase: {\n \"budget\": self.PHASE_BUDGETS[phase],\n \"used\": self.phase_usage[phase],\n \"remaining\": self.remaining_budget(phase),\n \"utilization\": (self.phase_usage[phase] / self.PHASE_BUDGETS[phase]) * 100\n }\n for phase in self.PHASE_BUDGETS\n }\n }\n\n# Usage\nbudget = TokenBudgetManager()\n\n# Phase 1: SPEC\nbudget.track_usage(\"spec\", 25_000)\nprint(budget.remaining_budget(\"spec\")) # 5,000 tokens remaining\n\n# Execute /clear\nexecute_clear()\n\n# Phase 2: DDD\nbudget.track_usage(\"ddd\", 85_000)\nbudget.track_usage(\"ddd\", 75_000)\nprint(budget.total_usage()) # 185,000 (triggers warning)\n```\n\n---\n\n### /clear Execution Strategy\n\nRule 1: Mandatory After SPEC Generation:\n\n```python\n# Pattern: SPEC → /clear → Implementation\nasync def spec_then_implement():\n \"\"\"Always execute /clear after SPEC.\"\"\"\n \n # Phase 1: SPEC Generation (heavy context)\n spec = await Agent(\n subagent_type=\"spec-builder\",\n prompt=\"Generate SPEC for user authentication\"\n )\n # Context: ~75K tokens (conversation + SPEC content)\n \n # MANDATORY: Execute /clear\n execute_clear()\n # Context: Reset to 0, saves 45-50K tokens\n \n # Phase 2: Implementation (fresh context)\n impl = await Agent(\n subagent_type=\"ddd-implementer\",\n prompt=\"Implement SPEC-001\",\n context={\n \"spec_id\": \"SPEC-001\", # Minimal reference\n # SPEC content loaded from file, not conversation\n }\n )\n # Context: Only current phase (~80K tokens)\n \n # Total savings: 45-50K tokens\n```\n\nRule 2: Context > 150K Threshold:\n\n```python\ndef monitor_context_size():\n \"\"\"Monitor and manage context size.\"\"\"\n \n current_tokens = get_current_context_tokens()\n \n if current_tokens > 150_000:\n # Warn user\n print(\" Context size: {current_tokens}K tokens\")\n print(\" Recommendation: Execute /clear to reset context\")\n \n # Provide context summary before clearing\n summary = generate_context_summary()\n \n # Execute /clear\n execute_clear()\n \n # Restore minimal context\n restore_minimal_context(summary)\n\ndef get_current_context_tokens() -> int:\n \"\"\"Get current context token count.\"\"\"\n # Use /context command or API\n result = execute_command(\"/context\")\n return parse_token_count(result)\n\ndef generate_context_summary() -> dict:\n \"\"\"Generate compact summary of current context.\"\"\"\n return {\n \"current_spec\": get_current_spec_id(),\n \"current_phase\": get_current_phase(),\n \"key_decisions\": extract_key_decisions(),\n \"pending_actions\": extract_pending_actions()\n }\n\ndef restore_minimal_context(summary: dict):\n \"\"\"Restore only essential context after /clear.\"\"\"\n # Load only necessary files\n load_file(f\".moai/specs/{summary['current_spec']}/spec.md\")\n # Do NOT reload entire conversation history\n```\n\nRule 3: After 50+ Messages:\n\n```python\nclass ConversationMonitor:\n \"\"\"Monitor conversation length and suggest /clear.\"\"\"\n \n def __init__(self):\n self.message_count = 0\n self.clear_threshold = 50\n \n def track_message(self):\n \"\"\"Track each message in conversation.\"\"\"\n self.message_count += 1\n \n if self.message_count >= self.clear_threshold:\n self.suggest_clear()\n \n def suggest_clear(self):\n \"\"\"Suggest executing /clear.\"\"\"\n print(f\" {self.message_count} messages in conversation\")\n print(\" Consider executing /clear to reset context\")\n print(\" This will improve response quality and speed\")\n\n# Usage\nmonitor = ConversationMonitor()\n\n# Each user/assistant message\nmonitor.track_message()\n```\n\n---\n\n### Selective File Loading\n\nGood Practices :\n\n```python\nclass SelectiveFileLoader:\n \"\"\"Load only necessary files for current task.\"\"\"\n \n def __init__(self):\n self.loaded_files = set()\n \n def load_for_task(self, task_type: str, context: dict):\n \"\"\"Load files specific to task type.\"\"\"\n \n if task_type == \"backend_implementation\":\n # Load only backend-related files\n files = [\n f\"src/{context['module']}.py\",\n f\"tests/test_{context['module']}.py\",\n f\".moai/specs/{context['spec_id']}/spec.md\"\n ]\n \n elif task_type == \"frontend_implementation\":\n # Load only frontend-related files\n files = [\n f\"src/components/{context['component']}.tsx\",\n f\"src/components/{context['component']}.test.tsx\",\n f\".moai/specs/{context['spec_id']}/spec.md\"\n ]\n \n elif task_type == \"testing\":\n # Load only test files\n files = [\n f\"tests/{context['test_module']}.py\",\n f\"src/{context['implementation_module']}.py\"\n ]\n \n else:\n # Default: Load spec only\n files = [f\".moai/specs/{context['spec_id']}/spec.md\"]\n \n # Load files\n for file in files:\n if file not in self.loaded_files:\n load_file(file)\n self.loaded_files.add(file)\n \n def load_headers_only(self, file_path: str):\n \"\"\"Load file metadata and headers only (not full content).\"\"\"\n with open(file_path) as f:\n # Read first 50 lines (headers, imports, class definitions)\n headers = \"\".join(f.readlines()[:50])\n return headers\n \n def load_function_signatures(self, file_path: str):\n \"\"\"Extract only function signatures from file.\"\"\"\n import ast\n \n with open(file_path) as f:\n tree = ast.parse(f.read())\n \n signatures = []\n for node in ast.walk(tree):\n if isinstance(node, ast.FunctionDef):\n args = [arg.arg for arg in node.args.args]\n signatures.append(f\"{node.name}({', '.join(args)})\")\n \n return signatures\n\n# Usage\nloader = SelectiveFileLoader()\n\n# Backend task: Load only backend files\nloader.load_for_task(\"backend_implementation\", {\n \"module\": \"auth\",\n \"spec_id\": \"SPEC-001\"\n})\n# Loaded: src/auth.py, tests/test_auth.py, spec.md\n# NOT loaded: frontend files, database files, docs\n\n# Estimated tokens: ~15K (vs 150K if loading entire codebase)\n```\n\nBad Practices :\n\n```python\n# BAD: Load entire codebase\ndef load_everything():\n for file in glob(\"src//*.py\"):\n load_file(file) # Loads 100+ files\n for file in glob(\"tests//*.py\"):\n load_file(file)\n # Result: 200K+ tokens, exceeds budget\n\n# BAD: Load node_modules\ndef load_dependencies():\n for file in glob(\"node_modules//*.js\"):\n load_file(file) # Millions of tokens\n\n# BAD: Load binary files\ndef load_binaries():\n for file in glob(\"/*.png\"):\n load_file(file) # Non-text data\n\n# BAD: Load conversation history\ndef load_history():\n load_file(\".moai/conversation_history.json\") # 500K+ tokens\n```\n\n---\n\n### Model Selection Strategy\n\nDecision Matrix:\n\n| Task Type | Model | Reason | Cost | Speed |\n|-----------|-------|--------|------|-------|\n| SPEC generation | Sonnet 4.5 | High-quality design | $$ | Slower |\n| Security review | Sonnet 4.5 | Precise analysis | $$ | Slower |\n| Architecture design | Sonnet 4.5 | Complex reasoning | $$ | Slower |\n| DDD implementation | Haiku 4.5 | Fast execution | $ | 3x faster |\n| Simple edits | Haiku 4.5 | Minimal complexity | $ | 3x faster |\n| Test generation | Haiku 4.5 | Pattern-based | $ | 3x faster |\n| Documentation | Haiku 4.5 | Template-based | $ | 3x faster |\n\nCost Comparison:\n\n```python\nclass ModelCostCalculator:\n \"\"\"Calculate cost savings with strategic model selection.\"\"\"\n \n COSTS_PER_1M_TOKENS = {\n \"sonnet-4.5\": {\n \"input\": 3.00,\n \"output\": 15.00\n },\n \"haiku-4.5\": {\n \"input\": 1.00,\n \"output\": 5.00\n }\n }\n \n def calculate_cost(self, model: str, input_tokens: int, output_tokens: int) -> float:\n \"\"\"Calculate cost for specific model and token usage.\"\"\"\n input_cost = (input_tokens / 1_000_000) * self.COSTS_PER_1M_TOKENS[model][\"input\"]\n output_cost = (output_tokens / 1_000_000) * self.COSTS_PER_1M_TOKENS[model][\"output\"]\n return input_cost + output_cost\n \n def compare_strategies(self, feature_token_budget: dict):\n \"\"\"Compare cost of all-Sonnet vs strategic mix.\"\"\"\n \n # Strategy 1: All Sonnet\n all_sonnet_cost = sum(\n self.calculate_cost(\"sonnet-4.5\", phase[\"input\"], phase[\"output\"])\n for phase in feature_token_budget.values()\n )\n \n # Strategy 2: Strategic mix\n strategic_costs = {\n \"spec\": self.calculate_cost(\n \"sonnet-4.5\", # Sonnet for SPEC\n feature_token_budget[\"spec\"][\"input\"],\n feature_token_budget[\"spec\"][\"output\"]\n ),\n \"ddd\": self.calculate_cost(\n \"haiku-4.5\", # Haiku for DDD\n feature_token_budget[\"ddd\"][\"input\"],\n feature_token_budget[\"ddd\"][\"output\"]\n ),\n \"docs\": self.calculate_cost(\n \"haiku-4.5\", # Haiku for docs\n feature_token_budget[\"docs\"][\"input\"],\n feature_token_budget[\"docs\"][\"output\"]\n )\n }\n strategic_total = sum(strategic_costs.values())\n \n savings = all_sonnet_cost - strategic_total\n savings_percent = (savings / all_sonnet_cost) * 100\n \n return {\n \"all_sonnet\": all_sonnet_cost,\n \"strategic_mix\": strategic_total,\n \"savings\": savings,\n \"savings_percent\": savings_percent\n }\n\n# Example calculation\ncalculator = ModelCostCalculator()\n\nfeature_budget = {\n \"spec\": {\"input\": 20_000, \"output\": 10_000},\n \"ddd\": {\"input\": 100_000, \"output\": 80_000},\n \"docs\": {\"input\": 30_000, \"output\": 10_000}\n}\n\ncomparison = calculator.compare_strategies(feature_budget)\nprint(f\"All Sonnet: ${comparison['all_sonnet']:.2f}\")\nprint(f\"Strategic Mix: ${comparison['strategic_mix']:.2f}\")\nprint(f\"Savings: ${comparison['savings']:.2f} ({comparison['savings_percent']:.1f}%)\")\n\n# Output:\n# All Sonnet: $32.40\n# Strategic Mix: $11.80\n# Savings: $20.60 (63.6%)\n```\n\n---\n\n## Advanced Implementation (10+ minutes)\n\n### Context Passing Optimization\n\nEfficient Context Structure:\n\n```python\nclass ContextOptimizer:\n \"\"\"Optimize context passed between agents.\"\"\"\n \n def __init__(self):\n self.target_size = 30_000 # 30K tokens\n self.max_size = 50_000 # 50K tokens\n \n def optimize_context(self, full_context: dict, agent_type: str) -> dict:\n \"\"\"Create optimized context for specific agent.\"\"\"\n \n # Extract agent-specific requirements\n optimized = self._extract_required_fields(full_context, agent_type)\n \n # Compress large data structures\n optimized = self._compress_large_fields(optimized)\n \n # Remove redundant information\n optimized = self._remove_redundancy(optimized)\n \n # Validate size\n size = self._estimate_tokens(optimized)\n if size > self.max_size:\n optimized = self._aggressive_compression(optimized)\n \n return optimized\n \n def _extract_required_fields(self, context: dict, agent_type: str) -> dict:\n \"\"\"Extract only fields required by specific agent.\"\"\"\n \n requirements = {\n \"backend-expert\": [\"spec_id\", \"api_design\", \"database_schema\"],\n \"frontend-expert\": [\"spec_id\", \"api_endpoints\", \"ui_components\"],\n \"security-expert\": [\"spec_id\", \"threat_model\", \"dependencies\"],\n \"test-engineer\": [\"spec_id\", \"code_structure\", \"test_strategy\"],\n \"docs-manager\": [\"spec_id\", \"api_spec\", \"architecture\"]\n }\n \n required = requirements.get(agent_type, [\"spec_id\"])\n \n return {\n field: context[field]\n for field in required\n if field in context\n }\n \n def _compress_large_fields(self, context: dict) -> dict:\n \"\"\"Compress large data structures.\"\"\"\n \n for key, value in context.items():\n if isinstance(value, str) and len(value) > 5000:\n # Compress long strings\n context[key] = self._summarize_text(value)\n \n elif isinstance(value, list) and len(value) > 100:\n # Sample large lists\n context[key] = value[:50] + [\"... (truncated)\"] + value[-50:]\n \n elif isinstance(value, dict) and len(str(value)) > 5000:\n # Compress nested dicts\n context[key] = self._compress_dict(value)\n \n return context\n \n def _summarize_text(self, text: str, max_length: int = 1000) -> str:\n \"\"\"Summarize long text to key points.\"\"\"\n # Extract first paragraph + last paragraph\n paragraphs = text.split(\"\\n\\n\")\n if len(paragraphs) > 2:\n summary = paragraphs[0] + \"\\n\\n...\\n\\n\" + paragraphs[-1]\n if len(summary) > max_length:\n return summary[:max_length] + \"...\"\n return summary\n return text[:max_length]\n \n def _estimate_tokens(self, context: dict) -> int:\n \"\"\"Estimate token count.\"\"\"\n import json\n json_str = json.dumps(context, default=str)\n # Rough estimate: 1 token ≈ 4 characters\n return len(json_str) // 4\n\n# Usage\noptimizer = ContextOptimizer()\n\nlarge_context = {\n \"spec_id\": \"SPEC-001\",\n \"full_code\": \"...\" * 10000, # 50KB code\n \"api_design\": {...},\n \"database_schema\": {...},\n \"test_results\": [...] * 500, # 500 test results\n \"conversation_history\": \"...\" * 20000 # 100KB history\n}\n\n# Optimize for backend-expert\nbackend_context = optimizer.optimize_context(large_context, \"backend-expert\")\n# Result: Only spec_id, api_design, database_schema\n# Size: ~25K tokens (vs 200K+ original)\n\nresult = await Agent(\n subagent_type=\"backend-expert\",\n prompt=\"Implement backend\",\n context=backend_context # Optimized context\n)\n```\n\n### Token Usage Monitoring\n\nReal-time Monitoring Dashboard:\n\n```python\nimport time\nfrom dataclasses import dataclass\nfrom typing import List\n\n@dataclass\nclass TokenUsageSnapshot:\n \"\"\"Snapshot of token usage at point in time.\"\"\"\n timestamp: float\n phase: str\n operation: str\n tokens_used: int\n cumulative_tokens: int\n budget_remaining: int\n\nclass TokenMonitor:\n \"\"\"Real-time token usage monitoring.\"\"\"\n \n def __init__(self, total_budget: int = 250_000):\n self.total_budget = total_budget\n self.snapshots: List[TokenUsageSnapshot] = []\n self.cumulative_usage = 0\n \n def record_usage(self, phase: str, operation: str, tokens: int):\n \"\"\"Record token usage event.\"\"\"\n self.cumulative_usage += tokens\n \n snapshot = TokenUsageSnapshot(\n timestamp=time.time(),\n phase=phase,\n operation=operation,\n tokens_used=tokens,\n cumulative_tokens=self.cumulative_usage,\n budget_remaining=self.total_budget - self.cumulative_usage\n )\n \n self.snapshots.append(snapshot)\n \n # Check thresholds\n if self.cumulative_usage > 150_000:\n self._warn_threshold()\n \n if self.cumulative_usage > self.total_budget:\n self._alert_exceeded()\n \n def get_usage_report(self) -> dict:\n \"\"\"Generate comprehensive usage report.\"\"\"\n \n phase_breakdown = {}\n for snapshot in self.snapshots:\n if snapshot.phase not in phase_breakdown:\n phase_breakdown[snapshot.phase] = 0\n phase_breakdown[snapshot.phase] += snapshot.tokens_used\n \n return {\n \"total_budget\": self.total_budget,\n \"total_used\": self.cumulative_usage,\n \"budget_remaining\": self.total_budget - self.cumulative_usage,\n \"utilization\": (self.cumulative_usage / self.total_budget) * 100,\n \"phase_breakdown\": phase_breakdown,\n \"efficiency_score\": self._calculate_efficiency(),\n \"recommendations\": self._generate_recommendations()\n }\n \n def _calculate_efficiency(self) -> float:\n \"\"\"Calculate token usage efficiency (0-100).\"\"\"\n # Higher is better (less waste)\n if self.cumulative_usage == 0:\n return 100.0\n \n # Efficiency based on staying within budget\n if self.cumulative_usage \u003c= self.total_budget:\n return 100 * (1 - (self.cumulative_usage / self.total_budget))\n else:\n # Penalty for exceeding budget\n return max(0, 100 - ((self.cumulative_usage - self.total_budget) / self.total_budget * 100))\n \n def _generate_recommendations(self) -> List[str]:\n \"\"\"Generate optimization recommendations.\"\"\"\n recommendations = []\n \n if self.cumulative_usage > 150_000:\n recommendations.append(\"Execute /clear to reset context\")\n \n phase_usage = {}\n for snapshot in self.snapshots:\n phase_usage[snapshot.phase] = phase_usage.get(snapshot.phase, 0) + snapshot.tokens_used\n \n for phase, usage in phase_usage.items():\n if usage > 100_000:\n recommendations.append(f\"Phase '{phase}' using {usage}K tokens - consider breaking into smaller tasks\")\n \n return recommendations\n\n# Usage\nmonitor = TokenMonitor(total_budget=250_000)\n\n# Record usage throughout workflow\nmonitor.record_usage(\"spec\", \"generate_spec\", 25_000)\nmonitor.record_usage(\"spec\", \"validate_spec\", 5_000)\n# Execute /clear here\nmonitor.record_usage(\"ddd\", \"analyze_phase\", 40_000)\nmonitor.record_usage(\"ddd\", \"preserve_phase\", 80_000)\nmonitor.record_usage(\"ddd\", \"improve_phase\", 60_000)\nmonitor.record_usage(\"docs\", \"generate_docs\", 30_000)\n\n# Generate report\nreport = monitor.get_usage_report()\nprint(f\"Total used: {report['total_used']:,} / {report['total_budget']:,}\")\nprint(f\"Utilization: {report['utilization']:.1f}%\")\nprint(f\"Efficiency: {report['efficiency_score']:.1f}\")\nprint(\"\\nRecommendations:\")\nfor rec in report['recommendations']:\n print(f\"- {rec}\")\n```\n\n---\n\n## Works Well With\n\nSkills:\n- moai-foundation-delegation-patterns - Context passing\n- moai-foundation-progressive-disclosure - Content structuring\n- moai-cc-memory - Context persistence\n\nCommands:\n- /clear - Context reset (mandatory after /moai:1-plan)\n- /context - Check current token usage\n- /moai:1-plan - SPEC generation (30K budget)\n- /moai:2-run - DDD implementation (180K budget)\n- /moai:3-sync - Documentation (40K budget)\n\nMemory:\n- Skill(\"moai-foundation-core\") modules/token-optimization.md - Optimization strategies\n- .moai/config/config.json - Budget configuration\n\n---\n\nVersion: 1.0.0\nLast Updated: 2025-11-25\nStatus: Production Ready\n","content_type":"text/markdown; charset=utf-8","language":"markdown","size":19040,"content_sha256":"fbb3da85dcadc35c8bb3005c924d03555c0edb785f7290fc9657160d599c1858"},{"filename":"modules/trust-5-framework.md","content":"# TRUST 5 Framework - Quality Assurance System\n\nPurpose: Automated quality gates ensuring code quality, security, maintainability, and traceability through five core principles.\n\nVersion: 2.0.0 (Modular Split)\nLast Updated: 2026-01-06\n\n---\n\n## Quick Reference (30 seconds)\n\nTRUST 5 is MoAI-ADK's comprehensive quality assurance framework enforcing five pillars:\n\n1. Test-first(T) - ≥85% coverage, RED-GREEN-REFACTOR cycle\n2. Readable(R) - Clear naming, ≤10 cyclomatic complexity\n3. Unified(U) - Consistent patterns, architecture compliance\n4. Secured(S) - OWASP Top 10 compliance, security validation\n5. Trackable(T) - Clear commits, requirement traceability\n\nIntegration Points:\n- Pre-commit hooks - Automated validation\n- CI/CD pipelines - Quality gate enforcement\n- quality-gate agent - TRUST 5 validation\n- /moai:2-run - Enforces ≥85% coverage\n\nQuick Validation:\n```python\nvalidations = [\n test_coverage >= 85, # T\n complexity \u003c= 10, # R\n consistency > 90, # U\n security_score == 100, # S\n has_clear_commits # T\n]\n```\n\nExtended Documentation:\n- [Implementation Details](trust-5-implementation.md) - Detailed patterns and code examples\n- [Validation Framework](trust-5-validation.md) - CI/CD integration and metrics\n\n---\n\n## Implementation Guide (5 minutes)\n\n### Principle 1: Test-First (T)\n\nRED-GREEN-REFACTOR Cycle:\n\n```\nRED Phase: Write failing test\n Test defines requirement\n Code doesn't exist yet\n Test fails as expected\n\nGREEN Phase: Write minimal code\n Simplest code to pass test\n Focus on making test pass\n Test now passes\n\nREFACTOR Phase: Improve quality\n Extract functions/classes\n Optimize performance\n Add documentation\n Keep tests passing\n```\n\nTest Coverage Requirements:\n\n- Critical (≥85%): Required for merge\n- Warning (70-84%): Review required\n- Failing (\u003c70%): Block merge, generate tests\n\nValidation Commands:\n```bash\n# Run tests with coverage\npytest --cov=src --cov-report=html --cov-fail-under=85\n\n# Generate coverage report\ncoverage report -m\n```\n\n---\n\n### Principle 2: Readable (R)\n\nReadability Metrics:\n\n- Cyclomatic Complexity: ≤10 (max 15)\n- Function Length: ≤50 lines (max 100)\n- Nesting Depth: ≤3 levels (max 5)\n- Comment Ratio: 15-20% (min 10%)\n- Type Hint Coverage: 100% (min 90%)\n\nReadability Checklist:\n\n- Clear function/variable names (noun_verb pattern)\n- Single responsibility principle\n- Type hints on all parameters and returns\n- Docstrings with examples (Google style)\n- No magic numbers (use named constants)\n- DRY principle applied (no code duplication)\n- SOLID principles followed\n\nValidation Commands:\n```bash\n# Pylint complexity check\npylint src/ --fail-under=8.0\n\n# Black format check\nblack --check src/\n\n# MyPy type check\nmypy src/ --strict\n```\n\n---\n\n### Principle 3: Unified (U)\n\nConsistency Requirements:\n\nArchitecture Consistency:\n- Same pattern across all modules\n- Same error handling approach\n- Same logging strategy\n- Same naming conventions\n\nTesting Consistency:\n- Same test structure (Arrange-Act-Assert)\n- Same fixtures/factories\n- Same assertion patterns\n- Same mock strategies\n\nDocumentation Consistency:\n- Same docstring format (Google style)\n- Same README structure\n- Same API documentation\n- Same changelog format (conventional commits)\n\nValidation Tools:\n```bash\n# Check architecture compliance\npython .moai/scripts/validate_architecture.py\n\n# Check consistent imports\nisort --check-only src/\n```\n\n---\n\n### Principle 4: Secured (S)\n\nOWASP Top 10 (2024) Compliance:\n\n1. Broken Access Control - RBAC, permission checks\n2. Cryptographic Failures - bcrypt, proper encryption\n3. Injection - Parameterized queries\n4. Insecure Design - Threat modeling\n5. Security Misconfiguration - Environment variables\n6. Vulnerable Components - Dependency scanning\n7. Authentication Failures - MFA, secure sessions\n8. Data Integrity - Checksums, signatures\n9. Logging Failures - Comprehensive logging\n10. SSRF - URL validation\n\nSecurity Validation:\n```bash\n# Bandit security scan\nbandit -r src/ -ll\n\n# Dependency audit\npip-audit\nsafety check\n\n# Secret scanning\ndetect-secrets scan\n```\n\n---\n\n### Principle 5: Trackable (T)\n\nTraceability Requirements:\n\nCommit Traceability:\n- Conventional commit format\n- Link to SPEC or issue\n- Clear description of changes\n- Test evidence included\n\nRequirement Traceability:\n- SPEC-XXX-REQ-YY mapping\n- Implementation - Test linkage\n- Test - Acceptance criteria\n- Acceptance - User story\n\nConventional Commit Format:\n```bash\n# Format: \u003ctype>(\u003cscope>): \u003csubject>\nfeat(auth): Add OAuth2 integration\n\nImplement OAuth2 authentication flow with Google provider.\nAdddesses SPEC-001-REQ-02.\n\nCloses #42\n```\n\n---\n\n## Advanced Patterns\n\nFor comprehensive implementation patterns including CI/CD integration, validation frameworks, and metrics dashboards, see:\n\n- [TRUST 5 Implementation](trust-5-implementation.md) - Detailed code patterns\n- [TRUST 5 Validation](trust-5-validation.md) - CI/CD and metrics\n\n---\n\n## Works Well With\n\nAgents:\n- quality-gate - Automated TRUST 5 validation\n- ddd-implementer - ANALYZE-PRESERVE-IMPROVE enforcement\n- security-expert - OWASP compliance checking\n- test-engineer - Test generation and coverage\n\nSkills:\n- moai-workflow-testing - Test framework setup\n- moai-domain-security - Security patterns\n\nCommands:\n- /moai:2-run - Enforces ≥85% coverage requirement\n- /moai:9-feedback - Quality improvement suggestions\n\n---\n\nVersion: 2.0.0\nLast Updated: 2026-01-06\nStatus: Production Ready\n","content_type":"text/markdown; charset=utf-8","language":"markdown","size":5472,"content_sha256":"e9dd5494e58de5ded8ddda9283a42e58fe7e9d0c09826411eb204ff523189940"},{"filename":"modules/trust-5-implementation.md","content":"# TRUST 5 Implementation Patterns\n\nPurpose: Detailed implementation patterns for TRUST 5 principles with working code examples.\n\nVersion: 1.0.0\nLast Updated: 2026-01-06\nParent: [trust-5-framework.md](trust-5-framework.md)\n\n---\n\n## Test-First Implementation\n\n### RED-GREEN-REFACTOR Example\n\n```python\n# RED: Write failing test first\ndef test_calculate_total_price_with_tax():\n item = ShoppingItem(name=\"Widget\", price=10.00)\n total = calculate_total_with_tax(item, tax_rate=0.10)\n assert total == 11.00 # Fails - function doesn't exist\n\n# GREEN: Minimal implementation\ndef calculate_total_with_tax(item, tax_rate):\n return item.price * (1 + tax_rate)\n\n# REFACTOR: Improve code quality\ndef calculate_total_with_tax(item: ShoppingItem, tax_rate: float) -> float:\n \"\"\"Calculate total price including tax.\n\n Args:\n item: Shopping item with price\n tax_rate: Tax rate as decimal (0.10 = 10%)\n\n Returns:\n Total price including tax\n\n Raises:\n ValueError: If tax_rate not between 0 and 1\n\n Example:\n >>> item = ShoppingItem(\"Widget\", 10.00)\n >>> calculate_total_with_tax(item, 0.10)\n 11.0\n \"\"\"\n if not 0 \u003c= tax_rate \u003c= 1:\n raise ValueError(\"Tax rate must be between 0 and 1\")\n\n return item.price * (1 + tax_rate)\n```\n\n---\n\n## Readable Code Patterns\n\n### Bad vs Good Examples\n\n```python\n# BAD: Unreadable, no types, magic numbers\ndef calc(x, y):\n if x > 0:\n if y > 0:\n if x + y \u003c 100:\n return x * 1.1 + y * 0.9\n return 0\n\n# GOOD: Readable, typed, constants\nTAX_RATE = 0.10\nDISCOUNT_RATE = 0.10\nMAX_TOTAL = 100.00\n\ndef calculate_order_total(\n base_amount: float,\n discount_amount: float\n) -> float:\n \"\"\"Calculate order total with tax and discount.\n\n Args:\n base_amount: Base order amount before tax\n discount_amount: Discount amount to apply\n\n Returns:\n Final order total with tax applied\n\n Raises:\n ValueError: If amounts are negative or exceed max\n \"\"\"\n if base_amount \u003c 0 or discount_amount \u003c 0:\n raise ValueError(\"Amounts must be non-negative\")\n\n subtotal = base_amount - discount_amount\n\n if subtotal > MAX_TOTAL:\n raise ValueError(f\"Total exceeds maximum {MAX_TOTAL}\")\n\n return subtotal * (1 + TAX_RATE)\n```\n\n---\n\n## Unified Pattern Examples\n\n### Standard Error Handling\n\n```python\nclass DomainError(Exception):\n \"\"\"Base error for domain-specific errors.\"\"\"\n pass\n\nclass ValidationError(DomainError):\n \"\"\"Validation failed.\"\"\"\n pass\n\ndef process_data(data: dict) -> Result:\n \"\"\"Standard processing pattern.\"\"\"\n try:\n validated = validate_input(data)\n result = perform_processing(validated)\n return Result(success=True, data=result)\n\n except ValidationError as e:\n logger.error(f\"Validation failed: {e}\")\n raise\n except Exception as e:\n logger.exception(f\"Processing failed: {e}\")\n raise DomainError(f\"Processing failed: {e}\") from e\n```\n\n---\n\n## Secured Code Patterns\n\n### Access Control (RBAC)\n\n```python\nfrom functools import wraps\n\ndef require_permission(permission: str):\n \"\"\"Decorator to enforce permission checks.\"\"\"\n def decorator(func):\n @wraps(func)\n def wrapper(user: User, *args, **kwargs):\n if not user.has_permission(permission):\n raise UnauthorizedError(\n f\"User lacks permission: {permission}\"\n )\n return func(user, *args, **kwargs)\n return wrapper\n return decorator\n\n@require_permission(\"user:update\")\ndef update_user_profile(user: User, profile_data: dict) -> UserProfile:\n \"\"\"Update user profile (requires permission).\"\"\"\n return user.update_profile(profile_data)\n```\n\n### Password Hashing\n\n```python\nfrom bcrypt import hashpw, gensalt, checkpw\n\ndef hash_password(plaintext: str) -> str:\n \"\"\"Hash password securely with bcrypt.\"\"\"\n salt = gensalt(rounds=12)\n return hashpw(plaintext.encode('utf-8'), salt).decode('utf-8')\n\ndef verify_password(plaintext: str, hashed: str) -> bool:\n \"\"\"Verify password against hash.\"\"\"\n return checkpw(plaintext.encode('utf-8'), hashed.encode('utf-8'))\n```\n\n### Injection Prevention\n\n```python\nfrom sqlalchemy import text\n\ndef safe_user_query(username: str) -> List[User]:\n \"\"\"Query users safely with parameterized query.\"\"\"\n query = text(\"SELECT * FROM users WHERE username = :username\")\n return db.session.execute(query, {\"username\": username}).fetchall()\n```\n\n### Secure Configuration\n\n```python\nimport os\n\ndef load_secure_config() -> dict:\n \"\"\"Load configuration from environment variables.\"\"\"\n config = {\n 'DEBUG': os.getenv('DEBUG', 'false').lower() == 'true',\n 'DATABASE_URL': os.getenv('DATABASE_URL'),\n 'SECRET_KEY': os.getenv('SECRET_KEY'),\n 'ALLOWED_HOSTS': os.getenv('ALLOWED_HOSTS', '').split(',')\n }\n\n required = ['DATABASE_URL', 'SECRET_KEY']\n for key in required:\n if not config.get(key):\n raise ValueError(f\"Required config missing: {key}\")\n\n logger.info(f\"Config loaded (DEBUG={config['DEBUG']})\")\n return config\n```\n\n---\n\n## Trackable Patterns\n\n### Traceability Matrix\n\n```yaml\n# .moai/specs/traceability.yaml\nrequirements:\n SPEC-001-REQ-01:\n description: \"User registration with email/password\"\n implementation:\n - src/auth/registration.py::register_user\n - src/models/user.py::User\n tests:\n - tests/auth/test_registration.py::test_register_user_success\n coverage: 95%\n status: Implemented\n\n SPEC-001-REQ-02:\n description: \"OAuth2 authentication\"\n implementation:\n - src/auth/oauth2.py::OAuth2Handler\n tests:\n - tests/auth/test_oauth2.py::test_oauth2_flow\n coverage: 92%\n status: Implemented\n```\n\n---\n\n## Works Well With\n\n- [trust-5-framework.md](trust-5-framework.md) - Overview and principles\n- [trust-5-validation.md](trust-5-validation.md) - CI/CD integration\n\n---\n\nVersion: 1.0.0\nLast Updated: 2026-01-06\n","content_type":"text/markdown; charset=utf-8","language":"markdown","size":6009,"content_sha256":"d3587bf87c3608cc885ae43008d4363e4a7de5b1332236dbbc5db73dce5ed9a5"},{"filename":"modules/trust-5-validation.md","content":"# TRUST 5 Validation Framework\n\nPurpose: CI/CD integration, validation engine, and metrics dashboard for TRUST 5 quality gates.\n\nVersion: 1.0.0\nLast Updated: 2026-01-06\nParent: [trust-5-framework.md](trust-5-framework.md)\n\n---\n\n## CI/CD Integration\n\n### Complete Quality Gate Pipeline\n\n```yaml\n# .github/workflows/trust-5-quality-gates.yml\nname: TRUST 5 Quality Gates\n\non:\n pull_request:\n branches: [main, develop]\n push:\n branches: [main, develop]\n\njobs:\n test-first:\n name: \"T1: Test Coverage ≥85%\"\n runs-on: ubuntu-latest\n steps:\n - uses: actions/checkout@v4\n - name: Set up Python\n uses: actions/setup-python@v4\n with:\n python-version: '3.13'\n - name: Install dependencies\n run: pip install -r requirements.txt pytest pytest-cov\n - name: Run tests with coverage\n run: pytest --cov=src --cov-report=xml --cov-fail-under=85\n - name: Upload coverage\n uses: codecov/codecov-action@v3\n with:\n file: ./coverage.xml\n fail_ci_if_error: true\n\n readable:\n name: \"R: Code Quality ≥8.0\"\n runs-on: ubuntu-latest\n steps:\n - uses: actions/checkout@v4\n - name: Pylint check\n run: pip install pylint && pylint src/ --fail-under=8.0\n - name: Black format check\n run: pip install black && black --check src/\n - name: MyPy type check\n run: pip install mypy && mypy src/ --strict\n\n unified:\n name: \"U: Consistency ≥90%\"\n runs-on: ubuntu-latest\n steps:\n - uses: actions/checkout@v4\n - name: Architecture validation\n run: python .moai/scripts/validate_architecture.py\n - name: Import consistency\n run: pip install isort && isort --check-only src/\n\n secured:\n name: \"S: Security Score 100\"\n runs-on: ubuntu-latest\n steps:\n - uses: actions/checkout@v4\n - name: Bandit security scan\n run: pip install bandit && bandit -r src/ -ll\n - name: Dependency audit\n run: pip install pip-audit safety && pip-audit && safety check\n - name: Secret scanning\n run: pip install detect-secrets && detect-secrets scan\n\n trackable:\n name: \"T2: Traceability Check\"\n runs-on: ubuntu-latest\n steps:\n - uses: actions/checkout@v4\n - name: Validate commit messages\n run: python .moai/scripts/validate_commits.py\n - name: Check traceability\n run: python .moai/scripts/check_traceability.py\n\n quality-gate:\n name: \"Final Quality Gate\"\n needs: [test-first, readable, unified, secured, trackable]\n runs-on: ubuntu-latest\n steps:\n - name: All gates passed\n run: echo \"TRUST 5 quality gates passed!\"\n```\n\n---\n\n## Validation Engine\n\n### TRUST5Validator Class\n\n```python\nfrom dataclasses import dataclass\nfrom typing import List\nimport subprocess\nimport re\n\n@dataclass\nclass ValidationResult:\n \"\"\"Result of TRUST 5 validation.\"\"\"\n passed: bool\n test_coverage: float\n code_quality: float\n consistency_score: float\n security_score: int\n traceability_score: float\n issues: List[str]\n warnings: List[str]\n\n def overall_score(self) -> float:\n \"\"\"Calculate overall TRUST 5 score.\"\"\"\n weights = {'test': 0.20, 'quality': 0.20, 'consistency': 0.20,\n 'security': 0.20, 'traceability': 0.20}\n return (\n self.test_coverage * weights['test'] +\n self.code_quality * weights['quality'] +\n self.consistency_score * weights['consistency'] +\n self.security_score * weights['security'] +\n self.traceability_score * weights['traceability']\n )\n\nclass TRUST5Validator:\n \"\"\"Comprehensive TRUST 5 validation engine.\"\"\"\n\n def __init__(self, src_dir: str = \"src/\"):\n self.src_dir = src_dir\n self.result = ValidationResult(\n passed=False, test_coverage=0.0, code_quality=0.0,\n consistency_score=0.0, security_score=0, traceability_score=0.0,\n issues=[], warnings=[]\n )\n\n def validate_all(self) -> ValidationResult:\n \"\"\"Run all TRUST 5 validations.\"\"\"\n self._validate_test_coverage()\n self._validate_readability()\n self._validate_consistency()\n self._validate_security()\n self._validate_traceability()\n\n self.result.passed = all([\n self.result.test_coverage >= 85,\n self.result.code_quality >= 8.0,\n self.result.consistency_score >= 90,\n self.result.security_score == 100,\n self.result.traceability_score >= 80\n ])\n return self.result\n```\n\n---\n\n## Metrics Dashboard\n\n```python\nclass TRUST5Metrics:\n \"\"\"Real-time TRUST 5 quality metrics.\"\"\"\n\n def __init__(self):\n self.test_coverage = 0.0 # Target: ≥85%\n self.code_quality = 0.0 # Target: ≥8.0\n self.consistency_score = 0.0 # Target: ≥90%\n self.security_score = 0 # Target: 100\n self.traceability_score = 0.0 # Target: ≥80%\n\n def get_dashboard_data(self) -> dict:\n \"\"\"Get metrics for dashboard display.\"\"\"\n return {\n 'overall_score': self.get_overall_score(),\n 'production_ready': self.is_production_ready(),\n 'metrics': {\n 'test_coverage': {'value': self.test_coverage, 'target': 85},\n 'code_quality': {'value': self.code_quality, 'target': 8.0},\n 'consistency': {'value': self.consistency_score, 'target': 90},\n 'security': {'value': self.security_score, 'target': 100},\n 'traceability': {'value': self.traceability_score, 'target': 80}\n }\n }\n\n def get_overall_score(self) -> float:\n \"\"\"Calculate overall TRUST 5 score (0-100).\"\"\"\n return (\n self.test_coverage * 0.20 +\n (self.code_quality * 10) * 0.20 +\n self.consistency_score * 0.20 +\n self.security_score * 0.20 +\n self.traceability_score * 0.20\n )\n\n def is_production_ready(self) -> bool:\n \"\"\"Check if code meets production standards.\"\"\"\n return (self.test_coverage >= 85 and self.code_quality >= 8.0 and\n self.consistency_score >= 90 and self.security_score == 100 and\n self.traceability_score >= 80)\n```\n\n---\n\n## Works Well With\n\n- [trust-5-framework.md](trust-5-framework.md) - Overview and principles\n- [trust-5-implementation.md](trust-5-implementation.md) - Code patterns\n\n---\n\nVersion: 1.0.0\nLast Updated: 2026-01-06\n","content_type":"text/markdown; charset=utf-8","language":"markdown","size":6520,"content_sha256":"e443241135c45ecde957ed6a54d5ea6356a00cee126ecec98a7fdd32e8654926"},{"filename":"references/examples.md","content":"# MoAI Foundation Core Examples\n\n실용적인 예시를 통해 MoAI Foundation Core의 6가지 핵심 원칙을 학습합니다.\n\n---\n\n## Example 1: TRUST 5 Quality Gate 적용\n\n**Scenario**: 새로운 기능을 개발한 후 TRUST 5 품질 게이트를 통과시키는 상황\n\n**Input**:\n```python\n# 개발된 코드에 TRUST 5 검증 요청\nAgent(\n subagent_type=\"core-quality\",\n prompt=\"Validate code quality using TRUST 5 framework\",\n context={\n \"target_path\": \"/src/features/user_auth.py\",\n \"validation_level\": \"strict\"\n }\n)\n```\n\n**Output**:\n```markdown\nTRUST 5 Validation Report\n=========================\n\nTest-first: PASS (87% coverage, threshold: 85%)\nReadable: PASS (naming conventions compliant)\nUnified: PASS (black + isort formatting verified)\nSecured: PASS (no OWASP vulnerabilities detected)\nTrackable: PASS (commit messages follow conventional format)\n\nOverall Status: APPROVED for merge\n```\n\n**Explanation**: TRUST 5의 5가지 품질 기준(Test-first, Readable, Unified, Secured, Trackable)을 자동으로 검증하여 코드 품질을 보장합니다. 85% 이상 테스트 커버리지, 일관된 코드 스타일, 보안 취약점 부재를 확인합니다.\n\n---\n\n## Example 2: SPEC-First DDD 3단계 워크플로우\n\n**Scenario**: 사용자 인증 기능을 SPEC-First DDD 방식으로 개발하는 전체 과정\n\n**Input**:\n```bash\n# Phase 1: SPEC 생성\n/moai:1-plan \"JWT 기반 사용자 인증 시스템 구현\"\n\n# Phase 2: DDD 실행 (Phase 1 완료 후 /clear 실행)\n/clear\n/moai:2-run SPEC-001\n\n# Phase 3: 문서화\n/moai:3-sync SPEC-001\n```\n\n**Output**:\n```markdown\nPhase 1 Result (.moai/specs/SPEC-001/spec.md):\n==============================================\nID: SPEC-001\nTitle: JWT Authentication System\nGEARS Format (current):\n- [Ubiquitous] The auth service shall hash passwords using bcrypt.\n- [Event-driven] When a user submits credentials, the auth service shall validate them and return a JWT.\n- [State-driven] While a JWT is valid, the resource gateway shall grant the user access to protected resources.\n- [Where, capability] Where SSO is enabled, the auth service shall federate identity to the upstream IdP.\n- [Unwanted] The auth service shall not store plain-text passwords.\n\nEARS Format (legacy reference, 6-month backward-compat — expires 2026-11-22):\n- [Ubiquitous] System shall hash passwords using bcrypt\n- [Event-driven] When user submits credentials, system shall validate and return JWT\n- [State-driven] While token is valid, user shall access protected resources\n- [Unwanted] System shall not store plain-text passwords\nToken Usage: 28K/30K\n\nPhase 2 Result:\n===============\nANALYZE: Requirements analyzed, 5 acceptance criteria identified\nPRESERVE: Existing behavior protected, characterization tests created\nIMPROVE: Implementation complete, code optimized\nCoverage: 92% (threshold: 85%)\nToken Usage: 165K/180K\n\nPhase 3 Result:\n===============\nAPI Documentation: Generated (docs/api/auth.md)\nArchitecture Diagram: Created (docs/diagrams/auth-flow.mermaid)\nToken Usage: 35K/40K\n```\n\n**Explanation**: SPEC-First DDD는 3단계로 진행됩니다. Phase 1에서 GEARS 형식(current; EARS는 6개월 backward-compat legacy reference로 유지)으로 요구사항을 정의하고, Phase 2에서 ANALYZE-PRESERVE-IMPROVE 사이클로 구현하며, Phase 3에서 문서를 생성합니다. 각 Phase 사이에 /clear를 실행하여 토큰을 절약합니다.\n\n---\n\n## Example 3: 에이전트 위임 패턴 (복잡한 작업)\n\n**Scenario**: 10개 이상의 파일이 관련된 복잡한 마이크로서비스 개발\n\n**Input**:\n```python\n# 복잡한 작업: 순차 + 병렬 위임 조합\nasync def develop_microservice():\n # Phase 1: 순차 실행 (의존성 있음)\n design = await Agent(\n subagent_type=\"api-designer\",\n prompt=\"Design REST API for order management service\"\n )\n\n # Phase 2: 병렬 실행 (독립적)\n backend, frontend, tests = await Promise.all([\n Agent(\n subagent_type=\"backend-expert\",\n prompt=\"Implement API endpoints\",\n context={\"design\": design}\n ),\n Agent(\n subagent_type=\"frontend-expert\",\n prompt=\"Create admin dashboard UI\",\n context={\"design\": design}\n ),\n Agent(\n subagent_type=\"ddd-implementer\",\n prompt=\"Generate integration tests\",\n context={\"design\": design}\n )\n ])\n\n # Phase 3: 최종 검증\n validation = await Agent(\n subagent_type=\"core-quality\",\n prompt=\"Validate complete implementation\",\n context={\"components\": [backend, frontend, tests]}\n )\n\n return validation\n```\n\n**Output**:\n```markdown\nDelegation Report\n=================\n\nPhase 1 (Sequential):\n- api-designer: Completed in 45s\n - 12 endpoints designed\n - OpenAPI spec generated\n\nPhase 2 (Parallel - 3 agents):\n- backend-expert: Completed in 120s\n - 8 API handlers implemented\n - Database models created\n- frontend-expert: Completed in 90s\n - 6 React components created\n - Admin dashboard ready\n- ddd-implementer: Completed in 75s\n - 24 integration tests generated\n - Mock data prepared\n\nPhase 3 (Validation):\n- core-quality: TRUST 5 PASSED\n - Coverage: 89%\n - No security issues\n - Code style compliant\n\nTotal Time: 195s (vs 330s sequential)\nEfficiency Gain: 41%\n```\n\n**Explanation**: 복잡한 작업은 순차/병렬 위임을 조합합니다. 의존성이 있는 작업(API 설계)은 먼저 순차 실행하고, 독립적인 작업(백엔드, 프론트엔드, 테스트)은 병렬로 실행하여 전체 시간을 41% 단축합니다.\n\n---\n\n## Common Patterns\n\n### Pattern 1: Token Budget 관리\n\n토큰 예산을 효율적으로 관리하는 패턴입니다.\n\n```python\n# SPEC Phase: 30K 예산\nAgent(subagent_type=\"workflow-spec\", prompt=\"Create SPEC\")\n# → SPEC 완료 후 반드시 /clear 실행 (45-50K 절약)\n\n# DDD Phase: 180K 예산\nAgent(subagent_type=\"ddd-implementer\", prompt=\"Implement with DDD\")\n# → 선택적 파일 로딩, 필요한 파일만 로드\n\n# Docs Phase: 40K 예산\nAgent(subagent_type=\"workflow-docs\", prompt=\"Generate documentation\")\n# → 결과 캐싱 및 템플릿 재사용\n```\n\n모니터링 방법:\n- /context 명령으로 현재 토큰 사용량 확인\n- 150K 초과 시 /clear 권장\n- 50+ 메시지 후 컨텍스트 초기화 고려\n\n### Pattern 2: Progressive Disclosure 구조\n\n스킬 문서를 3단계로 구조화하는 패턴입니다.\n\n```markdown\n## Quick Reference (30초, ~1000 토큰)\n- 핵심 개념만 포함\n- 즉시 사용 가능한 정보\n\n## Implementation Guide (5분, ~3000 토큰)\n- 단계별 워크플로우\n- 실용적인 예시\n\n## Advanced Patterns (10+분, ~5000 토큰)\n- 심층 기술 정보\n- 엣지 케이스 처리\n```\n\n파일 분리 기준:\n- SKILL.md: 500줄 이하 (핵심 내용)\n- modules/: 상세 내용 (무제한)\n- examples.md: 실행 가능한 예시\n\n### Pattern 3: 조건부 위임 (분석 기반)\n\n문제 유형에 따라 적절한 에이전트를 선택하는 패턴입니다.\n\n```python\n# 먼저 문제 분석\nanalysis = await Agent(\n subagent_type=\"debug-helper\",\n prompt=\"Analyze the error and classify type\"\n)\n\n# 분석 결과에 따라 위임\nif analysis.type == \"security\":\n await Agent(subagent_type=\"security-expert\", prompt=\"Fix security issue\")\nelif analysis.type == \"performance\":\n await Agent(subagent_type=\"performance-expert\", prompt=\"Optimize performance\")\nelif analysis.type == \"logic\":\n await Agent(subagent_type=\"backend-expert\", prompt=\"Fix business logic\")\nelse:\n await Agent(subagent_type=\"debug-expert\", prompt=\"General debugging\")\n```\n\n---\n\n## Anti-Patterns (피해야 할 패턴)\n\n### Anti-Pattern 1: 직접 실행\n\n**Problem**: MoAI가 에이전트 위임 없이 직접 코드를 작성하거나 수정함\n\n```python\n# 잘못된 예시\ndef moai_direct_execution():\n # MoAI가 직접 파일 수정 - 절대 금지!\n with open(\"src/app.py\", \"w\") as f:\n f.write(\"# Direct modification\")\n```\n\n**Solution**: 모든 작업은 전문 에이전트에게 위임\n\n```python\n# 올바른 예시\nawait Agent(\n subagent_type=\"backend-expert\",\n prompt=\"Modify src/app.py to add new feature\",\n context={\"requirements\": feature_spec}\n)\n```\n\n### Anti-Pattern 2: Phase 간 /clear 누락\n\n**Problem**: SPEC Phase 완료 후 /clear 없이 DDD Phase 진행하여 토큰 낭비\n\n```bash\n# 잘못된 예시\n/moai:1-plan \"feature\" # 30K 사용\n/moai:2-run SPEC-001 # 이전 컨텍스트 유지 → 토큰 부족!\n```\n\n**Solution**: Phase 완료 후 반드시 /clear 실행\n\n```bash\n# 올바른 예시\n/moai:1-plan \"feature\" # 30K 사용\n/clear # 컨텍스트 초기화 (45-50K 절약)\n/moai:2-run SPEC-001 # 새로운 180K 예산으로 시작\n```\n\n### Anti-Pattern 3: 과도한 순차 실행\n\n**Problem**: 독립적인 작업을 불필요하게 순차 실행\n\n```python\n# 잘못된 예시 - 비효율적\nbackend = await Agent(subagent_type=\"backend-expert\", ...)\nfrontend = await Agent(subagent_type=\"frontend-expert\", ...) # 대기 불필요\ndocs = await Agent(subagent_type=\"docs-generator\", ...) # 대기 불필요\n```\n\n**Solution**: 독립적인 작업은 병렬 실행\n\n```python\n# 올바른 예시 - 효율적\nbackend, frontend, docs = await Promise.all([\n Agent(subagent_type=\"backend-expert\", ...),\n Agent(subagent_type=\"frontend-expert\", ...),\n Agent(subagent_type=\"docs-generator\", ...)\n])\n```\n\n### Anti-Pattern 4: TRUST 5 검증 생략\n\n**Problem**: 품질 게이트 없이 코드 머지\n\n```bash\n# 잘못된 예시\ngit add . && git commit -m \"Add feature\" && git push\n# → 테스트 커버리지, 보안 취약점 미확인\n```\n\n**Solution**: 머지 전 반드시 TRUST 5 검증\n\n```python\n# 올바른 예시\nvalidation = await Agent(\n subagent_type=\"core-quality\",\n prompt=\"Validate with TRUST 5 before merge\"\n)\n\nif validation.passed:\n # 안전하게 머지\n await Agent(subagent_type=\"git-manager\", prompt=\"Create PR and merge\")\nelse:\n # 이슈 해결 후 재검증\n await Agent(subagent_type=\"debug-expert\", prompt=\"Fix validation issues\")\n```\n\n---\n\n## Quick Decision Matrix\n\n작업 복잡도에 따른 에이전트 선택 가이드:\n\n| 복잡도 | 파일 수 | 에이전트 수 | 실행 패턴 |\n|--------|---------|------------|----------|\n| Simple | 1개 | 1-2개 | 순차 |\n| Medium | 3-5개 | 2-3개 | 순차 |\n| Complex | 10+개 | 5+개 | 순차+병렬 혼합 |\n\n토큰 예산 배분:\n\n| Phase | 예산 | 전략 |\n|-------|------|------|\n| SPEC | 30K | 요구사항만 로드 |\n| DDD | 180K | 선택적 파일 로딩 |\n| Docs | 40K | 결과 캐싱 |\n| Total | 250K | Phase 분리 |\n\n---\n\nVersion: 1.0.0\nLast Updated: 2025-12-06\n","content_type":"text/markdown; charset=utf-8","language":"markdown","size":10726,"content_sha256":"1527f54100b8f4b7ddc2d14da42ee006d093bb5c1fb3bad669e2b0474e29d94d"},{"filename":"references/reference.md","content":"# moai-foundation-core Reference\n\nProgressive Disclosure Level 2: Extended documentation for foundational principles and architectural patterns.\n\n---\n\n## API Reference\n\n### Core Concepts\n\nTRUST 5 Framework:\n- Purpose: Automated quality gate system for code quality assurance\n- Components: Test-first, Readable, Unified, Secured, Trackable\n- Integration: Pre-commit hooks, CI/CD pipelines, agent workflows\n- Validation: Automated checks with configurable thresholds\n\nSPEC-First DDD:\n- Purpose: Specification-driven development workflow\n- Phases: SPEC (Plan), DDD (Run), Docs (Sync)\n- Format: GEARS (Generalized EARS) — primary notation; EARS (Easy Approach to Requirements Syntax) retained as legacy reference for the 6-month backward-compatibility window (expires 2026-11-22)\n- Token Budget: 30K (SPEC) + 180K (DDD) + 40K (Docs) = 250K total\n\nDelegation Patterns:\n- Purpose: Task orchestration via specialized agents\n- Core Principle: MoAI delegates all work through Agent() calls\n- Patterns: Sequential, Parallel, Conditional delegation\n- Agent Selection: Complexity-based agent matching\n\nToken Optimization:\n- Purpose: Efficient 200K token budget management\n- Strategies: Phase separation, selective loading, context reset\n- Savings: /clear after phases, model selection optimization\n- Monitoring: /context command for budget tracking\n\nProgressive Disclosure:\n- Purpose: Three-tier knowledge delivery architecture\n- Levels: Quick (30s), Implementation (5min), Advanced (10+min)\n- Token Allocation: 1K, 3K, 5K tokens respectively\n- Structure: SKILL.md core with modules/ overflow\n\nModular System:\n- Purpose: Scalable file organization for unlimited content\n- Structure: SKILL.md (500 lines) + modules/ (unlimited)\n- Principles: Topic-focused, self-contained modules\n- Discovery: Progressive navigation from core to deep dive\n\n---\n\n## Configuration Options\n\n### TRUST 5 Thresholds\n\n```yaml\ntrust_5:\n test_first:\n min_coverage: 0.85 # Minimum 85% test coverage\n coverage_tool: \"pytest-cov\" # Coverage measurement tool\n failure_action: \"block\" # block, warn, ignore\n\n readable:\n linter: \"ruff\" # Code linter tool\n max_complexity: 10 # Maximum cyclomatic complexity\n naming_convention: \"snake_case\"\n failure_action: \"warn\"\n\n unified:\n formatter: \"black\" # Code formatter\n import_sorter: \"isort\" # Import organization\n line_length: 88 # Maximum line length\n failure_action: \"auto_fix\"\n\n secured:\n scanner: \"bandit\" # Security scanner\n owasp_compliance: true # OWASP Top 10 check\n secret_detection: true # Credential scanning\n failure_action: \"block\"\n\n trackable:\n commit_format: \"conventional\" # Commit message format\n branch_naming: \"feature/*\" # Branch naming pattern\n changelog_required: true # Changelog requirement\n failure_action: \"warn\"\n```\n\n### Token Budget Allocation\n\n```yaml\ntoken_budget:\n total: 250000 # Total available tokens\n\n phases:\n spec:\n budget: 30000 # 30K for SPEC phase\n strategy: \"minimal_context\"\n clear_after: true # Execute /clear after phase\n\n ddd:\n budget: 180000 # 180K for DDD phase\n strategy: \"selective_loading\"\n file_priority: [\"tests\", \"src\", \"config\"]\n\n docs:\n budget: 40000 # 40K for docs phase\n strategy: \"cached_results\"\n template_reuse: true\n\n optimization:\n clear_threshold: 150000 # Suggest /clear at this level\n message_limit: 50 # Suggest /clear after messages\n model_selection:\n quality: \"sonnet\" # For quality-critical tasks\n speed: \"haiku\" # For speed/cost optimization\n```\n\n### Agent Selection Matrix\n\n```yaml\nagent_selection:\n by_complexity:\n simple: # 1 file\n agents: 1-2\n pattern: \"sequential\"\n\n medium: # 3-5 files\n agents: 2-3\n pattern: \"sequential\"\n\n complex: # 10+ files\n agents: 5+\n pattern: \"mixed\"\n\n by_domain:\n backend:\n primary: \"backend-expert\"\n supporting: [\"database-expert\", \"api-designer\"]\n\n frontend:\n primary: \"frontend-expert\"\n supporting: [\"ui-specialist\", \"accessibility-checker\"]\n\n security:\n primary: \"security-expert\"\n supporting: [\"compliance-checker\", \"penetration-tester\"]\n\n infrastructure:\n primary: \"devops-expert\"\n supporting: [\"cloud-architect\", \"monitoring-specialist\"]\n```\n\n---\n\n## Integration Patterns\n\n### Pattern 1: TRUST 5 Pre-Commit Hook\n\n```python\n# Pre-commit hook integration for TRUST 5 validation\nfrom moai_foundation_core import TRUST5Validator\n\ndef pre_commit_validation(staged_files: List[str]) -> bool:\n \"\"\"Run TRUST 5 validation on staged files.\"\"\"\n\n validator = TRUST5Validator()\n\n # Run all pillars\n results = {\n \"test_first\": validator.check_test_coverage(staged_files),\n \"readable\": validator.check_readability(staged_files),\n \"unified\": validator.check_formatting(staged_files),\n \"secured\": validator.check_security(staged_files),\n \"trackable\": validator.check_commit_message()\n }\n\n # Evaluate results\n all_passed = all(r.passed for r in results.values())\n\n if not all_passed:\n for pillar, result in results.items():\n if not result.passed:\n print(f\"[TRUST 5] {pillar.upper()}: {result.message}\")\n\n return all_passed\n```\n\n### Pattern 2: SPEC-First DDD Workflow\n\n```python\n# Complete SPEC-First DDD cycle implementation\nfrom moai_foundation_core import SPECManager, DDDExecutor, DocsGenerator\n\nasync def spec_first_workflow(requirements: str):\n \"\"\"Execute complete SPEC-First DDD workflow.\"\"\"\n\n # Phase 1: SPEC Generation (30K tokens)\n spec_manager = SPECManager()\n spec = await spec_manager.generate_spec(\n requirements=requirements,\n format=\"GEARS\" # current notation; format=\"EARS\" supported for legacy SPECs during 6-month backward-compat window\n )\n print(f\"Generated: {spec.id}\")\n\n # Critical: Clear context before Phase 2\n await execute_clear() # Saves 45-50K tokens\n\n # Phase 2: DDD Implementation (180K tokens)\n ddd = DDDExecutor(spec.id)\n\n # ANALYZE: Understand requirements and existing behavior\n analysis = await ddd.analyze()\n assert analysis.requirements_complete == True\n\n # PRESERVE: Ensure existing behavior is protected\n characterization = await ddd.preserve()\n assert await ddd.run_tests() == \"PASS\"\n\n # IMPROVE: Implement improvements incrementally\n improved = await ddd.improve()\n assert await ddd.run_tests() == \"PASS\"\n\n # Validate coverage\n coverage = await ddd.get_coverage()\n assert coverage >= 0.85\n\n # Phase 3: Documentation (40K tokens)\n docs = DocsGenerator(spec.id)\n await docs.generate_api_docs()\n await docs.generate_architecture_diagrams()\n await docs.update_project_readme()\n\n return {\"spec\": spec, \"coverage\": coverage}\n```\n\n### Pattern 3: Intelligent Agent Delegation\n\n```python\n# Complexity-based agent delegation\nfrom moai_foundation_core import TaskAnalyzer, AgentRouter\n\nasync def delegate_task(task_description: str, context: dict):\n \"\"\"Delegate task to appropriate agents based on complexity.\"\"\"\n\n # Analyze task complexity\n analyzer = TaskAnalyzer()\n analysis = analyzer.analyze(task_description, context)\n\n print(f\"Complexity: {analysis.complexity}\")\n print(f\"Affected files: {analysis.file_count}\")\n print(f\"Domains: {analysis.domains}\")\n\n # Route to appropriate agents\n router = AgentRouter()\n\n if analysis.complexity == \"simple\":\n # Sequential single agent\n result = await Agent(\n subagent_type=router.get_primary_agent(analysis.domains[0]),\n prompt=task_description,\n context=context\n )\n\n elif analysis.complexity == \"medium\":\n # Sequential multiple agents\n results = []\n for domain in analysis.domains:\n result = await Agent(\n subagent_type=router.get_primary_agent(domain),\n prompt=f\"Handle {domain} aspects: {task_description}\",\n context={**context, \"previous_results\": results}\n )\n results.append(result)\n\n else: # complex\n # Parallel then sequential integration\n parallel_results = await Promise.all([\n Agent(subagent_type=router.get_primary_agent(d), prompt=f\"{d}: {task_description}\")\n for d in analysis.domains\n ])\n\n # Integration phase\n result = await Agent(\n subagent_type=\"integration-specialist\",\n prompt=\"Integrate all components\",\n context={\"results\": parallel_results}\n )\n\n return result\n```\n\n### Pattern 4: Token-Optimized Context Management\n\n```python\n# Proactive token budget management\nfrom moai_foundation_core import TokenMonitor, ContextOptimizer\n\nclass TokenAwareWorkflow:\n \"\"\"Workflow with automatic token optimization.\"\"\"\n\n def __init__(self, total_budget: int = 200000):\n self.monitor = TokenMonitor(total_budget)\n self.optimizer = ContextOptimizer()\n\n async def execute_with_optimization(self, tasks: List[dict]):\n \"\"\"Execute tasks with automatic context management.\"\"\"\n\n results = []\n\n for task in tasks:\n # Check current usage\n usage = self.monitor.get_current_usage()\n\n if usage > 0.75: # 75% threshold\n print(f\"Token usage: {usage*100:.1f}%\")\n\n # Apply optimization strategies\n if usage > 0.9:\n print(\"Executing /clear to reset context\")\n await execute_clear()\n self.monitor.reset()\n else:\n # Selective context pruning\n self.optimizer.prune_least_relevant()\n\n # Execute task\n result = await self.execute_task(task)\n results.append(result)\n\n # Update token tracking\n self.monitor.add_usage(result.tokens_used)\n\n return results\n```\n\n---\n\n## Troubleshooting\n\n### Common Issues\n\nIssue: TRUST 5 validation fails inconsistently:\n- Cause: Different tool versions between local and CI\n- Solution: Pin tool versions in requirements.txt/pyproject.toml\n- Prevention: Use locked dependency files\n\nIssue: SPEC phase consumes too many tokens:\n- Cause: Excessive context loading during spec generation\n- Solution: Use minimal context mode for SPEC phase\n- Prevention: Configure `spec.strategy: \"minimal_context\"`\n\nIssue: Agent delegation creates infinite loops:\n- Cause: Circular dependencies between agents\n- Solution: Implement task ID tracking and loop detection\n- Prevention: Design clear agent responsibilities with no overlap\n\nIssue: Token budget exhausted mid-workflow:\n- Cause: Missing /clear between phases\n- Solution: Always execute /clear after Phase 1\n- Prevention: Enable automatic phase boundary detection\n\nIssue: Progressive disclosure not loading modules:\n- Cause: Incorrect cross-reference paths\n- Solution: Verify paths in SKILL.md match actual file locations\n- Prevention: Use relative paths from SKILL.md location\n\n### Diagnostic Commands\n\n```bash\n# TRUST 5 status check\nmoai-trust check --all --verbose\n\n# Token budget analysis\nmoai-context analyze --show-breakdown\n\n# Agent routing debug\nmoai-agent route --task \"description\" --dry-run\n\n# SPEC validation\nmoai-spec validate SPEC-001 --format GEARS # current notation; --format EARS supported for legacy SPECs during the 6-month backward-compat window\n```\n\n### Validation Utilities\n\n```python\nfrom moai_foundation_core import diagnose\n\n# Full system diagnostics\nreport = diagnose.run_full_check()\n\n# Individual component checks\ndiagnose.check_trust5_tools()\ndiagnose.check_agent_availability()\ndiagnose.check_token_tracking()\ndiagnose.verify_module_structure()\n```\n\n### Log Locations\n\n- TRUST 5 logs: `.moai/logs/trust5/`\n- SPEC artifacts: `.moai/specs/`\n- Agent execution logs: `.moai/logs/agents/`\n- Token usage history: `.moai/logs/tokens/`\n\n---\n\n## External Resources\n\n### Official Documentation\n\n- MoAI-ADK Documentation: See project README\n- Claude Code Skills Guide: https://docs.anthropic.com/claude-code/skills\n- GEARS Specification Format (current; canonical authoring guide): `.claude/skills/moai-workflow-spec/SKILL.md` § \"GEARS Format\"\n- EARS Specification Format (legacy reference, 6-month backward-compat): See `modules/spec-first-ddd.md` + `modules/spec-ears-format.md`\n\n### Module References\n\n- TRUST 5 Framework: `modules/trust-5-framework.md`\n- SPEC-First DDD: `modules/spec-first-ddd.md`\n- Delegation Patterns: `modules/delegation-patterns.md`\n- Token Optimization: `modules/token-optimization.md`\n- Progressive Disclosure: `modules/progressive-disclosure.md`\n- Modular System: `modules/modular-system.md`\n- Agents Reference: `modules/agents-reference.md`\n- Commands Reference: `modules/commands-reference.md`\n- Execution Rules: `modules/execution-rules.md`\n\n### Related Skills\n\n- moai-foundation-cc - Claude Code integration patterns\n- moai-workflow-project - Project management with core principles\n- moai-workflow-testing - Testing workflows with TRUST 5\n- moai-workflow-templates - Template management integration\n\n### Tool References\n\n- pytest: https://docs.pytest.org/\n- ruff: https://docs.astral.sh/ruff/\n- black: https://black.readthedocs.io/\n- bandit: https://bandit.readthedocs.io/\n\n### Best Practices\n\nTRUST 5 Implementation:\n- Run all validations before commits\n- Configure appropriate failure actions\n- Document exceptions and waivers\n- Track quality metrics over time\n\nSPEC-First Development:\n- Write clear GEARS specifications (current notation; EARS retained as legacy reference for the 6-month backward-compat window)\n- Execute /clear between phases\n- Maintain 85%+ test coverage\n- Generate documentation with each feature\n\nAgent Delegation:\n- Match complexity to agent count\n- Use parallel execution for independent tasks\n- Implement proper error handling\n- Track delegation outcomes\n\nToken Management:\n- Monitor usage proactively\n- Clear context at phase boundaries\n- Use selective file loading\n- Choose appropriate model for task\n\n### Version History\n\n| Version | Date | Changes |\n|---------|------------|---------------------------------------------------|\n| 2.3.0 | 2025-12-03 | Added agents, commands, execution rules modules |\n| 2.2.0 | 2025-11-28 | Optimized to 500-line SKILL.md |\n| 2.1.0 | 2025-11-25 | Added modular architecture patterns |\n| 2.0.0 | 2025-11-20 | Unified six foundational principles |\n| 1.0.0 | 2025-11-15 | Initial release with TRUST 5 and SPEC-First |\n\n---\n\nStatus: Reference Documentation Complete\nLast Updated: 2025-12-06\nSkill Version: 2.3.0\n","content_type":"text/markdown; charset=utf-8","language":"markdown","size":14935,"content_sha256":"f80106752f2af98979c56088ed5df15ecda5df9dc5743d29adcc172fde01e180"}],"content_json":{"type":"doc","content":[{"type":"heading","attrs":{"level":1},"content":[{"text":"MoAI Foundation Core","type":"text"}]},{"type":"paragraph","content":[{"text":"Foundational principles and architectural patterns that power MoAI-ADK's AI-driven development workflow.","type":"text"}]},{"type":"paragraph","content":[{"text":"Core Philosophy: Quality-first, domain-driven, modular, and efficient AI development through proven patterns and automated workflows.","type":"text"}]},{"type":"heading","attrs":{"level":2},"content":[{"text":"Quick Reference","type":"text"}]},{"type":"paragraph","content":[{"text":"What is MoAI Foundation Core?","type":"text"}]},{"type":"paragraph","content":[{"text":"Six essential principles that ensure quality, efficiency, and scalability in AI-powered development:","type":"text"}]},{"type":"ordered_list","attrs":{"order":1,"listStyle":"number"},"content":[{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"TRUST 5 Framework - Quality gate system (Tested, Readable, Unified, Secured, Trackable)","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"SPEC-First DDD - Specification-driven domain-driven development workflow","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Delegation Patterns - Task orchestration via specialized agents (never direct execution)","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Token Optimization - 200K budget management and context efficiency","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Progressive Disclosure - Three-tier knowledge delivery (Quick, Implementation, Advanced)","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Modular System - File splitting and reference architecture for scalability","type":"text"}]}]}]},{"type":"paragraph","content":[{"text":"Quick Access:","type":"text"}]},{"type":"bullet_list","content":[{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Quality standards in modules/trust-5-framework.md","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Development workflow in modules/spec-first-ddd.md","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Agent coordination in modules/delegation-patterns.md","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Budget management in modules/token-optimization.md","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Content structure in modules/progressive-disclosure.md","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"File organization in modules/modular-system.md","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Agent catalog in modules/agents-reference.md","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Command reference in modules/commands-reference.md","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Security and constraints in modules/execution-rules.md","type":"text"}]}]}]},{"type":"paragraph","content":[{"text":"Use Cases:","type":"text"}]},{"type":"bullet_list","content":[{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"New agent creation with quality standards","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"New skill development with structural guidelines","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Complex workflow orchestration","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Token budget planning and optimization","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Documentation architecture design","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Quality gate configuration","type":"text"}]}]}]},{"type":"hr","attrs":{"markup":"---"}},{"type":"heading","attrs":{"level":2},"content":[{"text":"Implementation Guide","type":"text"}]},{"type":"heading","attrs":{"level":3},"content":[{"text":"1. TRUST 5 Framework - Quality Assurance System","type":"text"}]},{"type":"paragraph","content":[{"text":"Purpose: Automated quality gates ensuring code quality, security, and maintainability.","type":"text"}]},{"type":"paragraph","content":[{"text":"Five Pillars:","type":"text"}]},{"type":"paragraph","content":[{"text":"Tested Pillar: Maintain comprehensive test coverage with characterization tests ensuring behavior preservation. Execute pytest with coverage reporting. Block merge and generate missing tests on failure. Characterization tests capture current behavior for legacy code, while specification tests validate domain requirements for new code. High coverage ensures code reliability and reduces production defects. Preserves behavior during refactoring and reduces debugging time by 60-70 percent.","type":"text"}]},{"type":"paragraph","content":[{"text":"Readable Pillar: Use clear and descriptive naming conventions. Execute ruff linter checks. Issue warning and suggest refactoring improvements on failure. Clear naming improves code comprehension and team collaboration. Reduces onboarding time by 40 percent and improves maintenance velocity.","type":"text"}]},{"type":"paragraph","content":[{"text":"Unified Pillar: Apply consistent formatting and import patterns. Execute black formatter and isort checks. Auto-format code or issue warning on failure. Consistency eliminates style debates and merge conflicts. Reduces code review time by 30 percent and improves readability.","type":"text"}]},{"type":"paragraph","content":[{"text":"Secured Pillar: Comply with OWASP security standards. Execute security-expert agent analysis. Block merge and require security review on failure. Security vulnerabilities create critical business and legal risks. Prevents 95+ percent of common security vulnerabilities.","type":"text"}]},{"type":"paragraph","content":[{"text":"Trackable Pillar: Write clear and structured commit messages. Match Git commit message regex patterns. Suggest proper commit message format on failure. Clear history enables debugging, auditing, and collaboration. Reduces issue investigation time by 50 percent.","type":"text"}]},{"type":"paragraph","content":[{"text":"Integration Points: Pre-commit hooks for automated validation, CI/CD pipelines for quality gate enforcement, Agent workflows for core-quality validation, Documentation for quality metrics.","type":"text"}]},{"type":"paragraph","content":[{"text":"Detailed Reference: modules/trust-5-framework.md","type":"text"}]},{"type":"hr","attrs":{"markup":"---"}},{"type":"heading","attrs":{"level":3},"content":[{"text":"2. SPEC-First DDD - Development Workflow","type":"text"}]},{"type":"paragraph","content":[{"text":"Purpose: Specification-driven development ensuring clear requirements before implementation.","type":"text"}]},{"type":"paragraph","content":[{"text":"Three-Phase Workflow:","type":"text"}]},{"type":"paragraph","content":[{"text":"Phase 1 SPEC (/moai:1-plan): workflow-spec generates GEARS format (primary; EARS retained as 6-month backward-compat legacy reference for the 88 pre-v3 SPECs). Output is .moai/specs/SPEC-XXX/spec.md. Execute /clear to save 45-50K tokens.","type":"text"}]},{"type":"paragraph","content":[{"text":"Phase 2 DDD (/moai:2-run): ANALYZE for requirements, PRESERVE for existing behavior, IMPROVE for enhancement. Validate with at least 85% coverage.","type":"text"}]},{"type":"paragraph","content":[{"text":"Phase 3 Docs (/moai:3-sync): API documentation, architecture diagrams, project reports.","type":"text"}]},{"type":"paragraph","content":[{"text":"GEARS Format (current notation): Five patterns — Ubiquitous \"The \u003csubject> shall \u003cbehavior>\" for system-wide always active requirements; Event-driven \"When \u003cevent> the \u003csubject> shall \u003cbehavior>\" for trigger-response requirements; State-driven \"While \u003cstate> the \u003csubject> shall \u003cbehavior>\" for conditional behavior; Where (capability gate) \"Where \u003ccapability or feature flag>, the \u003csubject> shall \u003cbehavior>\" for capability-conditioned behavior; Event-detected (replaces the deprecated conditional modality) \"When \u003cundesired-condition-detected>, the \u003csubject> shall \u003cresponse>\" for failure-mode handling. Unified compound clause: ","type":"text"},{"text":"[Where ...][While ...][When ...] The \u003csubject> shall \u003cbehavior>","type":"text","marks":[{"type":"code_inline"}]},{"text":" — any subset of the three modifiers may chain. The ","type":"text"},{"text":"\u003csubject>","type":"text","marks":[{"type":"code_inline"}]},{"text":" is generalized — any noun (system, component, service, agent, function, artifact). See the canonical authoring guide at ","type":"text"},{"text":".claude/skills/moai-workflow-spec/SKILL.md","type":"text","marks":[{"type":"code_inline"}]},{"text":" § \"GEARS Format\".","type":"text"}]},{"type":"paragraph","content":[{"text":"EARS Format (legacy reference, 6-month backward-compat — expires 2026-11-22): Five patterns Ubiquitous / Event-driven (WHEN/THEN) / State-driven (WHILE) / Unwanted (SHALL NOT) / Optional (WHERE possible). The 88 pre-v3 SPECs continue to use EARS; the lint engine emits a ","type":"text"},{"text":"LegacyEARSKeyword","type":"text","marks":[{"type":"code_inline"}]},{"text":" warning on residual deprecated conditional modality in NEW SPECs (warning non-strict, error under ","type":"text"},{"text":"moai spec lint --strict","type":"text","marks":[{"type":"code_inline"}]},{"text":"). For NEW SPECs, use GEARS. See ","type":"text"},{"text":"modules/spec-ears-format.md","type":"text","marks":[{"type":"code_inline"}]},{"text":" (legacy reference, deprecated — see GEARS Format guide).","type":"text"}]},{"type":"paragraph","content":[{"text":"Token Budget: SPEC takes 30K, DDD takes 180K, Docs takes 40K, Total is 250K.","type":"text"}]},{"type":"paragraph","content":[{"text":"Key Practice: Execute /clear after Phase 1 to initialize context.","type":"text"}]},{"type":"paragraph","content":[{"text":"Detailed Reference: modules/spec-first-ddd.md","type":"text"}]},{"type":"hr","attrs":{"markup":"---"}},{"type":"heading","attrs":{"level":3},"content":[{"text":"3. Delegation Patterns - Agent Orchestration","type":"text"}]},{"type":"paragraph","content":[{"text":"Purpose: Task delegation to specialized agents, avoiding direct execution.","type":"text"}]},{"type":"paragraph","content":[{"text":"Core Principle: MoAI must delegate all work through Agent() to specialized agents. Direct execution bypasses specialization, quality gates, and token optimization. Proper delegation improves task success rate by 40 percent and enables parallel execution.","type":"text"}]},{"type":"paragraph","content":[{"text":"Delegation Syntax: Call Task with subagent_type parameter for specialized agent, prompt parameter for clear specific task, and context parameter with relevant data dictionary.","type":"text"}]},{"type":"paragraph","content":[{"text":"Three Patterns:","type":"text"}]},{"type":"paragraph","content":[{"text":"Sequential for dependencies: Call Task to api-designer for design, then Task to backend-expert for implementation with design context.","type":"text"}]},{"type":"paragraph","content":[{"text":"Parallel for independent work: Call Promise.all with Task to backend-expert and Task to frontend-expert simultaneously.","type":"text"}]},{"type":"paragraph","content":[{"text":"Conditional for analysis-based: Call Task to debug-helper for analysis, then based on analysis.type, call Task to security-expert or other appropriate agent.","type":"text"}]},{"type":"paragraph","content":[{"text":"Agent Selection: Simple tasks with 1 file use 1-2 agents sequential. Medium tasks with 3-5 files use 2-3 agents sequential. Complex tasks with 10+ files use 5+ agents mixed.","type":"text"}]},{"type":"paragraph","content":[{"text":"Detailed Reference: modules/delegation-patterns.md","type":"text"}]},{"type":"hr","attrs":{"markup":"---"}},{"type":"heading","attrs":{"level":3},"content":[{"text":"4. Token Optimization - Budget Management","type":"text"}]},{"type":"paragraph","content":[{"text":"Purpose: Efficient 200K token budget through strategic context management.","type":"text"}]},{"type":"paragraph","content":[{"text":"Budget Allocation:","type":"text"}]},{"type":"paragraph","content":[{"text":"SPEC Phase takes 30K tokens. Strategy is to load requirements only and execute /clear after completion. Specification phase requires minimal context for requirement analysis. Saves 45-50K tokens for implementation phase.","type":"text"}]},{"type":"paragraph","content":[{"text":"DDD Phase takes 180K tokens. Strategy is selective file loading, load only implementation-relevant files. Implementation requires deep context but not full codebase. Enables 70 percent larger implementations within budget.","type":"text"}]},{"type":"paragraph","content":[{"text":"Docs Phase takes 40K tokens. Strategy is result caching and template reuse. Documentation builds on completed work artifacts. Reduces redundant file reads by 60 percent.","type":"text"}]},{"type":"paragraph","content":[{"text":"Total Budget is 250K tokens across all phases. Phase separation with context reset between phases provides clean context boundaries and prevents token bloat. Enables 2-3x larger projects within same budget.","type":"text"}]},{"type":"paragraph","content":[{"text":"Token Saving Strategies:","type":"text"}]},{"type":"paragraph","content":[{"text":"Phase Separation: Execute /clear between phases, after /moai:1-plan to save 45-50K, when context exceeds 150K, after 50+ messages.","type":"text"}]},{"type":"paragraph","content":[{"text":"Selective Loading: Load only necessary files.","type":"text"}]},{"type":"paragraph","content":[{"text":"Context Optimization: Target 20-30K tokens.","type":"text"}]},{"type":"paragraph","content":[{"text":"Model Selection: Sonnet for quality, Haiku for speed and cost with 70% cheaper rates for 60-70% total savings.","type":"text"}]},{"type":"paragraph","content":[{"text":"Detailed Reference: modules/token-optimization.md","type":"text"}]},{"type":"hr","attrs":{"markup":"---"}},{"type":"heading","attrs":{"level":3},"content":[{"text":"5. Progressive Disclosure - Content Architecture","type":"text"}]},{"type":"paragraph","content":[{"text":"Purpose: Three-tier knowledge delivery balancing value with depth.","type":"text"}]},{"type":"paragraph","content":[{"text":"Three Levels:","type":"text"}]},{"type":"paragraph","content":[{"text":"Quick Reference Level: 30 seconds time investment, core principles and essential concepts, approximately 1,000 tokens. Rapid value delivery for time-constrained users. Users gain 80 percent understanding in 5 percent of time.","type":"text"}]},{"type":"paragraph","content":[{"text":"Implementation Level: 5 minutes time investment, workflows, practical examples, integration patterns, approximately 3,000 tokens. Bridges concept to execution with actionable guidance. Enables immediate productive work without deep expertise.","type":"text"}]},{"type":"paragraph","content":[{"text":"Advanced Level: 10+ minutes time investment, deep technical dives, edge cases, optimization techniques, approximately 5,000 tokens. Provides mastery-level knowledge for complex scenarios. Reduces escalations by 70 percent through comprehensive coverage.","type":"text"}]},{"type":"paragraph","content":[{"text":"SKILL.md Structure (maximum 500 lines): Quick Reference section, Implementation Guide section, Advanced Patterns section, Works Well With section.","type":"text"}]},{"type":"paragraph","content":[{"text":"Module Architecture: SKILL.md as entry point with cross-references, modules directory for deep dives with unlimited size, examples.md for working samples, reference.md for external links.","type":"text"}]},{"type":"paragraph","content":[{"text":"File Splitting when exceeding 500 lines: SKILL.md contains Quick at 80-120 lines, Implementation at 180-250 lines, Advanced at 80-140 lines, References at 10-20 lines. Overflow content goes to modules/topic.md.","type":"text"}]},{"type":"paragraph","content":[{"text":"Detailed Reference: modules/progressive-disclosure.md","type":"text"}]},{"type":"hr","attrs":{"markup":"---"}},{"type":"heading","attrs":{"level":3},"content":[{"text":"6. Modular System - File Organization","type":"text"}]},{"type":"paragraph","content":[{"text":"Purpose: Scalable file structure enabling unlimited content.","type":"text"}]},{"type":"paragraph","content":[{"text":"Standard Structure: Create .claude/skills/skill-name/ directory containing SKILL.md as core file under 500 lines, modules directory for extended content with unlimited size including patterns.md, examples.md for working samples, reference.md for external links, scripts directory for utilities (optional), templates directory (optional).","type":"text"}]},{"type":"paragraph","content":[{"text":"File Principles: SKILL.md stays under 500 lines with progressive disclosure and cross-references. modules directory is topic-focused with no limits and self-contained content. examples.md is copy-paste ready with comments. reference.md contains API docs and resources.","type":"text"}]},{"type":"paragraph","content":[{"text":"Cross-Reference Syntax: Reference modules as Details in modules/patterns.md, reference examples as Examples in examples.md#auth, reference external docs as External in reference.md#api.","type":"text"}]},{"type":"paragraph","content":[{"text":"Discovery Flow: SKILL.md to Topic to modules/topic.md to Deep dive.","type":"text"}]},{"type":"paragraph","content":[{"text":"Detailed Reference: modules/modular-system.md","type":"text"}]},{"type":"hr","attrs":{"markup":"---"}},{"type":"heading","attrs":{"level":2},"content":[{"text":"Advanced Implementation","type":"text"}]},{"type":"paragraph","content":[{"text":"Advanced patterns including cross-module integration, quality validation, and error handling are available in the detailed module references.","type":"text"}]},{"type":"paragraph","content":[{"text":"Key Advanced Topics:","type":"text"}]},{"type":"bullet_list","content":[{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Cross-Module Integration: Combining TRUST 5 + SPEC-First DDD","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Token-Optimized Delegation: Parallel execution with context reset","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Progressive Agent Workflows: Escalation patterns","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Quality Validation: Pre/Post execution validation","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Error Handling: Delegation failure recovery","type":"text"}]}]}]},{"type":"paragraph","content":[{"text":"Detailed Reference: examples.md for working code samples","type":"text"}]},{"type":"hr","attrs":{"markup":"---"}},{"type":"heading","attrs":{"level":2},"content":[{"text":"Works Well With","type":"text"}]},{"type":"paragraph","content":[{"text":"Agents: agent-factory for creating agents with foundation principles, skill-factory for generating skills with modular architecture, core-quality for automated TRUST 5 validation, workflow-spec for GEARS format specification (current; EARS retained as legacy reference for 6-month backward-compat), workflow-ddd for ANALYZE-PRESERVE-IMPROVE execution, workflow-docs for documentation with progressive disclosure.","type":"text"}]},{"type":"paragraph","content":[{"text":"Skills: moai-cc-claude-md for CLAUDE.md with foundation patterns, moai-cc-configuration for config with TRUST 5, moai-cc-memory for token optimization, moai-context7-integration for MCP integration.","type":"text"}]},{"type":"paragraph","content":[{"text":"Tools: AskUserQuestion for direct user interaction and clarification needs.","type":"text"}]},{"type":"paragraph","content":[{"text":"Commands: /moai:1-plan for SPEC-First Phase 1, /moai:2-run for DDD Phase 2, /moai:3-sync for Documentation Phase 3, /moai:9-feedback for continuous improvement, /clear for token management.","type":"text"}]},{"type":"paragraph","content":[{"text":"Foundation Modules (Extended Documentation): modules/agents-reference.md for the 8-agent retained catalog (7 MoAI-custom + 1 Anthropic built-in ","type":"text"},{"text":"Explore","type":"text","marks":[{"type":"code_inline"}]},{"text":" per SPEC-V3R6-AGENT-TEAM-REBUILD-001), modules/commands-reference.md for 6 core commands workflow, modules/execution-rules.md for security, Git strategy, and compliance. For migration of references to the 12 archived agents (","type":"text"},{"text":"manager-strategy","type":"text","marks":[{"type":"code_inline"}]},{"text":", ","type":"text"},{"text":"manager-quality","type":"text","marks":[{"type":"code_inline"}]},{"text":", ","type":"text"},{"text":"manager-brain","type":"text","marks":[{"type":"code_inline"}]},{"text":", ","type":"text"},{"text":"manager-project","type":"text","marks":[{"type":"code_inline"}]},{"text":", ","type":"text"},{"text":"claude-code-guide","type":"text","marks":[{"type":"code_inline"}]},{"text":", ","type":"text"},{"text":"researcher","type":"text","marks":[{"type":"code_inline"}]},{"text":", and the 6 ","type":"text"},{"text":"expert-*","type":"text","marks":[{"type":"code_inline"}]},{"text":" agents), see ","type":"text"},{"text":".claude/rules/moai/workflow/archived-agent-rejection.md","type":"text","marks":[{"type":"code_inline"}]},{"text":".","type":"text"}]},{"type":"hr","attrs":{"markup":"---"}},{"type":"heading","attrs":{"level":2},"content":[{"text":"Quick Decision Guide","type":"text"}]},{"type":"paragraph","content":[{"text":"New Agent: Primary principle is TRUST 5 and Delegation. Supporting principles are Token Optimization and Modular.","type":"text"}]},{"type":"paragraph","content":[{"text":"New Skill: Primary principle is Progressive and Modular. Supporting principles are TRUST 5 and Token Optimization.","type":"text"}]},{"type":"paragraph","content":[{"text":"Workflow: Primary principle is Delegation Patterns. Supporting principles are SPEC-First and Token Optimization.","type":"text"}]},{"type":"paragraph","content":[{"text":"Quality: Primary principle is TRUST 5 Framework. Supporting principle is SPEC-First DDD.","type":"text"}]},{"type":"paragraph","content":[{"text":"Budget: Primary principle is Token Optimization. Supporting principles are Progressive and Modular.","type":"text"}]},{"type":"paragraph","content":[{"text":"Docs: Primary principle is Progressive and Modular. Supporting principle is Token Optimization.","type":"text"}]},{"type":"paragraph","content":[{"text":"Module Deep Dives: modules/trust-5-framework.md, modules/spec-first-ddd.md, modules/delegation-patterns.md, modules/token-optimization.md, modules/progressive-disclosure.md, modules/modular-system.md, modules/agents-reference.md, modules/commands-reference.md, modules/execution-rules.md.","type":"text"}]},{"type":"paragraph","content":[{"text":"Full Examples: examples.md External Resources: reference.md","type":"text"}]},{"type":"paragraph","content":[{"text":"\u003c!-- moai:evolvable-start id=\"rationalizations\" -->","type":"text"}]},{"type":"heading","attrs":{"level":2},"content":[{"text":"Common Rationalizations","type":"text"}]},{"type":"table","attrs":{"layout":null},"content":[{"type":"tr","content":[{"type":"th","attrs":{"colspan":1,"rowspan":1,"colwidth":null,"alignment":""},"content":[{"type":"paragraph","content":[{"text":"Rationalization","type":"text"}]}]},{"type":"th","attrs":{"colspan":1,"rowspan":1,"colwidth":null,"alignment":""},"content":[{"type":"paragraph","content":[{"text":"Reality","type":"text"}]}]}]},{"type":"tr","content":[{"type":"td","attrs":{"colspan":1,"rowspan":1,"colwidth":null,"alignment":""},"content":[{"type":"paragraph","content":[{"text":"\"TRUST 5 is a guideline, not a gate\"","type":"text"}]}]},{"type":"td","attrs":{"colspan":1,"rowspan":1,"colwidth":null,"alignment":""},"content":[{"type":"paragraph","content":[{"text":"TRUST 5 is a HARD quality gate. All five dimensions must pass before completion.","type":"text"}]}]}]},{"type":"tr","content":[{"type":"td","attrs":{"colspan":1,"rowspan":1,"colwidth":null,"alignment":""},"content":[{"type":"paragraph","content":[{"text":"\"I can skip the SPEC for this small change\"","type":"text"}]}]},{"type":"td","attrs":{"colspan":1,"rowspan":1,"colwidth":null,"alignment":""},"content":[{"type":"paragraph","content":[{"text":"Every change without a SPEC is untracked. SPEC-less changes accumulate into unmanageable technical debt.","type":"text"}]}]}]},{"type":"tr","content":[{"type":"td","attrs":{"colspan":1,"rowspan":1,"colwidth":null,"alignment":""},"content":[{"type":"paragraph","content":[{"text":"\"Delegation to an agent is overhead for simple tasks\"","type":"text"}]}]},{"type":"td","attrs":{"colspan":1,"rowspan":1,"colwidth":null,"alignment":""},"content":[{"type":"paragraph","content":[{"text":"MoAI is an orchestrator, not an implementer. Skipping delegation bypasses domain expertise and quality checks.","type":"text"}]}]}]},{"type":"tr","content":[{"type":"td","attrs":{"colspan":1,"rowspan":1,"colwidth":null,"alignment":""},"content":[{"type":"paragraph","content":[{"text":"\"I will skip the quality gate, the code is clearly correct\"","type":"text"}]}]},{"type":"td","attrs":{"colspan":1,"rowspan":1,"colwidth":null,"alignment":""},"content":[{"type":"paragraph","content":[{"text":"Clearly correct code still needs evidence. Tests and linting are mechanisms; confidence is not.","type":"text"}]}]}]},{"type":"tr","content":[{"type":"td","attrs":{"colspan":1,"rowspan":1,"colwidth":null,"alignment":""},"content":[{"type":"paragraph","content":[{"text":"\"Progressive disclosure is not important for this project\"","type":"text"}]}]},{"type":"td","attrs":{"colspan":1,"rowspan":1,"colwidth":null,"alignment":""},"content":[{"type":"paragraph","content":[{"text":"Even small projects benefit from token-efficient skill loading. Disclosure is about context budget, not project size.","type":"text"}]}]}]}]},{"type":"paragraph","content":[{"text":"\u003c!-- moai:evolvable-end -->","type":"text"}]},{"type":"paragraph","content":[{"text":"\u003c!-- moai:evolvable-start id=\"red-flags\" -->","type":"text"}]},{"type":"heading","attrs":{"level":2},"content":[{"text":"Red Flags","type":"text"}]},{"type":"bullet_list","content":[{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"MoAI executing implementation code directly instead of delegating to an agent","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"TRUST 5 dimensions partially checked (only Tested and Readable, ignoring Secured)","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"SPEC document exists but has no acceptance criteria","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Agent selected without consulting the selection decision tree","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Quality gate skipped with \"will check later\" comment","type":"text"}]}]}]},{"type":"paragraph","content":[{"text":"\u003c!-- moai:evolvable-end -->","type":"text"}]},{"type":"paragraph","content":[{"text":"\u003c!-- moai:evolvable-start id=\"verification\" -->","type":"text"}]},{"type":"heading","attrs":{"level":2},"content":[{"text":"Verification","type":"text"}]},{"type":"checkbox_list","attrs":{"id":null},"content":[{"type":"checkbox_item","attrs":{"checked":false},"content":[{"type":"paragraph","content":[{"text":"All five TRUST 5 dimensions addressed (Tested, Readable, Unified, Secured, Trackable)","type":"text"}]}]},{"type":"checkbox_item","attrs":{"checked":false},"content":[{"type":"paragraph","content":[{"text":"Agent selection documented with rationale matching the decision tree","type":"text"}]}]},{"type":"checkbox_item","attrs":{"checked":false},"content":[{"type":"paragraph","content":[{"text":"SPEC document has acceptance criteria with observable evidence requirements","type":"text"}]}]},{"type":"checkbox_item","attrs":{"checked":false},"content":[{"type":"paragraph","content":[{"text":"Delegation chain traceable: MoAI -> agent -> execution","type":"text"}]}]},{"type":"checkbox_item","attrs":{"checked":false},"content":[{"type":"paragraph","content":[{"text":"Progressive disclosure levels configured in skill frontmatter","type":"text"}]}]}]},{"type":"paragraph","content":[{"text":"\u003c!-- moai:evolvable-end -->","type":"text"}]},{"type":"hr","attrs":{"markup":"---"}},{"type":"heading","attrs":{"level":2},"content":[{"text":"Token Budget (absorbed from moai-foundation-context)","type":"text"}]},{"type":"paragraph","content":[{"text":"Context window optimization, /clear strategy, session state persistence, and multi-agent handoff patterns.","type":"text"}]},{"type":"heading","attrs":{"level":3},"content":[{"text":"Context Window Targets","type":"text"}]},{"type":"table","attrs":{"layout":null},"content":[{"type":"tr","content":[{"type":"th","attrs":{"colspan":1,"rowspan":1,"colwidth":null,"alignment":""},"content":[{"type":"paragraph","content":[{"text":"Model class","type":"text"}]}]},{"type":"th","attrs":{"colspan":1,"rowspan":1,"colwidth":null,"alignment":""},"content":[{"type":"paragraph","content":[{"text":"Window","type":"text"}]}]},{"type":"th","attrs":{"colspan":1,"rowspan":1,"colwidth":null,"alignment":""},"content":[{"type":"paragraph","content":[{"text":"75% threshold","type":"text"}]}]},{"type":"th","attrs":{"colspan":1,"rowspan":1,"colwidth":null,"alignment":""},"content":[{"type":"paragraph","content":[{"text":"/clear trigger","type":"text"}]}]}]},{"type":"tr","content":[{"type":"td","attrs":{"colspan":1,"rowspan":1,"colwidth":null,"alignment":""},"content":[{"type":"paragraph","content":[{"text":"Opus 4.7 (1M)","type":"text"}]}]},{"type":"td","attrs":{"colspan":1,"rowspan":1,"colwidth":null,"alignment":""},"content":[{"type":"paragraph","content":[{"text":"1,000,000 tokens","type":"text"}]}]},{"type":"td","attrs":{"colspan":1,"rowspan":1,"colwidth":null,"alignment":""},"content":[{"type":"paragraph","content":[{"text":"~750,000","type":"text"}]}]},{"type":"td","attrs":{"colspan":1,"rowspan":1,"colwidth":null,"alignment":""},"content":[{"type":"paragraph","content":[{"text":"Above threshold","type":"text"}]}]}]},{"type":"tr","content":[{"type":"td","attrs":{"colspan":1,"rowspan":1,"colwidth":null,"alignment":""},"content":[{"type":"paragraph","content":[{"text":"Sonnet/Opus standard","type":"text"}]}]},{"type":"td","attrs":{"colspan":1,"rowspan":1,"colwidth":null,"alignment":""},"content":[{"type":"paragraph","content":[{"text":"200,000 tokens","type":"text"}]}]},{"type":"td","attrs":{"colspan":1,"rowspan":1,"colwidth":null,"alignment":""},"content":[{"type":"paragraph","content":[{"text":"~150,000","type":"text"}]}]},{"type":"td","attrs":{"colspan":1,"rowspan":1,"colwidth":null,"alignment":""},"content":[{"type":"paragraph","content":[{"text":"Above threshold","type":"text"}]}]}]},{"type":"tr","content":[{"type":"td","attrs":{"colspan":1,"rowspan":1,"colwidth":null,"alignment":""},"content":[{"type":"paragraph","content":[{"text":"Haiku","type":"text"}]}]},{"type":"td","attrs":{"colspan":1,"rowspan":1,"colwidth":null,"alignment":""},"content":[{"type":"paragraph","content":[{"text":"200,000 tokens","type":"text"}]}]},{"type":"td","attrs":{"colspan":1,"rowspan":1,"colwidth":null,"alignment":""},"content":[{"type":"paragraph","content":[{"text":"~150,000","type":"text"}]}]},{"type":"td","attrs":{"colspan":1,"rowspan":1,"colwidth":null,"alignment":""},"content":[{"type":"paragraph","content":[{"text":"Above threshold","type":"text"}]}]}]}]},{"type":"heading","attrs":{"level":3},"content":[{"text":"Phase Token Allocation","type":"text"}]},{"type":"table","attrs":{"layout":null},"content":[{"type":"tr","content":[{"type":"th","attrs":{"colspan":1,"rowspan":1,"colwidth":null,"alignment":""},"content":[{"type":"paragraph","content":[{"text":"Phase","type":"text"}]}]},{"type":"th","attrs":{"colspan":1,"rowspan":1,"colwidth":null,"alignment":""},"content":[{"type":"paragraph","content":[{"text":"Budget","type":"text"}]}]},{"type":"th","attrs":{"colspan":1,"rowspan":1,"colwidth":null,"alignment":""},"content":[{"type":"paragraph","content":[{"text":"Strategy","type":"text"}]}]}]},{"type":"tr","content":[{"type":"td","attrs":{"colspan":1,"rowspan":1,"colwidth":null,"alignment":""},"content":[{"type":"paragraph","content":[{"text":"/moai plan","type":"text"}]}]},{"type":"td","attrs":{"colspan":1,"rowspan":1,"colwidth":null,"alignment":""},"content":[{"type":"paragraph","content":[{"text":"30,000","type":"text"}]}]},{"type":"td","attrs":{"colspan":1,"rowspan":1,"colwidth":null,"alignment":""},"content":[{"type":"paragraph","content":[{"text":"Load requirements only, /clear after completion","type":"text"}]}]}]},{"type":"tr","content":[{"type":"td","attrs":{"colspan":1,"rowspan":1,"colwidth":null,"alignment":""},"content":[{"type":"paragraph","content":[{"text":"/moai run","type":"text"}]}]},{"type":"td","attrs":{"colspan":1,"rowspan":1,"colwidth":null,"alignment":""},"content":[{"type":"paragraph","content":[{"text":"180,000","type":"text"}]}]},{"type":"td","attrs":{"colspan":1,"rowspan":1,"colwidth":null,"alignment":""},"content":[{"type":"paragraph","content":[{"text":"Selective file loading, on-demand skill loading","type":"text"}]}]}]},{"type":"tr","content":[{"type":"td","attrs":{"colspan":1,"rowspan":1,"colwidth":null,"alignment":""},"content":[{"type":"paragraph","content":[{"text":"/moai sync","type":"text"}]}]},{"type":"td","attrs":{"colspan":1,"rowspan":1,"colwidth":null,"alignment":""},"content":[{"type":"paragraph","content":[{"text":"40,000","type":"text"}]}]},{"type":"td","attrs":{"colspan":1,"rowspan":1,"colwidth":null,"alignment":""},"content":[{"type":"paragraph","content":[{"text":"Result caching, reduced redundant reads","type":"text"}]}]}]}]},{"type":"heading","attrs":{"level":3},"content":[{"text":"/clear Strategy","type":"text"}]},{"type":"paragraph","content":[{"text":"Mandatory /clear points:","type":"text"}]},{"type":"ordered_list","attrs":{"order":1,"listStyle":"number"},"content":[{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"After ","type":"text"},{"text":"/moai plan","type":"text","marks":[{"type":"code_inline"}]},{"text":" completion (before ","type":"text"},{"text":"/moai run","type":"text","marks":[{"type":"code_inline"}]},{"text":")","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"When context exceeds 150,000 tokens (Sonnet/standard)","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Before major phase transitions","type":"text"}]}]}]},{"type":"paragraph","content":[{"text":"Never use /clear when: In the middle of an agent task, when session state has not been persisted.","type":"text"}]},{"type":"heading","attrs":{"level":3},"content":[{"text":"Session State Persistence","type":"text"}]},{"type":"paragraph","content":[{"text":"Before /clear, persist in-flight state to ","type":"text"},{"text":".moai/specs/\u003cSPEC-ID>/progress.md","type":"text","marks":[{"type":"code_inline"}]},{"text":":","type":"text"}]},{"type":"bullet_list","content":[{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Current task status (completed, in-progress, blocked)","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"File modification summary","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Next action required","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Resume message for paste-back after /clear","type":"text"}]}]}]},{"type":"paragraph","content":[{"text":"Resume message format:","type":"text"}]},{"type":"code_block","attrs":{"wrap":false,"language":""},"content":[{"text":"Wave \u003cN> 이어서 진행. SPEC-\u003cID>부터 \u003capproach>.\nprogress.md: .moai/specs/\u003cID>/progress.md\n다음 단계: \u003ccommand>.","type":"text"}]},{"type":"heading","attrs":{"level":3},"content":[{"text":"Multi-Agent Handoff","type":"text"}]},{"type":"paragraph","content":[{"text":"When delegating to a sub-agent near context ceiling:","type":"text"}]},{"type":"ordered_list","attrs":{"order":1,"listStyle":"number"},"content":[{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Summarize findings in progress.md before Agent() call","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Pass only necessary context in spawn prompt (avoid full file dumps)","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Sub-agent result contributes to parent context on return — factor this in","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"If parent context > 120,000 tokens after return, save and /clear","type":"text"}]}]}]},{"type":"heading","attrs":{"level":2},"content":[{"text":"Full optimization patterns: ","type":"text"},{"text":"modules/token-budget-allocation.md","type":"text","marks":[{"type":"link","attrs":{"href":"modules/token-budget-allocation.md","title":null}}]}]}]},"metadata":{"date":"2026-06-05","name":"moai-foundation-core","author":"@skillopedia","source":{"stars":1050,"repo_name":"moai-adk","origin_url":"https://github.com/modu-ai/moai-adk/blob/HEAD/.claude/skills/moai-foundation-core/SKILL.md","repo_owner":"modu-ai","body_sha256":"37c38ecbb4d7f19686f0d22f5846377c2186f2bab311d073ee0ab906703f3f97","cluster_key":"2188f6a0edfbc943cba8c2a3904ba07184a79b4b5d7a75dae8815bc93692cb30","clean_bundle":{"format":"clean-skill-bundle-v1","source":"modu-ai/moai-adk/.claude/skills/moai-foundation-core/SKILL.md","attachments":[{"id":"e3b53d6e-7e6f-5138-beec-57a58659d5bc","key":"uploads/10433ee7-ad12-4ae0-b34e-97553e46c6c8/e3b53d6e-7e6f-5138-beec-57a58659d5bc/attachment.md","path":"modules/INDEX.md","size":7914,"sha256":"4d6b80604dc6ae0a4e8b1886db1c83f77196d652ec09acf3a28961295af8161b","contentType":"text/markdown; charset=utf-8"},{"id":"7ecfef89-cea8-5579-a8f3-6d53ebb05f45","key":"uploads/10433ee7-ad12-4ae0-b34e-97553e46c6c8/7ecfef89-cea8-5579-a8f3-6d53ebb05f45/attachment.md","path":"modules/agents-reference.md","size":12444,"sha256":"d75dc0963b567b3edc60f3c8e4b1facacdfdf3febda6df9bb3ceb32523dd26d1","contentType":"text/markdown; charset=utf-8"},{"id":"6743c9c0-77bc-529f-b65e-ac1a446355cb","key":"uploads/10433ee7-ad12-4ae0-b34e-97553e46c6c8/6743c9c0-77bc-529f-b65e-ac1a446355cb/attachment.md","path":"modules/commands-reference.md","size":12503,"sha256":"83eda5675ebc53c2e5a4f5b6bb3fa08d4a99bfc0747f62725049f10423a11993","contentType":"text/markdown; charset=utf-8"},{"id":"b2d1c70b-194e-5ced-adad-10d9e2a76f9d","key":"uploads/10433ee7-ad12-4ae0-b34e-97553e46c6c8/b2d1c70b-194e-5ced-adad-10d9e2a76f9d/attachment.md","path":"modules/delegation-advanced.md","size":7423,"sha256":"2d73256208745bed1e1d8d60fb32f713bd522c898ef98868f516d3409c351abe","contentType":"text/markdown; charset=utf-8"},{"id":"4714099c-c17a-5723-b44c-45352425cae0","key":"uploads/10433ee7-ad12-4ae0-b34e-97553e46c6c8/4714099c-c17a-5723-b44c-45352425cae0/attachment.md","path":"modules/delegation-implementation.md","size":7702,"sha256":"131a660b3406a28b5fd80a537a96e68bdf2b4f07987e18b739257498d37cba1a","contentType":"text/markdown; charset=utf-8"},{"id":"c9f69042-fb9a-52e7-8900-6b1146a010ee","key":"uploads/10433ee7-ad12-4ae0-b34e-97553e46c6c8/c9f69042-fb9a-52e7-8900-6b1146a010ee/attachment.md","path":"modules/delegation-patterns.md","size":6381,"sha256":"f0f00cef202b8fc061483ae4c0381812b7e2f9135a422caa5dfbae3d9eed3d08","contentType":"text/markdown; charset=utf-8"},{"id":"3e9d95ee-e442-5a52-92b7-bffb44cbbd23","key":"uploads/10433ee7-ad12-4ae0-b34e-97553e46c6c8/3e9d95ee-e442-5a52-92b7-bffb44cbbd23/attachment.md","path":"modules/execution-rules.md","size":17736,"sha256":"ec4bce16964904c67af43ae94d7061746cc70c508b563457db20e33f52c6d45b","contentType":"text/markdown; charset=utf-8"},{"id":"83b252de-e514-5d1c-94eb-370bb6102f48","key":"uploads/10433ee7-ad12-4ae0-b34e-97553e46c6c8/83b252de-e514-5d1c-94eb-370bb6102f48/attachment.md","path":"modules/modular-system.md","size":16014,"sha256":"fed2b1157b5afbccd1d618878c9cc69e83cb5fbcf8e960667486e81149049a40","contentType":"text/markdown; charset=utf-8"},{"id":"9d3de52b-7de1-5ea3-94a2-864e1f1879f2","key":"uploads/10433ee7-ad12-4ae0-b34e-97553e46c6c8/9d3de52b-7de1-5ea3-94a2-864e1f1879f2/attachment.md","path":"modules/patterns.md","size":283,"sha256":"069def7f327cdcab6872220d158c506cc80224ec253420a0319fb7f67abd2c33","contentType":"text/markdown; charset=utf-8"},{"id":"32b09a75-2dd8-5a2f-a756-eb09efd1781c","key":"uploads/10433ee7-ad12-4ae0-b34e-97553e46c6c8/32b09a75-2dd8-5a2f-a756-eb09efd1781c/attachment.md","path":"modules/progressive-disclosure.md","size":15590,"sha256":"dbb064d3886fcf3619531a1ae8e96f804b8fb66a28314b152ab2bec4380c012f","contentType":"text/markdown; charset=utf-8"},{"id":"c21cab11-b1ff-5c71-95cd-18f861129959","key":"uploads/10433ee7-ad12-4ae0-b34e-97553e46c6c8/c21cab11-b1ff-5c71-95cd-18f861129959/attachment.md","path":"modules/spec-ddd-implementation.md","size":9084,"sha256":"46ab0a7d108a8c6d57a2f9b712152fd1188706c14077463ae61b535395dd9a39","contentType":"text/markdown; charset=utf-8"},{"id":"43f27bd1-e43a-5ee9-843a-3aa645363918","key":"uploads/10433ee7-ad12-4ae0-b34e-97553e46c6c8/43f27bd1-e43a-5ee9-843a-3aa645363918/attachment.md","path":"modules/spec-ears-format.md","size":5934,"sha256":"3f29a915ca9fa7aefe18b8834d061a349dc9d90c74aa565a5da63fa9731ea670","contentType":"text/markdown; charset=utf-8"},{"id":"f5002b92-0d48-5567-bd41-d3e7a83d8db1","key":"uploads/10433ee7-ad12-4ae0-b34e-97553e46c6c8/f5002b92-0d48-5567-bd41-d3e7a83d8db1/attachment.md","path":"modules/spec-first-ddd.md","size":6285,"sha256":"55df55ecb8e7fde410f69c00a723a7ab7cd134b3547ddbaff3b9b9aba182cba6","contentType":"text/markdown; charset=utf-8"},{"id":"4a8de30d-8049-5598-892b-52271c8c6221","key":"uploads/10433ee7-ad12-4ae0-b34e-97553e46c6c8/4a8de30d-8049-5598-892b-52271c8c6221/attachment.md","path":"modules/token-optimization.md","size":19040,"sha256":"fbb3da85dcadc35c8bb3005c924d03555c0edb785f7290fc9657160d599c1858","contentType":"text/markdown; charset=utf-8"},{"id":"477d51cf-44ff-5fda-b097-9cb199fa8c14","key":"uploads/10433ee7-ad12-4ae0-b34e-97553e46c6c8/477d51cf-44ff-5fda-b097-9cb199fa8c14/attachment.md","path":"modules/trust-5-framework.md","size":5472,"sha256":"e9dd5494e58de5ded8ddda9283a42e58fe7e9d0c09826411eb204ff523189940","contentType":"text/markdown; charset=utf-8"},{"id":"fe44b0a3-6cb0-5642-b4aa-ea46e6392fb1","key":"uploads/10433ee7-ad12-4ae0-b34e-97553e46c6c8/fe44b0a3-6cb0-5642-b4aa-ea46e6392fb1/attachment.md","path":"modules/trust-5-implementation.md","size":6009,"sha256":"d3587bf87c3608cc885ae43008d4363e4a7de5b1332236dbbc5db73dce5ed9a5","contentType":"text/markdown; charset=utf-8"},{"id":"ff404d4f-5c5f-5cad-8391-221c53eb95e8","key":"uploads/10433ee7-ad12-4ae0-b34e-97553e46c6c8/ff404d4f-5c5f-5cad-8391-221c53eb95e8/attachment.md","path":"modules/trust-5-validation.md","size":6520,"sha256":"e443241135c45ecde957ed6a54d5ea6356a00cee126ecec98a7fdd32e8654926","contentType":"text/markdown; charset=utf-8"},{"id":"8eb33864-c7f6-5896-8449-22464ef3ef49","key":"uploads/10433ee7-ad12-4ae0-b34e-97553e46c6c8/8eb33864-c7f6-5896-8449-22464ef3ef49/attachment.md","path":"references/examples.md","size":10726,"sha256":"1527f54100b8f4b7ddc2d14da42ee006d093bb5c1fb3bad669e2b0474e29d94d","contentType":"text/markdown; charset=utf-8"},{"id":"cda6496f-af41-517c-9e66-429c29c7af24","key":"uploads/10433ee7-ad12-4ae0-b34e-97553e46c6c8/cda6496f-af41-517c-9e66-429c29c7af24/attachment.md","path":"references/reference.md","size":14935,"sha256":"f80106752f2af98979c56088ed5df15ecda5df9dc5743d29adcc172fde01e180","contentType":"text/markdown; charset=utf-8"}],"bundle_sha256":"a68cd66efe3c383298da4cd20d2a3ac95f88192bc1e1f7797c3f2263d6f08b3a","attachment_count":19,"text_attachments":19,"attachment_storage":"skillopedia-attachments-v1","binary_attachments":0,"excluded_attachments":[]},"cluster_size":1,"skill_md_path":".claude/skills/moai-foundation-core/SKILL.md","import_metadata":{"date":"2026-06-05","author":"@skillopedia","version":"v1","category":"productivity-workflow","category_label":"Productivity"},"exact_dupes_collapsed_into_this":0},"license":"Apache-2.0","version":"v1","category":"productivity-workflow","metadata":{"tags":"foundation, core, orchestration, agents, commands, trust-5, spec-first-ddd, token-budget, context-window, session-state","status":"active","updated":"2026-04-25","version":"3.0.0","category":"foundation","modularized":"true","related-skills":"moai-foundation-context"},"triggers":{"agents":["manager-spec","manager-develop","manager-docs","manager-git","plan-auditor","evaluator-active","builder-harness"],"phases":["plan","run","sync"],"keywords":["trust-5","spec-first","ddd","delegation","agent","token","progressive disclosure","modular","workflow","orchestration","quality gate","spec","gears","ears format","context window","token budget","token limit","session state","/clear","context management","multi-agent handoff","session persistence","context","session","budget","optimization","handoff","state","memory","multi-agent"]},"import_tag":"clean-skills-v1","description":"Provides MoAI-ADK foundational principles including TRUST 5 quality framework, SPEC-First DDD methodology, delegation patterns, progressive disclosure, agent catalog reference, and token budget management (absorbed from moai-foundation-context). Use when referencing TRUST 5 gates, SPEC workflow, or context window optimization.\n","allowed-tools":"Read, Grep, Glob, mcp__context7__resolve-library-id, mcp__context7__get-library-docs","compatibility":"Designed for Claude Code","user-invocable":false,"progressive_disclosure":{"enabled":true,"level1_tokens":100,"level2_tokens":5000}}},"renderedAt":1782981044556}

MoAI Foundation Core Foundational principles and architectural patterns that power MoAI-ADK's AI-driven development workflow. Core Philosophy: Quality-first, domain-driven, modular, and efficient AI development through proven patterns and automated workflows. Quick Reference What is MoAI Foundation Core? Six essential principles that ensure quality, efficiency, and scalability in AI-powered development: 1. TRUST 5 Framework - Quality gate system (Tested, Readable, Unified, Secured, Trackable) 2. SPEC-First DDD - Specification-driven domain-driven development workflow 3. Delegation Patterns -…