chore(rebar): Pier_T_rebar 작업 폴더 초기 구성 및 외부 의존 파일 통합

- Code\rebar_pipeline, review_pipeline, pier-program을 정션에서 실제 폴더로 전환
- Code\rhino_mcp 및 CLAUDE_rhino배경.md 추가, .mcp.json은 PYTHONPATH로 새 위치 사용
- pier-program 내부 .git 제거(이력은 backup\pier-program_20261028.bundle에 보관)
- worktree 가이드 반영(CLAUDE.local.md, HANDOFF.md)
- D:\Rhino-MCP 경로 참조를 새 위치로 치환

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
ahnyongjooandClaude Sonnet 5.5 committed 2026-10-28 11:20:18 +09:00
commit 964a841de1
3978 files changed
+58013356

No files matched your search

@@ -0,0 +1,167 @@
# hmcmkit Template Selection Guide
> Quick reference for choosing the right template for your task
---
## Template Selection Flowchart
```
What are you doing?
│
├─► Starting a new feature?
│ │
│ ├─► Using 9-phase Pipeline? ──► Use Pipeline Templates
│ │ (Phase 1 → 2 → 3 → ... → 9)
│ │
│ └─► Using PDCA only? ──► Use PDCA Templates
│ (Plan → Design → Do → Check → Act)
│
├─► Analyzing implementation?
│ └─► analysis.template.md
│
├─► Writing completion report?
│ └─► report.template.md
│
└─► Setting up new project?
└─► agents.template.md
```
---
## PDCA Templates (Core)
| Template | Phase | When to Use |
|----------|-------|-------------|
| **plan.template.md** | Plan | Starting a new feature, defining requirements |
| **design.template.md** | Design | Technical design for Dynamic level projects |
| **design-starter.template.md** | Design | Simple projects (static sites, portfolios) |
| **design-enterprise.template.md** | Design | Complex systems (microservices, k8s) |
| **analysis.template.md** | Check | Gap analysis, code review, performance check |
| **report.template.md** | Act | Completion report, retrospective |
### Level-Based Design Template Selection
```
Project Complexity?
│
├─► Simple (HTML/CSS, static site) ──► design-starter.template.md
│
├─► Medium (Web app, SaaS MVP) ──► design.template.md (default)
│
└─► Complex (Enterprise, MSA) ──► design-enterprise.template.md
```
---
## Pipeline Templates (9-Phase)
| Phase | Template | Purpose |
|-------|----------|---------|
| 1 | `pipeline/phase-1-schema.template.md` | Terminology & data model |
| 2 | `pipeline/phase-2-convention.template.md` | Coding rules & architecture |
| 3 | `pipeline/phase-3-mockup.template.md` | UI prototypes |
| 4 | `pipeline/phase-4-api.template.md` | API specification |
| 5 | `pipeline/phase-5-design-system.template.md` | Component library |
| 6 | `pipeline/phase-6-ui.template.md` | UI implementation |
| 7 | `pipeline/phase-7-seo-security.template.md` | SEO & security |
| 8 | `pipeline/phase-8-review.template.md` | Architecture/convention review |
| 9 | `pipeline/phase-9-deployment.template.md` | Deployment config |
### Pipeline vs PDCA
| Scenario | Use Pipeline | Use PDCA |
|----------|:------------:|:--------:|
| New project from scratch | ✅ | ⚠️ |
| Adding feature to existing project | ⚠️ | ✅ |
| Quick fix / bug fix | ❌ | ⚠️ |
| Enterprise-grade development | ✅ | ✅ |
---
## Other Templates
| Template | Purpose |
|----------|---------|
| **agents.template.md** | Generate agents.md for new projects |
| **iteration-report.template.md** | Evaluator-Optimizer iteration report |
| **_INDEX.template.md** | Folder document index |
---
## Template Features Comparison
### Clean Architecture Support
| Template | Layer Definition | Dependency Rules | Import Order |
|----------|:----------------:|:----------------:|:------------:|
| design.template.md | ✅ | ✅ | ✅ |
| design-starter.template.md | ❌ | ❌ | ❌ |
| design-enterprise.template.md | ✅ | ✅ | ✅ |
| phase-2-convention.template.md | ✅ | ✅ | ✅ |
| phase-8-review.template.md | ✅ | ✅ | ✅ |
### Convention Compliance Support
| Template | Naming | Folder Structure | Env Variables |
|----------|:------:|:----------------:|:-------------:|
| design.template.md | ✅ | ✅ | ✅ |
| analysis.template.md | ✅ | ✅ | ✅ |
| phase-2-convention.template.md | ✅ | ✅ | ✅ |
| phase-8-review.template.md | ✅ | ✅ | ✅ |
---
## Quick Commands
```bash
# PDCA Commands
/pdca-plan {feature} # Create plan document
/pdca-design {feature} # Create design document
/pdca-analyze {feature} # Run gap analysis
/pdca-report {feature} # Create completion report
# Pipeline Commands
/pipeline-start # Start 9-phase pipeline
/pipeline-status # Check current phase
/pipeline-next # Go to next phase
# Project Setup
/setup-ai-agent-code # Generate agents.md
/init-starter # Initialize Starter level project
/init-dynamic # Initialize Dynamic level project
/init-enterprise # Initialize Enterprise level project
```
---
## Cross-Reference Guide
### PDCA ↔ Pipeline Integration
When using both PDCA and Pipeline:
1. **Plan Phase**: Reference Phase 1 (Schema) and Phase 2 (Convention) outputs
2. **Design Phase**: Reference Phase 3 (Mockup) and Phase 4 (API) outputs
3. **Check Phase**: Use Phase 8 (Review) checklist for verification
### Document Location Convention
```
docs/
├── 01-plan/
│ ├── features/ # PDCA Plan documents
│ ├── schema.md # Pipeline Phase 1
│ └── conventions.md # Pipeline Phase 2
├── 02-design/
│ ├── features/ # PDCA Design documents
│ ├── mockup/ # Pipeline Phase 3
│ └── api/ # Pipeline Phase 4
├── 03-analysis/ # PDCA Check documents
└── 04-report/ # PDCA Act documents
```
---
**Version**: 1.0.0
**Last Updated**: 2026-01-20
@@ -0,0 +1,90 @@
---
template: index
version: 1.0
description: Folder document index template
variables:
- folder: Folder name
- phase: PDCA phase (Plan/Design/Check/Act)
---
# {folder} Index
> **PDCA Phase**: {phase}
> **Last Updated**: {date}
---
## Document List
| Document | Status | Last Modified | Owner | Description |
|----------|--------|---------------|-------|-------------|
| [example.md](./example.md) | ✅ Approved | YYYY-MM-DD | - | Description |
---
## Status Legend
| Status | Meaning | Description |
|--------|---------|-------------|
| ✅ Approved | Finalized | Review complete, reference baseline |
| 🔄 In Progress | Working | Currently being written |
| 👀 In Review | Pending Review | Awaiting review |
| ⏸️ On Hold | Paused | Temporarily stopped |
| ❌ Deprecated | Obsolete | No longer valid |
---
## PDCA Status
```
Current Phase: [{phase}] ← You are here
┌────────┐ ┌────────┐ ┌────────┐ ┌────────┐
│ Plan │───▶│ Design │───▶│ Do │───▶│ Check │
│ │ │ │ │ (Impl) │ │(Analyze)│
└────────┘ └────────┘ └────────┘ └────────┘
│
▼
┌────────┐
│ Act │
│(Improve)│
└────────┘
```
---
## Folder Structure
```
{folder}/
├── _INDEX.md ← Current file
├── {category1}/
│ └── ...
└── {category2}/
└── ...
```
---
## Related Links
| Phase | Folder | Description |
|-------|--------|-------------|
| Plan | [01-plan/](../01-plan/_INDEX.md) | Planning documents |
| Design | [02-design/](../02-design/_INDEX.md) | Design documents |
| Analysis | [03-analysis/](../03-analysis/_INDEX.md) | Analysis results |
| Report | [04-report/](../04-report/_INDEX.md) | Completion reports |
---
## Notes
{Additional notes or considerations about this folder}
---
## Update History
| Date | Changes |
|------|---------|
| {date} | Index created |
@@ -0,0 +1,244 @@
---
template: agent-version-analysis
version: 1.0
description: CC version impact analysis and hmcmkit improvement report template
variables:
- feature: Feature name (agent-version-analysis identifier)
- date: Creation date (YYYY-MM-DD)
- author: Author (typically CTO Team + Agent count)
- from_version: Baseline CC version
- to_version: Target CC version
- project: hmcmkit project name
- version: hmcmkit version
---
# CC v{from_version} → v{to_version} 영향 분석 및 hmcmkit 개선 보고서
> **Status**: ✅ Complete / 🔄 In Progress
>
> **Project**: {project}
> **hmcmkit Version**: {version}
> **Author**: {author}
> **Date**: {date}
> **PDCA Cycle**: #{cycle_number}
---
## Executive Summary
### 1.1 프로젝트 개요
| 항목 | 내용 |
|------|------|
| **분석 대상** | Antigravity Platform CLI v{from_version} → v{to_version} |
| **분석 범위** | 릴리스 N개 (v{from_version} ~ v{to_version}) |
| **시작일** | {start_date} |
| **완료일** | {date} |
| **기간** | {duration} |
### 1.2 성과 요약
```
┌──────────────────────────────────────────────┐
│ 분석 완료율: 100% │
├──────────────────────────────────────────────┤
│ 📊 총 변경사항: N건 │
│ 🔴 HIGH 영향: N건 │
│ 🟡 MEDIUM 영향: N건 │
│ 🟢 LOW 영향: N건 │
│ 🆕 ENH 기회: N건 (ENH-N ~ ENH-N) │
│ ✅ 연속 호환: N+M 릴리스 │
└──────────────────────────────────────────────┘
```
### 1.3 전달된 가치
| 관점 | 내용 |
|------|------|
| **문제** | CC CLI v{to_version} 업그레이드에 따른 hmcmkit 호환성 및 개선 기회 파악 필요 |
| **해결 방법** | 체계적 3-Phase 분석 (조사 → 영향 분석 → 브레인스토밍) |
| **기능/UX 효과** | {specific effects} |
| **핵심 가치** | {core value delivered} |
---
## 2. 관련 문서
| Phase | 문서 | 상태 |
|-------|------|------|
| Research | Agent 버전 변경사항 조사 | ✅ / 🔄 |
| Impact | hmcmkit 영향 분석 | ✅ / 🔄 |
| Plan | [{feature}.plan.md](../01-plan/features/{feature}.plan.md) | ✅ / 🔄 |
| Report | 본 문서 | 🔄 작성 완료 |
---
## 3. Agent 버전 변경사항 조사
### 3.1 릴리스 요약
| 버전 | 릴리스일 | 주요 변경 | 변경 수 |
|------|---------|----------|---------|
| v{version_N} | YYYY-MM-DD | {summary} | N |
### 3.2 Breaking Changes
| 변경사항 | 영향도 | hmcmkit 영향 | 마이그레이션 필요 |
|---------|--------|----------|-----------------|
### 3.3 신규 기능
| 기능 | 설명 | hmcmkit ENH 기회 |
|------|------|--------------|
### 3.4 버그 수정
| 이슈 | 설명 | hmcmkit 영향 |
|------|------|----------|
### 3.5 시스템 프롬프트 변경
| 항목 | 변경 전 | 변경 후 | 토큰 변화 |
|------|--------|--------|----------|
### 3.6 Hook 이벤트 변경
| 이벤트 | 상태 | hmcmkit 사용 여부 |
|--------|------|---------------|
---
## 4. hmcmkit 영향 분석
### 4.1 영향 요약
| 카테고리 | 건수 | HIGH | MEDIUM | LOW |
|---------|------|------|--------|-----|
| Breaking | N | N | N | N |
| Enhancement | N | N | N | N |
| Neutral | N | N | N | N |
### 4.2 ENH 기회 목록
| ENH | Priority | CC 기능 | hmcmkit 영향 | 영향 파일 |
|-----|----------|--------|----------|----------|
| ENH-{N} | P{0-3} | {feature} | {impact} | {files} |
### 4.3 파일 영향 매트릭스
| 파일 | 변경 유형 | ENH 참조 | 테스트 영향 |
|------|----------|----------|-----------|
### 4.4 철학 준수 검증
| ENH | Automation First | No Guessing | Docs=Code | 판정 |
|-----|-----------------|-------------|-----------|------|
---
## 5. 호환성 평가
### 5.1 호환성 매트릭스
| Agent 버전 | hmcmkit 호환 | 테스트 결과 | 비고 |
|---------|----------|-----------|------|
### 5.2 연속 호환 릴리스
```
v2.1.34 ──────────────────────────── v{to_version}
{N}개 연속 호환 릴리스
Breaking Changes: 0건
```
### 5.3 추천 Agent 버전
- **최소**: v{min_version}
- **추천**: v{recommended_version}
- **최적**: v{optimal_version}
---
## 6. 브레인스토밍 결과 (Plan Plus)
### 6.1 의도 탐색
| 질문 | 답변 |
|------|------|
| 이 업그레이드의 핵심 목표는? | {answer} |
| 가장 큰 리스크는? | {answer} |
| 놓치기 쉬운 기회는? | {answer} |
### 6.2 대안 탐색
| 접근법 | 장점 | 단점 | 선택 |
|--------|------|------|------|
### 6.3 YAGNI 검토
| ENH | 필요성 | 판정 | 근거 |
|-----|--------|------|------|
---
## 7. 구현 제안
### 7.1 우선순위별 구현 로드맵
#### P0 (즉시 구현)
| ENH | 설명 | 예상 작업량 |
|-----|------|-----------|
#### P1 (이번 사이클)
| ENH | 설명 | 예상 작업량 |
|-----|------|-----------|
#### P2 (다음 사이클)
| ENH | 설명 | 예상 작업량 |
|-----|------|-----------|
#### P3 (백로그)
| ENH | 설명 | 비고 |
|-----|------|------|
### 7.2 테스트 계획
| ENH | 테스트 유형 | 대상 파일 | TC 수 |
|-----|-----------|----------|-------|
---
## 8. GitHub Issues 모니터링
### 8.1 관련 Open Issues
| Issue # | 제목 | 영향도 | hmcmkit 대응 |
|---------|------|--------|----------|
### 8.2 관련 Closed Issues (이번 버전)
| Issue # | 제목 | 해결 버전 | hmcmkit 영향 |
|---------|------|----------|----------|
---
## 9. 결론 (Verdict)
### 9.1 최종 판정
- **호환성**: ✅ PASS / ❌ FAIL
- **업그레이드 권장**: YES / NO / CONDITIONAL
- **hmcmkit 버전 업데이트 필요**: YES (v{next_version}) / NO
### 9.2 핵심 권고사항
1. {recommendation_1}
2. {recommendation_2}
3. {recommendation_3}
### 9.3 다음 단계
- [ ] ENH P0 항목 즉시 구현
- [ ] hmcmkit.config.json CC 추천 버전 업데이트
- [ ] MEMORY.md Agent 버전 히스토리 업데이트
- [ ] 연속 호환 릴리스 카운트 업데이트
@@ -0,0 +1,227 @@
# {{PROJECT_NAME}}
> {{PROJECT_DESCRIPTION}}
---
## Core Principles
### 1. Automation First, Commands are Shortcuts
```
AI Agent automatically applies PDCA methodology.
Commands are shortcuts for power users.
```
### 2. SoR (Single Source of Truth) Priority
```
1st: Codebase (actual working code)
2nd: agents.md / Convention docs
3rd: docs/ design documents
```
### 3. No Guessing
```
Unknown → Check documentation
Not in docs → Ask user
Never guess
```
---
## Tech Stack
| Item | Value |
|------|-------|
| Language | {{LANGUAGE}} |
| Framework | {{FRAMEWORK}} |
| Package Manager | {{PACKAGE_MANAGER}} |
| Level | {{LEVEL}} |
| Tier | {{TIER}} |
### Language Tier Context (v1.3.0)
{{#if TIER_1}}
> **Tier 1 (AI-Native Essential)**
> - Full AI tool support (Copilot, AI Agent, Cursor)
> - Vibe Coding optimized
> - PDCA automation fully supported
{{/if}}
{{#if TIER_2}}
> **Tier 2 (Mainstream Recommended)**
> - Good AI tool compatibility
> - Domain-specific strengths
> - PDCA recommended
{{/if}}
{{#if TIER_3}}
> **Tier 3 (Domain Specific)**
> - Platform-specific requirements
> - Moderate AI support
> - Consider migration path for new features
{{/if}}
{{#if TIER_4}}
> **Tier 4 (Legacy/Niche)**
> - Maintenance mode
> - Migration plan recommended
> - New features should use Tier 1-2
{{/if}}
---
## Development Workflow
### Commands
```bash
# Type check
{{TYPECHECK_COMMAND}}
# Test
{{TEST_COMMAND}}
# Lint
{{LINT_COMMAND}}
# Build
{{BUILD_COMMAND}}
```
---
## Coding Conventions
### Naming Rules
| Target | Convention | Example |
|--------|-----------|---------|
| Components | PascalCase | `UserProfile`, `LoginForm` |
| Functions | camelCase | `getUserById`, `handleSubmit` |
| Constants | UPPER_SNAKE_CASE | `MAX_RETRY_COUNT`, `API_TIMEOUT` |
| Types/Interfaces | PascalCase | `UserProfile`, `ApiResponse` |
| Files (component) | PascalCase.tsx | `UserProfile.tsx` |
| Files (utility) | camelCase.ts | `formatDate.ts` |
| Folders | kebab-case | `user-profile/`, `auth-provider/` |
### Import Order
```typescript
// 1. External libraries (react, next, third-party)
import { useState, useEffect } from 'react'
import { useQuery } from '@tanstack/react-query'
// 2. Internal absolute imports (@/...)
import { Button } from '@/components/ui'
import { userService } from '@/services/user'
// 3. Relative imports (./...)
import { useLocalState } from './hooks'
import { formatData } from './utils'
// 4. Type imports
import type { User, ApiResponse } from '@/types'
// 5. Styles (last)
import './styles.css'
```
### Clean Architecture (Level: {{LEVEL}})
| Layer | Location | Responsibility | Can Import |
|-------|----------|----------------|------------|
| **Presentation** | `components/`, `hooks/`, `app/` | UI, user events | Application, Domain |
| **Application** | `services/`, `features/*/hooks/` | Business logic | Domain, Infrastructure |
| **Domain** | `types/`, `domain/` | Entities, core rules | Nothing (independent) |
| **Infrastructure** | `lib/`, `api/` | External services | Domain only |
### Environment Variables
| Prefix | Scope | Example | Notes |
|--------|-------|---------|-------|
| `NEXT_PUBLIC_` | Client (Browser) | `NEXT_PUBLIC_API_URL` | Exposed to browser |
| `DB_` | Server only | `DB_HOST`, `DB_PASSWORD` | Never expose |
| `API_` | Server only | `API_STRIPE_SECRET` | External API keys |
| `AUTH_` | Server only | `AUTH_SECRET` | Auth secrets |
### Additional Conventions
{{CONVENTIONS}}
---
## Project Structure
```
{{FOLDER_STRUCTURE}}
```
---
## PDCA Auto Behavior
### On New Feature Request
```
User: "Create login feature"
AI Agent: 1. Check docs/02-design/ → Create design if missing
2. Generate design document using template
3. Implement based on design
4. Suggest Gap analysis after completion
```
### On Bug Fix / Refactoring
```
AI Agent: 1. Compare code with design documents
2. Identify cause and fix
3. Suggest updating documentation
```
---
## Key Commands
| Command | Description |
|---------|-------------|
| `/pdca-status` | Check current PDCA status |
| `/pdca-design {feature}` | Create design document |
| `/pdca-analyze {feature}` | Run Gap analysis |
---
## Document Structure Rules
### hmcmkit-system/ (Current Implementation Reference)
```
- Update together with code changes
- Always reflects "current codebase state"
- Use this folder for implementation reference
```
### docs/pdca/ (Active Work)
```
- Active PDCA documents in progress
- Move to docs/archive/ after completion
```
### docs/archive/ (History)
```
- Completed plan/design documents
- Read-only (no modifications)
```
### Archive Trigger
```
Gap analysis completed (match rate >= 90%)
OR user explicit completion
→ Move to archive
```
---
## Reference
Use `/pdca-plan`, `/pdca-design`, `/pdca-analyze` commands for PDCA workflow.
---
**Generated by**: /setup-ai-agent-code
**Template Version**: 1.3.0 (Check-Act Iteration Loop)
@@ -0,0 +1,446 @@
---
template: analysis
version: 1.3
description: PDCA Check phase document template with Context Anchor, Clean Architecture and Convention compliance checks
variables:
- feature: Feature name
- date: Creation date (YYYY-MM-DD)
- author: Author
- project: Project name (from package.json or agents.md)
- version: Project version (from package.json)
---
# {feature} Analysis Report
> **Analysis Type**: Gap Analysis / Code Quality / Performance Analysis
>
> **Project**: {project}
> **Version**: {version}
> **Analyst**: {author}
> **Date**: {date}
> **Design Doc**: [{feature}.design.md](../02-design/features/{feature}.design.md)
### Pipeline References (for verification)
| Phase | Document | Verification Target |
|-------|----------|---------------------|
| Phase 1 | [Schema](../01-plan/schema.md) | Terminology consistency |
| Phase 2 | [Conventions](../01-plan/conventions.md) | Convention compliance |
| Phase 4 | [API Spec](../02-design/api/{feature}.md) | API implementation match |
| Phase 8 | [Review Checklist](./phase-8-review.md) | Architecture/Convention review |
---
## Context Anchor
> Carried from Plan → Design → Analysis. Verify implementation against strategic intent.
| Key | Value |
|-----|-------|
| **WHY** | {copied from Design Context Anchor} |
| **WHO** | {copied from Design Context Anchor} |
| **RISK** | {copied from Design Context Anchor} |
| **SUCCESS** | {copied from Design Context Anchor} |
| **SCOPE** | {copied from Design Context Anchor} |
---
## Strategic Alignment Check
> Verifies implementation against the full upstream chain: PRD → Plan → Design.
### PRD Alignment
| PRD Element | Expected | Implementation Status |
|-------------|----------|:---------------------:|
| Core Problem (WHY) | {from PRD} | ✅ Addressed / ❌ Missed |
| Target User (WHO) | {from PRD} | ✅ Addressed / ❌ Missed |
| Value Proposition | {from PRD} | ✅ Delivered / ⚠️ Partial |
### Success Criteria Status
| # | Criteria (from Plan) | Status | Evidence |
|---|---------------------|:------:|----------|
| SC-1 | {criteria text} | ✅/⚠️/❌ | {file:line or test result} |
| SC-2 | {criteria text} | ✅/⚠️/❌ | {file:line or test result} |
**Success Rate**: {X}/{Y} criteria met
### Decision Record Verification
| Source | Decision | Followed? | Deviation |
|--------|----------|:---------:|-----------|
| [PRD] | {decision} | ✅/❌ | {deviation if any} |
| [Plan] | {decision} | ✅/❌ | {deviation if any} |
| [Design] | {decision} | ✅/❌ | {deviation if any} |
---
## 1. Analysis Overview
### 1.1 Analysis Purpose
{Purpose of conducting this analysis}
### 1.2 Analysis Scope
- **Design Document**: `docs/02-design/features/{feature}.design.md`
- **Implementation Path**: `src/features/{feature}/`
- **Analysis Date**: {date}
---
## 2. Gap Analysis (Design vs Implementation)
### 2.1 API Endpoints
| Design | Implementation | Status | Notes |
|--------|---------------|--------|-------|
| POST /api/{resource} | POST /api/{resource} | ✅ Match | |
| GET /api/{resource}/:id | GET /api/{resource}/:id | ✅ Match | |
| - | POST /api/{resource}/bulk | ⚠️ Missing in design | Added in impl |
| DELETE /api/{resource}/:id | - | ❌ Not implemented | Needs impl |
### 2.2 Data Model
| Field | Design Type | Impl Type | Status |
|-------|-------------|-----------|--------|
| id | string | string | ✅ |
| email | string | string | ✅ |
| createdAt | Date | Date | ✅ |
| metadata | - | object | ⚠️ Missing in design |
### 2.3 Component Structure
| Design Component | Implementation File | Status |
|------------------|---------------------|--------|
| {ComponentA} | src/components/{ComponentA}.tsx | ✅ Match |
| {ComponentB} | - | ❌ Not implemented |
### 2.4 Functional Depth Analysis (v2.1.0)
> Measures actual implementation completeness, not just file existence.
| File | Depth Score | Placeholder Indicators | Missing Design Elements |
|------|:----------:|----------------------|------------------------|
| {file} | {0-100} | {indicators found} | {missing elements from Page UI Checklist} |
```
Scoring: 0=empty, 20=skeleton, 40=mock data, 60=partial logic, 80=mostly complete, 100=fully implemented
Threshold: Files scoring <60 are flagged as "SHALLOW"
```
**Shallow File Count**: {N} / {total} files ({percent}%)
### 2.5 Page UI Checklist Verification (v2.1.0)
> Cross-references Design document §5.4 Page UI Checklist against implementation.
| Page | Design Elements | Implemented | Missing | Rate |
|------|:--------------:|:-----------:|:-------:|:----:|
| {page} | {N} | {N} | {N} | {percent}% |
**Functional Match Rate**: {percent}%
### 2.6 API Contract Verification (v2.2.0)
> 3-way cross-reference: Design §4 ↔ Server (route.ts) ↔ Client (fetch calls)
> Detects runtime failures that structural/functional checks miss.
| # | Endpoint | Design | Server | Client | Contract |
|---|----------|:------:|:------:|:------:|:--------:|
| {N} | {endpoint} | ✅/❌ | ✅/❌ | ✅/❌ | PASS/FAIL |
**Contract Failures:**
| Endpoint | Layer | Issue | Fix Required |
|----------|-------|-------|-------------|
| {endpoint} | {Server/Client} | {mismatch description} | {fix} |
**Contract Match Rate**: {M}/{N} endpoints = {percent}%
### 2.7 Runtime Verification Results (v2.3.0)
> Actual execution results — not code reading, real HTTP calls and browser tests.
#### L1: API Endpoint Tests (curl)
| # | Test | Status | Expected | Actual | Pass |
|---|------|:------:|----------|--------|:----:|
| {N} | {description} | {status code} | {expected} | {actual response} | ✅/❌ |
**L1 Score**: {pass}/{total} = {percent}%
#### L2: UI Action Tests (Playwright)
| # | Page | Action | Expected Result | Pass |
|---|------|--------|----------------|:----:|
| {N} | {page} | {action} | {result} | ✅/❌ |
**L2 Score**: {pass}/{total} = {percent}%
#### L3: E2E Scenario Tests (Playwright)
| # | Scenario | Steps | Result | Pass |
|---|----------|:-----:|--------|:----:|
| {N} | {scenario name} | {step count} | {pass/fail + details} | ✅/❌ |
**L3 Score**: {pass}/{total} = {percent}%
**Runtime Match Rate**: (L1 × 0.4 + L2 × 0.3 + L3 × 0.3) = {percent}%
### 2.8 Match Rate Summary
```
┌─────────────────────────────────────────────┐
│ Structural Match Rate: {percent}% │
│ Functional Match Rate: {percent}% │
│ Contract Match Rate: {percent}% │
│ Runtime Match Rate: {percent}% (NEW) │
│ ─────────────────────────────────────────── │
│ Overall Match Rate: {percent}% │
│ = (Structural × 0.15) + (Functional × 0.25)│
│ + (Contract × 0.25) + (Runtime × 0.35) │
├─────────────────────────────────────────────┤
│ ✅ Match: {N} items ({percent}%) │
│ ⚠️ Shallow: {N} items ({percent}%) │
│ ❌ Not implemented: {N} items ({percent}%) │
└─────────────────────────────────────────────┘
```
---
## 3. Code Quality Analysis
### 3.1 Complexity Analysis
| File | Function | Complexity | Status | Recommendation |
|------|----------|------------|--------|----------------|
| {service}.ts | processData | 15 | ⚠️ High | Split function |
| utils.ts | formatDate | 3 | ✅ Good | - |
### 3.2 Code Smells
| Type | File | Location | Description | Severity |
|------|------|----------|-------------|----------|
| Long function | api.ts | L45-120 | 75 lines (recommended: <50) | 🟡 |
| Duplicate code | helpers.ts | L10, L45 | Same logic repeated | 🟡 |
| Magic number | config.ts | L23 | Hardcoded number | 🟢 |
### 3.3 Security Issues
| Severity | File | Location | Issue | Recommendation |
|----------|------|----------|-------|----------------|
| 🔴 Critical | auth.ts | L42 | Hardcoded secret | Move to env var |
| 🟡 Warning | api.ts | L15 | Missing input validation | Add validation |
| 🟢 Info | - | - | - | - |
---
## 4. Performance Analysis (if applicable)
### 4.1 Response Time
| Endpoint | Measured | Target | Status |
|----------|----------|--------|--------|
| GET /api/{resource} | 150ms | 200ms | ✅ |
| POST /api/{resource} | 350ms | 200ms | ❌ |
### 4.2 Bottlenecks
| Location | Problem | Impact | Recommendation |
|----------|---------|--------|----------------|
| Repository.findAll() | N+1 query | Increased response time | Eager Loading |
| ImageProcessor | Sync processing | Blocking | Async processing |
---
## 5. Test Coverage
### 5.1 Coverage Status
| Area | Current | Target | Status |
|------|---------|--------|--------|
| Statements | 72% | 80% | ❌ |
| Branches | 65% | 75% | ❌ |
| Functions | 80% | 80% | ✅ |
| Lines | 73% | 80% | ❌ |
### 5.2 Uncovered Areas
- `src/features/{feature}/handlers/errorHandler.ts`
- `src/features/{feature}/utils/parser.ts`
---
## 6. Clean Architecture Compliance
> Reference: `docs/02-design/{feature}.design.md` Section 9 (Clean Architecture)
### 6.1 Layer Dependency Verification
| Layer | Expected Dependencies | Actual Dependencies | Status |
|-------|----------------------|---------------------|--------|
| Presentation | Application, Domain | {actual imports} | ✅/❌ |
| Application | Domain, Infrastructure | {actual imports} | ✅/❌ |
| Domain | None (independent) | {actual imports} | ✅/❌ |
| Infrastructure | Domain only | {actual imports} | ✅/❌ |
### 6.2 Dependency Violations
| File | Layer | Violation | Recommendation |
|------|-------|-----------|----------------|
| `components/UserList.tsx` | Presentation | Imports `@/lib/api` directly | Use service hook instead |
| `services/user.ts` | Application | Imports `@/components/Button` | Remove UI dependency |
| - | - | - | - |
### 6.3 Layer Assignment Verification
| Component | Designed Layer | Actual Location | Status |
|-----------|---------------|-----------------|--------|
| {ComponentA} | Presentation | `src/components/{feature}/` | ✅ |
| {ServiceA} | Application | `src/services/{feature}.ts` | ✅ |
| {TypeA} | Domain | `src/types/{feature}.ts` | ✅ |
| {ApiClient} | Infrastructure | `src/lib/api/{feature}.ts` | ✅ |
### 6.4 Architecture Score
```
┌─────────────────────────────────────────────┐
│ Architecture Compliance: 85% │
├─────────────────────────────────────────────┤
│ ✅ Correct layer placement: 17/20 files │
│ ⚠️ Dependency violations: 2 files │
│ ❌ Wrong layer: 1 file │
└─────────────────────────────────────────────┘
```
---
## 7. Convention Compliance
> Reference: `docs/01-plan/conventions.md` or Phase 2 Pipeline output
### 7.1 Naming Convention Check
| Category | Convention | Files Checked | Compliance | Violations |
|----------|-----------|:-------------:|:----------:|------------|
| Components | PascalCase | 15 | 100% | - |
| Functions | camelCase | 42 | 98% | `GetUser` → `getUser` |
| Constants | UPPER_SNAKE_CASE | 8 | 100% | - |
| Files (component) | PascalCase.tsx | 15 | 93% | `userProfile.tsx` → `UserProfile.tsx` |
| Files (utility) | camelCase.ts | 12 | 100% | - |
| Folders | kebab-case | 10 | 90% | `userProfile/` → `user-profile/` |
### 7.2 Folder Structure Check
| Expected Path | Exists | Contents Correct | Notes |
|---------------|:------:|:----------------:|-------|
| `src/components/` | ✅ | ✅ | |
| `src/features/{feature}/` | ✅ | ✅ | |
| `src/services/` | ✅ | ⚠️ | Some services in features/ |
| `src/types/` | ✅ | ✅ | |
| `src/lib/` | ✅ | ✅ | |
### 7.3 Import Order Check
- [x] External libraries first
- [x] Internal absolute imports second (`@/...`)
- [ ] Relative imports third (`./...`)
- [x] Type imports fourth (`import type`)
- [x] Styles last
**Violations Found:**
| File | Issue | Line |
|------|-------|------|
| `components/Header.tsx` | Type import before relative import | L5-6 |
### 7.4 Environment Variable Check
| Variable | Convention | Actual | Status |
|----------|-----------|--------|--------|
| API URL | `NEXT_PUBLIC_API_URL` | `NEXT_PUBLIC_API_URL` | ✅ |
| DB Host | `DB_HOST` | `DATABASE_HOST` | ⚠️ Non-standard |
| Auth Secret | `AUTH_SECRET` | `AUTH_SECRET` | ✅ |
### 7.5 Convention Score
```
┌─────────────────────────────────────────────┐
│ Convention Compliance: 92% │
├─────────────────────────────────────────────┤
│ Naming: 95% │
│ Folder Structure: 90% │
│ Import Order: 88% │
│ Env Variables: 95% │
└─────────────────────────────────────────────┘
```
---
## 8. Overall Score
```
┌─────────────────────────────────────────────┐
│ Overall Score: 78/100 │
├─────────────────────────────────────────────┤
│ Design Match: 75 points │
│ Code Quality: 70 points │
│ Security: 65 points │
│ Testing: 70 points │
│ Performance: 80 points │
│ Architecture: 85 points (New) │
│ Convention: 92 points (New) │
└─────────────────────────────────────────────┘
```
---
## 9. Recommended Actions
### 9.1 Immediate (within 24 hours)
| Priority | Item | File | Assignee |
|----------|------|------|----------|
| 🔴 1 | Remove hardcoded secret | auth.ts:42 | - |
| 🔴 2 | Add input validation | api.ts:15 | - |
### 9.2 Short-term (within 1 week)
| Priority | Item | File | Expected Impact |
|----------|------|------|-----------------|
| 🟡 1 | Fix N+1 query | repository.ts | 60% response time reduction |
| 🟡 2 | Split function | service.ts | Improved maintainability |
### 9.3 Long-term (backlog)
| Item | File | Notes |
|------|------|-------|
| Refactoring | utils/ | Clean up duplicate code |
| Documentation | - | Add JSDoc |
---
## 10. Design Document Updates Needed
The following items require design document updates to match implementation:
- [ ] Add POST /api/{resource}/bulk endpoint
- [ ] Add metadata field to data model
- [ ] Update error code list
---
## 11. Next Steps
- [ ] Fix Critical issues
- [ ] Update design document
- [ ] Write completion report (`{feature}.report.md`)
---
## Version History
| Version | Date | Changes | Author |
|---------|------|---------|--------|
| 0.1 | {date} | Initial analysis | {author} |
@@ -0,0 +1,12 @@
# Invariants Registry Schema v1.0
# Critical business rules written by developer (10-20 rules)
# Location: .hmcmkit/invariants.yaml
version: "1.0"
invariants:
- id: "" # Unique ID (e.g., "INV-001")
rule: "" # Human-readable rule description
files: [] # Source files this rule applies to
check: "" # Logical condition (for documentation)
severity: "" # "critical" (blocks fix) | "warning" (flags only)
category: "" # "business-rule" | "state-machine" | "security" | "performance"
@@ -0,0 +1,19 @@
# Scenario Matrix Schema v1.0
# Auto-generated by PDCA Design phase, reviewed by developer
# Location: docs/02-design/scenarios/{module}.scenarios.yaml
version: "1.0"
module: "" # Module name (e.g., "user-auth")
file: "" # Target source file path
scenarios:
- id: "" # Unique ID (e.g., "S001")
name: "" # Human-readable scenario name
description: "" # What this scenario tests
input: {} # Input parameters
expected:
status: 200 # Expected HTTP status or return value
body: {} # Expected response body
why: "" # Why this behavior exists (design intent)
constraint: "" # What must NOT change (guardrail)
tags: [] # Tags for filtering (e.g., ["auth", "edge-case"])
test_command: "" # Optional: specific test command to verify
@@ -0,0 +1,113 @@
# {{project_name}} Coding Conventions
> PDCA Convention Document - 코드 작성 규칙 정의
**Version**: 1.0
**Created**: {{date}}
**Level**: {{level}}
---
## 1. Naming Conventions
### Files & Folders
| Target | Rule | Example |
|--------|------|---------|
| Component files | PascalCase | `UserProfile.tsx` |
| Utility files | camelCase | `formatDate.ts` |
| Folders | kebab-case | `user-profile/` |
| Constants | UPPER_SNAKE_CASE | `API_ENDPOINTS.ts` |
### Code
| Target | Rule | Example |
|--------|------|---------|
| Components | PascalCase | `UserProfile` |
| Functions | camelCase | `getUserById()` |
| Variables | camelCase | `userName` |
| Constants | UPPER_SNAKE_CASE | `MAX_RETRY` |
| Types/Interfaces | PascalCase | `UserProfile` |
---
## 2. Folder Structure
```
src/
├── components/ # UI 컴포넌트
├── features/ # 기능별 모듈
├── hooks/ # Custom hooks
├── lib/ # 유틸리티
├── types/ # 타입 정의
└── styles/ # 스타일
```
---
## 3. Import Order
```typescript
// 1. External libraries
import React from 'react'
// 2. Internal absolute (@/)
import { Button } from '@/components/ui'
// 3. Relative imports
import { useUser } from './hooks'
// 4. Type imports
import type { User } from '@/types'
// 5. Styles
import './styles.css'
```
---
## 4. Environment Variables
### Naming Convention
| Prefix | Scope | Example |
|--------|-------|---------|
| `NEXT_PUBLIC_` | Client-side | `NEXT_PUBLIC_API_URL` |
| `DB_` | Database | `DB_HOST`, `DB_PASSWORD` |
| `API_` | API keys | `API_SECRET_KEY` |
| `AUTH_` | Authentication | `AUTH_JWT_SECRET` |
### Required Files
- `.env.local` - 로컬 개발용
- `.env.example` - 템플릿 (커밋)
- `lib/env.ts` - 환경변수 검증
---
## 5. Code Style
- Indentation: 2 spaces
- Quotes: Single quotes (')
- Semicolons: None (Prettier)
- Max line length: 100
---
## 6. Commit Message
```
type(scope): description
Types: feat, fix, docs, style, refactor, test, chore
```
---
## Validation Checklist
- [ ] Naming convention 정의됨
- [ ] Folder structure 정의됨
- [ ] Import order 정의됨
- [ ] Environment variables 정의됨
- [ ] Code style 설정됨
---
*Generated by hmcmkit PDCA System*
@@ -0,0 +1,449 @@
---
template: design-enterprise
version: 1.0
description: Detailed design document for Enterprise level projects
variables:
- feature: Feature name
- date: Creation date (YYYY-MM-DD)
- author: Author
- version: Document version
- reviewers: Reviewers list
level: Enterprise
---
# {feature} Detailed Design Document
> **Version**: {version}
> **Created**: {date}
> **Author**: {author}
> **Status**: Draft
> **Reviewers**: {reviewers}
> **Planning Doc**: [{feature}.plan.md](../01-plan/features/{feature}.plan.md)
---
## 1. Executive Summary
### 1.1 Purpose
{High-level purpose of this feature}
### 1.2 Scope
{What is included and excluded from this design}
### 1.3 Goals
- {Goal 1}
- {Goal 2}
- {Goal 3}
---
## 2. Non-Functional Requirements
### 2.1 Performance
| Metric | Target | Rationale |
|--------|--------|-----------|
| Response time (P95) | < 200ms | User experience |
| Throughput | > 1000 RPS | Peak load |
| Database query time | < 50ms | Backend performance |
### 2.2 Scalability
- Horizontal scaling capability
- Expected growth: {X}% per month
- Auto-scaling thresholds
### 2.3 Availability
- Target SLA: 99.9%
- Recovery Time Objective (RTO): < 1 hour
- Recovery Point Objective (RPO): < 5 minutes
---
## 3. System Architecture
### 3.1 High-Level Architecture
```
┌──────────────────────────────────────────────────────────────┐
│ Load Balancer (ALB) │
└──────────────────────────────────────────────────────────────┘
│
┌───────────────┼───────────────┐
▼ ▼ ▼
┌─────────────────┐ ┌─────────────────┐ ┌─────────────────┐
│ Service A │ │ Service B │ │ Service C │
│ (API) │ │ (Worker) │ │ (Gateway) │
└─────────────────┘ └─────────────────┘ └─────────────────┘
│ │ │
└───────────────┼───────────────┘
▼
┌──────────────────────────────────────────────────────────────┐
│ Data Layer │
│ ┌─────────┐ ┌─────────┐ ┌─────────┐ ┌─────────┐ │
│ │PostgreSQL│ │ Redis │ │ S3 │ │ ElasticSearch│ │
│ └─────────┘ └─────────┘ └─────────┘ └─────────┘ │
└──────────────────────────────────────────────────────────────┘
```
### 3.2 Microservices Structure
| Service | Responsibility | Stack | Replicas |
|---------|---------------|-------|----------|
| {service-a} | {role} | {tech} | 3 |
| {service-b} | {role} | {tech} | 2 |
### 3.3 Clean Architecture Layers
```
┌─────────────────────────────────────────────────────────────┐
│ Presentation Layer │
│ (Controllers, DTOs, Mappers) │
├─────────────────────────────────────────────────────────────┤
│ Application Layer │
│ (Use Cases, Services, Handlers) │
├─────────────────────────────────────────────────────────────┤
│ Domain Layer │
│ (Entities, Value Objects, Interfaces) │
├─────────────────────────────────────────────────────────────┤
│ Infrastructure Layer │
│ (Repositories, External APIs, Database) │
└─────────────────────────────────────────────────────────────┘
```
### 3.4 Inter-Service Communication
| From | To | Protocol | Pattern |
|------|-----|----------|---------|
| API Gateway | Service A | gRPC | Request/Response |
| Service A | Service B | Message Queue | Event-driven |
---
## 4. Data Model
### 4.1 Entity Definitions
```typescript
// {Entity}
interface {Entity} {
id: string;
version: number; // Optimistic locking
createdAt: Date;
updatedAt: Date;
createdBy: string;
// Fields...
}
```
### 4.2 Database Schema
```sql
CREATE TABLE {table} (
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
version INTEGER NOT NULL DEFAULT 1,
created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
created_by UUID REFERENCES users(id),
-- Fields...
);
CREATE INDEX idx_{table}_created_at ON {table}(created_at);
```
### 4.3 Event Schema (Event-driven)
```typescript
interface {Feature}Event {
eventId: string;
eventType: '{feature}.created' | '{feature}.updated';
timestamp: string;
payload: {
// Event data
};
}
```
---
## 5. API Specification
### 5.1 Endpoint List
| Method | Path | Description | Rate Limit |
|--------|------|-------------|------------|
| GET | /api/v1/{resource} | List | 100/min |
| POST | /api/v1/{resource} | Create | 10/min |
| PUT | /api/v1/{resource}/:id | Update | 30/min |
| DELETE | /api/v1/{resource}/:id | Delete | 5/min |
### 5.2 Response Format (Standard)
```json
// Success
{
"data": { ... },
"meta": {
"requestId": "req_xxx",
"timestamp": "2024-01-01T00:00:00Z"
}
}
// Error
{
"error": {
"code": "VALIDATION_ERROR",
"message": "User-friendly message",
"details": [ ... ]
}
}
// Pagination
{
"data": [ ... ],
"pagination": {
"total": 100,
"page": 1,
"limit": 20,
"hasMore": true
}
}
```
---
## 6. Infrastructure
### 6.1 Kubernetes Resources
```yaml
apiVersion: apps/v1
kind: Deployment
metadata:
name: {service}
spec:
replicas: 3
template:
spec:
containers:
- name: {service}
resources:
requests:
cpu: "100m"
memory: "256Mi"
limits:
cpu: "500m"
memory: "512Mi"
```
### 6.2 Environment Variables
| Variable | Description | Scope |
|----------|-------------|-------|
| DB_HOST | Database host | Server |
| REDIS_URL | Redis connection | Server |
| NEXT_PUBLIC_API_URL | API base URL | Client |
---
## 7. Security
### 7.1 Authentication & Authorization
- Authentication: JWT with refresh tokens
- Authorization: RBAC with permissions
- Token expiry: Access 15min, Refresh 7days
### 7.2 Security Checklist
- [ ] Input validation (all endpoints)
- [ ] SQL injection prevention (parameterized queries)
- [ ] XSS prevention (output encoding)
- [ ] CSRF protection (tokens)
- [ ] Rate limiting (per endpoint)
- [ ] Audit logging (sensitive operations)
- [ ] Secrets management (no hardcoded secrets)
---
## 8. Monitoring & Observability
### 8.1 Monitoring Stack
| Component | Tool | Role |
|-----------|------|------|
| Error Tracking | **Sentry** | Error grouping, regression detection, session replay |
| Metrics | Prometheus | Counter/Gauge/Histogram, 15s scrape interval |
| Dashboards | Grafana | Unified view (Prometheus + Loki + Tempo + Sentry) |
| Logs | Loki + Promtail | JSON structured log aggregation, 30d retention |
| Tracing | Tempo + OpenTelemetry | Distributed tracing, 10% sampling (prod) |
| Alerting | Alertmanager | Route: Critical→PagerDuty, Warning→Slack |
### 8.2 Metrics & SLOs
| Metric | Type | SLO/Threshold | Alert |
|--------|------|---------------|-------|
| request_latency_seconds | Histogram | P95 < 200ms, P99 < 500ms | Warning > 500ms, Critical > 1s |
| error_rate | Counter | < 0.1% (SLO 99.9%) | Warning > 1%, Critical > 5% |
| cpu_usage | Gauge | < 70% (HPA target) | Warning > 80%, Critical > 95% |
| memory_usage | Gauge | < 80% (HPA target) | Warning > 85%, Critical > 95% |
| sentry_unresolved_issues | Gauge | < 5 critical | Warning > 5, Critical > 10 |
### 8.3 Logging
- Format: JSON structured
- Required fields: `timestamp, level, service, request_id, trace_id, user_id, message`
- Retention: 30 days
- Error logs: Sentry SDK가 자동 캡처 (breadcrumbs 포함)
### 8.4 Error Tracking (Sentry)
```
Frontend (Next.js):
- @sentry/nextjs SDK
- Error Boundary 자동 연동
- Session Replay (에러 시 100%)
- Performance Monitoring (10% sampling)
Backend (FastAPI):
- sentry-sdk[fastapi]
- ASGI middleware 자동 캡처
- SQLAlchemy integration (slow query 추적)
- Custom context: user_id, request_id, service_name
```
### 8.5 Alerts & Escalation
| Alert | Condition | Severity | Action |
|-------|-----------|----------|--------|
| High Error Rate | > 5% for 5min | Critical | PagerDuty page + Auto-Rollback |
| High Latency | P95 > 1s for 10min | Warning | Slack #error-alerts |
| Sentry New Issue | New unhandled exception | Warning | Self-Healing Agent trigger |
| Sentry Regression | Resolved issue re-opened | Critical | Self-Healing + PagerDuty |
| Sentry Spike | Error frequency > 10x baseline | Critical | Auto-Rollback + PagerDuty |
---
## 9. Error Handling & Self-Healing Pipeline
### 9.1 Error Flow
```
Exception 발생
↓
Sentry SDK 자동 캡처 (breadcrumbs + user + release)
↓
Sentry Alert Rule (new/regression/spike)
↓
Self-Healing Agent (Living Context 4-Layer)
↓
Auto-fix (max 5 iter) → 4중 검증 → Auto PR
↓
Canary Deploy (10%→25%→50%→100%)
↓
Post-deploy 검증 (Sentry issue resolved? error_rate 정상?)
↓
실패 시 → Auto-Rollback + Incident Memory 기록
```
### 9.2 Circuit Breaker
| State | Condition | Action |
|-------|-----------|--------|
| CLOSED | failures < 3 | Normal operation |
| OPEN | failures >= 3 | Block all transitions, 30s cooldown |
| HALF_OPEN | cooldown expired | 1 trial attempt → success=CLOSED, fail=OPEN |
---
## 10. Deployment
### 10.1 Load Balancer
```
Internet → CloudFront (CDN + WAF) → ALB → NGINX Ingress Controller → Services
↑
CORS 처리 (annotation)
Path-based routing
TLS termination (ACM)
```
- **ALB + NGINX Ingress** (기본): L7, CORS annotation, path routing, WAF 연동
- **NLB** (특수): L4, gRPC/WebSocket 전용, CORS는 앱단 처리
### 10.2 CI/CD Pipeline
```
PR → Lint/Test(≥80%) → Security Scan(Semgrep+Trivy) → Build → Push ECR
→ Deploy Staging(ArgoCD) → E2E Test → Approval Gate → Canary Deploy Prod
```
### 10.3 Canary Strategy (Argo Rollouts)
```
10% traffic (2min) → metric check → 25% (2min) → 50% (5min) → 100%
↓ fail
Auto-Rollback + Sentry alert
```
### 10.4 Rollback Strategy
1. **Auto-Rollback**: Canary metrics fail (error_rate > 1% or P95 > 200ms)
2. **Self-Healing Rollback**: 5회 fix 실패 시 자동 롤백
3. **Manual Rollback**: ArgoCD UI one-click revert
3. Database migration rollback scripts ready
---
## 10. Test Plan
### 10.1 Test Pyramid
| Type | Coverage Target | Tools |
|------|-----------------|-------|
| Unit | > 80% | Jest |
| Integration | Key paths | Supertest |
| E2E | Critical flows | Playwright |
| Load | Performance | k6 |
### 10.2 Key Test Scenarios
- [ ] Happy path: {description}
- [ ] Error handling: {description}
- [ ] Edge cases: {description}
- [ ] Concurrency: {description}
- [ ] Failover: {description}
---
## 11. Implementation Plan
### 11.1 Phases
| Phase | Scope | Duration |
|-------|-------|----------|
| 1 | Core infrastructure | 2 days |
| 2 | API implementation | 3 days |
| 3 | UI integration | 2 days |
| 4 | Testing & QA | 2 days |
### 11.2 Success Criteria
- [ ] All endpoints implemented
- [ ] Test coverage > 80%
- [ ] Zero Script QA passed
- [ ] Security scan passed
- [ ] Performance benchmarks met
- [ ] Documentation complete
---
## Document History
| Version | Date | Changes | Author | Reviewer |
|---------|------|---------|--------|----------|
| 0.1 | {date} | Initial draft | {author} | - |
@@ -0,0 +1,70 @@
---
template: design-starter
version: 1.0
description: Simplified design document for Starter level projects
variables:
- feature: Feature name
- date: Creation date (YYYY-MM-DD)
level: Starter
---
# {feature} Design
> **Created**: {date}
---
## Goal
{What this feature does in simple terms}
---
## How It Works
{Simple explanation of how the feature works}
```
User Action → What Happens → Result
```
---
## What We Need to Build
### Files to Create
| File | Purpose |
|------|---------|
| `pages/{feature}.html` | Main page |
| `css/{feature}.css` | Styles |
| `js/{feature}.js` | Interactivity |
### Layout
```
┌─────────────────────────────┐
│ Header │
├─────────────────────────────┤
│ │
│ Main Content │
│ │
├─────────────────────────────┤
│ Footer │
└─────────────────────────────┘
```
---
## Completion Checklist
- [ ] Feature works as expected
- [ ] Looks good on desktop
- [ ] Looks good on mobile
- [ ] Tested in browser
---
## Notes
{Any important notes or things to remember}
@@ -0,0 +1,540 @@
---
template: design
version: 1.3
description: PDCA Design phase document template with Context Anchor, Session Guide, and Clean Architecture support
variables:
- feature: Feature name
- date: Creation date (YYYY-MM-DD)
- author: Author
- project: Project name (from package.json or agents.md)
- version: Project version (from package.json)
---
# {feature} Design Document
> **Summary**: {One-line description}
>
> **Project**: {project}
> **Version**: {version}
> **Author**: {author}
> **Date**: {date}
> **Status**: Draft
> **Planning Doc**: [{feature}.plan.md](../01-plan/features/{feature}.plan.md)
### Pipeline References (if applicable)
| Phase | Document | Status |
|-------|----------|--------|
| Phase 1 | [Schema Definition](../01-plan/schema.md) | ✅/❌/N/A |
| Phase 2 | [Coding Conventions](../01-plan/conventions.md) | ✅/❌/N/A |
| Phase 3 | [Mockup](../02-design/mockup/{feature}.md) | ✅/❌/N/A |
| Phase 4 | [API Spec](../02-design/api/{feature}.md) | ✅/❌/N/A |
> **Note**: If Pipeline documents exist, reference them in the relevant sections below.
---
## Context Anchor
> Copied from Plan document. Ensures strategic context survives Design→Do handoff.
| Key | Value |
|-----|-------|
| **WHY** | {copied from Plan Context Anchor} |
| **WHO** | {copied from Plan Context Anchor} |
| **RISK** | {copied from Plan Context Anchor} |
| **SUCCESS** | {copied from Plan Context Anchor} |
| **SCOPE** | {copied from Plan Context Anchor} |
---
## Design Anchor (if Pencil MCP used)
> Locked design tokens from initial concept pages. Enforced on every new page.
> Capture with: `/design-anchor capture {feature}`
> File: `docs/02-design/styles/{feature}.design-anchor.md`
| Category | Tokens |
|----------|--------|
| **Colors** | primary: `{value}`, bg: `{value}`, text: `{value}` |
| **Typography** | {font-family}, sizes: {scale} |
| **Spacing** | {base-unit} grid, card: {value}, section: {value} |
| **Radius** | default: `{value}` |
| **Tone** | {design tone description} |
| **Layout** | {layout pattern description} |
> Remove this section if not using Pencil MCP for this feature.
---
## 1. Overview
### 1.1 Design Goals
{Technical goals this design aims to achieve}
### 1.2 Design Principles
- {Principle 1: e.g., Single Responsibility Principle}
- {Principle 2: e.g., Extensible architecture}
- {Principle 3}
---
## 2. Architecture Options (v1.7.0)
### 2.0 Architecture Comparison
Three architecture options are evaluated before detailed design. User selects one via Checkpoint 3.
| Criteria | Option A: Minimal | Option B: Clean | Option C: Pragmatic |
|----------|:-:|:-:|:-:|
| **Approach** | Least change, max reuse | Best separation, most maintainable | Good boundaries, balanced |
| **New Files** | {N} | {N} | {N} |
| **Modified Files** | {N} | {N} | {N} |
| **Complexity** | Low | High | Medium |
| **Maintainability** | Medium | High | High |
| **Effort** | Low | High | Medium |
| **Risk** | Low (coupled) | Low (clean) | Low (balanced) |
| **Recommendation** | Quick wins, hotfixes | Long-term projects | **Default choice** |
**Selected**: {Option A/B/C} — **Rationale**: {why this was chosen}
> The detailed design below follows the selected architecture option.
### 2.1 Component Diagram
```
┌─────────────┐ ┌─────────────┐ ┌─────────────┐
│ Client │────▶│ Server │────▶│ Database │
│ (Browser) │ │ (API) │ │ (Storage) │
└─────────────┘ └─────────────┘ └─────────────┘
```
### BaaS Architecture (Dynamic Level)
```
Client (Next.js) -> bkend.ai Service API (REST) -> MongoDB
<-> MCP (schema management)
Antigravity Platform
```
### 2.2 Data Flow
```
User Input → Validation → Business Logic → Data Storage → Response
```
### 2.3 Dependencies
| Component | Depends On | Purpose |
|-----------|-----------|---------|
| {Component A} | {Component B} | {Purpose} |
---
## 3. Data Model
### 3.1 Entity Definition
```typescript
// {Entity name}
interface {Entity} {
id: string; // Unique identifier
createdAt: Date; // Creation timestamp
updatedAt: Date; // Last update timestamp
// Additional fields...
}
```
### 3.2 Entity Relationships
```
[User] 1 ──── N [Post]
│
└── 1 ──── N [Comment]
```
### 3.3 Database Schema (if applicable)
```sql
CREATE TABLE {table_name} (
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
created_at TIMESTAMP WITH TIME ZONE DEFAULT NOW(),
updated_at TIMESTAMP WITH TIME ZONE DEFAULT NOW()
);
```
### MongoDB Collection Schema (Dynamic Level - bkend.ai)
| Field | Type | Required | Unique | Description |
|-------|------|----------|--------|-------------|
| _id | ObjectId | auto | auto | System generated |
| createdBy | String | auto | - | Creator user ID |
| createdAt | Date | auto | - | Creation timestamp |
| updatedAt | Date | auto | - | Update timestamp |
---
## 4. API Specification
### BaaS API (Dynamic Level)
Dynamic level uses bkend.ai auto-generated REST API.
CRUD endpoints are auto-generated when tables are created (no separate API implementation needed).
Reference: MCP tool `4_howto_implement_data_crud`
### 4.1 Endpoint List
| Method | Path | Description | Auth |
|--------|------|-------------|------|
| GET | /api/{resource} | List all | Required |
| GET | /api/{resource}/:id | Get detail | Required |
| POST | /api/{resource} | Create | Required |
| PUT | /api/{resource}/:id | Update | Required |
| DELETE | /api/{resource}/:id | Delete | Required |
### 4.2 Detailed Specification
#### `POST /api/{resource}`
**Request:**
```json
{
"field1": "string",
"field2": "number"
}
```
**Response (201 Created):**
```json
{
"id": "string",
"field1": "string",
"field2": "number",
"createdAt": "2024-01-01T00:00:00Z"
}
```
**Error Responses:**
- `400 Bad Request`: Input validation failed
- `401 Unauthorized`: Authentication required
- `409 Conflict`: Duplicate data
---
## 5. UI/UX Design (if applicable)
### 5.1 Screen Layout
```
┌────────────────────────────────────┐
│ Header │
├────────────────────────────────────┤
│ │
│ Main Content Area │
│ │
├────────────────────────────────────┤
│ Footer │
└────────────────────────────────────┘
```
### 5.2 User Flow
```
Home → Login → Dashboard → Use Feature → View Results
```
### 5.3 Component List
| Component | Location | Responsibility |
|-----------|----------|----------------|
| {ComponentA} | src/components/ | {Role} |
### 5.4 Page UI Checklist (v2.1.0)
> **CRITICAL**: List EVERY required UI element per page. Gap Detector verifies each item.
> Without this checklist, gap analysis only checks file existence (structural), not content (functional).
>
> **How to fill**: For each page, list all interactive elements (forms, buttons, filters, dropdowns,
> badges, toggles) and data display elements (cards, lists, scores, charts) that MUST be present.
> Include specific field names, option values, and data types.
#### {Page Name 1}
- [ ] {Element type}: {Description} ({specific details: options, fields, values})
- [ ] {Element type}: {Description}
#### {Page Name 2}
- [ ] {Element type}: {Description}
> **Example** (remove in actual document):
> #### Search Page
> - [ ] Filter: Property Type dropdown (6 options: Officetel, Apartment, House, Share House, Serviced Apt, Hotel)
> - [ ] Filter: Price range slider (weekly rent, min/max KRW inputs)
> - [ ] Filter: ARC Registration Available checkbox
> - [ ] Filter: Pet Allowed checkbox
> - [ ] Button: Save Search
> - [ ] Card: Weekly rent display (₩{amount}/week)
> - [ ] Card: Area display ({N}평)
> - [ ] Card: ARC badge (green, conditional)
> - [ ] Card: Pet badge (conditional)
> - [ ] Toggle: List / Map view
> - [ ] Sort: Recommended, Price ASC, Price DESC, Newest
---
## 6. Error Handling
### 6.1 Error Code Definition
| Code | Message | Cause | Handling |
|------|---------|-------|----------|
| 400 | Invalid input | Input error | Request re-entry from client |
| 401 | Unauthorized | Auth failure | Redirect to login page |
| 404 | Not found | Resource missing | Show 404 page |
| 500 | Internal error | Server error | Log error and notify user |
### 6.2 Error Response Format
```json
{
"error": {
"code": "ERROR_CODE",
"message": "User-friendly message",
"details": {}
}
}
```
---
## 7. Security Considerations
- [ ] Input validation (XSS, SQL Injection prevention)
- [ ] Authentication/Authorization handling
- [ ] Sensitive data encryption
- [ ] HTTPS enforcement
- [ ] Rate Limiting
---
## 8. Test Plan (v2.3.0)
> **CRITICAL**: Define WHAT to test here. Test CODE is written during Do phase alongside implementation.
> Do phase rule: code + test = 1 set. No module is "done" without its tests passing.
> Check phase: runs all tests, doesn't create new ones.
### 8.1 Test Scope
| Type | Target | Tool | Phase |
|------|--------|------|-------|
| L1: API Tests | Endpoints — status, params, response shape | curl / Playwright request | Do |
| L2: UI Action Tests | Page elements — forms, buttons, data display | Playwright | Do |
| L3: E2E Scenario Tests | User journeys — multi-page flows | Playwright | Do |
### 8.2 L1: API Test Scenarios
> Define expected behavior for each endpoint. Do phase writes the actual test code.
| # | Endpoint | Method | Test Description | Expected Status | Expected Response |
|---|----------|--------|-----------------|:--------------:|-------------------|
| 1 | /api/{resource} | GET | Returns list with data | 200 | `.data` is array, `.pagination.total` > 0 |
| 2 | /api/{resource}/:id | GET | Returns detail with relations | 200 | `.data.id` exists, nested relations loaded |
| 3 | /api/{resource} | POST | Creates with valid data | 201 | `.data.id` exists |
| 4 | /api/{resource} | POST | Rejects invalid data | 400 | `.error.code` = "VALIDATION_ERROR", `.error.details.fieldErrors` present |
| 5 | /api/{protected} | GET | Blocks unauthenticated | 401 | `.error.code` = "UNAUTHORIZED" |
| 6 | /api/{resource}?filter=X | GET | Filter reduces results | 200 | `filtered.data.length` < `all.data.length` |
### 8.3 L2: UI Action Test Scenarios
> Define per-page: what action → what result. Reference §5.4 Page UI Checklist.
| # | Page | Action | Expected Result | Data Verification |
|---|------|--------|----------------|-------------------|
| 1 | {page} | Load page | All §5.4 checklist elements visible | DB data renders (not skeleton) |
| 2 | {page} | Click filter | Results change | Count decreases |
| 3 | {page} | Submit form | Success state shown | API returns 201 |
| 4 | {page} | Invalid submit | Error message shown | Validation errors display |
### 8.4 L3: E2E Scenario Test Scenarios
> Define complete user journeys. Each scenario chains multiple pages.
| # | Scenario | Steps | Success Criteria |
|---|----------|-------|-----------------|
| 1 | Guest browsing | Home → Search(data>0) → Filter → Detail(title+host+price) | All data renders from DB |
| 2 | Auth flow | Register → Login → Access protected page | No 401 errors |
| 3 | Form submission | Navigate → Fill all fields → Submit → Verify success | Confirmation UI shown |
| 4 | i18n | Switch language → Verify text changes | UI text matches locale |
| 5 | Error handling | Wrong credentials → Error shown, Invalid form → Validation shown | User gets feedback |
### 8.5 Seed Data Requirements
> Tests need data. Define minimum seed data for tests to be meaningful.
| Entity | Minimum Count | Key Fields Required |
|--------|:------------:|---------------------|
| {entity} | {N} | {fields that must have values} |
> Do phase: implement `src/lib/db/seed.ts` before writing tests.
> Check phase: run seed before test execution.
---
## 9. Clean Architecture
> Reference: `docs/01-plan/conventions.md` or Phase 2 Pipeline output
### 9.1 Layer Structure
| Layer | Responsibility | Location |
|-------|---------------|----------|
| **Presentation** | UI components, hooks, pages | `src/components/`, `src/hooks/`, `src/app/` |
| **Application** | Use cases, services, business logic orchestration | `src/services/`, `src/features/*/hooks/` |
| **Domain** | Entities, types, core business rules | `src/types/`, `src/domain/` |
| **Infrastructure** | API clients, DB, external services | `src/lib/`, `src/api/` |
### 9.2 Dependency Rules
```
┌─────────────────────────────────────────────────────────────┐
│ Dependency Direction │
├─────────────────────────────────────────────────────────────┤
│ │
│ Presentation ──→ Application ──→ Domain ←── Infrastructure│
│ │ │
│ └──→ Infrastructure │
│ │
│ Rule: Inner layers MUST NOT depend on outer layers │
│ Domain is independent (no external dependencies) │
│ │
└─────────────────────────────────────────────────────────────┘
```
### 9.3 File Import Rules
| From | Can Import | Cannot Import |
|------|-----------|---------------|
| Presentation | Application, Domain | Infrastructure directly |
| Application | Domain, Infrastructure | Presentation |
| Domain | Nothing external (pure types/logic) | All external layers |
| Infrastructure | Domain only | Application, Presentation |
### 9.4 This Feature's Layer Assignment
| Component | Layer | Location |
|-----------|-------|----------|
| {ComponentA} | Presentation | `src/components/{feature}/` |
| {ServiceA} | Application | `src/services/{feature}.ts` |
| {TypeA} | Domain | `src/types/{feature}.ts` |
| {ApiClient} | Infrastructure | `src/lib/api/{feature}.ts` |
---
## 10. Coding Convention Reference
> Reference: `docs/01-plan/conventions.md` or Phase 2 Pipeline output
### 10.1 Naming Conventions
| Target | Rule | Example |
|--------|------|---------|
| Components | PascalCase | `UserProfile`, `LoginForm` |
| Functions | camelCase | `getUserById()`, `handleSubmit()` |
| Constants | UPPER_SNAKE_CASE | `MAX_RETRY_COUNT`, `API_BASE_URL` |
| Types/Interfaces | PascalCase | `UserProfile`, `ApiResponse` |
| Files (component) | PascalCase.tsx | `UserProfile.tsx` |
| Files (utility) | camelCase.ts | `formatDate.ts` |
| Folders | kebab-case | `user-profile/`, `auth-provider/` |
### 10.2 Import Order
```typescript
// 1. External libraries
import { useState } from 'react'
import { useQuery } from '@tanstack/react-query'
// 2. Internal absolute imports
import { Button } from '@/components/ui'
import { userService } from '@/services/user'
// 3. Relative imports
import { useLocalState } from './hooks'
// 4. Type imports
import type { User } from '@/types'
// 5. Styles
import './styles.css'
```
### 10.3 Environment Variables
| Prefix | Purpose | Scope | Example |
|--------|---------|-------|---------|
| `NEXT_PUBLIC_` | Client-side accessible | Browser | `NEXT_PUBLIC_API_URL` |
| `DB_` | Database connections | Server only | `DB_HOST`, `DB_PASSWORD` |
| `API_` | External API keys | Server only | `API_STRIPE_SECRET` |
| `AUTH_` | Authentication secrets | Server only | `AUTH_SECRET`, `AUTH_GOOGLE_ID` |
### 10.4 This Feature's Conventions
| Item | Convention Applied |
|------|-------------------|
| Component naming | {convention used} |
| File organization | {convention used} |
| State management | {convention used} |
| Error handling | {convention used} |
---
## 11. Implementation Guide
### 11.1 File Structure
```
src/
├── features/{feature}/
│ ├── components/
│ ├── hooks/
│ ├── api/
│ └── types/
```
### 11.2 Implementation Order
1. [ ] Define data model
2. [ ] Implement API
3. [ ] Implement UI components
4. [ ] Integration and testing
### 11.3 Session Guide
> Auto-generated from Design structure. Session split is recommended, not required.
> Use `/pdca do {feature} --scope module-N` to implement one module per session.
#### Module Map
| Module | Scope Key | Description | Estimated Turns |
|--------|-----------|-------------|:---------------:|
| {module name} | `module-1` | {description} | {turns} |
| {module name} | `module-2` | {description} | {turns} |
#### Recommended Session Plan
| Session | Phase | Scope | Turns |
|---------|-------|-------|:-----:|
| Session 1 | Plan + Design | 전체 | 30-35 |
| Session 2 | Do | `--scope module-1` | 40-50 |
| Session 3 | Do | `--scope module-2` | 40-50 |
| Session 4 | Check + Report | 전체 | 30-40 |
---
## Version History
| Version | Date | Changes | Author |
|---------|------|---------|--------|
| 0.1 | {date} | Initial draft | {author} |
+415
View File
@@ -0,0 +1,415 @@
---
template: do
version: 1.1
description: PDCA Do phase implementation guide template with Context Anchor and Session Scope
variables:
- feature: Feature name
- date: Creation date (YYYY-MM-DD)
- author: Author
- project: Project name
- version: Project version
---
# {feature} Implementation Guide
> **Summary**: {One-line description}
>
> **Project**: {project}
> **Version**: {version}
> **Author**: {author}
> **Date**: {date}
> **Status**: In Progress
> **Design Doc**: [{feature}.design.md](../02-design/features/{feature}.design.md)
---
## Context Anchor
> Carried from Plan → Design → Do. Review WHY before implementation.
| Key | Value |
|-----|-------|
| **WHY** | {copied from Design Context Anchor} |
| **WHO** | {copied from Design Context Anchor} |
| **RISK** | {copied from Design Context Anchor} |
| **SUCCESS** | {copied from Design Context Anchor} |
| **SCOPE** | {copied from Design Context Anchor} |
---
## Design Anchor (UI Implementation Guide)
> If Design Anchor exists, UI implementation MUST follow these locked tokens.
> Source: `docs/02-design/styles/{feature}.design-anchor.md`
| Category | Token | Value |
|----------|-------|-------|
| Primary Color | `--primary` | `{value}` |
| Background | `--bg` | `{value}` |
| Font | `font-family` | `{value}` |
| Radius | `border-radius` | `{value}` |
| Tone | — | {description} |
> shadcn/ui components must be styled to match these tokens. Design Anchor decides, code follows.
> Run `/design-anchor verify {feature}` after UI implementation to check consistency.
---
## Session Scope
> Scope: {--scope value or "전체 (all modules)"}
### Current Session Modules
| Module | Scope Key | Status |
|--------|-----------|:------:|
| {module} | `module-N` | ☐ This session |
| {module} | `module-N` | — Other session |
> Tip: Use `/pdca do {feature} --scope module-N` to focus on specific modules.
---
## Upstream Context Chain
> Full upstream documents loaded for implementation context continuity.
### Documents Loaded
| Document | Path | Key Context |
|----------|------|-------------|
| PRD | `docs/00-pm/{feature}.prd.md` | {WHY — core problem and value proposition} |
| Plan | `docs/01-plan/features/{feature}.plan.md` | {SUCCESS — criteria to meet} |
| Design | `docs/02-design/features/{feature}.design.md` | {HOW — architecture and data model} |
### Decision Record Chain
> Key decisions from PRD→Plan→Design that guide implementation.
| Source | Decision | Rationale |
|--------|----------|-----------|
| [PRD] | {decision} | {rationale} |
| [Plan] | {decision} | {rationale} |
| [Design] | {decision} | {rationale} |
### Success Criteria Tracking
> From Plan document. Each criterion must be addressed during implementation.
| # | Criteria | Scope Module | Status |
|---|---------|:------------:|:------:|
| SC-1 | {criteria text} | module-N | ☐ |
| SC-2 | {criteria text} | module-N | ☐ |
---
## 1. Pre-Implementation Checklist
### 1.1 Documents Verified
- [ ] PRD reviewed: `docs/00-pm/{feature}.prd.md`
- [ ] Plan document reviewed: `docs/01-plan/features/{feature}.plan.md`
- [ ] Design document reviewed: `docs/02-design/features/{feature}.design.md`
- [ ] Conventions understood: `CONVENTIONS.md` or `docs/01-plan/conventions.md`
### 1.2 Environment Ready
- [ ] Dependencies installed
- [ ] Development server running
- [ ] Test environment configured
- [ ] Required environment variables set
---
## 2. Implementation Strategy: Depth-First (v2.1.0)
> **CRITICAL RULE**: Implement DEEP, not WIDE.
>
> **Anti-pattern** (causes ~40% functional fidelity):
> Create 20+ files as skeletons → each file 30% complete → structural match 90% but functionally hollow
>
> **Correct pattern** (targets 80%+ functional fidelity):
> Implement 3-5 files fully → verify each file against Page UI Checklist → then next batch
>
> **Quality Gate**: Each file must score ≥60 on Functional Depth before creating next file.
> - No `// TODO` placeholders left behind
> - No `[1, 2, 3].map` skeleton arrays
> - No empty event handlers (`console.log` stubs)
> - All design-specified form fields present
> - Real data fetching, not hardcoded mock
### 2.0 Depth-First Rules (v2.3.0)
```
1. Maximum 3-5 files per implementation batch
2. Each batch follows: API route → Hook → Component → Page → TEST (bottom-up)
3. Code + Test = 1 set. No batch is "done" without tests passing.
4. Page UI Checklist items for current batch = 100% before next batch
5. curl/render verification after each batch
6. If session turn budget runs low, STOP and save progress
(5 files × 100% >> 20 files × 30%)
Implementation cycle per batch:
① API route.ts — implement endpoint
② Test L1 — curl test for that endpoint (status + response shape)
③ Hook + Component — implement UI
④ Test L2 — Playwright test for that page (elements + data display)
⑤ Page integration — connect everything
⑥ Verify — run tests, all green → next batch
Test files location: tests/e2e/{feature}.spec.ts
Test scenarios come from: Design §8 Test Plan (L1/L2/L3 scenarios)
```
### 2.1 Sub-Module Splitting (v2.1.0)
> If Design Session Guide has modules with >20 estimated turns,
> split into sub-modules of 3-5 files each.
| Sub-Module | Files | Turns | Quality Gate |
|------------|:-----:|:-----:|-------------|
| {module-Na} | 3-5 | 10-15 | All files functional, Page UI Checklist items met |
| {module-Nb} | 3-5 | 10-15 | All files functional, Page UI Checklist items met |
> **Turn Budget Reality Check**:
> - New file (skeleton): ~1 turn
> - File full implementation: ~3-5 turns
> - API + Hook + Component + Page set: ~12-15 turns
> - Overestimating turn count leads to shallow breadth-first implementation
### 2.2 Implementation Order (Bottom-Up per Batch)
| Step | Layer | Task | Files | Status |
|:----:|-------|------|:-----:|:------:|
| 1 | Data | Types + Validation schemas | 1-2 | ☐ |
| 2 | API | API route with Zod + Auth | 1 | ☐ |
| 3 | Logic | Hook with real fetch + state | 1 | ☐ |
| 4 | UI | Component with ALL design fields | 1-2 | ☐ |
| 5 | Page | Page composing components | 1 | ☐ |
| **Gate** | **Verify** | **curl 200 + UI Checklist 100%** | — | ☐ |
### 2.3 Functional Completeness Checklist (per file)
Before marking a file as "done", verify:
- [ ] No `// TODO` or `// placeholder` comments remaining
- [ ] No `console.log()` stub handlers (must have real logic or proper state updates)
- [ ] No hardcoded mock arrays (`[1,2,3].map` → must use real data or empty state)
- [ ] All form fields from Page UI Checklist present
- [ ] All interactive elements (buttons, toggles, dropdowns) have real handlers
- [ ] Loading state implemented (not just permanent skeleton)
- [ ] Error state implemented (not just silent catch)
- [ ] Data fetching connected (useEffect + hook, or SSR fetch)
---
## 3. Key Files to Create/Modify
### 3.1 New Files
| File Path | Purpose | Template |
|-----------|---------|----------|
| `src/types/{feature}.ts` | Type definitions | Interface definitions |
| `src/services/{feature}.ts` | Business logic | Service class/functions |
| `src/hooks/use{Feature}.ts` | React hooks | Custom hook pattern |
| `src/components/{feature}/index.tsx` | Main component | Component template |
### 3.2 Files to Modify
| File Path | Changes | Reason |
|-----------|---------|--------|
| `src/app/layout.tsx` | Add provider/context | Global state setup |
| `src/lib/api/client.ts` | Add endpoints | API integration |
| `src/types/index.ts` | Export new types | Type organization |
---
## 4. Dependencies
### 4.1 Required Packages
```bash
# Add any new dependencies here
npm install {package1} {package2}
# or
pnpm add {package1} {package2}
```
### 4.2 Dev Dependencies
```bash
npm install -D {dev-package1} {dev-package2}
```
---
## 5. Implementation Notes
### 5.1 Design Decisions Reference
> Key decisions from Design document to follow during implementation.
| Decision | Choice | Rationale |
|----------|--------|-----------|
| State Management | {choice} | {reason} |
| API Pattern | {choice} | {reason} |
| Error Handling | {choice} | {reason} |
### 5.2 Code Patterns to Follow
```typescript
// Example pattern from conventions
// Add specific patterns here based on project conventions
```
### 5.3 Code-to-Design Traceability (Phase 3)
> Add these comment patterns to create traceable links from code to design decisions.
```typescript
// At module/file level — link to Design section
// Design Ref: §3.1 Data Model — MongoDB with embedded documents for performance
// At critical business logic — link to Success Criteria
// Plan SC: Response time < 200ms for search queries
// At architecture decision points — link to Decision Record
// Decision: [Design] State Mgmt: Zustand — lightweight, no boilerplate
```
**Rules:**
- Add `// Design Ref:` at the top of files that implement a specific Design section
- Add `// Plan SC:` before code that directly addresses a Success Criteria
- Add `// Decision:` before code that implements a key architectural decision
- Keep comments concise (1 line) — they're pointers, not documentation
### 5.4 Things to Avoid
- [ ] Hardcoded values (use constants/config)
- [ ] Direct DOM manipulation (use React patterns)
- [ ] Inline styles (use Tailwind/CSS modules)
- [ ] Console.log in production code
### 5.4 Architecture Checklist (Phase 2 Based)
> Verify Clean Architecture compliance
- [ ] **Layer Structure** - Follow layer structure matching level
- Starter: components, lib, types
- Dynamic: components, features, services, types, lib/api
- Enterprise: presentation, application, domain, infrastructure
- [ ] **Dependency Direction** - Follow dependency direction rules
- Presentation → Application, Domain (not Infrastructure)
- Application → Domain, Infrastructure
- Domain → none (independent)
- Infrastructure → Domain only
- [ ] **Import Rules** - Follow import rules
- No direct @/lib/api imports from components
- No UI imports from services
### 5.5 Convention Checklist (Phase 2 Based)
> Verify coding convention compliance
- [ ] **Naming Convention**
- Components: PascalCase (UserProfile.tsx)
- Functions: camelCase (getUserById)
- Constants: UPPER_SNAKE_CASE (MAX_RETRY_COUNT)
- Files (component): PascalCase.tsx
- Files (utility): camelCase.ts
- Folders: kebab-case
- [ ] **Import Order**
1. External libraries (react, next)
2. Internal absolute imports (@/...)
3. Relative imports (./...)
4. Type imports (import type)
5. Styles
### 5.6 Security Checklist (Phase 7 Based)
> Verify security vulnerabilities
- [ ] **Input Validation**
- Validate all user input
- SQL Injection prevention (parameterized queries)
- XSS prevention (output escaping)
- [ ] **Auth**
- Store auth tokens securely (httpOnly cookie)
- Use CSRF tokens
- Encrypt sensitive data
### 5.7 API Checklist (Phase 4 Based)
> Verify API standards compliance
- [ ] **Response Format** - Use standard response format
- Success: `{ data, meta? }`
- Error: `{ error: { code, message, details? } }`
- Pagination: `{ data, pagination }`
- [ ] **Error Codes** - Use standard error codes
- VALIDATION_ERROR, UNAUTHORIZED, NOT_FOUND, etc.
- [ ] **HTTP Methods** - Follow RESTful rules
- GET (read), POST (create), PUT/PATCH (update), DELETE (delete)
---
## 6. Testing Checklist
### 6.1 Manual Testing
- [ ] Happy path works correctly
- [ ] Error states handled properly
- [ ] Loading states displayed
- [ ] Edge cases covered
### 6.2 Code Quality
- [ ] No TypeScript errors
- [ ] No ESLint warnings
- [ ] Follows naming conventions
- [ ] Proper error handling
---
## 7. Progress Tracking
### 7.1 Daily Progress
| Date | Tasks Completed | Notes |
|------|-----------------|-------|
| {date} | Started implementation | Initial setup |
### 7.2 Blockers
| Issue | Impact | Resolution |
|-------|--------|------------|
| {blocker} | {impact} | {how resolved} |
---
## 8. Post-Implementation
### 8.1 Self-Review Checklist
- [ ] All design requirements implemented
- [ ] Code follows conventions
- [ ] No hardcoded values
- [ ] Error handling complete
- [ ] Types properly defined
### 8.2 Ready for Check Phase
When all items above are complete:
```bash
# Run Gap Analysis
/pdca analyze {feature}
```
---
## Version History
| Version | Date | Changes | Author |
|---------|------|---------|--------|
| 0.1 | {date} | Initial implementation start | {author} |
@@ -0,0 +1,87 @@
# ArgoCD Application — Auto-generated by hmcmkit infra-architect
# GitOps: Git Repo → ArgoCD Sync → Kubernetes Apply
apiVersion: argoproj.io/v1alpha1
kind: Application
metadata:
name: ${project_name}-${environment}
namespace: argocd
labels:
app.kubernetes.io/managed-by: hmcmkit
finalizers:
- resources-finalizer.argocd.argoproj.io
spec:
project: default
source:
repoURL: ${git_repo_url}
targetRevision: ${target_branch}
path: infra/k8s/overlays/${environment}
helm:
valueFiles:
- values.yaml
destination:
server: https://kubernetes.default.svc
namespace: ${environment}
syncPolicy:
automated:
prune: true
selfHeal: true
allowEmpty: false
syncOptions:
- CreateNamespace=true
- PrunePropagationPolicy=foreground
retry:
limit: 3
backoff:
duration: 5s
factor: 2
maxDuration: 3m
---
# Argo Rollout for Canary Deploy (Production only)
apiVersion: argoproj.io/v1alpha1
kind: Rollout
metadata:
name: ${project_name}-api
namespace: ${environment}
spec:
replicas: 3
strategy:
canary:
steps:
- setWeight: 10
- pause: { duration: 2m }
- setWeight: 25
- pause: { duration: 2m }
- setWeight: 50
- pause: { duration: 5m }
- setWeight: 100
canaryService: ${project_name}-api-canary
stableService: ${project_name}-api-stable
analysis:
templates:
- templateName: success-rate
startingStep: 2
args:
- name: service-name
value: ${project_name}-api
selector:
matchLabels:
app: ${project_name}-api
template:
metadata:
labels:
app: ${project_name}-api
spec:
containers:
- name: api
image: ${ecr_registry}/${project_name}:latest
ports:
- containerPort: 3000
resources:
requests: { cpu: "250m", memory: "256Mi" }
limits: { cpu: "500m", memory: "512Mi" }
livenessProbe:
httpGet: { path: /health, port: 3000 }
initialDelaySeconds: 10
readinessProbe:
httpGet: { path: /ready, port: 3000 }
initialDelaySeconds: 5
@@ -0,0 +1,86 @@
# GitHub Actions — Dynamic Level Deploy
# Auto-generated by hmcmkit /pdca deploy
# Docker Build + Push + Deploy
name: Deploy
on:
push:
branches: [main, develop, 'release/**']
pull_request:
branches: [main]
env:
REGISTRY: ghcr.io
IMAGE_NAME: ${{ github.repository }}
jobs:
test-and-lint:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: actions/setup-node@v4
with:
node-version: '20'
cache: 'npm'
- run: npm ci
- run: npm run lint
- run: npm test
security-scan:
runs-on: ubuntu-latest
needs: test-and-lint
steps:
- uses: actions/checkout@v4
- name: Run Trivy vulnerability scanner
uses: aquasecurity/trivy-action@master
with:
scan-type: 'fs'
scan-ref: '.'
severity: 'CRITICAL,HIGH'
exit-code: '1'
build-and-push:
runs-on: ubuntu-latest
needs: [test-and-lint, security-scan]
permissions:
contents: read
packages: write
steps:
- uses: actions/checkout@v4
- uses: docker/login-action@v3
with:
registry: ${{ env.REGISTRY }}
username: ${{ github.actor }}
password: ${{ secrets.GITHUB_TOKEN }}
- uses: docker/build-push-action@v5
with:
context: .
push: true
tags: |
${{ env.REGISTRY }}/${{ env.IMAGE_NAME }}:${{ github.sha }}
${{ env.REGISTRY }}/${{ env.IMAGE_NAME }}:latest
deploy-dev:
if: github.ref == 'refs/heads/develop'
runs-on: ubuntu-latest
needs: build-and-push
environment: development
steps:
- uses: actions/checkout@v4
- name: Deploy to DEV (Docker Compose)
run: |
echo "Deploying to DEV environment"
# docker compose -f docker-compose.yml up -d
deploy-staging:
if: startsWith(github.ref, 'refs/heads/release/')
runs-on: ubuntu-latest
needs: build-and-push
environment: staging
steps:
- uses: actions/checkout@v4
- name: Deploy to STAGING
run: |
echo "Deploying to STAGING environment"
# Add staging deploy commands
@@ -0,0 +1,174 @@
# GitHub Actions — Enterprise Level Deploy
# Auto-generated by hmcmkit /pdca deploy
# EKS + ArgoCD + Canary (Argo Rollouts) + Security Scan
name: Enterprise Deploy
on:
push:
branches: [main, develop, 'release/**']
pull_request:
branches: [main]
env:
AWS_REGION: ap-northeast-2
ECR_REGISTRY: ${{ secrets.AWS_ACCOUNT_ID }}.dkr.ecr.ap-northeast-2.amazonaws.com
IMAGE_NAME: ${{ github.event.repository.name }}
ARGOCD_SERVER: ${{ secrets.ARGOCD_SERVER }}
SENTRY_ORG: ${{ secrets.SENTRY_ORG }}
SENTRY_PROJECT: ${{ secrets.SENTRY_PROJECT }}
SENTRY_AUTH_TOKEN: ${{ secrets.SENTRY_AUTH_TOKEN }}
jobs:
test-and-lint:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: actions/setup-node@v4
with:
node-version: '20'
cache: 'npm'
- run: npm ci
- run: npm run lint
- run: npm test -- --coverage
- name: Coverage gate (80%+)
run: |
COVERAGE=$(npx nyc report --reporter=text-summary | grep 'Statements' | awk '{print $3}' | tr -d '%')
if (( $(echo "$COVERAGE < 80" | bc -l) )); then
echo "Coverage $COVERAGE% is below 80% threshold"
exit 1
fi
security-scan:
runs-on: ubuntu-latest
needs: test-and-lint
steps:
- uses: actions/checkout@v4
- name: SAST — Semgrep
uses: returntocorp/semgrep-action@v1
with:
config: 'p/owasp-top-ten'
- name: Container Scan — Trivy
uses: aquasecurity/trivy-action@master
with:
scan-type: 'fs'
severity: 'CRITICAL,HIGH'
exit-code: '1'
build-and-push:
runs-on: ubuntu-latest
needs: [test-and-lint, security-scan]
permissions:
id-token: write
contents: read
steps:
- uses: actions/checkout@v4
- uses: aws-actions/configure-aws-credentials@v4
with:
role-to-assume: ${{ secrets.AWS_ROLE_ARN }}
aws-region: ${{ env.AWS_REGION }}
- uses: aws-actions/amazon-ecr-login@v2
- uses: docker/build-push-action@v5
with:
context: .
push: true
tags: |
${{ env.ECR_REGISTRY }}/${{ env.IMAGE_NAME }}:${{ github.sha }}
${{ env.ECR_REGISTRY }}/${{ env.IMAGE_NAME }}:latest
- name: Sentry Release — Create release & upload sourcemaps
uses: getsentry/action-release@v1
env:
SENTRY_AUTH_TOKEN: ${{ env.SENTRY_AUTH_TOKEN }}
SENTRY_ORG: ${{ env.SENTRY_ORG }}
SENTRY_PROJECT: ${{ env.SENTRY_PROJECT }}
with:
environment: ${{ github.ref == 'refs/heads/main' && 'production' || 'staging' }}
version: ${{ github.sha }}
sourcemaps: './apps/web/.next'
set_commits: auto
deploy-dev:
if: github.ref == 'refs/heads/develop'
runs-on: ubuntu-latest
needs: build-and-push
environment: development
steps:
- uses: actions/checkout@v4
- name: Deploy to DEV (Docker Compose on EC2)
run: |
echo "Deploying to DEV via Docker Compose"
# ssh deploy@dev-server "cd /app && docker compose pull && docker compose up -d"
deploy-staging:
if: startsWith(github.ref, 'refs/heads/release/')
runs-on: ubuntu-latest
needs: build-and-push
environment: staging
steps:
- uses: actions/checkout@v4
- name: Update Helm values for staging
run: |
sed -i "s|image.tag:.*|image.tag: ${{ github.sha }}|" infra/k8s/overlays/staging/values.yaml
- name: Commit and push (ArgoCD auto-sync)
run: |
git config user.name "hmcmkit-deploy"
git config user.email "deploy@hmcmkit.dev"
git add infra/
git commit -m "chore(deploy): update staging image to ${{ github.sha }}"
git push
deploy-prod:
if: github.ref == 'refs/heads/main'
runs-on: ubuntu-latest
needs: build-and-push
environment:
name: production
url: https://app.example.com
steps:
- uses: actions/checkout@v4
- name: Update Helm values for production (Canary)
run: |
sed -i "s|image.tag:.*|image.tag: ${{ github.sha }}|" infra/k8s/overlays/prod/values.yaml
- name: Commit and push (ArgoCD + Argo Rollouts canary)
run: |
git config user.name "hmcmkit-deploy"
git config user.email "deploy@hmcmkit.dev"
git add infra/
git commit -m "chore(deploy): canary prod image to ${{ github.sha }}"
git push
post-deploy-monitoring:
if: github.ref == 'refs/heads/main'
runs-on: ubuntu-latest
needs: deploy-prod
steps:
- name: Wait for canary stabilization
run: sleep 300 # 5min — canary 10% traffic period
- name: Verify Sentry — no new critical issues
run: |
ISSUES=$(curl -s -H "Authorization: Bearer ${{ env.SENTRY_AUTH_TOKEN }}" \
"https://sentry.io/api/0/projects/${{ env.SENTRY_ORG }}/${{ env.SENTRY_PROJECT }}/issues/?query=is:unresolved+release:${{ github.sha }}&statsPeriod=5m" \
| jq 'length')
echo "New unresolved issues: $ISSUES"
if [ "$ISSUES" -gt "5" ]; then
echo "::error::Too many new issues ($ISSUES) — triggering rollback"
exit 1
fi
- name: Verify Prometheus — error rate check
run: |
ERROR_RATE=$(curl -s "http://${{ secrets.PROMETHEUS_URL }}/api/v1/query?query=rate(http_requests_total{status=~\"5..\"}[5m])/rate(http_requests_total[5m])" \
| jq '.data.result[0].value[1]' -r 2>/dev/null || echo "0")
echo "Current error rate: $ERROR_RATE"
if (( $(echo "$ERROR_RATE > 0.01" | bc -l) )); then
echo "::error::Error rate $ERROR_RATE exceeds 1% threshold"
exit 1
fi
- name: On failure — trigger auto-rollback
if: failure()
run: |
echo "::warning::Post-deploy checks failed — triggering Argo Rollouts abort"
curl -X PUT "${{ env.ARGOCD_SERVER }}/api/v1/applications/${{ env.IMAGE_NAME }}/rollback" \
-H "Authorization: Bearer ${{ secrets.ARGOCD_TOKEN }}"
@@ -0,0 +1,116 @@
# kube-prometheus-stack Helm Values — Auto-generated by hmcmkit
# helm install monitoring prometheus-community/kube-prometheus-stack -f values.yaml
prometheus:
prometheusSpec:
retention: 15d
resources:
requests: { cpu: "500m", memory: "1Gi" }
limits: { cpu: "1", memory: "2Gi" }
serviceMonitorSelector: {}
podMonitorSelector: {}
grafana:
enabled: true
adminPassword: "${GRAFANA_ADMIN_PASSWORD}"
dashboardProviders:
dashboardproviders.yaml:
apiVersion: 1
providers:
- name: default
folder: ''
type: file
options:
path: /var/lib/grafana/dashboards/default
datasources:
datasources.yaml:
apiVersion: 1
datasources:
- name: Prometheus
type: prometheus
url: http://monitoring-kube-prometheus-prometheus:9090
isDefault: true
- name: Loki
type: loki
url: http://loki:3100
- name: Tempo
type: tempo
url: http://tempo:3100
- name: Sentry
type: sentry
url: "${SENTRY_API_URL}"
jsonData:
orgSlug: "${SENTRY_ORG_SLUG}"
secureJsonData:
authToken: "${SENTRY_AUTH_TOKEN}"
# Pre-built dashboards
dashboards:
default:
service-health:
json: |
# Service Health Dashboard — Error Rate + Latency + Sentry Issues
# Auto-generated by hmcmkit enterprise
error-tracking:
json: |
# Error Tracking Dashboard — Sentry integration
# Panels: Unresolved issues, Error rate trend, Top errors, Affected users
alertmanager:
config:
route:
receiver: 'slack-notifications'
group_by: ['alertname', 'namespace']
group_wait: 30s
group_interval: 5m
repeat_interval: 4h
routes:
- match:
severity: critical
receiver: 'pagerduty-critical'
- match:
severity: warning
receiver: 'slack-notifications'
receivers:
- name: 'slack-notifications'
slack_configs:
- api_url: "${SLACK_WEBHOOK_URL}"
channel: '#error-alerts'
title: '[{{ .Status }}] {{ .CommonLabels.alertname }}'
text: '{{ .CommonAnnotations.description }}'
- name: 'pagerduty-critical'
pagerduty_configs:
- service_key: "${PAGERDUTY_SERVICE_KEY}"
severity: critical
- name: 'self-healing-webhook'
webhook_configs:
- url: "${SELF_HEALING_WEBHOOK_URL}"
send_resolved: true
# Custom PrometheusRules for Self-Healing triggers
additionalPrometheusRules:
- name: self-healing-rules
groups:
- name: error-detection
rules:
- alert: HighErrorRate
expr: rate(http_requests_total{status=~"5.."}[5m]) / rate(http_requests_total[5m]) > 0.01
for: 2m
labels:
severity: warning
annotations:
description: "Error rate > 1% for {{ $labels.service }} — Self-Healing candidate"
- alert: CriticalErrorRate
expr: rate(http_requests_total{status=~"5.."}[5m]) / rate(http_requests_total[5m]) > 0.05
for: 2m
labels:
severity: critical
annotations:
description: "Error rate > 5% for {{ $labels.service }} — Auto-Rollback triggered"
- alert: HighLatency
expr: histogram_quantile(0.95, rate(http_request_duration_seconds_bucket[5m])) > 0.5
for: 5m
labels:
severity: warning
annotations:
description: "P95 latency > 500ms for {{ $labels.service }}"
@@ -0,0 +1,27 @@
# Loki + Promtail Helm Values — Auto-generated by hmcmkit
# helm install loki grafana/loki-stack -f loki-stack.values.yaml
loki:
enabled: true
persistence:
enabled: true
size: 10Gi
config:
table_manager:
retention_deletes_enabled: true
retention_period: 168h # 7 days
promtail:
enabled: true
config:
clients:
- url: http://loki:3100/loki/api/v1/push
scrape_configs:
- job_name: kubernetes-pods
kubernetes_sd_configs:
- role: pod
relabel_configs:
- source_labels: [__meta_kubernetes_pod_label_app]
target_label: app
- source_labels: [__meta_kubernetes_namespace]
target_label: namespace
@@ -0,0 +1,86 @@
# OpenTelemetry Collector + Tempo — Auto-generated by hmcmkit
# Distributed tracing: App → OTel Collector → Tempo → Grafana
# OpenTelemetry Collector
# helm install otel open-telemetry/opentelemetry-collector -f otel-tempo.values.yaml
opentelemetry-collector:
mode: deployment
config:
receivers:
otlp:
protocols:
grpc: { endpoint: "0.0.0.0:4317" }
http: { endpoint: "0.0.0.0:4318" }
processors:
batch:
timeout: 5s
send_batch_size: 1024
exporters:
otlp:
endpoint: "tempo:4317"
tls: { insecure: true }
prometheus:
endpoint: "0.0.0.0:8889"
connectors:
spanmetrics:
histogram:
explicit:
buckets: [5ms, 10ms, 25ms, 50ms, 100ms, 250ms, 500ms, 1s, 2.5s]
dimensions:
- name: http.method
- name: http.status_code
- name: service.name
service:
pipelines:
traces:
receivers: [otlp]
processors: [batch]
exporters: [otlp]
traces/sentry:
receivers: [otlp]
processors: [batch]
exporters: [sentry]
metrics:
receivers: [otlp, spanmetrics]
processors: [batch]
exporters: [prometheus]
# Sentry Exporter — Forward error spans to Sentry for correlation
# Traces with error status → Sentry issue linkage
sentry-exporter:
dsn: "${SENTRY_DSN}"
environment: "${ENVIRONMENT}"
insecure: false
# Tempo (Trace Backend)
# helm install tempo grafana/tempo -f otel-tempo.values.yaml
tempo:
persistence:
enabled: true
size: 10Gi
config:
server:
http_listen_port: 3100
distributor:
receivers:
otlp:
protocols:
grpc: {}
storage:
trace:
backend: local
local:
path: /var/tempo/traces
# Blackbox Exporter (Uptime Monitoring)
# helm install blackbox prometheus-community/prometheus-blackbox-exporter
blackbox-exporter:
config:
modules:
http_2xx:
prober: http
timeout: 5s
http:
valid_http_versions: ["HTTP/1.1", "HTTP/2.0"]
valid_status_codes: [200, 301, 302]
follow_redirects: true
@@ -0,0 +1,130 @@
# Security Layer Templates — Auto-generated by hmcmkit security-architect
# 8 Security Components for Enterprise deployments
---
# 1. CloudFront Distribution
apiVersion: cloudfront
kind: Distribution
spec:
origins:
- domainName: ${alb_domain}
originProtocolPolicy: https-only
defaultCacheBehavior:
viewerProtocolPolicy: redirect-to-https
allowedMethods: [GET, HEAD, OPTIONS, PUT, POST, PATCH, DELETE]
webACLId: ${waf_acl_arn}
comment: "hmcmkit-managed CDN + DDoS protection"
---
# 2. AWS WAF — OWASP Top 10
# Apply via Terraform: aws_wafv2_web_acl
waf_rules:
- name: AWSManagedRulesCommonRuleSet
priority: 1
vendor: AWS
- name: AWSManagedRulesSQLiRuleSet
priority: 2
vendor: AWS
- name: AWSManagedRulesKnownBadInputsRuleSet
priority: 3
vendor: AWS
- name: rate-limit
priority: 10
limit: 2000 # requests per 5 minutes per IP
---
# 3. VPC Design
vpc:
cidr: "10.0.0.0/16"
subnets:
public:
- "10.0.1.0/24" # ALB, NAT Gateway
- "10.0.2.0/24"
private:
- "10.0.10.0/24" # EKS nodes, application
- "10.0.11.0/24"
database:
- "10.0.20.0/24" # RDS (no internet access)
- "10.0.21.0/24"
nat_gateway: single # staging: single, prod: per-az
---
# 4. IAM — IRSA (IAM Roles for Service Accounts)
apiVersion: v1
kind: ServiceAccount
metadata:
name: ${project_name}-api
namespace: ${environment}
annotations:
eks.amazonaws.com/role-arn: arn:aws:iam::${aws_account_id}:role/${project_name}-${environment}-api
---
# 5. Network Policy (Calico/Cilium)
apiVersion: networking.k8s.io/v1
kind: NetworkPolicy
metadata:
name: ${project_name}-api-policy
namespace: ${environment}
spec:
podSelector:
matchLabels:
app: ${project_name}-api
policyTypes: [Ingress, Egress]
ingress:
- from:
- namespaceSelector:
matchLabels:
name: ingress-nginx
ports:
- port: 3000
egress:
- to:
- namespaceSelector:
matchLabels:
name: ${environment}
ports:
- port: 5432 # PostgreSQL
- port: 6379 # Redis
---
# 6. ACM + cert-manager
apiVersion: cert-manager.io/v1
kind: ClusterIssuer
metadata:
name: letsencrypt-prod
spec:
acme:
server: https://acme-v02.api.letsencrypt.org/directory
privateKeySecretRef:
name: letsencrypt-prod-key
solvers:
- http01:
ingress:
class: nginx
---
# 7. Secrets Rotation Policy
secrets_rotation:
provider: aws-secrets-manager
rotation_interval: 30d
secrets:
- name: db-credentials
type: rds
auto_rotate: true
- name: api-keys
type: custom
auto_rotate: false # manual rotation
---
# 8. Backup & DR
backup:
rds:
retention_period: 7 # days (staging)
# retention_period: 35 # days (production)
copy_to_region: ap-northeast-1 # Cross-region backup
snapshot_schedule: "cron(0 3 * * ? *)" # Daily 3AM UTC
s3:
versioning: true
lifecycle_rule:
transition_to_ia: 30 # days
transition_to_glacier: 90
@@ -0,0 +1,73 @@
# Staging EKS On-Demand — Auto-generated by hmcmkit
# Creates EKS cluster for PR/release testing, destroys after verification
# Cost optimization: ~$10-30/month vs $150+/month always-on
name: Staging EKS On-Demand
on:
pull_request:
branches: [main]
types: [opened, synchronize]
workflow_dispatch:
inputs:
action:
description: 'create or destroy'
required: true
default: 'create'
type: choice
options: [create, destroy]
env:
CLUSTER_NAME: staging-${{ github.event.pull_request.number || 'manual' }}
AWS_REGION: ap-northeast-2
jobs:
create-staging:
if: github.event_name == 'pull_request' || github.event.inputs.action == 'create'
runs-on: ubuntu-latest
environment: staging
steps:
- uses: actions/checkout@v4
- uses: aws-actions/configure-aws-credentials@v4
with:
role-to-assume: ${{ secrets.AWS_ROLE_ARN }}
aws-region: ${{ env.AWS_REGION }}
- name: Create EKS cluster (eksctl)
run: |
eksctl create cluster \
--name ${{ env.CLUSTER_NAME }} \
--region ${{ env.AWS_REGION }} \
--version 1.29 \
--nodegroup-name staging-nodes \
--node-type t3.medium \
--nodes 2 \
--nodes-min 1 \
--nodes-max 3 \
--managed \
--spot \
--tags "Environment=staging,ManagedBy=hmcmkit,PR=${{ github.event.pull_request.number }}"
- name: Deploy application
run: |
kubectl apply -f infra/k8s/overlays/staging/
echo "Staging deployed: ${{ env.CLUSTER_NAME }}"
- name: Run verification
run: |
echo "Waiting for pods to be ready..."
kubectl wait --for=condition=ready pod -l app --timeout=300s
echo "Staging verification complete"
destroy-staging:
if: github.event.action == 'closed' || github.event.inputs.action == 'destroy'
runs-on: ubuntu-latest
steps:
- uses: aws-actions/configure-aws-credentials@v4
with:
role-to-assume: ${{ secrets.AWS_ROLE_ARN }}
aws-region: ${{ env.AWS_REGION }}
- name: Destroy EKS cluster
run: |
eksctl delete cluster --name ${{ env.CLUSTER_NAME }} --region ${{ env.AWS_REGION }} --wait
echo "Staging cluster destroyed: ${{ env.CLUSTER_NAME }}"
@@ -0,0 +1,83 @@
# Terraform Main — Auto-generated by hmcmkit infra-architect
# Level: Enterprise | Provider: AWS
#
# Usage:
# cd infra/terraform/environments/{env}
# terraform init
# terraform plan
# terraform apply
terraform {
required_version = ">= 1.5"
required_providers {
aws = { source = "hashicorp/aws", version = "~> 5.0" }
}
backend "s3" {
bucket = "${project_name}-terraform-state"
key = "${environment}/terraform.tfstate"
region = "${aws_region}"
dynamodb_table = "${project_name}-terraform-locks"
encrypt = true
}
}
provider "aws" {
region = var.aws_region
default_tags {
tags = {
Project = var.project_name
Environment = var.environment
ManagedBy = "terraform"
GeneratedBy = "hmcmkit"
}
}
}
# ── Modules ──
module "vpc" {
source = "../../modules/vpc"
project_name = var.project_name
environment = var.environment
vpc_cidr = var.vpc_cidr
}
module "eks" {
source = "../../modules/eks"
project_name = var.project_name
environment = var.environment
vpc_id = module.vpc.vpc_id
private_subnets = module.vpc.private_subnet_ids
cluster_version = var.eks_cluster_version
node_instance_types = var.node_instance_types
depends_on = [module.vpc]
}
module "rds" {
source = "../../modules/rds"
project_name = var.project_name
environment = var.environment
vpc_id = module.vpc.vpc_id
db_subnets = module.vpc.database_subnet_ids
engine = "postgres"
engine_version = "15.4"
instance_class = var.db_instance_class
multi_az = var.environment == "prod" ? true : false
depends_on = [module.vpc]
}
# ── Variables ──
variable "project_name" { type = string }
variable "environment" { type = string }
variable "aws_region" { type = string; default = "ap-northeast-2" }
variable "vpc_cidr" { type = string; default = "10.0.0.0/16" }
variable "eks_cluster_version" { type = string; default = "1.29" }
variable "node_instance_types" { type = list(string); default = ["t3.medium"] }
variable "db_instance_class" { type = string; default = "db.t3.medium" }
# ── Outputs ──
output "vpc_id" { value = module.vpc.vpc_id }
output "eks_cluster_endpoint" { value = module.eks.cluster_endpoint }
output "rds_endpoint" { value = module.rds.endpoint }
@@ -0,0 +1,257 @@
# PDCA Iteration Report: {{FEATURE_NAME}}
## Overview
| Item | Value |
|------|-------|
| Feature | {{FEATURE_NAME}} |
| Date | {{DATE}} |
| Total Iterations | {{TOTAL_ITERATIONS}} |
| Final Status | {{STATUS}} |
| Duration | {{DURATION}} |
## Iteration Configuration
```yaml
evaluators:
- gap-detector
- code-analyzer
- qa-monitor
thresholds:
gap_analysis: {{GAP_THRESHOLD}}%
code_quality: {{QUALITY_THRESHOLD}}%
functional: {{FUNCTIONAL_THRESHOLD}}%
limits:
max_iterations: {{MAX_ITERATIONS}}
fixes_per_iteration: {{FIX_LIMIT}}
```
## Score Progression
### Summary Chart
```
Score (%)
100 ┤
90 ┼──────────────────────────── Target ──────
80 ┤ ╭────────╮
70 ┤ ╭──╯ ╰──────────────────────────
60 ┤───╯
50 ┤
└───┬────┬────┬────┬────┬────┬────┬────┬───
Init 1 2 3 4 5 6 7
Iteration
```
### Detailed Scores
| Iteration | Gap Analysis | Code Quality | Functional | Overall |
|-----------|--------------|--------------|------------|---------|
| Initial | {{INIT_GAP}}% | {{INIT_QUALITY}}% | {{INIT_FUNC}}% | {{INIT_OVERALL}}% |
{{#ITERATIONS}}
| {{ITER_NUM}} | {{GAP}}% | {{QUALITY}}% | {{FUNC}}% | {{OVERALL}}% |
{{/ITERATIONS}}
| **Final** | **{{FINAL_GAP}}%** | **{{FINAL_QUALITY}}%** | **{{FINAL_FUNC}}%** | **{{FINAL_OVERALL}}%** |
## Issues Fixed
### By Severity
| Severity | Initial | Fixed | Remaining |
|----------|---------|-------|-----------|
| 🔴 Critical | {{CRITICAL_INIT}} | {{CRITICAL_FIXED}} | {{CRITICAL_REMAIN}} |
| 🟡 Warning | {{WARNING_INIT}} | {{WARNING_FIXED}} | {{WARNING_REMAIN}} |
| 🟢 Info | {{INFO_INIT}} | {{INFO_FIXED}} | {{INFO_REMAIN}} |
### By Category
| Category | Initial | Fixed | Remaining |
|----------|---------|-------|-----------|
| Design-Impl Gap | {{GAP_INIT}} | {{GAP_FIXED}} | {{GAP_REMAIN}} |
| Security | {{SEC_INIT}} | {{SEC_FIXED}} | {{SEC_REMAIN}} |
| Code Quality | {{QUAL_INIT}} | {{QUAL_FIXED}} | {{QUAL_REMAIN}} |
| Functional | {{FUNC_INIT}} | {{FUNC_FIXED}} | {{FUNC_REMAIN}} |
## Iteration Details
{{#ITERATIONS}}
### Iteration {{ITER_NUM}}
**Scores:** Gap {{GAP}}% | Quality {{QUALITY}}% | Functional {{FUNC}}%
**Issues Addressed:**
{{#ISSUES}}
- [{{SEVERITY}}] {{DESCRIPTION}}
- Location: `{{LOCATION}}`
- Fix: {{FIX_DESCRIPTION}}
{{/ISSUES}}
**Files Modified:**
{{#FILES}}
- {{ACTION}}: `{{PATH}}`
{{/FILES}}
---
{{/ITERATIONS}}
## Changes Summary
### Created Files
{{#CREATED_FILES}}
- `{{PATH}}`
- Purpose: {{PURPOSE}}
{{/CREATED_FILES}}
### Modified Files
{{#MODIFIED_FILES}}
- `{{PATH}}`
- Changes: {{CHANGES}}
{{/MODIFIED_FILES}}
### Deleted Files
{{#DELETED_FILES}}
- `{{PATH}}`
- Reason: {{REASON}}
{{/DELETED_FILES}}
## Remaining Issues
{{#HAS_REMAINING_ISSUES}}
The following issues could not be auto-fixed and require manual attention:
{{#REMAINING_ISSUES}}
### {{ISSUE_NUM}}. {{TITLE}}
- **Severity:** {{SEVERITY}}
- **Category:** {{CATEGORY}}
- **Location:** `{{LOCATION}}`
- **Description:** {{DESCRIPTION}}
- **Reason Not Fixed:** {{REASON}}
- **Suggested Action:** {{SUGGESTION}}
{{/REMAINING_ISSUES}}
{{/HAS_REMAINING_ISSUES}}
{{^HAS_REMAINING_ISSUES}}
✅ All identified issues have been addressed.
{{/HAS_REMAINING_ISSUES}}
## Recommendations
### Immediate Actions
{{#IMMEDIATE_ACTIONS}}
1. {{ACTION}}
{{/IMMEDIATE_ACTIONS}}
### Follow-up Tasks
{{#FOLLOWUP_TASKS}}
- [ ] {{TASK}}
{{/FOLLOWUP_TASKS}}
## Quality Metrics
### Before/After Comparison
| Metric | Before | After | Change |
|--------|--------|-------|--------|
| Design-Impl Match | {{BEFORE_GAP}}% | {{AFTER_GAP}}% | {{CHANGE_GAP}} |
| Security Score | {{BEFORE_SEC}} | {{AFTER_SEC}} | {{CHANGE_SEC}} |
| Complexity Avg | {{BEFORE_COMPLEX}} | {{AFTER_COMPLEX}} | {{CHANGE_COMPLEX}} |
| Code Duplication | {{BEFORE_DUP}} | {{AFTER_DUP}} | {{CHANGE_DUP}} |
## Next Steps
```
{{#SUCCESS}}
✅ Iteration successful. Proceed with:
1. Review changes: /pdca-analyze {{FEATURE_NAME}}
2. Manual testing of critical paths
3. Create completion report: /pdca-report {{FEATURE_NAME}}
{{/SUCCESS}}
{{#PARTIAL}}
⚠️ Partial success. Manual intervention needed:
1. Review remaining issues above
2. Make manual fixes or design decisions
3. Re-run iteration: /pdca-iterate {{FEATURE_NAME}}
{{/PARTIAL}}
{{#FAILURE}}
❌ Iteration failed. Required actions:
1. Review failure reasons in report
2. Update design document if needed
3. Address blocking issues manually
4. Re-attempt: /pdca-iterate {{FEATURE_NAME}}
{{/FAILURE}}
```
---
## Appendix
### A. Evaluator Criteria Used
#### Gap Analysis
```yaml
api_endpoints:
match_rate: {{GAP_THRESHOLD}}%
weight: 30%
data_models:
match_rate: {{MODEL_THRESHOLD}}%
weight: 30%
components:
match_rate: {{COMP_THRESHOLD}}%
weight: 20%
error_handling:
coverage: {{ERROR_THRESHOLD}}%
weight: 20%
```
#### Code Quality
```yaml
security:
critical_issues: 0
weight: 40%
complexity:
max_per_function: 15
weight: 20%
duplication:
max_lines: 10
weight: 20%
maintainability:
min_score: 70
weight: 20%
```
### B. Tool Usage Statistics
| Tool | Invocations | Success Rate |
|------|-------------|--------------|
| Read | {{READ_COUNT}} | {{READ_SUCCESS}}% |
| Write | {{WRITE_COUNT}} | {{WRITE_SUCCESS}}% |
| Edit | {{EDIT_COUNT}} | {{EDIT_SUCCESS}}% |
| Grep | {{GREP_COUNT}} | {{GREP_SUCCESS}}% |
| Bash | {{BASH_COUNT}} | {{BASH_SUCCESS}}% |
### C. Performance Metrics
| Metric | Value |
|--------|-------|
| Total Duration | {{TOTAL_DURATION}} |
| Avg Iteration Time | {{AVG_ITER_TIME}} |
| Evaluation Time | {{EVAL_TIME}} |
| Fix Application Time | {{FIX_TIME}} |
---
*Generated by hmcmkit Evaluator-Optimizer Pattern*
*POPUP STUDIO PTE. LTD. - https://popupstudio.ai*
@@ -0,0 +1,65 @@
# Schema Definition
> Phase 1 Deliverable: Project data structure definition
**Project**: {{project_name}}
**Date**: {{date}}
**Version**: 1.0
---
## 1. Terminology Definition
| Term | Definition | Original Term | Notes |
|------|------------|---------------|-------|
| | | | |
---
## 2. Entity List
| Entity | Description | Key Attributes |
|--------|-------------|----------------|
| | | |
---
## 3. Entity Details
### 3.1 {{Entity1}}
**Description**:
**Attributes**:
| Attribute | Type | Required | Description |
|-----------|------|----------|-------------|
| id | string | Y | Unique identifier |
| | | | |
**Relationships**:
- 1:N → {{RelatedEntity}}
---
## 4. Entity Relationship Diagram
```
[Entity1] 1 ─── N [Entity2]
│
└── 1 ─── N [Entity3]
```
---
## 5. Validation Checklist
- [ ] All core entities defined
- [ ] Terms are clear and consistent
- [ ] Entity relationships are clear
- [ ] No missing attributes
---
## 6. Next Steps
Proceed to Phase 2: Coding Convention Definition
@@ -0,0 +1,207 @@
# Coding Conventions
> Phase 2 Deliverable: Code writing rules definition
**Project**: {{project_name}}
**Date**: {{date}}
**Version**: 1.0
---
## 1. Naming Conventions
### 1.1 Files/Folders
| Target | Rule | Example |
|--------|------|---------|
| Component files | PascalCase | `UserProfile.tsx` |
| Utility files | camelCase | `formatDate.ts` |
| Folders | kebab-case | `user-profile/` |
| Constant files | UPPER_SNAKE_CASE | `API_ENDPOINTS.ts` |
### 1.2 Code
| Target | Rule | Example |
|--------|------|---------|
| Components | PascalCase | `UserProfile` |
| Functions | camelCase | `getUserById` |
| Variables | camelCase | `userName` |
| Constants | UPPER_SNAKE_CASE | `MAX_RETRY_COUNT` |
| Types/Interfaces | PascalCase | `UserProfile` |
| Enum | PascalCase | `UserRole` |
---
## 2. Folder Structure
```
src/
├── components/ # Reusable components
│ ├── ui/ # Basic UI components
│ └── common/ # Common components
├── features/ # Feature-based modules
│ └── {{feature}}/
│ ├── components/
│ ├── hooks/
│ └── types.ts
├── hooks/ # Common custom hooks
├── utils/ # Utility functions
├── types/ # Global type definitions
├── constants/ # Constants
└── styles/ # Global styles
```
---
## 3. Code Style
### 3.1 General
- Indentation: 2 spaces
- Quotes: Single quotes (')
- Semicolons: None
### 3.2 Functions
```typescript
// Preferred: Arrow functions
const handleClick = () => {
// ...
}
// Components: function declaration
function UserProfile({ user }: Props) {
return <div>{user.name}</div>
}
```
### 3.3 Import Order
```typescript
// 1. External libraries
import { useState } from 'react'
// 2. Internal modules (absolute paths)
import { Button } from '@/components/ui'
// 3. Relative paths
import { useUser } from './hooks'
// 4. Types
import type { User } from '@/types'
// 5. Styles
import './styles.css'
```
---
## 4. Component Rules
### 4.1 Structure
```typescript
// 1. Import
// 2. Type definition
// 3. Constants
// 4. Component
// 5. Export
```
### 4.2 Props
```typescript
interface Props {
user: User
onSelect?: (user: User) => void
}
```
---
## 5. Environment Variable Conventions
### 5.1 Naming Rules
| Prefix | Purpose | Exposure |
|--------|---------|----------|
| `NEXT_PUBLIC_` | Client-side accessible | Browser |
| `DB_` | Database | Server only |
| `API_` | External API keys | Server only |
| `AUTH_` | Authentication | Server only |
### 5.2 .env File Structure
```
project-root/
├── .env.example # Template (included in Git)
├── .env.local # Local development (Git ignored)
├── .env.development # Development environment
├── .env.staging # Staging environment
└── .env.production # Production (no sensitive info)
```
### 5.3 Environment Variable List
| Variable | Purpose | Exposed | Secrets |
|----------|---------|:-------:|:-------:|
| `NEXT_PUBLIC_APP_URL` | App URL | ✅ | |
| `DATABASE_URL` | DB connection | | ✅ |
| `AUTH_SECRET` | Auth secret | | ✅ |
| | | | |
---
## 6. Clean Architecture
### 6.1 Layer Structure (Level: {{level}})
**Starter**:
```
src/
├── components/ # UI
├── lib/ # Utilities
└── types/ # Types
```
**Dynamic**:
```
src/
├── components/ # Presentation
├── features/ # Application + Presentation
├── services/ # Application
├── types/ # Domain
└── lib/api/ # Infrastructure
```
**Enterprise**:
```
src/
├── presentation/ # UI, hooks
├── application/ # services, use-cases
├── domain/ # entities, types
└── infrastructure/ # api, db
```
### 6.2 Dependency Rules
| Layer | Can Depend On | Cannot Depend On |
|-------|---------------|------------------|
| Presentation | Application, Domain | Infrastructure directly |
| Application | Domain, Infrastructure | Presentation |
| Domain | None (independent) | All external layers |
| Infrastructure | Domain | Presentation |
---
## 7. Validation Checklist
### Naming/Structure
- [ ] Naming rules are clear
- [ ] Folder structure is defined
- [ ] Code style is consistent
- [ ] Matches ESLint/Prettier config
### Environment Variables
- [ ] .env.example completed
- [ ] Environment variable naming rules followed
- [ ] Secrets list organized (for Phase 9 deployment)
### Architecture
- [ ] Layer structure decided (matching level)
- [ ] Dependency direction rules defined
---
## 8. Next Steps
Proceed to Phase 3: Mockup Development
@@ -0,0 +1,103 @@
# Mockup Specification
> Phase 3 Deliverable: HTML/CSS/JS mockup definition
**Project**: {{project_name}}
**Date**: {{date}}
**Version**: 1.0
---
## 1. Mockup Scope
### 1.1 Screens to Implement
| Screen | File | Description | Priority |
|--------|------|-------------|----------|
| Home | `index.html` | Main page | High |
| | | | |
### 1.2 Mock Data
| Data | File | Description |
|------|------|-------------|
| Users | `data/users.json` | User list |
| | | |
---
## 2. Screen Details
### 2.1 {{PageName}}
**Path**: `mockup/pages/{{page}}.html`
**Layout**:
```
┌─────────────────────────────────┐
│ Header │
├─────────────────────────────────┤
│ │
│ Content │
│ │
├─────────────────────────────────┤
│ Footer │
└─────────────────────────────────┘
```
**Key Features**:
- [ ] Feature 1
- [ ] Feature 2
**Interactions**:
- Button click → Show modal
- Form submit → Display result
---
## 3. Mock Data Structure
### 3.1 {{DataName}}
```json
// data/{{data}}.json
{
"items": [
{
"id": "1",
"name": "Sample",
...
}
]
}
```
---
## 4. Folder Structure
```
mockup/
├── pages/
│ ├── index.html
│ └── ...
├── styles/
│ └── main.css
├── scripts/
│ └── app.js
└── data/
└── *.json
```
---
## 5. Validation Checklist
- [ ] All main screens implemented
- [ ] Interactions are working
- [ ] Feature verification possible with mock data
- [ ] Responsive design considered
---
## 6. Next Steps
Proceed to Phase 4: API Design/Implementation (Starter skips to Phase 5)
@@ -0,0 +1,151 @@
# API Design Specification
> Phase 4 Deliverable: API endpoint definition
**Project**: {{project_name}}
**Date**: {{date}}
**Version**: 1.0
---
## 1. API Overview
**Base URL**: `{{base_url}}`
**Authentication**: Bearer Token / Session
---
## 2. Common Standards
### 2.1 RESTful Principles
- URL: Resource-based (nouns, plural) - `/users`, `/products`
- HTTP Methods: GET(read), POST(create), PUT(full update), PATCH(partial update), DELETE(delete)
- Status Codes: 2xx(success), 4xx(client error), 5xx(server error)
### 2.2 Response Format (Standard)
```json
// Success Response
{
"data": { ... },
"meta": {
"timestamp": "2026-01-08T10:00:00Z"
}
}
// Error Response
{
"error": {
"code": "ERROR_CODE",
"message": "User-friendly message",
"details": [
{ "field": "email", "message": "Please enter a valid email" }
]
}
}
// Pagination Response
{
"data": [...],
"pagination": {
"page": 1,
"limit": 20,
"total": 100,
"totalPages": 5
}
}
```
### 2.3 Error Codes
| Code | HTTP Status | Description |
|------|-------------|-------------|
| VALIDATION_ERROR | 400 | Validation failed |
| UNAUTHORIZED | 401 | Authentication required |
| FORBIDDEN | 403 | Permission denied |
| NOT_FOUND | 404 | Resource not found |
| CONFLICT | 409 | Conflict (duplicate, etc.) |
| INTERNAL_ERROR | 500 | Internal server error |
---
## 3. Endpoints
### 3.1 Authentication API
#### POST /api/auth/login
Login
**Request**:
```json
{
"email": "user@example.com",
"password": "password123"
}
```
**Response** (200 OK):
```json
{
"data": {
"user": {
"id": "1",
"email": "user@example.com",
"name": "User"
},
"token": "jwt_token",
"expiresAt": "2026-01-09T10:00:00Z"
}
}
```
---
### 3.2 {{Resource}} API
#### GET /api/{{resources}}
List all
**Query Parameters**:
| Parameter | Type | Required | Description |
|-----------|------|----------|-------------|
| page | number | N | Page number (default: 1) |
| limit | number | N | Items per page (default: 20) |
**Response** (200 OK):
```json
{
"data": [...],
"pagination": {
"page": 1,
"limit": 20,
"total": 100,
"totalPages": 5
}
}
```
#### GET /api/{{resources}}/:id
Get detail
#### POST /api/{{resources}}
Create
#### PUT /api/{{resources}}/:id
Update
#### DELETE /api/{{resources}}/:id
Delete
---
## 4. Validation Checklist
- [ ] All required endpoints defined
- [ ] Request/Response formats are clear
- [ ] Error handling is defined
- [ ] Authentication/Authorization policies are clear
---
## 5. Next Steps
Proceed to Phase 5: Design System
@@ -0,0 +1,126 @@
# Design System Specification
> Phase 5 Deliverable: Component system definition
**Project**: {{project_name}}
**Date**: {{date}}
**Version**: 1.0
---
## 1. Design Tokens
### 1.1 Colors
```css
:root {
/* Primary */
--primary: #0066FF;
--primary-hover: #0052CC;
/* Neutral */
--background: #FFFFFF;
--foreground: #171717;
--muted: #F5F5F5;
/* Semantic */
--success: #22C55E;
--warning: #F59E0B;
--error: #EF4444;
}
```
### 1.2 Typography
| Name | Size | Weight | Usage |
|------|------|--------|-------|
| h1 | 36px | 700 | Page title |
| h2 | 24px | 600 | Section title |
| body | 16px | 400 | Body text |
| small | 14px | 400 | Helper text |
### 1.3 Spacing
```
4px, 8px, 12px, 16px, 24px, 32px, 48px, 64px
```
---
## 2. Component List
### 2.1 Basic Components
| Component | Status | Description |
|-----------|--------|-------------|
| Button | ✅ | Button |
| Input | ✅ | Input field |
| Card | ✅ | Card container |
| Badge | ✅ | Badge/Tag |
| Avatar | ✅ | Avatar |
### 2.2 Form Components
| Component | Status | Description |
|-----------|--------|-------------|
| Form | ✅ | Form wrapper |
| Label | ✅ | Label |
| Select | ✅ | Select dropdown |
| Checkbox | ✅ | Checkbox |
### 2.3 Feedback Components
| Component | Status | Description |
|-----------|--------|-------------|
| Dialog | ✅ | Dialog/Modal |
| Toast | ✅ | Toast notification |
| Alert | ✅ | Alert banner |
---
## 3. Component Details
### 3.1 Button
**Variants**:
- `default`: Default style
- `outline`: Border only
- `ghost`: No background
- `destructive`: Delete/Danger action
**Sizes**:
- `sm`: Small button
- `default`: Default size
- `lg`: Large button
**Usage Example**:
```tsx
<Button variant="default" size="default">
Button
</Button>
<Button variant="outline" size="sm">
Small Button
</Button>
```
---
## 4. Installed Components
```bash
# shadcn/ui component installation log
npx shadcn@latest add button
npx shadcn@latest add input
npx shadcn@latest add card
# ...
```
---
## 5. Validation Checklist
- [ ] All required basic components exist
- [ ] Design tokens applied consistently
- [ ] Accessibility (a11y) considered
- [ ] Responsive design supported
---
## 6. Next Steps
Proceed to Phase 6: UI Implementation + API Integration
@@ -0,0 +1,235 @@
# UI Implementation Specification
> Phase 6 Deliverable: Screen implementation and API integration
**Project**: {{project_name}}
**Date**: {{date}}
**Version**: 1.0
---
## 1. Page List
| Page | Route | File | Status |
|------|-------|------|--------|
| Home | `/` | `app/page.tsx` | ⬜ |
| Login | `/login` | `app/login/page.tsx` | ⬜ |
| | | | |
---
## 2. Page Details
### 2.1 {{PageName}}
**Route**: `{{path}}`
**File**: `{{file}}`
**Layout**:
```
┌─────────────────────────────────┐
│ Header │
├─────────────────────────────────┤
│ │
│ Content │
│ │
└─────────────────────────────────┘
```
**Components Used**:
- `Header`
- `Card`
- `Button`
**API Integration**:
| API | Purpose | Hook |
|-----|---------|------|
| GET /api/users | User list | `useUsers()` |
**State Management**:
- `isLoading`: Loading state
- `error`: Error state
- `data`: Data
---
## 3. Custom Hooks
### 3.1 useAuth
```typescript
function useAuth() {
// Authentication state management
return { user, login, logout, isLoading }
}
```
### 3.2 use{{Resource}}
```typescript
function use{{Resource}}() {
// {{Resource}} CRUD
return { data, isLoading, error, create, update, remove }
}
```
---
## 4. State Management Architecture
```
Server State: React Query / SWR
├── useQuery: Read operations
├── useMutation: Create/Update/Delete
└── Cache invalidation
Client State: useState / Zustand
├── UI state (modals, toggles, etc.)
└── Form state
Global State: Context / Zustand
├── Authentication info
└── Theme settings
```
---
## 5. API Client Architecture
### 5.1 3-Layer Structure
```
UI Components
↓
Service Layer (business logic)
↓
API Client Layer (HTTP communication)
```
### 5.2 API Client Configuration
```typescript
// lib/api/client.ts
class ApiClient {
private baseUrl: string
async request<T>(endpoint: string, config = {}): Promise<ApiResponse<T>> {
const headers = new Headers(config.headers)
headers.set('Content-Type', 'application/json')
// Auto-inject token
const token = this.getToken()
if (token) headers.set('Authorization', `Bearer ${token}`)
// Execute request and handle errors
// ...
}
}
export const apiClient = new ApiClient()
```
### 5.3 Service Layer Pattern
```typescript
// services/{{resource}}Service.ts
export const {{resource}}Service = {
getList(filter?: Filter) {
return apiClient.get<PaginatedResponse<Item>>('/{{resources}}', params)
},
getById(id: string) {
return apiClient.get<Item>(`/{{resources}}/${id}`)
},
create(data: CreateInput) {
return apiClient.post<Item>('/{{resources}}', data)
},
update(id: string, data: UpdateInput) {
return apiClient.put<Item>(`/{{resources}}/${id}`, data)
},
delete(id: string) {
return apiClient.delete<void>(`/{{resources}}/${id}`)
},
}
```
---
## 6. Error Handling
### 6.1 Error Type Definition
```typescript
// types/api.ts
interface ApiError {
code: string
message: string
details?: Array<{ field: string; message: string }>
}
// Error code constants
const ERROR_CODES = {
VALIDATION_ERROR: 'Please check your input',
UNAUTHORIZED: 'Login required',
FORBIDDEN: 'Permission denied',
NOT_FOUND: 'Resource not found',
INTERNAL_ERROR: 'Server error occurred',
} as const
```
### 6.2 Error Boundary
```typescript
<ErrorBoundary fallback={<ErrorPage />}>
<App />
</ErrorBoundary>
```
### 6.3 API Error Handling
```typescript
// In custom hook
if (error) {
const message = ERROR_CODES[error.code] || error.message
return <Alert variant="destructive">{message}</Alert>
}
```
---
## 7. Client-Side Security
### 7.1 Security Checklist
- [ ] XSS prevention (escape user input)
- [ ] CSRF token included (in API requests)
- [ ] No sensitive info stored on client
- [ ] httpOnly cookies used (auth tokens)
### 7.2 Token Management
```typescript
// Recommended: httpOnly cookies (server-side setting)
// Fallback: localStorage (aware of XSS risk)
localStorage.setItem('auth_token', token)
// Prohibited: Storing passwords, card numbers, etc.
```
---
## 8. Validation Checklist
### 8.1 UI Implementation
- [ ] All pages implemented
- [ ] Responsive design applied
- [ ] Design system (Phase 5) followed
### 8.2 API Integration
- [ ] API client 3-layer structure applied
- [ ] Service layer separated
- [ ] API response format (Phase 4) followed
### 8.3 State Management
- [ ] Loading state handled
- [ ] Error state handled
- [ ] User-friendly error messages per error code
### 8.4 Security (Phase 7 prep)
- [ ] XSS prevention applied
- [ ] No sensitive data exposed
---
## 9. Next Steps
Proceed to Phase 7: SEO/Security
@@ -0,0 +1,151 @@
# SEO/Security Specification
> Phase 7 Deliverable: Search optimization and security configuration
**Project**: {{project_name}}
**Date**: {{date}}
**Version**: 1.0
---
## 1. SEO Configuration
### 1.1 Metadata
**Global Settings** (`app/layout.tsx`):
```typescript
export const metadata: Metadata = {
title: {
default: '{{siteName}}',
template: '%s | {{siteName}}',
},
description: '{{siteDescription}}',
keywords: ['keyword1', 'keyword2'],
openGraph: {
type: 'website',
locale: 'en_US',
url: '{{siteUrl}}',
siteName: '{{siteName}}',
images: [{ url: '/og-image.png' }],
},
twitter: {
card: 'summary_large_image',
},
}
```
### 1.2 Page-specific Metadata
| Page | Title | Description |
|------|-------|-------------|
| Home | {{siteName}} | {{siteDescription}} |
| | | |
### 1.3 Structured Data
```json
{
"@context": "https://schema.org",
"@type": "WebSite",
"name": "{{siteName}}",
"url": "{{siteUrl}}"
}
```
---
## 2. Sitemap & Robots
### 2.1 sitemap.xml
```typescript
// app/sitemap.ts
export default function sitemap() {
return [
{ url: '{{siteUrl}}', lastModified: new Date() },
// Add dynamic pages
]
}
```
### 2.2 robots.txt
```typescript
// app/robots.ts
export default function robots() {
return {
rules: { userAgent: '*', allow: '/' },
sitemap: '{{siteUrl}}/sitemap.xml',
}
}
```
---
## 3. Security Settings
### 3.1 Authentication/Authorization
| Item | Setting | Status |
|------|---------|--------|
| Session management | JWT / Session | ⬜ |
| CSRF protection | Token | ⬜ |
| Permission check | Middleware | ⬜ |
### 3.2 Security Headers
```typescript
// next.config.js
headers: [
{
key: 'X-Frame-Options',
value: 'DENY',
},
{
key: 'X-Content-Type-Options',
value: 'nosniff',
},
{
key: 'Referrer-Policy',
value: 'origin-when-cross-origin',
},
]
```
### 3.3 Input Validation
- [ ] Server-side validation
- [ ] XSS prevention (escape handling)
- [ ] SQL injection prevention (parameterized queries)
---
## 4. Performance Optimization
### 4.1 Images
- [ ] Use next/image
- [ ] WebP format
- [ ] Appropriate sizes setting
### 4.2 Fonts
- [ ] Use next/font
- [ ] Apply subset
### 4.3 Code Splitting
- [ ] Dynamic imports
- [ ] Lazy loading
---
## 5. Validation Checklist
### SEO
- [ ] All pages have metadata
- [ ] Open Graph is configured
- [ ] sitemap.xml is generated
- [ ] robots.txt is correct
### Security
- [ ] Authentication works properly
- [ ] Security headers are set
- [ ] Input validation is implemented
- [ ] HTTPS is enforced
---
## 6. Next Steps
Proceed to Phase 8: Architecture/Convention Review
@@ -0,0 +1,191 @@
# Code Review Report
> Phase 8 Deliverable: Architecture/Convention review results
**Project**: {{project_name}}
**Review Date**: {{date}}
**Reviewer**: {{reviewer}}
---
## 1. Review Scope
- [x] Architecture consistency
- [x] Convention compliance (Phase 2)
- [x] API consistency (Phase 4)
- [x] UI-API integration (Phase 6)
- [x] Security vulnerabilities (Phase 7)
- [x] Environment variable settings (Phase 2/9)
---
## 2. Phase Verification Matrix
### 2.1 Design Phase Verification
| Phase | Verification Item | Status | Notes |
|-------|------------------|--------|-------|
| 1 | Terminology consistency | ✅/⚠️/❌ | |
| 2 | Convention definition | ✅/⚠️/❌ | |
| 3 | Mockup approval | ✅/⚠️/❌ | |
| 4 | API specification | ✅/⚠️/❌ | |
| 5 | Design system | ✅/⚠️/❌ | |
### 2.2 Implementation Phase Verification
| Phase | Verification Item | Status | Notes |
|-------|------------------|--------|-------|
| 6 | UI-API integration | ✅/⚠️/❌ | |
| 7 | SEO/Security | ✅/⚠️/❌ | |
### 2.3 Environment Variable Verification
| Item | Phase 2 Definition | Phase 9 Setting | Status |
|------|-------------------|-----------------|--------|
| NEXT_PUBLIC_* | ✅/❌ | ✅/❌ | |
| DATABASE_URL | ✅/❌ | ✅/❌ | |
| AUTH_SECRET | ✅/❌ | ✅/❌ | |
---
## 3. Architecture Review
### 3.1 Folder Structure (Based on Phase 2)
| Item | Status | Notes |
|------|--------|-------|
| Matches convention | ✅/⚠️/❌ | |
| Separation of concerns | ✅/⚠️/❌ | |
| Dependency direction | ✅/⚠️/❌ | |
### 3.2 Clean Architecture Verification
| Layer | Dependency Rule | Status |
|-------|-----------------|--------|
| Presentation | → Application, Domain only | ✅/❌ |
| Application | → Domain, Infrastructure only | ✅/❌ |
| Domain | Independent (no dependencies) | ✅/❌ |
| Infrastructure | → Domain only | ✅/❌ |
### 3.3 Discovered Issues
| ID | Severity | Location | Description | Recommended Action |
|----|----------|----------|-------------|-------------------|
| A-1 | High/Medium/Low | | | |
---
## 4. Convention Review (Phase 2)
### 4.1 Naming
| Item | Status | Notes |
|------|--------|-------|
| Files/Folders | ✅/⚠️/❌ | |
| Variables/Functions | ✅/⚠️/❌ | |
| Components | ✅/⚠️/❌ | |
### 4.2 Code Style
| Item | Status | Notes |
|------|--------|-------|
| Import order | ✅/⚠️/❌ | |
| Type definitions | ✅/⚠️/❌ | |
### 4.3 Discovered Issues
| ID | Severity | Location | Description | Recommended Action |
|----|----------|----------|-------------|-------------------|
| C-1 | | | | |
---
## 5. API Consistency Review (Phase 4)
### 5.1 RESTful Principles
| Item | Status | Notes |
|------|--------|-------|
| Resource-based URLs | ✅/⚠️/❌ | |
| Appropriate HTTP methods | ✅/⚠️/❌ | |
| Status code consistency | ✅/⚠️/❌ | |
### 5.2 Response Format
| Item | Status | Notes |
|------|--------|-------|
| Standard format compliance | ✅/⚠️/❌ | `{ data, meta?, error? }` |
| Error code consistency | ✅/⚠️/❌ | |
| Pagination format | ✅/⚠️/❌ | |
---
## 6. Code Quality
### 6.1 Evaluation
| Item | Status | Notes |
|------|--------|-------|
| Duplicate code | ✅/⚠️/❌ | |
| Function complexity | ✅/⚠️/❌ | |
| Error handling | ✅/⚠️/❌ | |
| Type safety | ✅/⚠️/❌ | |
### 6.2 Discovered Issues
| ID | Severity | Location | Description | Recommended Action |
|----|----------|----------|-------------|-------------------|
| Q-1 | | | | |
---
## 7. Security Review (Phase 7)
### 7.1 Client Security
| Item | Status | Notes |
|------|--------|-------|
| XSS protection | ✅/⚠️/❌ | |
| CSRF protection | ✅/⚠️/❌ | |
| Sensitive info exposure | ✅/⚠️/❌ | |
### 7.2 Server Security
| Item | Status | Notes |
|------|--------|-------|
| Input validation | ✅/⚠️/❌ | |
| Authentication/Authorization | ✅/⚠️/❌ | |
| Error messages | ✅/⚠️/❌ | No sensitive info exposed |
---
## 8. Refactoring Plan
### 8.1 High Priority (Required before deployment)
| Issue ID | Task | Estimated Effort |
|----------|------|------------------|
| | | |
### 8.2 Medium Priority (Post-deployment improvement)
| Issue ID | Task | Estimated Effort |
|----------|------|------------------|
| | | |
### 8.3 Low Priority (Future improvement)
| Issue ID | Task | Estimated Effort |
|----------|------|------------------|
| | | |
---
## 9. Summary
### 9.1 Overall Score
| Area | Score | Related Phase |
|------|-------|---------------|
| Architecture | ⭐⭐⭐⭐⭐ / 5 | Phase 2 |
| API consistency | ⭐⭐⭐⭐⭐ / 5 | Phase 4 |
| UI/UX | ⭐⭐⭐⭐⭐ / 5 | Phase 5, 6 |
| Security | ⭐⭐⭐⭐⭐ / 5 | Phase 7 |
| Overall quality | ⭐⭐⭐⭐⭐ / 5 | |
### 9.2 Conclusion
- [ ] Ready for deployment (All Phase verifications passed)
- [ ] Deployable after fixes (Some issues exist)
- [ ] Major refactoring required
---
## 10. Next Steps
Proceed to Phase 9: Deployment after refactoring completion
### 10.1 Phase 9 Preparation Checklist
- [ ] Finalize environment variable list (Based on Phase 2)
- [ ] Confirm secrets list
- [ ] Prepare CI/CD environment-specific settings
@@ -0,0 +1,182 @@
# Deployment Report
> Phase 9 Deliverable: Deployment completion report
**Project**: {{project_name}}
**Deployment Date**: {{date}}
**Deployer**: {{deployer}}
**Environment**: Production
---
## 1. Deployment Information
| Item | Value |
|------|-------|
| Deployment Version | v{{version}} |
| Environment | Production |
| Deployment Method | {{deployMethod}} |
| Deployment URL | {{deployUrl}} |
---
## 2. Environment Variable Management (Phase 2 Link)
### 2.1 Environment Variable List
| Variable Name | Purpose | Development | Staging | Production |
|---------------|---------|:-----------:|:-------:|:----------:|
| NEXT_PUBLIC_APP_URL | App URL | localhost | staging.* | prod.* |
| DATABASE_URL | DB connection | ✅ | ✅ | ✅ |
| AUTH_SECRET | Auth secret | ✅ | ✅ | ✅ |
| | | | | |
### 2.2 Environment-specific .env Files
```
├── .env.example # Template (included in Git)
├── .env.local # Local development (Git ignored)
├── .env.development # Development environment
├── .env.staging # Staging environment
└── .env.production # Production environment
```
### 2.3 CI/CD Secrets Configuration
| Secret Name | Environment | Configuration Location |
|-------------|-------------|----------------------|
| DATABASE_URL | Production | GitHub Secrets / Vercel |
| AUTH_SECRET | Production | GitHub Secrets / Vercel |
| | | |
### 2.4 Environment Variable Validation
```bash
# Run validation script
node scripts/check-env.js
```
---
## 3. Pre-deployment Checklist
### 3.1 Environment Variable Check
- [ ] .env.example is up to date
- [ ] Matches Phase 2 definition
- [ ] All secrets are configured
- [ ] NEXT_PUBLIC_* distinction verified
### 3.2 Prerequisites
- [ ] Domain connection complete
- [ ] SSL certificate configured
- [ ] Database migration complete
### 3.3 Build
- [ ] Production build successful
- [ ] No build errors
- [ ] Build warnings reviewed/resolved
### 3.4 Testing
- [ ] Local environment tests passed
- [ ] Staging environment tests passed
---
## 4. Deployment Execution
### 4.1 Deployment Log
```
{{deployLog}}
```
### 4.2 Deployment Result
| Item | Status |
|------|--------|
| Deployment successful | ✅/❌ |
| Health check | ✅/❌ |
| Service operational | ✅/❌ |
---
## 5. Post-deployment Verification
### 5.1 Feature Verification
| Feature | Status | Notes |
|---------|--------|-------|
| Login | ✅/❌ | |
| Sign up | ✅/❌ | |
| Core feature 1 | ✅/❌ | |
| Core feature 2 | ✅/❌ | |
### 5.2 Performance Verification (Phase 7 Link)
| Metric | Measured Value | Target | Status |
|--------|----------------|--------|--------|
| LCP | | < 2.5s | ✅/❌ |
| FID | | < 100ms | ✅/❌ |
| CLS | | < 0.1 | ✅/❌ |
### 5.3 Security Verification (Phase 7 Link)
- [ ] HTTPS enforced
- [ ] Security headers configured
- [ ] No environment variable exposure
### 5.4 Error Monitoring
- [ ] Error logs checked (last 1 hour)
- [ ] No 5xx errors
- [ ] 4xx errors within normal range
---
## 6. Rollback Plan
### 6.1 Rollback Conditions
- Critical functionality errors
- 5xx error spike
- Data integrity issues
### 6.2 Rollback Procedure
```bash
# Vercel
vercel rollback
# Kubernetes
kubectl rollout undo deployment/{{appName}}
# Manual
git revert HEAD && git push
```
---
## 7. Deployment Completion Notification
- [ ] Team Slack channel announcement
- [ ] Stakeholder notification
- [ ] Release notes written
---
## 8. Follow-up Tasks
| Task | Owner | Deadline | Status |
|------|-------|----------|--------|
| Check monitoring dashboard | | D+1 | ⬜ |
| Collect user feedback | | D+7 | ⬜ |
| Performance optimization | | D+14 | ⬜ |
---
## 9. Project Completion
Development Pipeline 9 phases complete!
### 9.1 Phase Completion Check
| Phase | Deliverable | Complete |
|-------|-------------|:--------:|
| 1 | Glossary | ✅ |
| 2 | Conventions | ✅ |
| 3 | Mockup | ✅ |
| 4 | API Spec | ✅ |
| 5 | Design System | ✅ |
| 6 | UI Implementation | ✅ |
| 7 | SEO/Security | ✅ |
| 8 | Review | ✅ |
| 9 | Deployment | ✅ |
Start new cycle from Phase 1 for next feature development
@@ -0,0 +1,246 @@
# Zero Script QA Report
> Verification through structured JSON logs and real-time monitoring without test scripts
**Project**: {{project_name}}
**Verification Date**: {{date}}
**Scope**: {{scope}}
**Environment**: Docker Compose (Local/Staging)
---
## 1. Zero Script QA Overview
### 1.1 Methodology
```
Traditional: Write test code → Execute → Check results → Maintain
Zero Script: Log infrastructure → Manual UX testing → AI log analysis → Auto issue detection
```
### 1.2 Workflow
```
1. docker compose up -d
2. docker compose logs -f ← Antigravity Platform monitoring
3. User: Manual UX testing in browser
4. Antigravity Platform: Log analysis → Issue detection → Documentation → Fix
```
---
## 2. Logging Infrastructure Check
### 2.1 Environment Settings
| Item | Setting | Status |
|------|---------|:------:|
| LOG_LEVEL | DEBUG | ✅/❌ |
| LOG_FORMAT | json | ✅/❌ |
| Request ID propagation | X-Request-ID | ✅/❌ |
### 2.2 Service Logging Status
| Service | JSON Logs | Request ID | Status |
|---------|:---------:|:----------:|:------:|
| API (Backend) | ✅/❌ | ✅/❌ | ✅/⚠️/❌ |
| Web (Frontend) | ✅/❌ | ✅/❌ | ✅/⚠️/❌ |
| Nginx | ✅/❌ | ✅/❌ | ✅/⚠️/❌ |
---
## 3. Verification Targets
| Feature | API/Screen | Request ID | Status |
|---------|------------|------------|:------:|
| {{feature1}} | {{endpoint1}} | req_xxx | ⬜ |
| {{feature2}} | {{endpoint2}} | req_xxx | ⬜ |
---
## 4. Verification Results
### 4.1 {{Feature1}}
**Scenario**: {{scenarioDescription}}
**Request ID**: `req_{{requestId}}`
**Log Stream**:
```json
{"timestamp":"{{timestamp}}","level":"INFO","service":"web","request_id":"req_{{requestId}}","message":"API Request started","data":{"method":"POST","endpoint":"/api/{{endpoint}}"}}
{"timestamp":"{{timestamp}}","level":"INFO","service":"nginx","request_id":"req_{{requestId}}","message":"HTTP Request","data":{"method":"POST","uri":"/api/{{endpoint}}","status":200}}
{"timestamp":"{{timestamp}}","level":"INFO","service":"api","request_id":"req_{{requestId}}","message":"Request started","data":{"method":"POST","path":"/api/{{endpoint}}"}}
{"timestamp":"{{timestamp}}","level":"DEBUG","service":"api","request_id":"req_{{requestId}}","message":"Processing business logic","data":{}}
{"timestamp":"{{timestamp}}","level":"INFO","service":"api","request_id":"req_{{requestId}}","message":"Request completed","data":{"status":200,"duration_ms":45}}
{"timestamp":"{{timestamp}}","level":"INFO","service":"web","request_id":"req_{{requestId}}","message":"API Request completed","data":{"status":200,"duration_ms":48}}
```
**Result**: ✅ Pass / ❌ Fail
**Performance**: {{duration_ms}}ms (Target: < 1000ms)
**Issue** (if failed):
```
- Request ID: req_{{requestId}}
- Error log:
- Cause:
- Solution:
```
---
### 4.2 {{Feature2}}
**Scenario**: {{scenarioDescription}}
**Request ID**: `req_{{requestId}}`
**Log Stream**:
```json
// Paste logs here
```
**Result**: ✅/❌
---
## 5. Detected Issues
### 5.1 Error Logs (level: ERROR)
| Request ID | Service | Message | Severity |
|------------|---------|---------|----------|
| req_xxx | api | {{errorMessage}} | 🔴/🟡/🟢 |
### 5.2 Slow Responses (> 1000ms)
| Request ID | Endpoint | Duration | Recommended Action |
|------------|----------|----------|-------------------|
| req_xxx | /api/xxx | {{duration}}ms | Caching/Optimization |
### 5.3 Consecutive Failures
| Endpoint | Failure Count | Pattern | Recommended Action |
|----------|---------------|---------|-------------------|
| /api/xxx | {{count}} | {{pattern}} | {{action}} |
---
## 6. Issue Details
### ISSUE-{{number}}: {{title}}
**Request ID**: `req_{{requestId}}`
**Severity**: 🔴 Critical / 🟡 Warning / 🟢 Info
**Reproduction Steps**:
1. {{step1}}
2. {{step2}}
3. {{step3}}
**Related Logs**:
```json
{"timestamp":"...","level":"ERROR","request_id":"req_xxx","message":"...","data":{}}
```
**Root Cause**:
{{rootCause}}
**Recommended Fix**:
{{recommendation}}
**Status**: ⬜ Unresolved / 🔄 In Progress / ✅ Resolved
---
## 7. Verification Summary
### 7.1 Statistics
| Item | Value |
|------|-------|
| Total tests | {{total}} |
| Passed | {{passed}} |
| Failed | {{failed}} |
| Pass rate | {{passRate}}% |
| Average response time | {{avgDuration}}ms |
### 7.2 Issue Status
| Severity | Count | Resolved |
|----------|-------|----------|
| 🔴 Critical | {{critical}} | {{criticalResolved}} |
| 🟡 Warning | {{warning}} | {{warningResolved}} |
| 🟢 Info | {{info}} | {{infoResolved}} |
---
## 8. Conclusion
- [ ] All tests passed, no critical issues → Proceed to next Phase
- [ ] Warning issues exist → Proceed after recommended fixes
- [ ] Critical issues exist → Fix required, re-verification needed
---
## 8.1 Validation Checklist
### Logging Infrastructure
- [ ] JSON log format applied
- [ ] Request ID generation and propagation
- [ ] Log level settings per environment
- [ ] Docker logging configuration
### Backend Logging
- [ ] Logging middleware implemented
- [ ] All API calls logged (including 200 OK)
- [ ] Business logic logging
- [ ] Detailed error logging
### Frontend Logging
- [ ] Logger module implemented
- [ ] API client integration
- [ ] Error boundary logging
### QA Workflow
- [ ] Docker Compose configured
- [ ] Real-time monitoring ready
- [ ] Issue documentation template ready
---
## 9. Monitoring Commands
```bash
# Stream all logs
docker compose logs -f
# Filter errors only
docker compose logs -f | grep '"level":"ERROR"'
# Trace specific Request ID
docker compose logs -f | grep 'req_{{requestId}}'
# Find slow responses (1000ms+)
docker compose logs -f | grep -E '"duration_ms":[0-9]{4,}'
# Specific service only
docker compose logs -f api
docker compose logs -f web
```
---
## 10. Log Format Guide
### JSON Log Standard
```json
{
"timestamp": "ISO 8601 format",
"level": "DEBUG|INFO|WARNING|ERROR",
"service": "api|web|nginx|worker",
"request_id": "req_xxxxxxxx",
"message": "Log message",
"data": { "additional": "data" }
}
```
### Request ID Propagation Rules
```
Client → API Gateway → Backend → Database
↓ ↓ ↓ ↓
req_abc req_abc req_abc req_abc
```
@@ -0,0 +1,236 @@
---
template: plan-plus
version: 1.0
description: Brainstorming-enhanced PDCA Plan template with User Intent, Alternatives, and YAGNI sections
variables:
- feature: Feature name
- date: Creation date (YYYY-MM-DD)
- author: Author
- project: Project name (from package.json or agents.md)
- version: Project version (from package.json)
---
# {feature} Planning Document
> **Summary**: {One-line description}
>
> **Project**: {project}
> **Version**: {version}
> **Author**: {author}
> **Date**: {date}
> **Status**: Draft
> **Method**: Plan Plus (Brainstorming-Enhanced PDCA)
---
## Executive Summary
| Perspective | Content |
|-------------|---------|
| **Problem** | {Core problem this feature solves in 1-2 sentences} |
| **Solution** | {Selected approach summary in 1-2 sentences} |
| **Function/UX Effect** | {Expected functional and UX impact} |
| **Core Value** | {Core value proposition in 1-2 sentences} |
---
## 1. User Intent Discovery
### 1.1 Core Problem
{The core problem this feature solves — discovered through brainstorming Q1}
### 1.2 Target Users
| User Type | Usage Context | Key Need |
|-----------|---------------|----------|
| {User type} | {Context} | {Key need} |
### 1.3 Success Criteria
- [ ] {Measurable success criterion 1}
- [ ] {Measurable success criterion 2}
### 1.4 Constraints
| Constraint | Details | Impact |
|------------|---------|--------|
| {Constraint} | {Details} | High/Medium/Low |
---
## 2. Alternatives Explored
### 2.1 Approach A: {name} {Mark "— Selected" if chosen}
| Aspect | Details |
|--------|---------|
| **Summary** | {One-line description} |
| **Pros** | {Advantages} |
| **Cons** | {Disadvantages} |
| **Effort** | {Estimated complexity: Low/Medium/High} |
| **Best For** | {When this approach is most suitable} |
### 2.2 Approach B: {name}
| Aspect | Details |
|--------|---------|
| **Summary** | {One-line description} |
| **Pros** | {Advantages} |
| **Cons** | {Disadvantages} |
| **Effort** | {Estimated complexity} |
| **Best For** | {When this approach is most suitable} |
### 2.3 Decision Rationale
**Selected**: Approach {A/B}
**Reason**: {Selection reason — based on specific trade-offs}
---
## 3. YAGNI Review
### 3.1 Included (v1 Must-Have)
- [ ] {Essential feature 1}
- [ ] {Essential feature 2}
- [ ] {Essential feature 3}
### 3.2 Deferred (v2+ Maybe)
| Feature | Reason for Deferral | Revisit When |
|---------|---------------------|--------------|
| {Feature} | {Why not needed now} | {When to reconsider} |
### 3.3 Removed (Won't Do)
| Feature | Reason for Removal |
|---------|-------------------|
| {Feature} | {Removal reason} |
---
## 4. Scope
### 4.1 In Scope
- [ ] {Included item 1}
- [ ] {Included item 2}
- [ ] {Included item 3}
### 4.2 Out of Scope
- {Excluded item 1} — (from YAGNI Review)
- {Excluded item 2}
---
## 5. Requirements
### 5.1 Functional Requirements
| ID | Requirement | Priority | Status |
|----|-------------|----------|--------|
| FR-01 | {Requirement description} | High/Medium/Low | Pending |
| FR-02 | {Requirement description} | High/Medium/Low | Pending |
### 5.2 Non-Functional Requirements
| Category | Criteria | Measurement Method |
|----------|----------|-------------------|
| Performance | {e.g., Response time < 200ms} | {Tool/Method} |
| Security | {e.g., OWASP Top 10 compliance} | {Verification method} |
---
## 6. Success Criteria
### 6.1 Definition of Done
- [ ] All functional requirements implemented
- [ ] Unit tests written and passing
- [ ] Code review completed
- [ ] Documentation completed
### 6.2 Quality Criteria
- [ ] Test coverage above 80%
- [ ] Zero lint errors
- [ ] Build succeeds
---
## 7. Risks and Mitigation
| Risk | Impact | Likelihood | Mitigation |
|------|--------|------------|------------|
| {Risk 1} | High/Medium/Low | High/Medium/Low | {Mitigation plan} |
| {Risk 2} | High/Medium/Low | High/Medium/Low | {Mitigation plan} |
---
## 8. Architecture Considerations
### 8.1 Project Level Selection
| Level | Characteristics | Recommended For | Selected |
|-------|-----------------|-----------------|:--------:|
| **Starter** | Simple structure (`components/`, `lib/`, `types/`) | Static sites, portfolios, landing pages | |
| **Dynamic** | Feature-based modules, BaaS integration (bkend.ai) | Web apps with backend, SaaS MVPs, fullstack apps | |
| **Enterprise** | Strict layer separation, DI, microservices | High-traffic systems, complex architectures | |
### 8.2 Key Decisions
| Decision | Options | Selected | Rationale |
|----------|---------|----------|-----------|
| {Decision} | {Option list} | {Selected} | {Rationale} |
### 8.3 Component Overview
```
{Component structure diagram}
```
### 8.4 Data Flow
```
{Data flow diagram}
```
---
## 9. Convention Prerequisites
### 9.1 Applicable Conventions
- [ ] Existing project conventions verified
- [ ] Naming rules confirmed
- [ ] Folder structure rules confirmed
---
## 10. Next Steps
1. [ ] Write design document (`/pdca design {feature}`)
2. [ ] Team review and approval
3. [ ] Start implementation (`/pdca do {feature}`)
---
## Appendix: Brainstorming Log
> Key decisions from Plan Plus Phases 1-4.
| Phase | Question | Answer | Decision |
|-------|----------|--------|----------|
| Intent | {Question summary} | {Answer summary} | {Decision} |
| Alternatives | {Compared items} | {Selection} | {Rationale} |
| YAGNI | {Reviewed items} | {Include/Exclude} | {Reason} |
---
## Version History
| Version | Date | Changes | Author |
|---------|------|---------|--------|
| 0.1 | {date} | Initial draft (Plan Plus) | {author} |
@@ -0,0 +1,273 @@
---
template: plan
version: 1.3
description: PDCA Plan phase document template with Context Anchor and Architecture considerations
variables:
- feature: Feature name
- date: Creation date (YYYY-MM-DD)
- author: Author
- project: Project name (from package.json or agents.md)
- version: Project version (from package.json)
---
# {feature} Planning Document
> **Summary**: {One-line description}
>
> **Project**: {project}
> **Version**: {version}
> **Author**: {author}
> **Date**: {date}
> **Status**: Draft
---
## Executive Summary
| Perspective | Content |
|-------------|---------|
| **Problem** | {Core problem this feature solves} |
| **Solution** | {Selected solution approach} |
| **Function/UX Effect** | {Expected functional and UX impact} |
| **Core Value** | {Core value proposition} |
---
## Context Anchor
> Auto-generated from Executive Summary. Propagated to Design/Do documents for context continuity.
| Key | Value |
|-----|-------|
| **WHY** | {Core problem — extracted from Executive Summary Problem} |
| **WHO** | {Target users — extracted from Scope or Requirements} |
| **RISK** | {Top risk — extracted from Risks section} |
| **SUCCESS** | {Measurable criteria — extracted from Success Criteria} |
| **SCOPE** | {Phase breakdown — extracted from Scope section} |
---
## 1. Overview
### 1.1 Purpose
{The problem this feature solves or the goal it achieves}
### 1.2 Background
{Why this feature is needed, business context}
### 1.3 Related Documents
- Requirements: {link}
- References: {link}
---
## 2. Scope
### 2.1 In Scope
- [ ] {Included item 1}
- [ ] {Included item 2}
- [ ] {Included item 3}
### 2.2 Out of Scope
- {Excluded item 1}
- {Excluded item 2}
---
## 3. Requirements
### 3.1 Functional Requirements
| ID | Requirement | Priority | Status |
|----|-------------|----------|--------|
| FR-01 | {Requirement description} | High/Medium/Low | Pending |
| FR-02 | {Requirement description} | High/Medium/Low | Pending |
### 3.2 Non-Functional Requirements
| Category | Criteria | Measurement Method |
|----------|----------|-------------------|
| Performance | {e.g., Response time < 200ms} | {Tool/Method} |
| Security | {e.g., OWASP Top 10 compliance} | {Verification method} |
| Accessibility | {e.g., WCAG 2.1 AA} | {Verification method} |
---
## 4. Success Criteria
### 4.1 Definition of Done
- [ ] All functional requirements implemented
- [ ] Unit tests written and passing
- [ ] Code review completed
- [ ] Documentation completed
### 4.2 Quality Criteria
- [ ] Test coverage above 80%
- [ ] Zero lint errors
- [ ] Build succeeds
---
## 5. Risks and Mitigation
| Risk | Impact | Likelihood | Mitigation |
|------|--------|------------|------------|
| {Risk 1} | High/Medium/Low | High/Medium/Low | {Mitigation plan} |
| {Risk 2} | High/Medium/Low | High/Medium/Low | {Mitigation plan} |
---
## 6. Impact Analysis
> **Purpose**: List every existing consumer of the resources being changed.
> Changes can break existing functionality in unexpected ways.
> This section forces a full inventory of current usage before making changes.
### 6.1 Changed Resources
| Resource | Type | Change Description |
|----------|------|--------------------|
| {e.g., BilliContract model} | DB Model / API / Schema / Config | {What is being added, modified, or removed} |
### 6.2 Current Consumers
For each changed resource above, list **all** existing code paths that use it:
| Resource | Operation | Code Path | Impact |
|----------|-----------|-----------|--------|
| {resource} | CREATE | {e.g., user-app/contract/new → createBilliContract} | {None / Needs verification / Breaking} |
| {resource} | READ | {e.g., admin/queries/contract.ts → GET_CONTRACT_DETAIL} | {None / Needs verification / Breaking} |
| {resource} | UPDATE | {e.g., admin/hooks/use-contracts.ts → useUpdateContract} | {None / Needs verification / Breaking} |
| {resource} | DELETE | {e.g., admin/queries/contract.ts → DELETE_CONTRACT} | {None / Needs verification / Breaking} |
### 6.3 Verification
- [ ] All consumers listed above verified to work with the proposed changes
- [ ] No auth/permission changes break existing operations
- [ ] No field additions/removals break existing queries or mutations
---
## 7. Architecture Considerations
### 7.1 Project Level Selection
| Level | Characteristics | Recommended For | Selected |
|-------|-----------------|-----------------|:--------:|
| **Starter** | Simple structure (`components/`, `lib/`, `types/`) | Static sites, portfolios, landing pages | ☐ |
| **Dynamic** | Feature-based modules, BaaS integration (bkend.ai) | Web apps with backend, SaaS MVPs, fullstack apps | ☐ |
| **Enterprise** | Strict layer separation, DI, microservices | High-traffic systems, complex architectures | ☐ |
### 7.2 Key Architectural Decisions
| Decision | Options | Selected | Rationale |
|----------|---------|----------|-----------|
| Framework | Next.js / React / Vue | {selected} | {reason} |
| State Management | Context / Zustand / Redux / Jotai | {selected} | {reason} |
| API Client | fetch / axios / react-query | {selected} | {reason} |
| Form Handling | react-hook-form / formik / native | {selected} | {reason} |
| Styling | Tailwind / CSS Modules / styled-components | {selected} | {reason} |
| Testing | Jest / Vitest / Playwright | {selected} | {reason} |
| Backend | BaaS (bkend.ai) / Custom Server / Serverless | {selected} | Dynamic -> bkend.ai recommended |
### 7.3 Clean Architecture Approach
```
Selected Level: {Starter/Dynamic/Enterprise}
Folder Structure Preview:
┌─────────────────────────────────────────────────────┐
│ Starter: │
│ src/components/, src/lib/, src/types/ │
├─────────────────────────────────────────────────────┤
│ Dynamic: │
│ src/components/, src/features/, src/services/, │
│ src/types/, src/lib/bkend.ts, .mcp.json │
├─────────────────────────────────────────────────────┤
│ Enterprise: │
│ src/presentation/, src/application/, │
│ src/domain/, src/infrastructure/ │
└─────────────────────────────────────────────────────┘
```
---
## 8. Convention Prerequisites
### 8.1 Existing Project Conventions
Check which conventions already exist in the project:
- [ ] `agents.md` has coding conventions section
- [ ] `docs/01-plan/conventions.md` exists (Phase 2 output)
- [ ] `CONVENTIONS.md` exists at project root
- [ ] ESLint configuration (`.eslintrc.*`)
- [ ] Prettier configuration (`.prettierrc`)
- [ ] TypeScript configuration (`tsconfig.json`)
### 8.2 Conventions to Define/Verify
| Category | Current State | To Define | Priority |
|----------|---------------|-----------|:--------:|
| **Naming** | {exists/missing} | {specific rules} | High |
| **Folder structure** | {exists/missing} | {structure rules} | High |
| **Import order** | {exists/missing} | {import rules} | Medium |
| **Environment variables** | {exists/missing} | {env var list} | Medium |
| **Error handling** | {exists/missing} | {error patterns} | Medium |
### 8.3 Environment Variables Needed
| Variable | Purpose | Scope | To Be Created |
|----------|---------|-------|:-------------:|
| `NEXT_PUBLIC_API_URL` | API endpoint | Client | ☐ |
| `DATABASE_URL` | DB connection | Server | ☐ |
| `AUTH_SECRET` | Auth secret key | Server | ☐ |
| {variable} | {purpose} | {scope} | ☐ |
### 8.4 Pipeline Integration
If using 9-phase Development Pipeline, check the following:
| Phase | Status | Document Location | Command |
|-------|:------:|-------------------|---------|
| Phase 1 (Schema) | ☐ | `docs/01-plan/schema.md` | `/pipeline-next` |
| Phase 2 (Convention) | ☐ | `docs/01-plan/conventions.md` | `/pipeline-next` |
**Pipeline Templates Available:**
- `templates/pipeline/phase-1-schema.template.md`
- `templates/pipeline/phase-2-convention.template.md`
**Quick Start:**
```bash
# Check pipeline status
/pipeline-status
# Start pipeline from Phase 1
/pipeline-start
# Go to next phase
/pipeline-next
```
---
## 9. Next Steps
1. [ ] Write design document (`{feature}.design.md`)
2. [ ] Team review and approval
3. [ ] Start implementation
---
## Version History
| Version | Date | Changes | Author |
|---------|------|---------|--------|
| 0.1 | {date} | Initial draft | {author} |
@@ -0,0 +1,317 @@
---
template: pm-prd
version: 2.0
description: PM Agent Team PRD output template. Combines 5-Step Discovery, Strategic Analysis, Market Research, GTM, PRD 8-section, and Execution deliverables.
variables:
- feature: Feature name
- date: Creation date (YYYY-MM-DD)
- author: Author
---
# {feature} - Product Requirements Document
> **Date**: {date}
> **Author**: {author}
> **Method**: hmcmkit PM Agent Team (based on pm-skills by Pawel Huryn, MIT)
> **Status**: Draft
---
## Executive Summary
| Perspective | Content |
|-------------|---------|
| **Problem** | {Core problem in 1-2 sentences} |
| **Solution** | {Proposed solution in 1-2 sentences} |
| **Target User** | {Primary user segment} |
| **Core Value** | {Why this matters} |
---
## 1. Opportunity Discovery
### 1.1 Desired Outcome
{Measurable business/product outcome}
### 1.2 Brainstormed Ideas (Top 5)
| # | Idea | Perspective | Rationale |
|---|------|-------------|-----------|
### 1.3 Opportunity Solution Tree
```
Outcome: {desired outcome}
├── Opportunity 1: {customer need/pain}
│ ├── Solution A: {approach}
│ └── Solution B: {approach}
├── Opportunity 2: {customer need/pain}
│ ├── Solution C: {approach}
│ └── Solution D: {approach}
└── Opportunity 3: {customer need/pain}
└── Solution E: {approach}
```
### 1.4 Prioritized Opportunities
| # | Opportunity | Importance | Satisfaction | Score |
|---|------------|:----------:|:------------:|:-----:|
| 1 | {opportunity} | {0-1} | {0-1} | {score} |
### 1.5 Key Assumptions & Risk Prioritization
| # | Assumption | Category | Impact | Risk | Score | Action |
|---|-----------|----------|:------:|:----:|:-----:|--------|
### 1.6 Recommended Experiments
| # | Tests Assumption | Method | Success Criteria | Effort |
|---|-----------------|--------|-----------------|:------:|
---
## 2. Value Proposition & Strategy
### 2.1 JTBD Value Proposition (6-Part)
| Part | Content |
|------|---------|
| **Who** | {target customer segment} |
| **Why** | {core problem, JTBD} |
| **What Before** | {current situation, existing solutions} |
| **How** | {how product solves the problem} |
| **What After** | {improved outcome} |
| **Alternatives** | {competitive alternatives, why choose us} |
**Value Proposition Statement**: {1-2 sentence summary}
### 2.2 Lean Canvas
| Section | Content |
|---------|---------|
| **Problem** | {top 3 problems} |
| **Solution** | {top 3 features} |
| **UVP** | {unique value proposition} |
| **Unfair Advantage** | {defensibility} |
| **Customer Segments** | {target segments} |
| **Channels** | {acquisition channels} |
| **Revenue Streams** | {revenue model} |
| **Cost Structure** | {key costs} |
| **Key Metrics** | {north star + supporting metrics} |
### 2.3 SWOT Analysis
| | Helpful | Harmful |
|---|---------|---------|
| **Internal** | Strengths: {list} | Weaknesses: {list} |
| **External** | Opportunities: {list} | Threats: {list} |
**SO Strategy**: {leverage strengths for opportunities}
**WT Strategy**: {mitigate weaknesses against threats}
### 2.4 Additional Strategic Analysis (if applicable)
{PESTLE, Porter's Five Forces, Pricing Strategy, Ansoff Matrix — context-dependent}
---
## 3. Market Research
### 3.1 User Personas
#### Persona 1: {name} (Primary)
| Attribute | Details |
|-----------|---------|
| **Demographics** | {age, role, context} |
| **Primary JTBD** | {core job to be done} |
| **Pain Points** | 1. {pain} 2. {pain} 3. {pain} |
| **Desired Gains** | 1. {gain} 2. {gain} 3. {gain} |
| **Unexpected Insight** | {counterintuitive finding} |
| **Product Fit** | {how product addresses needs} |
#### Persona 2: {name}
{same structure}
#### Persona 3: {name}
{same structure}
### 3.2 Competitive Landscape
| Competitor | Strengths | Weaknesses | Our Opportunity |
|-----------|-----------|------------|-----------------|
**Differentiation Strategy**: {key differentiators to emphasize}
### 3.3 Market Sizing
| Metric | Current Estimate | 3-Year Projection |
|--------|:---------------:|:-----------------:|
| **TAM** | {total addressable market} | {projection} |
| **SAM** | {serviceable addressable} | {projection} |
| **SOM** | {serviceable obtainable} | {projection} |
**Key Assumptions**: {numbered list of critical assumptions}
### 3.4 Customer Journey Map (Primary Persona)
| Stage | Touchpoint | Actions | Emotions | Pain Points | Opportunities |
|-------|-----------|---------|----------|-------------|---------------|
| Awareness | | | | | |
| Consideration | | | | | |
| Decision | | | | | |
| Onboarding | | | | | |
| Usage | | | | | |
| Advocacy | | | | | |
**Moments of Truth**: {key moments}
---
## 4. Go-To-Market
### 4.1 Beachhead Segment
| Criteria | Score (1-5) | Evidence |
|----------|:-----------:|---------|
| Burning Pain | {score} | {evidence} |
| Willingness to Pay | {score} | {evidence} |
| Winnable Share | {score} | {evidence} |
| Referral Potential | {score} | {evidence} |
**Primary Beachhead**: {selected segment}
**90-Day Acquisition Plan**: {key actions}
### 4.2 GTM Strategy
| Element | Details |
|---------|---------|
| **Channels** | {primary acquisition channels} |
| **Messaging** | {core message for beachhead segment} |
| **Success Metrics** | {KPIs and targets} |
| **Launch Timeline** | Pre-launch / Launch / Post-launch phases |
### 4.3 Ideal Customer Profile (ICP)
| Attribute | Details |
|-----------|---------|
| Industry/Vertical | {specific industry} |
| Company Size | {employees, revenue} |
| Role/Title | {decision maker + end user} |
| Primary JTBD | {core job} |
| Budget Range | {willingness to pay} |
### 4.4 Competitive Battlecards
| Category | Us | {Competitor 1} | {Competitor 2} |
|----------|-----|----------------|----------------|
| Positioning | | | |
| Key Strength | | | |
| Key Weakness | | | |
| Price | | | |
| Best For | | | |
### 4.5 Growth Loops
| Loop Type | Trigger | Action | Output | Metric |
|-----------|---------|--------|--------|--------|
---
## 5. Product Requirements (PRD)
### 5.1 Summary
{2-3 sentence product summary}
### 5.2 Background & Context
{Why now? What changed? What became possible?}
### 5.3 Objectives & Key Results
| Objective | Key Result | Target |
|-----------|-----------|--------|
| {objective} | {measurable KR} | {target value} |
### 5.4 Market Segments
{Target segments defined by problems/JTBD, not demographics}
### 5.5 Value Propositions
{Customer jobs, gains, pains solved - reference Section 2.1}
### 5.6 Solution (Key Features)
| Feature | Description | Priority | Addresses |
|---------|-------------|----------|-----------|
| {feature} | {description} | Must/Should/Could | {which opportunity/pain} |
### 5.7 Assumptions & Risks
| # | Assumption | Category | Confidence | Validation Method |
|---|-----------|----------|:----------:|-------------------|
### 5.8 Release Plan
| Phase | Scope | Timeframe |
|-------|-------|-----------|
| v1 (MVP) | {core features} | {relative timeframe} |
| v2 | {enhancements} | {relative timeframe} |
---
## 6. Execution Deliverables
### 6.1 Pre-mortem
| # | Failure Mode | Category | Likelihood | Impact | Prevention Strategy |
|---|-------------|----------|:----------:|:------:|-------------------|
**Top 3 Risks**: {risks to address before v1}
### 6.2 User Stories
| ID | User Story | Priority | Acceptance Criteria (Given/When/Then) |
|----|-----------|:--------:|--------------------------------------|
### 6.3 Job Stories
| ID | When (Situation) | I want to (Motivation) | So I can (Outcome) |
|----|-----------------|----------------------|-------------------|
### 6.4 Test Scenarios
| ID | Story Ref | Scenario | Steps | Expected Result | Priority |
|----|-----------|----------|-------|----------------|:--------:|
### 6.5 Stakeholder Map
| Stakeholder | Role | Power | Interest | Strategy |
|------------|------|:-----:|:--------:|----------|
---
## Attribution
This PRD was generated by hmcmkit PM Agent Team.
Frameworks based on [pm-skills](https://github.com/phuryn/pm-skills) by Pawel Huryn (MIT License).
- Opportunity Solution Tree: Teresa Torres, *Continuous Discovery Habits*
- Brainstorm & Assumptions: Multi-perspective ideation + 8-category risk assessment (4 Product + 4 GTM)
- Value Proposition: JTBD 6-Part (Pawel Huryn & Aatir Abdul Rauf)
- Lean Canvas: Ash Maurya
- SWOT/PESTLE/Porter's: Strategic analysis frameworks
- Beachhead Segment: Geoffrey Moore, *Crossing the Chasm*
- GTM Strategy: Product Compass methodology
- ICP & Battlecard: Sales-ready competitive tools
- Growth Loops: Product-led & sales-led mechanisms
- Pre-mortem: Gary Klein, prospective hindsight
- User Stories: 3C + INVEST (Ron Jeffries)
- Job Stories: Alan Klement, *When Coffee and Kale Compete*
- Test Scenarios: BDD Given/When/Then
- Stakeholder Map: Mendelow's Power/Interest matrix
@@ -0,0 +1,240 @@
---
template: report
version: 1.1
description: PDCA Act phase document template (completion report)
variables:
- feature: Feature name
- date: Creation date (YYYY-MM-DD)
- author: Author
- project: Project name (from package.json or agents.md)
- version: Project version (from package.json)
---
# {feature} Completion Report
> **Status**: Complete / Partial / Cancelled
>
> **Project**: {project}
> **Version**: {version}
> **Author**: {author}
> **Completion Date**: {date}
> **PDCA Cycle**: #{cycle_number}
---
## Executive Summary
### 1.1 Project Overview
| Item | Content |
|------|---------|
| Feature | {feature} |
| Start Date | {start_date} |
| End Date | {date} |
| Duration | {duration} |
### 1.2 Results Summary
```
┌─────────────────────────────────────────────┐
│ Completion Rate: 95% │
├─────────────────────────────────────────────┤
│ ✅ Complete: 19 / 20 items │
│ ⏳ In Progress: 1 / 20 items │
│ ❌ Cancelled: 0 / 20 items │
└─────────────────────────────────────────────┘
```
### 1.3 Value Delivered
| Perspective | Content |
|-------------|---------|
| **Problem** | {Core problem that was solved} |
| **Solution** | {Solution approach that was applied} |
| **Function/UX Effect** | {Actual achieved functional/UX impact with metrics} |
| **Core Value** | {Validated core value} |
---
## 1.4 Success Criteria Final Status
> From Plan document — final evaluation of each criterion.
| # | Criteria | Status | Evidence |
|---|---------|:------:|----------|
| SC-1 | {criteria text} | ✅ Met | {file:line, test result, or metric} |
| SC-2 | {criteria text} | ✅ Met | {file:line, test result, or metric} |
**Success Rate**: {X}/{Y} criteria met ({percentage}%)
## 1.5 Decision Record Summary
> Key decisions from PRD→Plan→Design chain and their outcomes.
| Source | Decision | Followed? | Outcome |
|--------|----------|:---------:|---------|
| [PRD] | {decision} | ✅ | {actual outcome} |
| [Plan] | {decision} | ✅ | {actual outcome} |
| [Design] | {decision} | ✅ | {actual outcome} |
---
## 2. Related Documents
| Phase | Document | Status |
|-------|----------|--------|
| Plan | [{feature}.plan.md](../01-plan/features/{feature}.plan.md) | ✅ Finalized |
| Design | [{feature}.design.md](../02-design/features/{feature}.design.md) | ✅ Finalized |
| Check | [{feature}.analysis.md](../03-analysis/{feature}.analysis.md) | ✅ Complete |
| Act | Current document | 🔄 Writing |
---
## 3. Completed Items
### 3.1 Functional Requirements
| ID | Requirement | Status | Notes |
|----|-------------|--------|-------|
| FR-01 | {Requirement 1} | ✅ Complete | |
| FR-02 | {Requirement 2} | ✅ Complete | |
| FR-03 | {Requirement 3} | ✅ Complete | Scope reduced |
| FR-04 | {Requirement 4} | ⏳ Next cycle | Time constraint |
### 3.2 Non-Functional Requirements
| Item | Target | Achieved | Status |
|------|--------|----------|--------|
| Performance | < 200ms | 150ms | ✅ |
| Test Coverage | 80% | 82% | ✅ |
| Accessibility | WCAG 2.1 AA | AA compliant | ✅ |
### 3.3 Deliverables
| Deliverable | Location | Status |
|-------------|----------|--------|
| Components | src/features/{feature}/components/ | ✅ |
| API | src/features/{feature}/api/ | ✅ |
| Tests | src/features/{feature}/__tests__/ | ✅ |
| Documentation | docs/ | ✅ |
---
## 4. Incomplete Items
### 4.1 Carried Over to Next Cycle
| Item | Reason | Priority | Estimated Effort |
|------|--------|----------|------------------|
| FR-04 | Time constraint | High | 2 days |
| Performance optimization | Out of scope | Medium | 1 day |
### 4.2 Cancelled/On Hold Items
| Item | Reason | Alternative |
|------|--------|-------------|
| - | - | - |
---
## 5. Quality Metrics
### 5.1 Final Analysis Results
| Metric | Target | Final | Change |
|--------|--------|-------|--------|
| Design Match Rate | 90% | 95% | +20% |
| Code Quality Score | 70 | 85 | +15 |
| Test Coverage | 80% | 82% | +12% |
| Security Issues | 0 Critical | 0 | ✅ |
### 5.2 Resolved Issues
| Issue | Resolution | Result |
|-------|------------|--------|
| Hardcoded secret | Moved to env var | ✅ Resolved |
| N+1 query | Eager Loading | ✅ Resolved |
| Missing input validation | Added Zod schema | ✅ Resolved |
---
## 6. Lessons Learned & Retrospective
### 6.1 What Went Well (Keep)
- {Positive 1: e.g., Design documentation improved implementation efficiency}
- {Positive 2: e.g., Early code review caught bugs proactively}
- {Positive 3}
### 6.2 What Needs Improvement (Problem)
- {Improvement 1: e.g., Initial scope estimation was inaccurate}
- {Improvement 2: e.g., Test cases written too late}
- {Improvement 3}
### 6.3 What to Try Next (Try)
- {Try 1: e.g., Adopt TDD approach}
- {Try 2: e.g., Smaller PR units}
- {Try 3}
---
## 7. Process Improvement Suggestions
### 7.1 PDCA Process
| Phase | Current | Improvement Suggestion |
|-------|---------|------------------------|
| Plan | Insufficient requirement gathering | Add user interviews |
| Design | - | - |
| Do | Poor design reference | Introduce design checklist |
| Check | Manual analysis | Introduce automation tools |
### 7.2 Tools/Environment
| Area | Improvement Suggestion | Expected Benefit |
|------|------------------------|------------------|
| CI/CD | Auto deployment | Reduced deployment time |
| Testing | Add E2E tests | Quality improvement |
---
## 8. Next Steps
### 8.1 Immediate
- [ ] Production deployment
- [ ] Monitoring setup
- [ ] User guide creation
### 8.2 Next PDCA Cycle
| Item | Priority | Expected Start |
|------|----------|----------------|
| {Next feature 1} | High | {date} |
| {Next feature 2} | Medium | {date} |
---
## 9. Changelog
### v1.0.0 ({date})
**Added:**
- {Added feature 1}
- {Added feature 2}
**Changed:**
- {Changed item}
**Fixed:**
- {Fixed bug}
---
## Version History
| Version | Date | Changes | Author |
|---------|------|---------|--------|
| 1.0 | {date} | Completion report created | {author} |
@@ -0,0 +1,130 @@
# {{project_name}} Schema Definition
> PDCA Schema Document - 데이터 구조 및 용어 정의
**Version**: 1.0
**Created**: {{date}}
**Level**: {{level}}
---
## 1. Terminology (용어 정의)
| Term | Definition | Original | Notes |
|------|------------|----------|-------|
| User | 시스템 사용자 | 사용자 | |
| | | | |
---
## 2. Entity Overview
| Entity | Description | Key Fields |
|--------|-------------|------------|
| User | 사용자 정보 | id, email, name |
| | | |
---
## 3. Entity Details
### 3.1 User
**Description**: 시스템 사용자 엔티티
**Fields**:
| Field | Type | Required | Description |
|-------|------|----------|-------------|
| id | string | Y | UUID |
| email | string | Y | 이메일 (unique) |
| name | string | Y | 표시 이름 |
| createdAt | datetime | Y | 생성일시 |
| updatedAt | datetime | Y | 수정일시 |
**Relationships**:
- 1:N → Post (작성한 글)
### 3.2 {{Entity2}}
**Description**:
**Fields**:
| Field | Type | Required | Description |
|-------|------|----------|-------------|
| id | string | Y | UUID |
| | | | |
---
## 4. Entity Relationships
```
┌─────────┐ 1:N ┌─────────┐
│ User │─────────────→ │ Post │
└─────────┘ └─────────┘
│
│ 1:N
▼
┌─────────┐
│ Comment │
└─────────┘
```
---
## 5. Type Definitions (TypeScript)
```typescript
// types/user.ts
export interface User {
id: string
email: string
name: string
createdAt: Date
updatedAt: Date
}
// types/api.ts
export interface ApiResponse<T> {
data: T
meta?: {
total?: number
page?: number
}
}
export interface ApiError {
error: {
code: string
message: string
details?: Record<string, unknown>
}
}
```
---
## 6. Error Codes
| Code | Description | HTTP Status |
|------|-------------|-------------|
| VALIDATION_ERROR | 입력값 검증 실패 | 400 |
| UNAUTHORIZED | 인증 필요 | 401 |
| FORBIDDEN | 권한 없음 | 403 |
| NOT_FOUND | 리소스 없음 | 404 |
| CONFLICT | 중복/충돌 | 409 |
| INTERNAL_ERROR | 서버 오류 | 500 |
---
## Validation Checklist
- [ ] 모든 주요 용어 정의됨
- [ ] 핵심 Entity 정의됨
- [ ] Entity 관계 명확함
- [ ] TypeScript 타입 정의됨
- [ ] Error codes 정의됨
---
*Generated by hmcmkit PDCA System*
@@ -0,0 +1,86 @@
# API Design Patterns
> Shared API design patterns for Skills and Agents
>
> Usage: Add to frontmatter imports in SKILL.md or Agent.md
> ```yaml
> imports:
> - ${PLUGIN_ROOT}/templates/shared/api-patterns.md
> ```
## RESTful Endpoint Conventions
| Action | HTTP Method | Path | Example |
|--------|-------------|------|---------|
| List | GET | /resources | GET /users |
| Get one | GET | /resources/:id | GET /users/123 |
| Create | POST | /resources | POST /users |
| Update | PUT/PATCH | /resources/:id | PUT /users/123 |
| Delete | DELETE | /resources/:id | DELETE /users/123 |
## Request/Response Standards
### Request Headers
```http
Content-Type: application/json
Authorization: Bearer {token}
X-Request-ID: {uuid}
```
### Success Response
```json
{
"success": true,
"data": { /* response payload */ },
"meta": {
"timestamp": "2026-01-26T00:00:00Z",
"requestId": "uuid"
}
}
```
### Pagination
```json
{
"data": [...],
"pagination": {
"page": 1,
"pageSize": 20,
"totalCount": 100,
"totalPages": 5
}
}
```
## API Documentation Pattern
```markdown
## POST /api/resource
**Description**: Create a new resource
**Request Body**:
| Field | Type | Required | Description |
|-------|------|----------|-------------|
| name | string | Yes | Resource name |
**Response** (201 Created):
| Field | Type | Description |
|-------|------|-------------|
| id | string | Created resource ID |
**Errors**:
- 400: Invalid request body
- 401: Authentication required
```
## Rate Limiting Headers
```http
X-RateLimit-Limit: 100
X-RateLimit-Remaining: 99
X-RateLimit-Reset: 1706227200
```
@@ -0,0 +1,139 @@
# bkend.ai Common Patterns
## MCP Fixed Tools (Always Available)
| Tool | Purpose | Parameters |
|------|---------|------------|
| `get_context` | Session context (org/project/env, API endpoint) | None |
| `search_docs` | Search bkend documentation (Auth/Storage guides) | query: string |
| `get_operation_schema` | Get tool input/output schema | operation: string, schemaType: "input" \| "output" |
**Important**: `get_context` MUST be called first. It returns the API endpoint URL dynamically.
## MCP Resources (Read-Only, Cached)
| URI Pattern | Description | Cache TTL |
|-------------|-------------|-----------|
| `bkend://orgs` | Organization list | 60s |
| `bkend://orgs/{orgId}/projects` | Project list | 60s |
| `bkend://orgs/{orgId}/projects/{pId}/environments` | Environment list | 60s |
| `bkend://orgs/{orgId}/projects/{pId}/environments/{eId}/tables` | Table list with schema | 60s |
Access via `resources/list` and `resources/read` MCP methods.
Prefer Resources over Tools for read-only listing (lighter, cached).
## REST Service API
Base URL is provided dynamically by `get_context` response.
Typical endpoints:
- MCP: https://api.bkend.ai/mcp
- Service API: Use the endpoint from `get_context` (e.g., https://api-client.bkend.ai/v1)
**Important**: Do NOT hardcode the Service API base URL. Always reference `get_context` output.
## Required Headers (REST Service API)
```
x-project-id: {projectId}
x-environment: dev | staging | prod
Authorization: Bearer {accessToken}
Content-Type: application/json
```
## API Response Format
List responses use consistent pagination:
```json
{
"items": [...],
"pagination": { "page": 1, "limit": 20, "total": 100, "totalPages": 5 }
}
```
**ID Field**: Always use `id` (NOT `_id`).
## Query Parameters
### Filtering
- AND filter: `?filter[field]=value` (multiple fields = AND)
- Operators: `$eq`, `$ne`, `$gt`, `$gte`, `$lt`, `$lte`, `$in`, `$nin`
- Text search: `?search=keyword`
### Pagination & Sorting
- Page: `?page=1` (default: 1)
- Limit: `?limit=20` (default: 20, max: 100)
- Sort: `?sort=field:asc` (or `desc`)
## File Upload (Presigned URL)
- Presigned URL validity: 15 minutes
- Upload via PUT method with Content-Type header
- Complete upload by registering metadata: POST /v1/files
## Error Response Format
```json
{ "error": { "code": "ERROR_CODE", "message": "Human readable message" } }
```
## HTTP Status Mapping
| Status | Meaning |
|--------|---------|
| 200 | Success |
| 400 | Bad Request (validation) |
| 401 | Unauthorized (token expired/missing) |
| 403 | Forbidden (insufficient permissions) |
| 404 | Not Found |
| 409 | Conflict (unique constraint violation) |
| 429 | Rate Limit Exceeded (100 requests/hour) |
| 500 | Internal Server Error |
## MCP Endpoint
```
URL: https://api.bkend.ai/mcp
Transport: Streamable HTTP
Protocol: JSON-RPC 2.0
Auth: OAuth 2.1 + PKCE
```
## MCP Setup (Antigravity Platform)
```bash
ai-agent mcp add bkend --transport http https://api.bkend.ai/mcp
```
## .mcp.json (Project Config)
```json
{
"mcpServers": {
"bkend": {
"type": "http",
"url": "https://api.bkend.ai/mcp"
}
}
}
```
## Authentication
- OAuth 2.1 + PKCE (browser auto-auth)
- No API Key needed
- Access Token: 1 hour
- Refresh Token: 30 days
## Environment Auto-Provisioning
| Plan | Available Environments |
|------|----------------------|
| Free | dev (1) |
| Pro | dev, staging, prod |
| Enterprise | dev, staging, prod + custom |
## Resource Hierarchy
```
Organization (team/billing) → Project (service unit) → Environment (dev/staging/prod, data isolation)
```
@@ -0,0 +1,149 @@
# Error Handling Patterns
> Shared error handling patterns for Skills and Agents
>
> Usage: Add to frontmatter imports in SKILL.md or Agent.md
> ```yaml
> imports:
> - ${PLUGIN_ROOT}/templates/shared/error-handling-patterns.md
> ```
## Standard Error Response Format
```json
{
"success": false,
"error": {
"code": "ERROR_CODE",
"message": "Human readable message",
"details": {}
}
}
```
## Error Code Conventions
| Category | Prefix | Example |
|----------|--------|---------|
| Authentication | AUTH_ | AUTH_INVALID_TOKEN |
| Validation | VALIDATION_ | VALIDATION_REQUIRED_FIELD |
| Permission | PERMISSION_ | PERMISSION_DENIED |
| Resource | RESOURCE_ | RESOURCE_NOT_FOUND |
| Server | SERVER_ | SERVER_INTERNAL_ERROR |
## Error Handling Rules
1. **Always return structured errors** - Never expose raw exceptions
2. **Use appropriate HTTP status codes**:
- 400: Client error (validation, bad request)
- 401: Authentication required
- 403: Permission denied
- 404: Resource not found
- 500: Server error
3. **Log errors with context** - Include request ID, user ID, timestamp
4. **Sanitize error messages** - Remove sensitive data before response
## Try-Catch Pattern
```javascript
try {
// Operation
} catch (error) {
debugLog('ModuleName', 'Operation failed', {
error: error.message,
context: { /* relevant data */ }
});
return {
success: false,
error: {
code: categorizeError(error),
message: sanitizeErrorMessage(error)
}
};
}
```
## Sentry Integration (Enterprise Level)
### Frontend — Next.js Error Boundary + Sentry
```typescript
// app/error.tsx (Next.js App Router)
'use client';
import * as Sentry from '@sentry/nextjs';
import { useEffect } from 'react';
export default function Error({ error, reset }: { error: Error; reset: () => void }) {
useEffect(() => {
Sentry.captureException(error);
}, [error]);
return (
<div>
<h2>Something went wrong</h2>
<button onClick={reset}>Try again</button>
</div>
);
}
```
### Backend — FastAPI Error Middleware + Sentry
```python
# services/shared/middleware/error_handler.py
import sentry_sdk
from fastapi import Request
from fastapi.responses import JSONResponse
async def error_handler(request: Request, exc: Exception):
# Sentry captures automatically via ASGI integration
# Add custom context for Self-Healing Agent
sentry_sdk.set_context("request", {
"url": str(request.url),
"method": request.method,
"headers": dict(request.headers),
})
sentry_sdk.set_tag("service", SERVICE_NAME)
return JSONResponse(
status_code=500,
content={
"success": False,
"error": {
"code": "SERVER_INTERNAL_ERROR",
"message": "An unexpected error occurred",
"request_id": request.state.request_id,
}
}
)
```
### Error Severity → Self-Healing Mapping
| Sentry Level | Self-Healing Action | Auto-Rollback |
|-------------|---------------------|---------------|
| Fatal | Immediate escalation (PagerDuty) | Yes |
| Error (new) | Self-Healing trigger | No (wait for fix) |
| Error (regression) | Self-Healing + PagerDuty | Yes if spike |
| Warning | Log only | No |
| Info | Ignore | No |
### Structured Logging for Sentry Correlation
```python
# JSON log format — correlates with Sentry events
import structlog
logger = structlog.get_logger()
logger.error(
"payment_failed",
user_id=user.id,
amount=amount,
error=str(exc),
trace_id=span.trace_id, # Links to Tempo trace
sentry_event_id=sentry_sdk.last_event_id(), # Links to Sentry
request_id=request.state.request_id,
)
```
@@ -0,0 +1,68 @@
# Naming Conventions
> Shared naming conventions for Skills and Agents
>
> Usage: Add to frontmatter imports in SKILL.md or Agent.md
> ```yaml
> imports:
> - ${PLUGIN_ROOT}/templates/shared/naming-conventions.md
> ```
## Code Naming
| Category | Convention | Example |
|----------|------------|---------|
| Components | PascalCase | `UserProfile`, `LoginForm` |
| Functions | camelCase | `getUserById`, `validateInput` |
| Constants | UPPER_SNAKE_CASE | `MAX_RETRY_COUNT`, `API_BASE_URL` |
| Variables | camelCase | `userName`, `isLoading` |
| Files | kebab-case | `user-profile.tsx`, `api-client.js` |
| CSS Classes | kebab-case | `user-card`, `nav-menu` |
| Database Tables | snake_case | `user_profiles`, `order_items` |
## File Structure Naming
```
src/
├── components/ # PascalCase
│ └── UserCard.tsx
├── hooks/ # camelCase with use- prefix
│ └── useAuth.ts
├── utils/ # camelCase
│ └── formatDate.ts
├── types/ # PascalCase
│ └── User.ts
└── api/ # kebab-case
└── user-api.ts
```
## Environment Variables
| Prefix | Purpose | Example |
|--------|---------|---------|
| NEXT_PUBLIC_ | Client-side (Next.js) | NEXT_PUBLIC_API_URL |
| DB_ | Database | DB_HOST, DB_PORT |
| API_ | External APIs | API_KEY, API_SECRET |
| AUTH_ | Authentication | AUTH_SECRET, AUTH_PROVIDER |
| SMTP_ | Email | SMTP_HOST, SMTP_PORT |
| STORAGE_ | File storage | STORAGE_BUCKET |
## Boolean Naming
```javascript
// Preferred prefixes for booleans
is - isActive, isLoading, isValid
has - hasPermission, hasError
can - canEdit, canDelete
should - shouldRefresh, shouldValidate
```
## Event Handler Naming
```javascript
// Prefix with 'handle' or 'on'
handleClick // internal handler
onClick // prop passed to component
handleSubmit // form submission
onSuccess // callback prop
```