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,324 @@
---
name: agent-version-analysis
classification: workflow
classification-reason: Orchestrates multi-phase research and analysis pipeline independent of model capability
deprecation-risk: none
description: |
CC CLI version upgrade impact analysis — research changes, analyze hmcmkit impact, generate report.
Triggers: agent-version-analysis, CC upgrade, version analysis, Agent 버전 분석, 버전 영향.
argument-hint: "[from_version] [to_version]"
user-invocable: true
agents:
research: hmcmkit:agent-version-researcher
analyze: hmcmkit:hmcmkit-impact-analyst
brainstorm: null
report: hmcmkit:report-generator
default: null
allowed-tools:
- Read
- Write
- Edit
- Glob
- Grep
- Bash
- Task
- TaskCreate
- TaskUpdate
- TaskList
- TaskGet
- AskUserQuestion
- Agent
- WebSearch
- WebFetch
imports:
- ${PLUGIN_ROOT}/templates/agent-version-analysis.template.md
- ${PLUGIN_ROOT}/templates/plan-plus.template.md
- ${PLUGIN_ROOT}/templates/report.template.md
next-skill: pdca plan
pdca-phase: null
task-template: "[CC-Version-Analysis] CC v{from} → v{to}"
hooks:
Stop:
- type: command
command: "node ${HMCMKIT_PLUGIN_ROOT}/scripts/unified-stop.js"
timeout: 10000
---
# CC Version Analysis — Antigravity Platform CLI 버전 영향 분석 워크플로우
> CC CLI 버전 업그레이드 시 hmcmkit plugin에 대한 영향을 체계적으로 조사, 분석하고
> 개선 기회를 도출하는 전문 워크플로우 스킬.
## Overview
이 스킬은 CC CLI의 새 버전이 출시되었을 때 다음을 자동화합니다:
1. **Phase 1 (Research)**: CC 변경사항 심층 조사
2. **Phase 2 (Analyze)**: hmcmkit 아키텍처 영향 분석
3. **Phase 3 (Brainstorm)**: Plan Plus 브레인스토밍으로 개선안 도출
4. **Phase 4 (Report)**: 종합 영향 분석 보고서 작성
**Agent Team 구성**:
- `agent-version-researcher`: Agent 버전 변경사항 외부 조사
- `hmcmkit-impact-analyst`: hmcmkit 내부 아키텍처 영향 분석
- `report-generator`: 최종 보고서 생성
## HARD-GATE
<HARD-GATE>
Do NOT skip any phase. Each phase produces artifacts that feed into the next.
Do NOT generate the final report without completing Research and Analysis phases.
Do NOT implement any ENH items — this skill is analysis-only.
All documents MUST be written in Korean (한국어).
</HARD-GATE>
## Invocation
```
/agent-version-analysis # Auto-detect: installed vs latest
/agent-version-analysis 2.1.78 2.1.85 # Specific version range
/agent-version-analysis to 2.1.85 # From current installed to target
```
## Process Flow
```
┌─────────────────────────────────────────────────────┐
│ CC Version Analysis │
├─────────────────────────────────────────────────────┤
│ │
│ Phase 0: Setup & Version Detection │
│ ├── Detect installed CC version (ai-agent --version) │
│ ├── Determine target version (args or latest) │
│ ├── Create Task tracking structure │
│ └── Load previous analysis from memory │
│ │
│ Phase 1: Research (agent-version-researcher agent) │
│ ├── Official docs (code.ai-agent.com) │
│ ├── GitHub (anthropics/ai-agent-code) │
│ │ ├── Releases & changelog │
│ │ ├── Issues (open & recently closed) │
│ │ ├── PRs (merged in version range) │
│ │ └── Commits (significant changes) │
│ ├── npm registry (@anthropic-ai/ai-agent-code) │
│ ├── Technical blogs & community │
│ └── Output: CC Change Report (structured) │
│ │
│ Phase 2: Analyze (hmcmkit-impact-analyst agent) │
│ ├── Map CC changes → hmcmkit components │
│ ├── Identify ENH opportunities │
│ ├── File impact matrix │
│ ├── Philosophy compliance check │
│ ├── Test impact assessment │
│ └── Output: hmcmkit Impact Analysis (structured) │
│ │
│ Phase 3: Brainstorm (Plan Plus methodology) │
│ ├── Intent discovery (핵심 목표/리스크/기회) │
│ ├── Alternative exploration │
│ ├── YAGNI review (각 ENH 필요성 검증) │
│ ├── Priority assignment (P0~P3) │
│ └── Output: Prioritized ENH roadmap │
│ │
│ Phase 4: Report Generation │
│ ├── Merge all phase outputs │
│ ├── Generate from template │
│ │ (agent-version-analysis.template.md) │
│ ├── Save to docs/04-report/features/ │
│ ├── Update MEMORY.md (version history) │
│ └── Output: Final Impact Report (Korean) │
│ │
└─────────────────────────────────────────────────────┘
```
## Phase Details
### Phase 0: Setup & Version Detection
```
1. Detect installed CC version:
$ ai-agent --version
2. Determine target version:
- If args provided: use specified versions
- If no args: search for latest available version
3. Create Task structure:
TaskCreate: "[CC-Version-Analysis] CC v{from} → v{to}"
├── Task: "Phase 1: CC 변경사항 조사"
├── Task: "Phase 2: hmcmkit 영향 분석"
├── Task: "Phase 3: Plan Plus 브레인스토밍"
└── Task: "Phase 4: 보고서 작성"
4. Load previous analysis context:
- Read memory/cc_version_history_*.md
- Read last ENH number from MEMORY.md
- Read existing PDCA status from .hmcmkit/state/pdca-status.json
```
### Phase 1: Research (Agent: agent-version-researcher)
**Input**: from_version, to_version
**Output**: Structured CC Change Report
Launch the `agent-version-researcher` agent with:
```
Research CC CLI changes from v{from} to v{to}.
Sources: official docs, GitHub (issues/PRs/releases), npm, blogs.
Categorize by: Breaking/Feature/Fix/Performance/SystemPrompt/Hook/Config.
Rate impact: HIGH/MEDIUM/LOW.
Flag hmcmkit-relevant changes.
Output structured markdown tables.
```
**Parallel research tasks** (when using Agent Team):
- Task 1: GitHub releases + changelog
- Task 2: GitHub issues (open + recently closed)
- Task 3: Official docs changes
- Task 4: System prompt diff analysis
### Phase 2: Analyze (Agent: hmcmkit-impact-analyst)
**Input**: Phase 1 CC Change Report
**Output**: hmcmkit Impact Analysis
Launch the `hmcmkit-impact-analyst` agent with:
```
Analyze hmcmkit impact from these CC changes: {phase1_output}
Map each change to hmcmkit components (agents/skills/hooks/lib/scripts).
Identify ENH opportunities starting from ENH-{last+1}.
Check philosophy compliance (Automation First, No Guessing, Docs=Code).
Assess test impact per ENH.
```
**Analysis scope**:
- 29 agents: frontmatter compatibility
- 31 skills: allowed-tools, hooks compatibility
- 12 hook events: new events, changed behavior
- 210 lib exports: API compatibility
- 50 scripts: stdin/stdout protocol
- 1,186 TCs: test coverage gaps
### Phase 3: Brainstorm (Plan Plus Methodology)
**Input**: Phase 2 Impact Analysis
**Output**: Prioritized ENH Roadmap
Apply Plan Plus brainstorming phases:
#### 3.1 Intent Discovery
Ask and answer:
- 이 CC 업그레이드에서 hmcmkit이 얻을 수 있는 최대 가치는?
- 놓치면 안 되는 critical change는?
- 기존 workaround를 대체할 수 있는 native 기능은?
#### 3.2 Alternative Exploration
For each HIGH/MEDIUM ENH:
- 구현 방법 A vs B vs C 비교
- 최소 구현 (MVP) vs 완전 구현 trade-off
- 다른 ENH와의 의존성/시너지
#### 3.3 YAGNI Review
Each ENH must pass:
- ✅ 현재 사용자가 실제로 필요로 하는가?
- ✅ 구현하지 않으면 어떤 문제가 발생하는가?
- ✅ 다음 Agent 버전에서 더 나은 방법이 나올 가능성은?
- ❌ YAGNI fail → P3 강등 또는 제거
#### 3.4 Priority Assignment
Final priority based on:
- P0: Core PDCA workflow 직접 개선 또는 known pain point 해결
- P1: 중요한 새 기능 활성화 또는 major DX 개선
- P2: Nice-to-have, 문서 업데이트
- P3: Cosmetic, minor optimization, future consideration
### Phase 4: Report Generation
**Input**: All phase outputs
**Output**: Final Korean report in docs/
1. **Generate report** from `agent-version-analysis.template.md`
2. **Save to**: `docs/04-report/features/cc-v{from}-v{to}-impact-analysis.report.md`
3. **Also create Plan** (if ENH count > 0):
`docs/01-plan/features/cc-v{from}-v{to}-impact-analysis.plan.md`
4. **Update MEMORY.md**:
- CC version history section
- ENH number range
- Consecutive compatible releases count
- Open/closed GitHub issues
5. **Update memory file**: `memory/cc_version_history_v{from}_v{to}.md`
## Task Management Protocol
All work MUST be tracked via Task Management System:
```
[CC-Version-Analysis] CC v{from} → v{to} # Parent task
├── [Research] Phase 1: CC 변경사항 조사 # agent-version-researcher
│ ├── GitHub releases 조사
│ ├── GitHub issues 조사
│ ├── 공식 문서 변경 조사
│ └── 시스템 프롬프트 변경 분석
├── [Analyze] Phase 2: hmcmkit 영향 분석 # hmcmkit-impact-analyst
│ ├── 컴포넌트 매핑
│ ├── ENH 기회 식별
│ ├── 파일 영향 매트릭스
│ └── 철학 준수 검증
├── [Brainstorm] Phase 3: 브레인스토밍 # Plan Plus
│ ├── 의도 탐색
│ ├── 대안 탐색
│ └── YAGNI 검토
└── [Report] Phase 4: 보고서 작성 # report-generator
├── 템플릿 기반 보고서 생성
├── MEMORY.md 업데이트
└── 최종 검토
```
## Agent Team Configuration
When invoked with CTO Team (`/pdca team`):
| Role | Agent | Model | Task |
|------|-------|-------|------|
| Lead | cto-lead | leader-agent | Overall orchestration |
| Researcher | agent-version-researcher | leader-agent | Phase 1: CC research |
| Analyst | hmcmkit-impact-analyst | leader-agent | Phase 2: hmcmkit analysis |
| Reporter | report-generator | helper-agent | Phase 4: Report writing |
**Parallel execution**:
- Phase 1 tasks can run in parallel (GitHub, docs, npm)
- Phase 2 depends on Phase 1 completion
- Phase 3 depends on Phase 2 completion
- Phase 4 depends on Phase 3 completion
## Quality Checklist
Before completing, verify:
- [ ] All CC changes from version range are captured
- [ ] Every change has impact classification (HIGH/MEDIUM/LOW)
- [ ] Every ENH has priority (P0/P1/P2/P3)
- [ ] Philosophy compliance checked for all ENH items
- [ ] File impact matrix is complete
- [ ] Test impact assessed for all ENH items
- [ ] Report is written in Korean
- [ ] MEMORY.md is updated
- [ ] Task tracking shows all items completed
- [ ] Executive Summary includes 4-perspective value table
## Previous Analysis Reference
This skill builds on established analysis patterns:
- `docs/04-report/features/ai-agent-code-v2172-impact-analysis.report.md`
- `docs/04-report/features/ai-agent-code-v2178-impact-analysis.report.md`
- `memory/cc_version_history_v2134_v2172.md`
Always read previous reports first to maintain consistency in:
- ENH numbering (continue from last used number)
- Report structure and depth
- Consecutive compatible release tracking
- GitHub issues monitoring continuity
@@ -0,0 +1,268 @@
---
name: ai-agent-code-learning
classification: capability
classification-reason: Highly likely to be subsumed by model's native capabilities
deprecation-risk: high
description: |
Antigravity Platform learning — configure and optimize Antigravity Platform settings, tips, and workflows.
Triggers: learn, setup, ai-agent code, optimize, 학습, 설정, 최적화.
argument-hint: "[learn|setup|upgrade] [level]"
agent: ai-agent-code-guide
allowed-tools:
- Read
- Write
- Edit
- Glob
- Grep
- Bash
- AskUserQuestion
user-invocable: true
imports:
- ${PLUGIN_ROOT}/templates/shared/naming-conventions.md
next-skill: null
pdca-phase: null
task-template: "[Learn] Antigravity Platform {level}"
hooks:
Stop:
- type: command
command: "node ${HMCMKIT_PLUGIN_ROOT}/scripts/learning-stop.js"
timeout: 10000
---
# Antigravity Platform Learning Skill
> Master Antigravity Platform configuration and optimization
## Actions
| Action | Description | Example |
|--------|-------------|---------|
| `learn` | Start learning guide | `/ai-agent-code-learning learn 1` |
| `setup` | Auto-generate settings | `/ai-agent-code-learning setup` |
| `upgrade` | Latest features guide | `/ai-agent-code-learning upgrade` |
### learn [level]
Learning content by level:
- **Level 1**: Basics - Writing agents.md, Using Plan Mode
- **Level 2**: Automation - Commands, Hooks, Permission management
- **Level 3**: Specialization - Agents, Skills, MCP integration
- **Level 4**: Team Optimization - GitHub Action, Team rule standardization
- **Level 5**: PDCA Methodology - hmcmkit methodology learning
### setup
Auto-generate appropriate settings after analyzing current project:
1. Analyze/generate agents.md
2. Check .ai-agent/ folder structure
3. Suggest required configuration files
### upgrade
Guide to latest Antigravity Platform features and best practices.
## Learning Levels
### Level 1: Basics (15 min)
```markdown
## What is agents.md?
A shared knowledge repository for the team. When AI Agent makes mistakes,
add rules to prevent the same mistakes from recurring.
## Example
# Development Workflow
## Package Management
- **Always use `pnpm`** (`npm`, `yarn` prohibited)
## Coding Conventions
- Prefer `type`, avoid `interface`
- **Never use `enum`** → Use string literal unions
## Prohibited
- ❌ No console.log (use logger)
- ❌ No any type
```
### Level 2: Automation (30 min)
```markdown
## What are Slash Commands?
Execute repetitive daily tasks with `/command-name`.
## Command Location
.ai-agent/commands/{command-name}.md
## PostToolUse Hook
Auto-formatting after code modification:
// .ai-agent/settings.local.json
{
"hooks": {
"PostToolUse": [{
"matcher": "Write|Edit",
"hooks": [{
"type": "command",
"command": "pnpm format || true"
}]
}]
}
}
```
### Level 3: Specialization (45 min)
```markdown
## What are Sub-agents?
AI agents specialized for specific tasks.
## What are Skills?
Domain-specific expert context. AI Agent auto-references when working on related tasks.
## MCP Integration
Connect external tools (Slack, GitHub, Jira, etc.) via .mcp.json.
```
### Level 4: Team Optimization (1 hour)
```markdown
## PR Automation with GitHub Action
Mention @ai-agent in PR comments to auto-update documentation.
## Team Rule Standardization
1. Manage agents.md with Git
2. Add rules during PR review
3. Gradually accumulate team knowledge
## Agent Teams (v1.5.1)
Parallel PDCA execution with multiple AI agents working simultaneously.
Requirements:
HMCMKIT_EXPERIMENTAL_AGENT_TEAMS=1
Usage:
/pdca team {feature} Start team mode
/pdca team status Check teammate progress
/pdca team cleanup End team session
Team composition by level:
Dynamic: 2 teammates (developer, qa)
Enterprise: 4 teammates (architect, developer, qa, reviewer)
```
### Level 5: PDCA Methodology
```markdown
## What is PDCA?
Document-driven development methodology.
Plan → Design → Do → Check → Act
## Folder Structure
docs/
├── 01-plan/ # Planning
├── 02-design/ # Design
├── 03-analysis/ # Analysis
└── 04-report/ # Reports
## Learn More
Use /pdca skill to learn PDCA methodology.
```
### Level 6: Advanced Features (v1.5.1)
```markdown
## Output Styles
Customize how AI Agent responds based on your project level.
Available styles:
hmcmkit-learning Best for beginners (learning points, TODO markers)
hmcmkit-pdca-guide Best for PDCA workflows (status badges, checklists)
hmcmkit-enterprise Best for architects (tradeoff analysis, cost impact)
Usage:
/output-style Select interactively
/output-style hmcmkit-learning Apply directly
Auto-recommendation:
Starter → hmcmkit-learning
Dynamic → hmcmkit-pdca-guide
Enterprise → hmcmkit-enterprise
## Agent Memory
All hmcmkit agents automatically remember context across sessions.
No configuration needed.
Memory scopes:
project 9 agents remember per-project context (.ai-agent/agent-memory/)
user 2 agents remember cross-project learning (~/.ai-agent/agent-memory/)
Agents with user-scope memory:
starter-guide Remembers your learning progress across projects
pipeline-guide Remembers your pipeline preferences globally
## Agent Teams
Parallel PDCA execution for Dynamic and Enterprise projects.
See Level 4 for details.
```
## Output Format
```
📚 Antigravity Platform Learning Complete!
**Current Level**: {level}
**Learned**: {summary}
🎯 Next Steps:
- Continue learning with /ai-agent-code-learning learn {next_level}
- Auto-generate settings with /ai-agent-code-learning setup
- Check latest trends with /ai-agent-code-learning upgrade
```
## Current Settings Analysis
Files to analyze:
- agents.md (root)
- .ai-agent/settings.local.json
- .ai-agent/commands/
- .ai-agent/agents/
- .ai-agent/skills/
- .mcp.json
## Skills 2.0 Hot Reload (CC 2.1.0+)
CC 2.1.0+ supports hot reload for skill changes. No session restart needed.
### Hot Reload Scope
- SKILL.md body changes: Instant reflection
- Frontmatter field changes: Instant reflection
- New skill additions: Instant reflection
### Development Workflow
1. Edit SKILL.md content and save
2. Next slash invoke reflects changes immediately
3. Use `/reload-plugins` for forced refresh
### Tips
- Test with `/eval run [skill-name]` after changes
- Use `classification` frontmatter to categorize skills
- Monitor with `/loop 5m /pdca status` for ongoing work
+228
View File
@@ -0,0 +1,228 @@
---
name: audit
classification: workflow
classification-reason: Audit logging persists regardless of model advancement
deprecation-risk: none
description: |
View audit logs, decision traces, and session history for AI transparency.
Triggers: audit, log, decision trace, history, 감사 로그, 결정 추적.
argument-hint: "[log|trace|summary|search] [query]"
user-invocable: true
allowed-tools:
- Read
- Glob
- Grep
- Bash
imports: []
next-skill: null
pdca-phase: null
task-template: "[Audit] {action}"
---
# Audit Skill
> User-invocable skill for viewing audit logs, decision traces, and session history.
## Arguments
| Argument | Description | Example |
|----------|-------------|---------|
| (none) | Show recent audit log entries (same as `log`) | `/audit` |
| `log` | Show recent audit log entries (last 20) | `/audit log` |
| `trace <feature>` | Show decision traces for a feature | `/audit trace user-auth` |
| `summary` | Show daily/weekly audit summary | `/audit summary` |
| `search <query>` | Search audit logs by action type, feature, or date | `/audit search "phase_transition"` |
## Action Details
### log (Default)
Display recent audit log entries.
1. Read today's audit log from `.hmcmkit/audit/YYYY-MM-DD.jsonl`
2. If today's log is empty or has fewer than 20 entries, also read yesterday's log
3. Parse JSONL entries (one JSON object per line)
4. Display the last 20 entries in reverse chronological order
5. Format each entry with timestamp, action, feature, and details
**JSONL Entry Schema**:
```json
{
"timestamp": "2026-03-19T10:30:00.000Z",
"action": "phase_transition",
"feature": "user-auth",
"from": "plan",
"to": "design",
"automationLevel": "semi-auto",
"triggeredBy": "user",
"details": "Plan approved, transitioning to Design"
}
```
**Output Format**:
```
--- Audit Log (Last 20 Entries) -------------------
[2026-03-19 10:30] phase_transition | user-auth
plan -> design (Semi-Auto, user-triggered)
[2026-03-19 10:25] checkpoint_created | user-auth
Checkpoint cp-1710842700000 before Design phase
[2026-03-19 10:20] automation_level_changed | -
L1 -> L2 (trust score: 72)
...
---------------------------------------------------
Total entries today: 45
```
### trace <feature>
Show decision traces for a specific feature.
1. Read decision trace files from `.hmcmkit/decisions/YYYY-MM-DD.jsonl`
2. Filter entries matching the specified feature
3. Display chronological decision chain with rationale
**Decision Trace Entry Schema**:
```json
{
"timestamp": "2026-03-19T10:30:00.000Z",
"feature": "user-auth",
"decision": "advance_to_design",
"rationale": "Plan document complete, matchRate N/A at this phase",
"alternatives": ["request_plan_revision", "skip_to_do"],
"chosenBecause": "Plan deliverable exists and passes validation",
"automationLevel": "semi-auto",
"confidence": 0.92
}
```
**Output Format**:
```
--- Decision Trace: user-auth ---------------------
[10:15] START -> pm
Decision: Begin PDCA cycle
Rationale: New feature request detected
[10:20] pm -> plan
Decision: advance_to_plan
Rationale: PRD document generated successfully
Alternatives: [reject_prd, revise_scope]
Confidence: 0.88
[10:30] plan -> design
Decision: advance_to_design
Rationale: Plan document complete, passes validation
Alternatives: [request_plan_revision, skip_to_do]
Confidence: 0.92
---------------------------------------------------
Total decisions: 3
```
### summary
Show daily or weekly audit summary.
1. Read audit logs for the current day (and optionally past 7 days)
2. Aggregate by action type and count occurrences
3. Calculate key metrics:
- Total actions recorded
- Phase transitions count
- Automation vs manual ratio
- Error/recovery events
- Average trust score change
4. Display formatted summary
**Output Format**:
```
--- Audit Summary (2026-03-19) --------------------
Total Actions : 45
Phase Transitions : 12
Checkpoints Created : 4
Errors Recorded : 1
Recoveries : 1
Action Breakdown:
phase_transition : 12 (27%)
checkpoint_created : 4 (9%)
match_rate_recorded : 8 (18%)
automation_level_change: 2 (4%)
iteration_completed : 6 (13%)
other : 13 (29%)
Automation Ratio: 67% auto / 33% manual
Trust Score Change: +3 (69 -> 72)
---------------------------------------------------
Weekly Trend (last 7 days):
Mon: 32 actions | Tue: 45 actions | Wed: 28 actions
...
```
### search <query>
Search audit logs by action type, feature name, or date range.
1. Parse the search query to determine filter type:
- If query matches an action type (e.g., `phase_transition`), filter by action
- If query matches a feature name, filter by feature
- If query matches a date (YYYY-MM-DD), filter by date
- Otherwise, perform full-text search across all fields
2. Read relevant JSONL files from `.hmcmkit/audit/`
3. Apply filters and return matching entries (max 50 results)
4. Display results in chronological order
**Search Examples**:
```bash
# Search by action type
/audit search "phase_transition"
# Search by feature name
/audit search "user-auth"
# Search by date
/audit search "2026-03-18"
# Full-text search
/audit search "error"
```
## File Locations
| Path | Format | Purpose |
|------|--------|---------|
| `.hmcmkit/audit/YYYY-MM-DD.jsonl` | JSONL | Daily audit log entries |
| `.hmcmkit/audit/summary/` | JSON | Pre-computed daily/weekly summaries |
| `.hmcmkit/decisions/YYYY-MM-DD.jsonl` | JSONL | Decision trace entries |
## Module Dependencies
| Module | Function | Usage |
|--------|----------|-------|
| `lib/audit/audit-logger.js` | `readAuditLog()` | Read audit entries |
| `lib/audit/audit-logger.js` | `searchAuditLog()` | Search/filter entries |
| `lib/audit/decision-tracer.js` | `getDecisionTrace()` | Read decision traces |
## Retention Policy
- Audit logs: 30-day retention, auto-cleanup via daily hook
- Decision traces: 30-day retention, linked to audit logs
- Total storage budget: 100MB (auto-prune oldest when exceeded)
## Usage Examples
```bash
# View recent log entries
/audit
# View decision trace for a feature
/audit trace user-auth
# View daily summary
/audit summary
# Search for phase transitions
/audit search "phase_transition"
# Search by feature
/audit search "user-auth"
```
@@ -0,0 +1,114 @@
---
name: bkend-auth
classification: capability
classification-reason: Pattern guidance may overlap with model's built-in knowledge as it improves
deprecation-risk: medium
description: |
bkend.ai authentication — email/social login, JWT tokens, RBAC, session management.
Triggers: bkend auth, login, signup, JWT, RBAC, 인증, 로그인, 회원가입.
user-invocable: false
agent: hmcmkit:bkend-expert
allowed-tools:
- Read
- Write
- Edit
- Glob
- Grep
- Bash
- mcp__bkend__*
imports:
- ${PLUGIN_ROOT}/templates/shared/bkend-patterns.md
---
# bkend.ai Authentication & Security Guide
## Auth Methods
| Method | Description |
|--------|-------------|
| Email + Password | Email/password signup and login |
| Social (Google) | OAuth 2.0 social login |
| Social (GitHub) | OAuth 2.0 social login |
| Magic Link | Email link login (no password) |
## JWT Token Structure
- **Access Token**: 1 hour validity
- **Refresh Token**: 7 days validity
- Auto-refresh: `POST /v1/auth/refresh`
## Password Policy
8+ characters, uppercase + lowercase + numbers + special characters
## MCP Auth Workflow
bkend MCP does NOT have dedicated auth tools. Use this workflow:
1. **Search docs**: `search_docs` with query "email signup" or "social login"
2. **Get examples**: `search_docs` with query "auth code examples"
3. **Generate code**: AI generates REST API code based on search results
### Searchable Auth Docs
| Doc ID | Content |
|--------|---------|
| `3_howto_implement_auth` | Signup, login, token management guide |
| `6_code_examples_auth` | Email, social, magic link code examples |
### Key Pattern
```
User: "Add social login"
→ search_docs(query: "social login implementation")
→ Returns auth guide with REST API patterns
→ AI generates social login code
```
## REST Auth API (Core Endpoints)
For the complete endpoint list, use `search_docs` or check Live Reference.
| Method | Endpoint | Description |
|--------|----------|-------------|
| POST | /v1/auth/email/signup | Sign up |
| POST | /v1/auth/email/signin | Sign in |
| GET | /v1/auth/me | Current user |
| POST | /v1/auth/refresh | Refresh token |
| POST | /v1/auth/signout | Sign out |
| GET/POST | /v1/auth/:provider/callback | Social login callback |
| POST | /v1/auth/password/reset/request | Password reset |
| POST | /v1/auth/password/reset/confirm | Confirm reset |
| POST | /v1/auth/password/change | Change password |
| GET | /v1/auth/sessions | List sessions |
| DELETE | /v1/auth/sessions/:sessionId | Remove session |
| DELETE | /v1/auth/withdraw | Delete account |
**Additional endpoints** (MFA, invitations, user management): use `search_docs` or Live Reference.
## RBAC (Role-Based Access Control)
| Group | Description | Scope |
|-------|-------------|-------|
| admin | Full CRUD | All data |
| user | Authenticated user | Full read, own write |
| self | Owner only | createdBy-based |
| guest | Unauthenticated | Read only (usually) |
## RLS (Row Level Security)
- Per-table row-level access control
- 4-level policies: admin/user/self/guest
- Auto-filtering based on createdBy field
## Session Management
- Per-device session tracking
- `GET /v1/auth/sessions` - List sessions
- `DELETE /v1/auth/sessions/:sessionId` - Remove session
## Official Documentation (Live Reference)
For the latest authentication documentation, use WebFetch:
- Auth Overview: https://raw.githubusercontent.com/popup-studio-ai/bkend-docs/main/en/authentication/01-overview.md
- MCP Auth Guide: https://raw.githubusercontent.com/popup-studio-ai/bkend-docs/main/en/mcp/06-auth-tools.md
- Security: https://raw.githubusercontent.com/popup-studio-ai/bkend-docs/main/en/security/01-overview.md
- Full TOC: https://raw.githubusercontent.com/popup-studio-ai/bkend-docs/main/SUMMARY.md
@@ -0,0 +1,89 @@
---
name: bkend-cookbook
classification: capability
classification-reason: Pattern guidance may overlap with model's built-in knowledge as it improves
deprecation-risk: medium
description: |
bkend.ai project tutorials (todo to SaaS) and common error troubleshooting.
Triggers: bkend tutorial, cookbook, troubleshooting, 튜토리얼, 에러 해결.
user-invocable: false
agent: hmcmkit:bkend-expert
allowed-tools:
- Read
- Write
- Edit
- Glob
- Grep
- Bash
- mcp__bkend__*
imports:
- ${PLUGIN_ROOT}/templates/shared/bkend-patterns.md
---
# bkend.ai Cookbook & Troubleshooting
## Single Project Guides
| Project | Level | Key Features |
|---------|-------|-------------|
| Todo App | Beginner | Basic CRUD, state management |
| Note App | Beginner | Rich text, categories |
| Blog | Intermediate | Posts, tags, file upload |
| Chat App | Intermediate | Real-time messaging |
| E-commerce | Intermediate | Products, orders, payments |
| Booking System | Intermediate | Reservations, calendar |
| Social Feed | Advanced | Posts, follows, feeds |
| Dashboard | Advanced | Charts, analytics, roles |
| Multi-tenant | Advanced | Organization-scoped data |
| SaaS Starter | Advanced | Subscriptions, billing, onboarding |
## Full Guide Projects (4, each with quick-start + 7 chapters)
| Project | Auth | Core CRUD | Files | Advanced | AI |
|---------|------|-----------|-------|----------|-----|
| Blog | Email/Social | Articles, Tags | Images | Bookmarks | AI summary |
| Recipe App | Email/Social | Recipes, Ingredients | Photos | Meal Plan, Shopping List | AI recommendations |
| Shopping Mall | Email/Social | Stores, Products, Orders | Product images | Reviews | AI search |
| Social Network | Email/Social | Profiles, Posts | Media | Follows, Feeds | AI recommendations |
## Common Implementation Pattern
```
1. Auth setup (email + social login)
2. Core CRUD (main data tables)
3. File upload (images/media)
4. Advanced features (search, filters, relationships)
5. AI integration (recommendations, summaries)
6. Troubleshooting & optimization
```
## Troubleshooting Quick Reference
| Error | Cause | Solution |
|-------|-------|----------|
| 401 Unauthorized | Token expired | POST /v1/auth/refresh |
| 403 Forbidden | Insufficient permissions | Check RBAC settings |
| 404 Not Found | Wrong path/ID | Verify endpoint and environment |
| 409 Conflict | Unique field duplicate | Check duplicate data |
| 429 Rate Limit | Request limit exceeded (100/h) | Check Retry-After header |
| CORS Error | Domain not registered | Register in bkend console |
| MCP Connection Failed | OAuth incomplete | Complete browser auth |
| Schema Validation | BSON type mismatch | Check schema with backend_table_get |
## FAQ
| Question | Answer |
|----------|--------|
| Table not visible | Check environment (dev/staging/prod) |
| MCP tools not showing | Run `ai-agent mcp list` to verify connection |
| Social login not working | Check Provider settings in console |
| File upload fails | Verify size limits (image 10MB, video 100MB) |
| Slow queries | Add indexes via backend_index_manage |
| Data not syncing | Check x-environment header matches |
## Official Documentation (Live Reference)
For the latest cookbook and troubleshooting, use WebFetch:
- Cookbooks: https://raw.githubusercontent.com/popup-studio-ai/bkend-docs/main/en/cookbooks/blog/01-quick-start.md
- Troubleshooting: https://raw.githubusercontent.com/popup-studio-ai/bkend-docs/main/en/troubleshooting/01-common-errors.md
- Full TOC: https://raw.githubusercontent.com/popup-studio-ai/bkend-docs/main/SUMMARY.md
@@ -0,0 +1,138 @@
---
name: bkend-data
classification: capability
classification-reason: Pattern guidance may overlap with model's built-in knowledge as it improves
deprecation-risk: medium
description: |
bkend.ai database — CRUD, column types, filtering, sorting, relations, indexing.
Triggers: bkend table, CRUD, column, filter, sort, relation, 테이블, 데이터.
user-invocable: false
agent: hmcmkit:bkend-expert
allowed-tools:
- Read
- Write
- Edit
- Glob
- Grep
- Bash
- mcp__bkend__*
imports:
- ${PLUGIN_ROOT}/templates/shared/bkend-patterns.md
---
# bkend.ai Database Guide
## Column Types (7)
| Type | Description | Example |
|------|-------------|---------|
| String | Text | name, email |
| Number | Numeric | age, price |
| Boolean | True/false | isActive |
| Date | Date/time | birthDate |
| Array | Array | tags: ["a","b"] |
| Object | Nested object | address: {city, zip} |
| Mixed | Any type | metadata |
## Constraints
- `required`: Field must have a value
- `unique`: No duplicate values allowed
- `default`: Default value when not provided
## Auto System Fields
| Field | Type | Description |
|-------|------|-------------|
| id | String | Auto-generated unique ID |
| createdBy | String | Creator user ID |
| createdAt | Date | Creation timestamp |
| updatedAt | Date | Last update timestamp |
**Important**: bkend uses `id` (NOT `_id`) in all API responses.
## MCP Table Management Tools
| Tool | Purpose | Scope |
|------|---------|-------|
| `backend_table_create` | Create table | table:create |
| `backend_table_list` | List tables | table:read |
| `backend_table_get` | Get table detail + schema | table:read |
| `backend_table_delete` | Delete table | table:delete |
| `backend_field_manage` | Add/modify/delete fields | table:update |
| `backend_index_manage` | Manage indexes | table:update |
| `backend_schema_version_list` | Schema version history | table:read |
| `backend_schema_version_get` | Schema version detail | table:read |
| `backend_schema_version_apply` | Apply schema version (rollback) | table:update |
| `backend_index_version_list` | Index version history | table:read |
| `backend_index_version_get` | Index version detail | table:read |
## MCP Data CRUD Tools
| Tool | Purpose | Key Parameters |
|------|---------|----------------|
| `backend_data_list` | List records (filter, sort, paginate) | tableId, page?, limit?, sortBy?, sortDirection?, andFilters?, orFilters? |
| `backend_data_get` | Get single record | tableId, recordId |
| `backend_data_create` | Create record | tableId, data: { field: value } |
| `backend_data_update` | Partial update record | tableId, recordId, data: { field: value } |
| `backend_data_delete` | Delete record | tableId, recordId |
All Data CRUD tools require: organizationId, projectId, environmentId (from `get_context`).
### Filter Operators
| Operator | Meaning | Example |
|----------|---------|---------|
| `$eq` | Equal | `{ "status": { "$eq": "active" } }` |
| `$ne` | Not equal | `{ "role": { "$ne": "admin" } }` |
| `$gt` / `$gte` | Greater than / >= | `{ "age": { "$gt": 18 } }` |
| `$lt` / `$lte` | Less than / <= | `{ "price": { "$lt": 100 } }` |
| `$in` / `$nin` | In / Not in array | `{ "tag": { "$in": ["a","b"] } }` |
## MCP Guide Docs (via search_docs)
Use `search_docs` tool to access these guides:
| Doc ID | Content |
|--------|---------|
| `4_howto_implement_data_crud` | CRUD implementation patterns |
| `7_code_examples_data` | CRUD + file upload code examples |
Use `get_operation_schema` to get any tool's input/output schema.
## REST Data API
| Method | Endpoint | Description |
|--------|----------|-------------|
| GET | /v1/data/{table} | List (filter, sort, page, limit) |
| POST | /v1/data/{table} | Create |
| GET | /v1/data/{table}/{id} | Get single |
| PATCH | /v1/data/{table}/{id} | Partial update |
| DELETE | /v1/data/{table}/{id} | Delete |
## Filtering
- Text search: `?search=keyword`
- AND filter: `?filter[field1]=value1&filter[field2]=value2`
- Comparison operators: `$eq`, `$ne`, `$gt`, `$gte`, `$lt`, `$lte`, `$in`, `$nin`
- Sort: `?sort=field:asc` (or desc)
- Pagination: `?page=1&limit=20` (default 20, max 100)
## Relations & Joins
- Configure table relationships
- Join queries for related data retrieval
## Index Management
- Single/compound index creation
- Manage via MCP `backend_index_manage`
- Essential for query performance optimization
## Official Documentation (Live Reference)
For the latest database documentation, use WebFetch:
- MCP Data Tools: https://raw.githubusercontent.com/popup-studio-ai/bkend-docs/main/en/mcp/05-data-tools.md
- MCP Table Tools: https://raw.githubusercontent.com/popup-studio-ai/bkend-docs/main/en/mcp/04-table-tools.md
- Database Guide: https://raw.githubusercontent.com/popup-studio-ai/bkend-docs/main/en/database/01-overview.md
- Full TOC: https://raw.githubusercontent.com/popup-studio-ai/bkend-docs/main/SUMMARY.md
@@ -0,0 +1,143 @@
---
name: bkend-quickstart
classification: capability
classification-reason: Pattern guidance may overlap with model's built-in knowledge as it improves
deprecation-risk: medium
description: |
bkend.ai onboarding — MCP setup, resource hierarchy, tenant/user model, first project.
Triggers: bkend quickstart, onboarding, setup, MCP, 시작하기, 온보딩.
user-invocable: false
agent: hmcmkit:bkend-expert
allowed-tools:
- Read
- WebFetch
- mcp__bkend__*
imports:
- ${PLUGIN_ROOT}/templates/shared/bkend-patterns.md
---
# bkend.ai Quick Start Guide
## What is bkend.ai
MCP-based BaaS platform providing Database, Authentication, and Storage services.
Manage backend via natural language from AI tools (Antigravity Platform, Cursor).
## Resource Hierarchy
```
Organization (team/billing) -> Project (service unit) -> Environment (dev/staging/prod, data isolation)
```
## Tenant vs User
- **Tenant**: Service builder (OAuth 2.1 auth, MCP/Management API access)
- **User**: App end-user (JWT auth, Service API access)
- One person can have both roles
## MCP Setup (Antigravity Platform)
### Quick Setup (One Command)
```bash
ai-agent mcp add bkend --transport http https://api.bkend.ai/mcp
```
### Step-by-Step Guide
1. **Prerequisites**: bkend.ai account (signup at https://console.bkend.ai)
2. **Run setup command**: `ai-agent mcp add bkend --transport http https://api.bkend.ai/mcp`
3. **OAuth authentication**: Browser auto-opens for OAuth 2.1 + PKCE auth (no API key needed)
4. **Verify connection**: Ask "Show my connected bkend projects" or use `get_context` MCP tool
5. **Create .mcp.json** (optional, for team sharing):
```json
{
"mcpServers": {
"bkend": {
"type": "http",
"url": "https://api.bkend.ai/mcp"
}
}
}
```
### Troubleshooting MCP Connection
| Problem | Solution |
|---------|----------|
| OAuth popup not appearing | Check browser popup blocker |
| MCP tools not visible | Run `ai-agent mcp list` to verify, re-add if needed |
| Connection lost | Re-authenticate (automatic on next MCP call) |
| Wrong project/env | Use `get_context` to check current session |
## MCP Fixed Tools
| Tool | Purpose |
|------|---------|
| `get_context` | Session context (org/project/env, API endpoint) |
| `search_docs` | Search bkend documentation |
| `get_operation_schema` | Get tool input/output schema |
## Searchable Guides (via search_docs)
| Doc ID | Content |
|--------|---------|
| `1_concepts` | BSON schema, permissions, hierarchy |
| `2_tutorial` | Project~table creation tutorial |
## MCP Project Management Tools
| Tool | Purpose | Key Parameters |
|------|---------|----------------|
| `backend_org_list` | List organizations | None |
| `backend_project_list` | List projects | organizationId |
| `backend_project_get` | Get project detail | organizationId, projectId |
| `backend_project_create` | Create project | organizationId, name, description? |
| `backend_project_update` | Update project | organizationId, projectId, name?, description? |
| `backend_project_delete` | Delete project (irreversible!) | organizationId, projectId |
| `backend_env_list` | List environments | organizationId, projectId |
| `backend_env_get` | Get environment detail | organizationId, projectId, environmentId |
| `backend_env_create` | Create environment | organizationId, projectId, name |
## MCP Resources (Read-Only)
Lightweight, cached (60s TTL) read-only queries via bkend:// URI:
| URI | Description |
|-----|-------------|
| `bkend://orgs` | Organization list |
| `bkend://orgs/{orgId}/projects` | Project list |
| `bkend://orgs/{orgId}/projects/{pId}/environments` | Environment list |
| `bkend://orgs/{orgId}/projects/{pId}/environments/{eId}/tables` | Table list with schema |
**Tip**: Prefer Resources over Tools for listing operations (lighter, cached).
## First Project Checklist
1. Sign up at bkend.ai -> Create Organization
2. Create Project -> dev environment auto-created
3. Connect MCP -> `ai-agent mcp add bkend`
4. Create first table -> "Create a users table"
5. Start data operations -> CRUD via natural language
## Console URL
```
https://console.bkend.ai
```
## Next Steps
- Database operations: refer to bkend-data skill
- Authentication: refer to bkend-auth skill
- File storage: refer to bkend-storage skill
- Practical tutorials: refer to bkend-cookbook skill
## Official Documentation (Live Reference)
For the latest bkend documentation, use WebFetch:
- Quick Start: https://raw.githubusercontent.com/popup-studio-ai/bkend-docs/main/en/getting-started/02-quick-start.md
- Core Concepts: https://raw.githubusercontent.com/popup-studio-ai/bkend-docs/main/en/getting-started/03-core-concepts.md
- Antigravity Platform Setup: https://raw.githubusercontent.com/popup-studio-ai/bkend-docs/main/en/ai-tools/04-ai-agent-code-setup.md
- MCP Overview: https://raw.githubusercontent.com/popup-studio-ai/bkend-docs/main/en/mcp/01-overview.md
- Full TOC: https://raw.githubusercontent.com/popup-studio-ai/bkend-docs/main/SUMMARY.md
@@ -0,0 +1,116 @@
---
name: bkend-storage
classification: capability
classification-reason: Pattern guidance may overlap with model's built-in knowledge as it improves
deprecation-risk: medium
description: |
bkend.ai file storage — upload (presigned URL), download (CDN), visibility levels, buckets.
Triggers: bkend file, upload, download, presigned URL, storage, 파일 업로드, 스토리지.
user-invocable: false
agent: hmcmkit:bkend-expert
allowed-tools:
- Read
- Write
- Edit
- Glob
- Grep
- Bash
- mcp__bkend__*
imports:
- ${PLUGIN_ROOT}/templates/shared/bkend-patterns.md
---
# bkend.ai Storage Guide
## Upload Methods
| Method | Use Case | Process |
|--------|----------|---------|
| Single | Normal files | Presigned URL -> PUT upload -> Register metadata |
| Multiple | Multiple files | Repeat single upload |
| Multipart | Large files | Initialize -> Part URLs -> Complete |
## Presigned URL
- Validity: 15 minutes
- PUT method with file binary
- Content-Type header required
## File Visibility (4 levels)
| Level | Access | URL Type |
|-------|--------|----------|
| public | Anyone | CDN URL (no expiry) |
| private | Owner only | Presigned URL (1 hour) |
| protected | Authenticated users | Presigned URL (1 hour) |
| shared | Specified targets | Presigned URL (1 hour) |
## Size Limits
| Category | Max Size |
|----------|----------|
| Images | 10 MB |
| Videos | 100 MB |
| Documents | 20 MB |
## Storage Categories
images, documents, media, attachments
## MCP Storage Workflow
bkend MCP does NOT have dedicated storage tools. Use this workflow:
1. **Search docs**: `search_docs` with query "file upload presigned url"
2. **Get examples**: `search_docs` with query "file upload code examples"
3. **Generate code**: AI generates REST API code for file operations
### Searchable Storage Docs
| Doc ID | Content |
|--------|---------|
| `7_code_examples_data` | CRUD + file upload code examples |
## REST Storage API
| Method | Endpoint | Description |
|--------|----------|-------------|
| POST | /v1/files/presigned-url | Generate presigned URL |
| POST | /v1/files | Register metadata (complete upload) |
| GET | /v1/files | File list |
| GET | /v1/files/:fileId | File detail |
| PATCH | /v1/files/:fileId | Update metadata |
| DELETE | /v1/files/:fileId | Delete file |
| POST | /v1/files/:fileId/download-url | Generate download URL |
## Multipart Upload (Large Files)
| Method | Endpoint | Description |
|--------|----------|-------------|
| POST | /v1/files/multipart/init | Initialize multipart upload |
| POST | /v1/files/multipart/presigned-url | Get part upload URL |
| POST | /v1/files/multipart/complete | Complete multipart upload |
| POST | /v1/files/multipart/abort | Abort multipart upload |
## Upload Flow (Single File)
```
1. POST /v1/files/presigned-url -> { url, fileId }
2. PUT {url} with file binary + Content-Type header
3. POST /v1/files with { fileId, filename, contentType, size, visibility }
```
## Multipart Upload Flow (Large File)
```
1. POST /v1/files/multipart/init -> { uploadId }
2. POST /v1/files/multipart/presigned-url -> [{ partNumber, url }]
3. PUT each part URL with file chunk
4. POST /v1/files/multipart/complete -> { file }
```
## Official Documentation (Live Reference)
For the latest storage documentation, use WebFetch:
- Storage Overview: https://raw.githubusercontent.com/popup-studio-ai/bkend-docs/main/en/storage/01-overview.md
- MCP Storage Guide: https://raw.githubusercontent.com/popup-studio-ai/bkend-docs/main/en/mcp/07-storage-tools.md
- Full TOC: https://raw.githubusercontent.com/popup-studio-ai/bkend-docs/main/SUMMARY.md
+195
View File
@@ -0,0 +1,195 @@
---
name: btw
classification: workflow
classification-reason: "Manages /btw command lifecycle: record, list, analyze, promote, stats. User-driven workflow with CRUD on btw-suggestions.json"
deprecation-risk: none
description: |
By-The-Way: 작업 중 개선 제안을 즉시 수집하고 관리하는 스킬.
Triggers: /btw, /btw list, /btw analyze, /btw promote, /btw stats
Keywords: btw, 개선, 제안, suggestion, improve, idea, feedback
argument-hint: "/btw {suggestion} | /btw list | /btw analyze | /btw promote {id} | /btw stats"
user-invocable: true
allowed-tools:
- Read
- Write
- Edit
- Glob
- Grep
- Bash
---
# /btw - By-The-Way Suggestion Collector
작업 중 "이거 스킬로 만들면 좋겠다", "이 패턴 자동화하면 좋겠다" 등의
개선 제안을 즉시 기록하고 관리하는 도구.
## Commands
### `/btw {suggestion}` - Record a suggestion
1. Read `.hmcmkit/btw-suggestions.json` (create if not exists)
2. Generate next ID: `btw-NNN` (zero-padded, sequential)
3. Create suggestion entry:
```json
{
"id": "btw-001",
"timestamp": "ISO-8601",
"suggestion": "{user input}",
"context": {
"file": "{current working file if identifiable}",
"pdcaPhase": "{current PDCA phase from .hmcmkit-memory.json or null}",
"feature": "{current feature or null}"
},
"category": "auto-detect",
"status": "pending",
"promotedTo": null,
"priority": null,
"teamContext": {
"isTeamSession": false,
"phase": "{PDCA phase or null}",
"role": "{teammate role that discovered this, or 'user'}",
"pattern": "{orchestration pattern or null}"
}
}
```
4. Auto-detect category from suggestion text:
- `skill-request`: mentions "skill", "스킬", "자동화", "automate"
- `bug-pattern`: mentions "bug", "버그", "오류", "error", "fix"
- `improvement`: mentions "개선", "improve", "better", "refactor"
- `documentation`: mentions "문서", "doc", "설명", "explain"
- `general`: default
5. Update `stats.total` count
6. Respond: "Recorded btw-{NNN}: {truncated suggestion}. Use `/btw list` to view all."
### `/btw list` - List all suggestions
1. Read `.hmcmkit/btw-suggestions.json`
2. Display table:
```
ID | Status | Category | Suggestion (truncated)
---------|----------|----------------|----------------------
btw-001 | pending | skill-request | @Flow 모델에서 옵션 목록을 자동...
btw-002 | promoted | improvement | DataProxy 패턴에 검증 로직을...
```
3. Show summary: Total: N | Pending: N | Promoted: N | Dismissed: N
### `/btw analyze` - Analyze suggestions for skill candidates
1. Read all pending suggestions from `.hmcmkit/btw-suggestions.json`
2. Group by category and find patterns:
- Cluster similar suggestions (keyword overlap)
- Count frequency of similar topics
- Identify suggestions that map to existing hmcmkit skills vs. new skill needs
3. For each skill candidate:
- Estimate skill classification: workflow vs capability
- Suggest skill name and description
- Reference source suggestion IDs
4. Output analysis:
```
Skill Candidates from /btw Analysis
=====================================
1. [NEW SKILL] hunikflow-validation (capability)
Based on: btw-001, btw-005, btw-008
Frequency: 3 mentions
Description: Validation pattern guide for @Flow entities
2. [EXISTING SKILL ENHANCEMENT] code-review
Based on: btw-003
Suggestion: Add DataProxy-specific review rules
```
5. Save analysis timestamp to `stats.lastAnalyzed`
### `/btw promote {id}` - Promote suggestion to skill creation
1. Find suggestion by ID in `.hmcmkit/btw-suggestions.json`
2. Validate status is "pending" (cannot promote already promoted/dismissed)
3. Update suggestion:
- `status`: "promoted"
- `promotedTo`: skill name (derived from suggestion)
4. Trigger skill-create workflow with context from the suggestion:
- Pass suggestion text as skill description seed
- Pass context (file, feature) as project context
5. Respond: "Promoted btw-{id} -> skill-create pipeline. Run `/skill-create` to continue."
### `/btw stats` - Show statistics
1. Read `.hmcmkit/btw-suggestions.json`
2. Calculate and display:
```
/btw Statistics
===============
Total suggestions: 12
By status: pending=8, promoted=3, dismissed=1
By category: skill-request=5, improvement=4, bug-pattern=2, general=1
Promotion rate: 25.0%
Last analyzed: 2026-03-13T10:00:00Z
Top keywords: @Flow(3), DataProxy(2), validation(2)
```
## Data File: `.hmcmkit/btw-suggestions.json`
Initialize with this structure if file does not exist:
```json
{
"version": "1.0",
"suggestions": [],
"stats": {
"total": 0,
"promoted": 0,
"dismissed": 0,
"lastAnalyzed": null
}
}
```
## Category Auto-Detection Rules
| Pattern | Category |
|---------|----------|
| skill, 스킬, automate, 자동화, command, 명령 | skill-request |
| bug, 버그, error, 오류, fix, 수정 | bug-pattern |
| improve, 개선, better, refactor, 리팩토링, optimize | improvement |
| doc, 문서, explain, 설명, readme, guide | documentation |
| (default) | general |
## Integration Points
- **PDCA Context**: Reads `.hmcmkit-memory.json` for current phase/feature
- **skill-create**: `/btw promote` triggers skill-create workflow
- **skill-needs-extractor**: `/btw analyze` results feed into gap analysis
- **CTO Team**: Phase transition triggers btw summary (see below)
## CTO Team Integration
When `/btw` is used during a CTO Team session (`/pdca team`):
### Auto-Detection
- Check if team session is active via `.hmcmkit/runtime/agent-state.json`
- If active: set `teamContext.isTeamSession = true` and populate phase/role/pattern
- If not active: set `teamContext.isTeamSession = false` (default behavior)
### Phase Transition Hook
CTO Lead automatically reads btw-suggestions.json at every phase transition:
- **0 pending**: Silent skip (no output, no turns spent)
- **1+ pending**: Brief summary (top 3, category counts) in 1-2 turns
- CTO does NOT auto-promote — user decides via `/btw promote {id}`
### Session End
`cto-stop.js` hook outputs btw stats at session end:
- Total suggestions collected during session
- Category breakdown
- Promotion rate
### teamContext Field
Added to each suggestion entry when recorded during a team session:
```json
"teamContext": {
"isTeamSession": true,
"phase": "do",
"role": "user",
"pattern": "swarm"
}
```
This enables `/btw analyze` to group suggestions by PDCA phase and identify phase-specific patterns.
@@ -0,0 +1,131 @@
---
name: code-review
classification: workflow
classification-reason: Process automation persists regardless of model advancement
deprecation-risk: none
description: |
Code review — analyze quality, detect bugs, ensure best practices with actionable feedback.
Triggers: code review, quality check, bug detection, 코드 리뷰, 품질 검사.
argument-hint: "[file|directory|pr]"
user-invocable: true
agent: hmcmkit:code-analyzer
allowed-tools:
- Read
- Glob
- Grep
- LSP
- Task
- Bash
imports:
- ${PLUGIN_ROOT}/templates/pipeline/phase-8-review.template.md
next-skill: null
pdca-phase: check
task-template: "[Code-Review] {feature}"
hooks:
Stop:
- type: command
command: "node ${HMCMKIT_PLUGIN_ROOT}/scripts/code-review-stop.js"
timeout: 10000
---
# Code Review Skill
> Skill for code quality analysis and review
## Arguments
| Argument | Description | Example |
|----------|-------------|---------|
| `[file]` | Review specific file | `/code-review src/lib/auth.ts` |
| `[directory]` | Review entire directory | `/code-review src/features/` |
| `[pr]` | PR review (PR number) | `/code-review pr 123` |
## Review Categories
### 1. Code Quality
- Duplicate code detection
- Function/file complexity analysis
- Naming convention check
- Type safety verification
### 2. Bug Detection
- Potential bug pattern detection
- Null/undefined handling check
- Error handling inspection
- Boundary condition verification
### 3. Security
- XSS/CSRF vulnerability check
- SQL Injection pattern detection
- Sensitive information exposure check
- Authentication/authorization logic review
### 4. Performance
- N+1 query pattern detection
- Unnecessary re-render check
- Memory leak pattern detection
- Optimization opportunity identification
## Review Output Format
```
## Code Review Report
### Summary
- Files reviewed: N
- Issues found: N (Critical: N, Major: N, Minor: N)
- Score: N/100
### Critical Issues
1. [FILE:LINE] Issue description
Suggestion: ...
### Major Issues
...
### Minor Issues
...
### Recommendations
- ...
```
## Agent Integration
This Skill calls the `code-analyzer` Agent for in-depth code analysis.
| Agent | Role |
|-------|------|
| code-analyzer | Code quality, security, performance analysis |
## Usage Examples
```bash
# Review specific file
/code-review src/lib/auth.ts
# Review entire directory
/code-review src/features/user/
# PR review
/code-review pr 42
# Review current changes
/code-review staged
```
## Confidence-Based Filtering
code-analyzer Agent uses confidence-based filtering:
| Confidence | Display | Description |
|------------|---------|-------------|
| High (90%+) | Always shown | Definite issues |
| Medium (70-89%) | Selectively shown | Possible issues |
| Low (<70%) | Hidden | Uncertain suggestions |
## PDCA Integration
- **Phase**: Check (Quality verification)
- **Trigger**: Auto-suggested after implementation
- **Output**: docs/03-analysis/code-review-{date}.md
+192
View File
@@ -0,0 +1,192 @@
---
name: control
classification: workflow
classification-reason: Automation control persists regardless of model advancement
deprecation-risk: none
description: |
Control hmcmkit automation level (L0-L4), view trust score, and manage guardrails.
Triggers: control, automation level, trust score, guardrail, 자동화 레벨, 제어.
argument-hint: "[status|level|pause|resume|trust]"
user-invocable: true
allowed-tools:
- Read
- Write
- Glob
- Grep
- Bash
- AskUserQuestion
imports: []
next-skill: null
pdca-phase: null
task-template: "[Control] {action}"
---
# Control Skill
> User-invocable skill for managing hmcmkit automation level and system status.
## Arguments
| Argument | Description | Example |
|----------|-------------|---------|
| (none) | Show current status (same as `status`) | `/control` |
| `status` | Show automation level, trust score, guardrails | `/control status` |
| `level <0-4>` | Set automation level manually | `/control level 2` |
| `pause` | Pause all automation (equivalent to L0) | `/control pause` |
| `resume` | Resume to previous automation level | `/control resume` |
| `trust` | Show trust score details and history | `/control trust` |
## Automation Levels
| Level | Name | Description | Approval Gates |
|:-----:|------|-------------|----------------|
| L0 | Manual | All actions require explicit user approval | Every phase transition |
| L1 | Guided | Suggestions provided, user confirms each step | Every phase transition |
| L2 | Semi-Auto | Routine transitions auto, key decisions gated | do->check, check->report, report->archive |
| L3 | Auto | Most transitions auto, only destructive ops gated | report->archive |
| L4 | Full-Auto | Fully automated PDCA cycle, minimal intervention | Initial feature approval only |
## Action Details
### status (Default)
Display the current automation control state.
1. Read runtime control state from `.hmcmkit/runtime/control-state.json`
2. Read trust score from `.hmcmkit/state/trust-score.json`
3. Read active guardrails from `lib/control/` configuration
4. Display formatted status panel
**Output Format**:
```
--- hmcmkit Control Panel ----------------------------
Automation Level : L2 (Semi-Auto)
Trust Score : 72/100
Active Guardrails: 8/8
Paused : No
Features Active : 2/3
---------------------------------------------------
Guardrails:
[ON] Destructive operation detection
[ON] Blast radius limiter (max 10 files)
[ON] Loop breaker (max 5 iterations)
[ON] Checkpoint auto-creation
[ON] Permission escalation gate
[ON] Stale feature timeout (7d)
[ON] Context overflow protection
[ON] Concurrent write lock
---------------------------------------------------
```
### level <0-4>
Set the automation level manually.
1. Validate input is a number 0-4
2. Read current level from `.hmcmkit/runtime/control-state.json`
3. If escalating (going higher), warn user about reduced oversight
4. If de-escalating, apply immediately without confirmation
5. Update `.hmcmkit/runtime/control-state.json` with new level
6. Write audit log entry via `lib/audit/audit-logger.js`
7. Display confirmation with new level details
**Escalation Rule**: Level increases require explicit confirmation via AskUserQuestion.
Level decreases are immediate (safe direction).
**Level Mapping to Automation**:
| Level | automationLevel | Description |
|:-----:|:---------------:|-------------|
| L0 | manual | All manual |
| L1 | guide | Guided suggestions |
| L2 | semi-auto | Semi-automatic (default) |
| L3 | auto | Mostly automatic |
| L4 | full-auto | Fully automatic |
### pause
Pause all automation immediately.
1. Save current level to `.hmcmkit/runtime/control-state.json` as `previousLevel`
2. Set level to L0 (Manual)
3. Set `paused: true` flag
4. Write audit log: `automation_paused`
5. Display confirmation: "Automation paused. All operations require manual approval."
### resume
Resume automation to the previous level before pause.
1. Read `previousLevel` from `.hmcmkit/runtime/control-state.json`
2. If not paused, display: "Automation is not paused."
3. Restore level to `previousLevel`
4. Clear `paused` flag
5. Write audit log: `automation_resumed`
6. Display confirmation with restored level
### trust
Show trust score details and contributing factors.
1. Read trust score from `.hmcmkit/state/trust-score.json`
2. Calculate score breakdown:
- PDCA completion rate (0-25 points)
- Match rate average (0-25 points)
- Error recovery rate (0-20 points)
- Session stability (0-15 points)
- User override frequency (0-15 points, inverse)
3. Display detailed breakdown
**Output Format**:
```
--- Trust Score Details ---------------------------
Overall Score: 72/100
Breakdown:
PDCA Completion Rate : 18/25 (72% cycles completed)
Match Rate Average : 22/25 (88% average)
Error Recovery Rate : 14/20 (70% recovered)
Session Stability : 12/15 (80% stable)
User Override Freq : 6/15 (40% override rate)
---------------------------------------------------
Level Recommendation: L2 (Semi-Auto)
Score 0-30 -> L0 (Manual)
Score 31-50 -> L1 (Guided)
Score 51-70 -> L2 (Semi-Auto)
Score 71-85 -> L3 (Auto)
Score 86+ -> L4 (Full-Auto)
---------------------------------------------------
```
## State Files
| File | Purpose |
|------|---------|
| `.hmcmkit/runtime/control-state.json` | Runtime control state (level, paused, previousLevel) |
| `.hmcmkit/state/trust-score.json` | Trust score and contributing metrics |
## Module Dependencies
| Module | Function | Usage |
|--------|----------|-------|
| `lib/control/automation-controller.js` | `getLevel()`, `setLevel()` | Read/write automation level |
| `lib/control/automation-controller.js` | `pause()`, `resume()` | Pause/resume automation |
| `lib/audit/audit-logger.js` | `writeAuditLog()` | Record control changes |
## Usage Examples
```bash
# Check current status
/control
# Set to Semi-Auto
/control level 2
# Pause all automation
/control pause
# Resume previous level
/control resume
# View trust score
/control trust
```
+108
View File
@@ -0,0 +1,108 @@
---
name: deploy
description: Deploy feature to target environment (dev/staging/prod) with level-based strategy
version: 3.0.0
category: workflow
agent: hmcmkit:infra-architect
pdca_phase: do
triggers:
- deploy
- /pdca deploy
- 배포
- デプロイ
- 部署
---
# Deploy Skill
> Deploy code to target environment with automated CI/CD pipeline generation.
> Strategy adapts based on project level (Starter/Dynamic/Enterprise).
## Usage
```bash
/pdca deploy {feature} # Deploy to default env (dev)
/pdca deploy {feature} --env dev # Deploy to DEV
/pdca deploy {feature} --env staging # Deploy to STAGING (requires DEV 90%+)
/pdca deploy {feature} --env prod # Deploy to PROD (requires STAGING 95%+ & Human Approval)
/pdca deploy status # Show deploy state machine status
```
## Level-Based Strategy
| Level | Strategy | Environments | Tools |
|-------|----------|-------------|-------|
| **Starter** | Guide only | dev | GitHub Pages, Netlify, Vercel |
| **Dynamic** | Docker + GHA | dev, staging | Docker Compose, GitHub Actions |
| **Enterprise** | 6-Layer CI/CD | dev, staging, prod | Terraform, EKS, ArgoCD, Canary |
## Deploy Flow
```
/pdca deploy feature --env dev
│
▼
① Level Detection (Starter/Dynamic/Enterprise)
│
▼
② Generate CI/CD Files (if not exist)
├── .github/workflows/deploy.yml
├── Dockerfile (Dynamic/Enterprise)
├── docker-compose.yml (DEV)
├── k8s/ manifests (Enterprise)
└── terraform/ (Enterprise)
│
▼
③ Deploy State Machine Transition
init → dev → verify(90%) → staging → verify(95%) → approval → prod(canary) → complete
│
▼
④ Return to PDCA Check phase
```
## Environment Promotion Gates
| Gate | Condition | Action |
|------|-----------|--------|
| DEV → STAGING | Match Rate ≥ 90% | Auto-promote |
| STAGING → PROD | Match Rate ≥ 95% + Human Approval | Require `/pdca deploy --env prod` |
| PROD Canary | Error rate < threshold | Auto-rollout 10% → 25% → 50% → 100% |
## Generated Files
### Starter
- Deployment guide document only
### Dynamic
- `.github/workflows/deploy.yml` — Docker build + push + deploy
- `Dockerfile` — Multi-stage build
- `docker-compose.yml` — DEV environment
- `.env.example` — Environment variables template
### Enterprise (additional)
- `infra/terraform/` — AWS infrastructure
- `infra/k8s/` — Kubernetes manifests
- `infra/argocd/` — ArgoCD Application + Helm
- Security scan steps in CI/CD
## Rollback
```bash
/pdca deploy rollback {feature} # Rollback current deploy
/pdca deploy rollback {feature} --env prod # Rollback specific environment
```
Rollback triggers:
- Manual: `/pdca deploy rollback` command
- Auto: Error rate spike detected by ops-metrics (> 5% threshold)
- Canary fail: Argo Rollouts auto-rollback on metrics failure
Rollback resets deploy state machine to `idle` and restores previous version.
## Hook Events
| Event | When | Hook |
|-------|------|------|
| `deploy-start` | Deploy initiated | Pre-validation |
| `deploy-complete` | Deploy successful | Post-notification |
| `deploy-failed` | Deploy failed | Error handling + rollback suggestion |
@@ -0,0 +1,602 @@
---
name: desktop-app
classification: capability
classification-reason: Specialized domain knowledge with limited model overlap
deprecation-risk: low
description: |
Desktop app development guide — Electron and Tauri for cross-platform apps.
Triggers: desktop app, Electron, Tauri, mac app, windows app, 데스크톱 앱.
agent: hmcmkit:pipeline-guide
allowed-tools:
- Read
- Write
- Edit
- Glob
- Grep
- Bash
- WebSearch
user-invocable: true
---
# Desktop App Development Expertise
## Overview
A guide for developing desktop apps using web technologies (HTML, CSS, JavaScript).
Support Windows, macOS, and Linux simultaneously with a single codebase.
---
## Framework Selection Guide
### Framework Selection by Tier (v1.3.0)
| Framework | Tier | Recommendation | Use Case |
|-----------|------|----------------|----------|
| **Tauri** | Tier 2 | ⭐ Primary | Lightweight (3MB), Rust security |
| **Electron** | Tier 3 | Supported | Mature ecosystem, VS Code-like apps |
> **AI-Native Recommendation**: Tauri
> - 35% YoY growth
> - 20-40MB memory vs Electron's 200-400MB
> - Mobile support (iOS/Android) via Tauri 2.0
> - Rust backend = memory safety
> **Ecosystem Recommendation**: Electron
> - Mature tooling
> - Node.js integration
> - Proven at scale (VS Code, Slack)
### Level-wise Recommendations
```
Starter → Tauri (v2) [Tier 2]
- Simpler setup than Electron
- Smaller output bundles (~3MB vs ~150MB)
Dynamic → Tauri + auto-update [Tier 2]
- Includes server integration, auto-update
- Lower memory footprint
Enterprise → Tauri [Tier 2] or Electron [Tier 3]
- Tauri for performance and security
- Electron for complex Node.js integration
```
---
## Electron Guide
### Project Creation
```bash
# Create with electron-vite (recommended)
npm create @electron-vite/create my-electron-app
cd my-electron-app
# Install dependencies
npm install
# Start development server
npm run dev
```
### Folder Structure
```
my-electron-app/
├── src/
│ ├── main/ # Main process (Node.js)
│ │ └── index.ts # App entry point, window management
│ ├── preload/ # Preload script
│ │ └── index.ts # Renderer↔Main bridge
│ └── renderer/ # Renderer process (Web)
│ ├── src/ # React/Vue code
│ └── index.html # HTML entry point
├── resources/ # App icons, assets
├── electron.vite.config.ts # Build configuration
├── electron-builder.yml # Deployment configuration
└── package.json
```
### Core Concept: Process Separation
```
┌─────────────────────────────────────────────────────┐
│ Electron App │
├─────────────────────────────────────────────────────┤
│ Main Process (Node.js) │
│ - System API access (files, network, etc.) │
│ - Window creation/management │
│ - Menu, tray management │
├─────────────────────────────────────────────────────┤
│ Preload Script (Bridge) │
│ - Safe main↔renderer communication │
│ - Expose only specific APIs │
├─────────────────────────────────────────────────────┤
│ Renderer Process (Chromium) │
│ - Web UI (React, Vue, etc.) │
│ - DOM access │
│ - No direct Node.js API access (security) │
└─────────────────────────────────────────────────────┘
```
### Main Process
```typescript
// src/main/index.ts
import { app, BrowserWindow, ipcMain } from 'electron';
import { join } from 'path';
let mainWindow: BrowserWindow | null = null;
function createWindow() {
mainWindow = new BrowserWindow({
width: 1200,
height: 800,
webPreferences: {
preload: join(__dirname, '../preload/index.js'),
sandbox: false,
},
});
// Dev mode: Load Vite server
if (process.env.NODE_ENV === 'development') {
mainWindow.loadURL('http://localhost:5173');
mainWindow.webContents.openDevTools();
} else {
// Production: Load built files
mainWindow.loadFile(join(__dirname, '../renderer/index.html'));
}
}
app.whenReady().then(createWindow);
app.on('window-all-closed', () => {
if (process.platform !== 'darwin') {
app.quit();
}
});
// IPC: Handle requests from renderer
ipcMain.handle('read-file', async (event, filePath) => {
const fs = await import('fs/promises');
return fs.readFile(filePath, 'utf-8');
});
```
### Preload Script
```typescript
// src/preload/index.ts
import { contextBridge, ipcRenderer } from 'electron';
// APIs to safely expose to renderer
contextBridge.exposeInMainWorld('electronAPI', {
// Read file
readFile: (filePath: string) => ipcRenderer.invoke('read-file', filePath),
// Save file dialog
saveFile: (content: string) => ipcRenderer.invoke('save-file', content),
// App version
getVersion: () => process.env.npm_package_version,
// Platform
platform: process.platform,
});
// Type definitions (for use in renderer)
declare global {
interface Window {
electronAPI: {
readFile: (path: string) => Promise<string>;
saveFile: (content: string) => Promise<void>;
getVersion: () => string;
platform: NodeJS.Platform;
};
}
}
```
### Renderer Process
```typescript
// src/renderer/src/App.tsx
import { useState } from 'react';
function App() {
const [content, setContent] = useState('');
const handleOpenFile = async () => {
const result = await window.electronAPI.readFile('/path/to/file.txt');
setContent(result);
};
return (
<div className="app">
<h1>My Electron App</h1>
<p>Platform: {window.electronAPI.platform}</p>
<button onClick={handleOpenFile}>Open File</button>
<pre>{content}</pre>
</div>
);
}
export default App;
```
### Creating Menus
```typescript
// src/main/menu.ts
import { Menu, app, shell } from 'electron';
const template: Electron.MenuItemConstructorOptions[] = [
{
label: 'File',
submenu: [
{ label: 'New File', accelerator: 'CmdOrCtrl+N', click: () => {} },
{ label: 'Open', accelerator: 'CmdOrCtrl+O', click: () => {} },
{ type: 'separator' },
{ label: 'Quit', role: 'quit' },
],
},
{
label: 'Edit',
submenu: [
{ label: 'Undo', role: 'undo' },
{ label: 'Redo', role: 'redo' },
{ type: 'separator' },
{ label: 'Cut', role: 'cut' },
{ label: 'Copy', role: 'copy' },
{ label: 'Paste', role: 'paste' },
],
},
{
label: 'Help',
submenu: [
{
label: 'Documentation',
click: () => shell.openExternal('https://docs.example.com'),
},
],
},
];
// Add macOS app menu
if (process.platform === 'darwin') {
template.unshift({
label: app.getName(),
submenu: [
{ role: 'about' },
{ type: 'separator' },
{ role: 'services' },
{ type: 'separator' },
{ role: 'hide' },
{ role: 'unhide' },
{ type: 'separator' },
{ role: 'quit' },
],
});
}
export const menu = Menu.buildFromTemplate(template);
```
### System Tray
```typescript
// src/main/tray.ts
import { Tray, Menu, nativeImage } from 'electron';
import { join } from 'path';
let tray: Tray | null = null;
export function createTray() {
const icon = nativeImage.createFromPath(join(__dirname, '../../resources/icon.png'));
tray = new Tray(icon.resize({ width: 16, height: 16 }));
const contextMenu = Menu.buildFromTemplate([
{ label: 'Open', click: () => {} },
{ type: 'separator' },
{ label: 'Quit', role: 'quit' },
]);
tray.setToolTip('My App');
tray.setContextMenu(contextMenu);
}
```
---
## Tauri Guide
### Project Creation
```bash
# Prerequisite: Rust installation required
# Install from https://rustup.rs
# Create Tauri project
npm create tauri-app my-tauri-app
cd my-tauri-app
# Install dependencies
npm install
# Start development server
npm run tauri dev
```
### Folder Structure
```
my-tauri-app/
├── src/ # Frontend (React, Vue, etc.)
│ ├── App.tsx
│ └── main.tsx
├── src-tauri/ # Tauri backend (Rust)
│ ├── src/
│ │ ├── main.rs # Main entry point
│ │ └── lib.rs # Command definitions
│ ├── tauri.conf.json # Tauri configuration
│ └── Cargo.toml # Rust dependencies
├── public/
└── package.json
```
### Command Definition (Rust)
```rust
// src-tauri/src/lib.rs
use tauri::command;
#[command]
fn greet(name: &str) -> String {
format!("Hello, {}!", name)
}
#[command]
async fn read_file(path: &str) -> Result<String, String> {
std::fs::read_to_string(path)
.map_err(|e| e.to_string())
}
#[cfg_attr(mobile, tauri::mobile_entry_point)]
pub fn run() {
tauri::Builder::default()
.invoke_handler(tauri::generate_handler![greet, read_file])
.run(tauri::generate_context!())
.expect("error while running tauri application");
}
```
### Calling from Frontend
```typescript
// src/App.tsx
import { invoke } from '@tauri-apps/api/core';
function App() {
const [greeting, setGreeting] = useState('');
const handleGreet = async () => {
const result = await invoke('greet', { name: 'World' });
setGreeting(result as string);
};
const handleReadFile = async () => {
try {
const content = await invoke('read_file', { path: '/path/to/file.txt' });
console.log(content);
} catch (error) {
console.error(error);
}
};
return (
<div>
<button onClick={handleGreet}>Greet</button>
<p>{greeting}</p>
</div>
);
}
```
---
## Web vs Desktop Differences
### File System Access
```typescript
// Web: Not possible (user must select directly)
// Desktop: Free access
// Electron
const fs = require('fs');
fs.writeFileSync('/path/to/file.txt', 'content');
// Tauri
await invoke('write_file', { path: '/path/to/file.txt', content: 'content' });
```
### System Integration
```
Things impossible on web but possible on desktop:
- System tray icon
- Global shortcuts
- Native notifications
- Drag and drop (file path access)
- Full clipboard control
- Native menus
```
### Offline Support
```
Web: Requires Service Worker, limited
Desktop: Works offline by default
⚠️ Server integration features must handle offline!
```
---
## Build & Deployment
### Electron Build
```yaml
# electron-builder.yml
appId: com.example.myapp
productName: My App
directories:
buildResources: resources
files:
- '!**/.vscode/*'
- '!src/*'
- '!electron.vite.config.*'
mac:
artifactName: ${name}-${version}-${arch}.${ext}
target:
- dmg
- zip
icon: resources/icon.icns
win:
artifactName: ${name}-${version}-${arch}.${ext}
target:
- nsis
icon: resources/icon.ico
linux:
target:
- AppImage
- deb
```
```bash
# Execute build
npm run build:mac
npm run build:win
npm run build:linux
```
### Auto-update
```typescript
// src/main/updater.ts
import { autoUpdater } from 'electron-updater';
autoUpdater.checkForUpdatesAndNotify();
autoUpdater.on('update-available', () => {
// Notify update available
});
autoUpdater.on('update-downloaded', () => {
// Restart to apply update
autoUpdater.quitAndInstall();
});
```
### Tauri Build
```bash
# Build for current platform
npm run tauri build
# Output locations
# macOS: src-tauri/target/release/bundle/dmg/
# Windows: src-tauri/target/release/bundle/msi/
# Linux: src-tauri/target/release/bundle/appimage/
```
---
## Desktop PDCA Checklist
### Phase 1: Schema
```
□ Decide local data storage method (SQLite, JSON file, etc.)
□ Decide if cloud sync is needed
```
### Phase 3: Mockup
```
□ Consider platform-specific UI guidelines (macOS, Windows)
□ Plan keyboard shortcuts
□ Design menu structure
```
### Phase 6: UI
```
□ Support dark/light mode
□ Handle window resizing
□ Handle platform-specific UI differences (window control positions, etc.)
```
### Phase 7: Security
```
□ Don't expose Node.js APIs directly (use contextBridge)
□ Security handling when loading external URLs
□ Encrypt sensitive data storage
```
### Phase 9: Deployment
```
□ Code signing (macOS Notarization, Windows Signing)
□ Set up auto-update
□ App Store submission (if needed)
```
---
## Useful Libraries
### Electron
| Library | Purpose |
|---------|---------|
| electron-store | Local settings/data storage |
| electron-updater | Auto-update |
| electron-log | Logging |
| better-sqlite3 | SQLite database |
### Tauri
| Library | Purpose |
|---------|---------|
| tauri-plugin-store | Settings storage |
| tauri-plugin-sql | SQLite support |
| tauri-plugin-log | Logging |
| tauri-plugin-updater | Auto-update |
---
## Requesting from AI Agent
### Project Creation
```
"Set up a [app description] app project with Electron + React.
- Use electron-vite
- Support system tray
- Set up auto-update"
```
### Feature Implementation
```
"Implement file open/save functionality.
- Use native file dialogs
- Save recent file list
- Support drag and drop"
```
### Build Configuration
```
"Create electron-builder configuration.
- macOS: DMG + notarization
- Windows: NSIS installer
- Auto-update server integration"
```
@@ -0,0 +1,124 @@
---
name: development-pipeline
classification: workflow
classification-reason: Process automation persists regardless of model advancement
deprecation-risk: none
description: |
Complete 9-phase development pipeline guide — from schema to deployment.
Triggers: development pipeline, where to start, phase, 개발 파이프라인, 순서, 시작.
agent: hmcmkit:pipeline-guide
allowed-tools:
- Read
- Write
- Glob
- Grep
- TodoWrite
user-invocable: true
# hooks: Managed by hooks/hooks.json (unified-stop.js handles development-pipeline) - GitHub #9354 workaround
---
# Development Pipeline Skill
> Complete knowledge of the 9-phase development pipeline
## When to Use
- When user says "I have little development experience"
- When using `/pipeline-*` commands
- When asked "How do I start development?", "What's the order?"
- When starting a new project from scratch
## Optional Application Principle
```
This skill is optional, not mandatory.
Activation conditions:
- When non-developers/beginner developers start development
- When user explicitly requests guidance
- When /pipeline-start command is used
Deactivation conditions:
- When experienced developers want to "proceed freely"
- For non-development AI work (documentation, analysis, etc.)
- For existing project maintenance/bug fixes
```
## 9-Phase Pipeline Overview
```
Phase 1: Schema/Terminology ──→ Define data structures and domain terms
Phase 2: Coding Convention ────→ Define code writing rules
Phase 3: Mockup Development ───→ Feature validation with HTML/CSS/JS + JSON
Phase 4: API Design/Impl ──────→ Backend API + Zero Script QA
Phase 5: Design System ────────→ Build component system
Phase 6: UI Implementation ────→ Actual UI implementation and API integration
Phase 7: SEO/Security ─────────→ Search optimization and security hardening
Phase 8: Review ───────────────→ Architecture/convention quality verification
Phase 9: Deployment ───────────→ Production deployment
```
## Relationship with PDCA (Key Concept)
```
❌ Wrong understanding: Mapping entire Pipeline to PDCA
❌ (Plan=Phase1-3, Do=Phase4-6, Check=Phase7-8, Act=Phase9)
✅ Correct understanding: Run PDCA cycle within each Phase
Phase N
├── Plan: Plan what to do in this Phase
├── Design: Detailed design
├── Do: Execute/implement
├── Check: Verify/review
└── Act: Confirm and move to next Phase
```
## Phase Application by Level
| Phase | Starter | Dynamic | Enterprise |
|-------|---------|---------|------------|
| 1. Schema/Terms | Simple | Detailed | Detailed |
| 2. Convention | Basic | Extended | Extended |
| 3. Mockup | O | O | O |
| 4. API | - | bkend.ai | Direct impl |
| 5. Design System | Optional | O | O |
| 6. UI + API | Static UI | Integration | Integration |
| 7. SEO/Security | SEO only | O | O |
| 8. Review | - | O | O |
| 9. Deployment | Static hosting | Vercel etc. | K8s |
### Starter Level Flow
```
Phase 1 → 2 → 3 → 5(optional) → 6(static) → 7(SEO) → 9
```
### Dynamic Level Flow
```
Phase 1 → 2 → 3 → 4(bkend.ai) → 5 → 6 → 7 → 8 → 9
```
### Enterprise Level Flow
```
Phase 1 → 2 → 3 → 4(direct impl) → 5 → 6 → 7 → 8 → 9
```
## Phase Deliverables Summary
| Phase | Key Deliverables |
|-------|-----------------|
| 1 | `docs/01-plan/schema.md`, `terminology.md` |
| 2 | `CONVENTIONS.md`, `docs/01-plan/naming.md` |
| 3 | `mockup/` folder, `docs/02-design/mockup-spec.md` |
| 4 | `docs/02-design/api-spec.md`, `src/api/` |
| 5 | `components/ui/`, `docs/02-design/design-system.md` |
| 6 | `src/pages/`, `src/features/` |
| 7 | `docs/02-design/seo-spec.md`, `security-spec.md` |
| 8 | `docs/03-analysis/architecture-review.md` |
| 9 | `docs/04-report/deployment-report.md` |
## Related Skills
- `phase-1-schema/` ~ `phase-9-deployment/`: Detailed guides per Phase
- `pdca-methodology/`: How to apply PDCA
- `starter/`, `dynamic/`, `enterprise/`: Level-specific knowledge
+398
View File
@@ -0,0 +1,398 @@
---
name: dynamic
classification: capability
classification-reason: Pattern guidance may overlap with model's built-in knowledge as it improves
deprecation-risk: medium
description: |
Fullstack development with bkend.ai BaaS — authentication, database, API integration.
Triggers: fullstack, BaaS, login, signup, database, web app, 풀스택, 인증, init dynamic.
argument-hint: "[init|guide|help]"
agent: hmcmkit:bkend-expert
allowed-tools:
- Read
- Write
- Edit
- Glob
- Grep
- Bash
- mcp__bkend__*
user-invocable: true
imports:
- ${PLUGIN_ROOT}/templates/design.template.md
next-skill: phase-1-schema
pdca-phase: plan
task-template: "[Init-Dynamic] {feature}"
---
# Intermediate (Dynamic) Skill
## Actions
| Action | Description | Example |
|--------|-------------|---------|
| `init` | Project initialization (/init-dynamic feature) | `/dynamic init my-saas` |
| `guide` | Display development guide | `/dynamic guide` |
| `help` | BaaS integration help | `/dynamic help` |
### init (Project Initialization)
1. Create Next.js + Tailwind project structure
2. Configure bkend.ai MCP (.mcp.json)
3. Create agents.md (Level: Dynamic specified)
4. Create docs/ folder structure
5. src/lib/bkend.ts client template
6. Initialize .hmcmkit-memory.json
### guide (Development Guide)
- bkend.ai auth/data configuration guide
- Phase 1-9 full Pipeline guide
- API integration patterns
### help (BaaS Help)
- Explain bkend.ai basic concepts
- Auth, database, file storage usage
- MCP integration methods
## Target Audience
- Frontend developers
- Solo entrepreneurs
- Those who want to build fullstack services quickly
## Tech Stack
```
Frontend:
- React / Next.js 14+
- TypeScript
- Tailwind CSS
- TanStack Query (data fetching)
- Zustand (state management)
Backend (BaaS):
- bkend.ai
- Auto REST API
- MongoDB database
- Built-in authentication (JWT)
- Real-time features (WebSocket)
Deployment:
- Vercel (frontend)
- bkend.ai (backend)
```
### Language Tier Guidance (v1.3.0)
> **Recommended**: Tier 1-2 languages
>
> Dynamic level supports full-stack development with strong AI compatibility.
| Tier | Allowed | Reason |
|------|---------|--------|
| Tier 1 | ✅ Primary | Full AI support |
| Tier 2 | ✅ Yes | Mobile (Flutter/RN), Modern web (Vue, Astro) |
| Tier 3 | ⚠️ Limited | Platform-specific needs only |
| Tier 4 | ❌ No | Migration recommended |
**Mobile Development**:
- React Native (Tier 1 via TypeScript) - Recommended
- Flutter (Tier 2 via Dart) - Supported
## Project Structure
```
project/
├── src/
│ ├── app/ # Next.js App Router
│ │ ├── (auth)/ # Auth-related routes
│ │ │ ├── login/
│ │ │ └── register/
│ │ ├── (main)/ # Main routes
│ │ │ ├── dashboard/
│ │ │ └── settings/
│ │ ├── layout.tsx
│ │ └── page.tsx
│ │
│ ├── components/ # UI components
│ │ ├── ui/ # Basic UI (Button, Input...)
│ │ └── features/ # Feature-specific components
│ │
│ ├── hooks/ # Custom hooks
│ │ ├── useAuth.ts
│ │ └── useQuery.ts
│ │
│ ├── lib/ # Utilities
│ │ ├── bkend.ts # bkend.ai client
│ │ └── utils.ts
│ │
│ ├── stores/ # State management (Zustand)
│ │ └── auth-store.ts
│ │
│ └── types/ # TypeScript types
│ └── index.ts
│
├── docs/ # PDCA documents
│ ├── 01-plan/
│ ├── 02-design/
│ │ ├── data-model.md # Data model
│ │ └── api-spec.md # API specification
│ ├── 03-analysis/
│ └── 04-report/
│
├── .mcp.json # bkend.ai MCP config (type: http)
├── .env.local # Environment variables
├── package.json
└── README.md
```
## Core Patterns
### bkend.ai Client Setup
```typescript
// lib/bkend.ts - REST Service API Client
const API_BASE = process.env.NEXT_PUBLIC_BKEND_API_URL || 'https://api.bkend.ai/v1';
const PROJECT_ID = process.env.NEXT_PUBLIC_BKEND_PROJECT_ID!;
const ENVIRONMENT = process.env.NEXT_PUBLIC_BKEND_ENV || 'dev';
async function bkendFetch(path: string, options: RequestInit = {}) {
const token = localStorage.getItem('bkend_access_token');
const res = await fetch(`${API_BASE}${path}`, {
...options,
headers: {
'Content-Type': 'application/json',
'x-project-id': PROJECT_ID,
'x-environment': ENVIRONMENT,
...(token && { Authorization: `Bearer ${token}` }),
...options.headers,
},
});
if (!res.ok) throw new Error(await res.text());
return res.json();
}
export const bkend = {
auth: {
signup: (body: {email: string; password: string}) => bkendFetch('/auth/email/signup', {method: 'POST', body: JSON.stringify(body)}),
signin: (body: {email: string; password: string}) => bkendFetch('/auth/email/signin', {method: 'POST', body: JSON.stringify(body)}),
me: () => bkendFetch('/auth/me'),
refresh: (refreshToken: string) => bkendFetch('/auth/refresh', {method: 'POST', body: JSON.stringify({refreshToken})}),
signout: () => bkendFetch('/auth/signout', {method: 'POST'}),
},
data: {
list: (table: string, params?: Record<string,string>) => bkendFetch(`/data/${table}?${new URLSearchParams(params)}`),
get: (table: string, id: string) => bkendFetch(`/data/${table}/${id}`),
create: (table: string, body: any) => bkendFetch(`/data/${table}`, {method: 'POST', body: JSON.stringify(body)}),
update: (table: string, id: string, body: any) => bkendFetch(`/data/${table}/${id}`, {method: 'PATCH', body: JSON.stringify(body)}),
delete: (table: string, id: string) => bkendFetch(`/data/${table}/${id}`, {method: 'DELETE'}),
},
};
```
### Authentication Hook
```typescript
// hooks/useAuth.ts
import { create } from 'zustand';
import { persist } from 'zustand/middleware';
import { bkend } from '@/lib/bkend';
interface AuthState {
user: User | null;
isLoading: boolean;
login: (email: string, password: string) => Promise<void>;
logout: () => void;
}
export const useAuth = create<AuthState>()(
persist(
(set) => ({
user: null,
isLoading: false,
login: async (email, password) => {
set({ isLoading: true });
const { user, token } = await bkend.auth.login({ email, password });
set({ user, isLoading: false });
},
logout: () => {
bkend.auth.logout();
set({ user: null });
},
}),
{ name: 'auth-storage' }
)
);
```
### Data Fetching (TanStack Query)
```typescript
// List query
const { data, isLoading, error } = useQuery({
queryKey: ['items', filters],
queryFn: () => bkend.collection('items').find(filters),
});
// Single item query
const { data: item } = useQuery({
queryKey: ['items', id],
queryFn: () => bkend.collection('items').findById(id),
enabled: !!id,
});
// Create/Update (Mutation)
const mutation = useMutation({
mutationFn: (newItem) => bkend.collection('items').create(newItem),
onSuccess: () => {
queryClient.invalidateQueries(['items']);
},
});
```
### Protected Route
```typescript
// components/ProtectedRoute.tsx
'use client';
import { useAuth } from '@/hooks/useAuth';
import { redirect } from 'next/navigation';
export function ProtectedRoute({ children }: { children: React.ReactNode }) {
const { user, isLoading } = useAuth();
if (isLoading) return <LoadingSpinner />;
if (!user) redirect('/login');
return <>{children}</>;
}
```
## Data Model Design Principles
```typescript
// Base fields (auto-generated)
interface BaseDocument {
_id: string;
createdAt: Date;
updatedAt: Date;
}
// User reference
interface Post extends BaseDocument {
userId: string; // Author ID (reference)
title: string;
content: string;
tags: string[]; // Array field
metadata: { // Embedded object
viewCount: number;
likeCount: number;
};
}
```
## MCP Integration
### Antigravity Platform CLI (Recommended)
```bash
ai-agent mcp add bkend --transport http https://api.bkend.ai/mcp
```
### .mcp.json (Per Project)
```json
{
"mcpServers": {
"bkend": {
"type": "http",
"url": "https://api.bkend.ai/mcp"
}
}
}
```
### Authentication
- OAuth 2.1 + PKCE (browser auto-auth)
- No API Key/env vars needed
- First MCP request opens browser -> login to bkend console -> select Organization -> approve permissions
- Verify: "Show my bkend projects"
```
## Environment Variables (.env.local)
```
NEXT_PUBLIC_BKEND_API_URL=https://api.bkend.ai/v1
NEXT_PUBLIC_BKEND_PROJECT_ID=your-project-id
NEXT_PUBLIC_BKEND_ENV=dev
```
Note: Project ID is found in bkend console (console.bkend.ai).
Via MCP: "Show my project list" -> backend_project_list
## Limitations
```
❌ Complex backend logic (serverless function limits)
❌ Large-scale traffic (within BaaS limits)
❌ Custom infrastructure control
❌ Microservices architecture
```
## When to Upgrade
Move to **Enterprise Level** if you need:
```
→ "Traffic will increase significantly"
→ "I want to split into microservices"
→ "I need my own server/infrastructure"
→ "I need complex backend logic"
```
## hmcmkit Features for Dynamic Level (v1.5.1)
### Output Style: hmcmkit-pdca-guide (Recommended)
For optimal PDCA workflow experience, activate the PDCA guide style:
```
/output-style hmcmkit-pdca-guide
```
This provides:
- PDCA status badges showing current phase progress
- Gap analysis suggestions after code changes
- Automatic next-phase guidance with checklists
### Agent Teams (2 Teammates)
Dynamic projects support Agent Teams for parallel PDCA execution:
| Role | Agents | PDCA Phases |
|------|--------|-------------|
| developer | bkend-expert | Do, Act |
| qa | qa-monitor, gap-detector | Check |
**To enable:**
1. Set environment: `HMCMKIT_EXPERIMENTAL_AGENT_TEAMS=1`
2. Start team mode: `/pdca team {feature}`
3. Monitor progress: `/pdca team status`
### Agent Memory (Auto-Active)
All hmcmkit agents automatically remember project context across sessions.
No setup needed — agents use `project` scope memory for this codebase.
---
## Common Mistakes
| Mistake | Solution |
|---------|----------|
| CORS error | Register domain in bkend.ai console |
| 401 Unauthorized | Token expired, re-login or refresh token |
| Data not showing | Check collection name, query conditions |
| Type error | Sync TypeScript type definitions with schema |
@@ -0,0 +1,496 @@
---
name: enterprise
classification: capability
classification-reason: Specialized domain knowledge with limited model overlap
deprecation-risk: low
description: |
Enterprise-grade systems with microservices, Kubernetes, Terraform, and AI Native methodology.
Triggers: microservices, k8s, terraform, monorepo, AI native, 마이크로서비스, init enterprise.
argument-hint: "[init|guide|help]"
agents:
default: hmcmkit:enterprise-expert
infra: hmcmkit:infra-architect
architecture: hmcmkit:enterprise-expert
security: hmcmkit:security-architect
team: hmcmkit:cto-lead
allowed-tools:
- Read
- Write
- Edit
- Glob
- Grep
- Bash
- Task
- WebSearch
user-invocable: true
imports:
- ${PLUGIN_ROOT}/templates/design-enterprise.template.md
next-skill: phase-1-schema
pdca-phase: plan
task-template: "[Init-Enterprise] {feature}"
---
# Advanced (Enterprise) Skill
## Actions
| Action | Description | Example |
|--------|-------------|---------|
| `init` | Project initialization (/init-enterprise feature) | `/enterprise init my-platform` |
| `guide` | Display development guide | `/enterprise guide` |
| `help` | MSA/Infrastructure help | `/enterprise help` |
### init (Project Initialization)
1. Create Turborepo monorepo structure
2. apps/, packages/, services/, infra/ folder structure
3. Create agents.md (Level: Enterprise specified)
4. docs/ 5-category structure
5. infra/terraform/, infra/k8s/ base templates
6. Initialize .hmcmkit-memory.json
### guide (Development Guide)
- AI Native 10-Day development cycle
- Microservices architecture patterns
- Phase 1-9 full Pipeline (Enterprise version)
### help (Infrastructure Help)
- Kubernetes basic concepts
- Terraform IaC patterns
- AWS EKS, RDS configuration guide
## Target Audience
- Senior developers
- CTOs / Architects
- Large-scale system operators
## Tech Stack
```
Frontend:
- Next.js 14+ (Turborepo monorepo)
- TypeScript
- Tailwind CSS
- TanStack Query
- Zustand
- Sentry Browser SDK (@sentry/nextjs) — Error tracking + Session Replay
Backend:
- Python FastAPI (microservices) — default
- PostgreSQL (schema separation)
- Redis (cache, Pub/Sub)
- RabbitMQ / SQS (message queue)
- Sentry Server SDK (sentry-sdk[fastapi]) — Error tracking + APM
Infrastructure:
- AWS (EKS, RDS, S3, CloudFront)
- Kubernetes (Kustomize)
- Terraform (IaC)
- ArgoCD (GitOps)
- ALB + NGINX Ingress Controller (L7 load balancing)
- CORS: Ingress annotation으로 처리
nginx.ingress.kubernetes.io/enable-cors: "true"
- NLB(L4)는 gRPC/WebSocket 전용 서비스에만 사용
CI/CD:
- GitHub Actions
- Docker
- Semgrep (SAST) + Trivy (Container Scan)
Monitoring & Error Tracking:
- Sentry — Error tracking, grouping, regression detection
- Prometheus + Grafana — Metrics & dashboards
- Loki + Promtail — Log aggregation
- Tempo + OpenTelemetry — Distributed tracing
- Alertmanager → PagerDuty (critical) / Slack (warning)
Self-Healing Pipeline:
- Sentry Webhook → Self-Healing Agent trigger
- 4-Layer Living Context (Scenarios, Invariants, Impact, Incidents)
- Auto-fix (max 5 iterations) → Auto PR → Canary Deploy
- Auto-Rollback on error rate spike
```
### Language Tier Guidance (v1.3.0)
> **Supported**: All Tiers
>
> Enterprise level handles complex requirements including legacy system integration.
| Tier | Usage | Guidance |
|------|-------|----------|
| Tier 1 | Primary services | New development, core features |
| Tier 2 | System/Cloud | Go (K8s), Rust (performance critical) |
| Tier 3 | Platform native | iOS (Swift), Android (Kotlin), legacy Java |
| Tier 4 | Legacy integration | Migration plan required |
**Migration Path**:
- PHP → TypeScript (Next.js API routes)
- Ruby → Python (FastAPI)
- Java → Kotlin or Go
## Project Structure
```
project/
├── apps/ # Frontend apps (Turborepo)
│ ├── web/ # Main web app
│ ├── admin/ # Admin
│ └── docs/ # Documentation site
│
├── packages/ # Shared packages
│ ├── ui/ # UI components
│ ├── api-client/ # API client
│ └── config/ # Shared config
│
├── services/ # Backend microservices
│ ├── auth/ # Auth service
│ ├── user/ # User service
│ ├── {domain}/ # Domain-specific services
│ └── shared/ # Shared modules
│
├── infra/ # Infrastructure code
│ ├── terraform/
│ │ ├── modules/ # Reusable modules
│ │ └── environments/ # Environment-specific config
│ └── k8s/
│ ├── base/ # Common manifests
│ └── overlays/ # Environment-specific patches
│
├── docs/ # PDCA documents
│ ├── 00-requirement/
│ ├── 01-development/ # Design documents (multiple)
│ ├── 02-scenario/
│ ├── 03-refactoring/
│ └── 04-operation/
│
├── scripts/ # Utility scripts
├── .github/workflows/ # CI/CD
├── docker-compose.yml
├── turbo.json
└── pnpm-workspace.yaml
```
## Clean Architecture (4-Layer)
```
┌─────────────────────────────────────────────────────────┐
│ API Layer │
│ - FastAPI routers │
│ - Request/Response DTOs │
│ - Auth/authz middleware │
├─────────────────────────────────────────────────────────┤
│ Application Layer │
│ - Service classes │
│ - Use Case implementation │
│ - Transaction management │
├─────────────────────────────────────────────────────────┤
│ Domain Layer │
│ - Entity classes (pure Python) │
│ - Repository interfaces (ABC) │
│ - Business rules │
├─────────────────────────────────────────────────────────┤
│ Infrastructure Layer │
│ - Repository implementations (SQLAlchemy) │
│ - External API clients │
│ - Cache, messaging │
│ - Sentry SDK integration (error capture) │
└─────────────────────────────────────────────────────────┘
Dependency direction: Top → Bottom
Domain Layer depends on nothing
```
## Error Handling & Self-Healing Pipeline
```
Exception 발생 (Frontend/Backend)
↓
Sentry SDK 자동 캡처 (stack trace + breadcrumbs + user context)
↓
Sentry Alert Rule (new issue / regression / spike)
↓
Webhook → Self-Healing Agent trigger
↓
Living Context 4-Layer 로딩
├── Scenario Matrix: 테스트 시나리오
├── Invariants: 불변 조건 (critical = 수정 차단)
├── Impact Map: blast radius 계산
└── Incident Memory: 과거 장애 교훈
↓
Antigravity Platform Fix (max 5 iterations)
↓
4중 검증 (scenarios + invariants + impact + anti-patterns)
↓
Pass → Auto PR → Human Review → Canary Deploy (10%→25%→50%→100%)
Fail → Escalation → PagerDuty + Slack + Auto-Rollback
↓
Post-deploy: Sentry에서 issue resolved 확인 + error_rate 모니터링
```
### Load Balancer Strategy
```
ALB + NGINX Ingress Controller (기본, 권장)
─────────────────────────────────────
- L7 로드밸런싱 (HTTP/HTTPS/gRPC)
- CORS: Ingress annotation으로 처리 (앱 코드 불필요)
- Path-based routing (/api/auth/*, /api/users/*)
- AWS Certificate Manager (ACM) TLS 연동
- WAF 연동 가능
NLB (특수 케이스만)
─────────────────────────────────────
- L4 로드밸런싱 (TCP/UDP)
- 극도의 저지연 필요 시 (< 1ms)
- WebSocket/gRPC 전용 서비스
- CORS 처리 불가 → 앱단에서 직접 처리 필요
```
## Core Patterns
### Repository Pattern
```python
# domain/repositories/user_repository.py (interface)
from abc import ABC, abstractmethod
class UserRepository(ABC):
@abstractmethod
async def find_by_id(self, id: str) -> User | None:
pass
@abstractmethod
async def save(self, user: User) -> User:
pass
# infrastructure/repositories/user_repository_impl.py (implementation)
class UserRepositoryImpl(UserRepository):
def __init__(self, db: AsyncSession):
self.db = db
async def find_by_id(self, id: str) -> User | None:
result = await self.db.execute(
select(UserModel).where(UserModel.id == id)
)
return result.scalar_one_or_none()
```
### Inter-service Communication
```python
# Synchronous (Internal API)
async def get_user_info(user_id: str) -> dict:
async with httpx.AsyncClient() as client:
response = await client.get(
f"{USER_SERVICE_URL}/internal/users/{user_id}",
headers={"X-Internal-Token": INTERNAL_TOKEN}
)
return response.json()
# Asynchronous (message queue)
await message_queue.publish(
topic="user.created",
message={"user_id": user.id, "email": user.email}
)
```
### Terraform Module
```hcl
# modules/eks/main.tf
resource "aws_eks_cluster" "this" {
name = "${var.environment}-${var.project_name}-eks"
role_arn = aws_iam_role.cluster.arn
version = var.kubernetes_version
vpc_config {
subnet_ids = var.subnet_ids
}
tags = merge(var.tags, {
Environment = var.environment
})
}
```
### Kubernetes Deployment
```yaml
# k8s/base/backend/deployment.yaml
apiVersion: apps/v1
kind: Deployment
metadata:
name: user-service
spec:
replicas: 2
template:
spec:
containers:
- name: user-service
image: ${ECR_REGISTRY}/user-service:${TAG}
resources:
requests:
cpu: "100m"
memory: "256Mi"
limits:
cpu: "500m"
memory: "512Mi"
livenessProbe:
httpGet:
path: /health
port: 8000
```
## Environment Configuration
| Environment | Infrastructure | Deployment Method |
|-------------|---------------|-------------------|
| Local | Docker Compose | Manual |
| Staging | EKS | ArgoCD Auto Sync |
| Production | EKS | ArgoCD Manual Sync |
## Security Rules
```
✅ Allowed
- Retrieve secrets from Secrets Manager
- IAM role-based access
- VPC internal communication
- mTLS (inter-service)
❌ Prohibited
- Hardcoded secrets
- DB in public subnet
- Using root account
- Excessive IAM permissions
```
## CI/CD Pipeline
```
Push to feature/*
↓
GitHub Actions (CI)
- Lint
- Test
- Build Docker image
- Push to ECR
↓
PR to staging
↓
ArgoCD Auto Sync (Staging)
↓
PR to main
↓
ArgoCD Manual Sync (Production)
```
## SoR Priority
```
1st Priority: Codebase
- scripts/init-db.sql (source of truth for DB schema)
- services/{service}/app/ (each service implementation)
2nd Priority: agents.md / Convention docs
- services/agents.md
- frontend/agents.md
- infra/agents.md
3rd Priority: docs/ design documents
- For understanding design intent
- If different from code, code is correct
```
---
## AI Native Development
### 3 Core Principles
1. **Document-First Design**: Write design docs BEFORE code
2. **Monorepo Context Control**: All code in one repo for AI context
3. **PR-Based Collaboration**: Every change through PR
### 10-Day Development Pattern
| Day | Focus | Output |
|-----|-------|--------|
| 1 | Architecture | Market analysis + System architecture |
| 2-3 | Core | Auth, User + Business services |
| 4-5 | UX | PO feedback → Documentation → Implementation |
| 6-7 | QA | Zero Script QA + bug fixes |
| 8 | Infra | Terraform + GitOps |
| 9-10 | Production | Security review + Deployment |
---
## Monorepo Benefits for AI
```
Mono-repo:
└─ project/
├─ frontend/ ──────┐
├─ services/ ──────┤ AI reads completely
├─ infra/ ─────────┤ Context unified
└─ packages/ ──────┘
✅ AI understands full context
✅ Single source of truth for types
✅ Atomic commits across layers
✅ Consistent patterns enforced
```
### agents.md Hierarchy
```
project/
├── agents.md # Project-wide context
├── frontend/agents.md # Frontend conventions
├── services/agents.md # Backend conventions
└── infra/agents.md # Infra conventions
```
Rule: Area-specific agents.md overrides project-level rules
---
## hmcmkit Features for Enterprise Level (v1.5.1)
### Output Style: hmcmkit-enterprise (Recommended)
For CTO-level architecture perspectives, activate the enterprise style:
```
/output-style hmcmkit-enterprise
```
This provides:
- Architecture tradeoff analysis tables (Option/Pros/Cons/Recommendation)
- Performance, security, and scalability perspectives for every decision
- Cost impact estimates for infrastructure changes
- Deployment strategy recommendations (Blue/Green, Canary, Rolling)
- SOLID principles and Clean Architecture compliance checks
### Agent Teams (4 Teammates)
Enterprise projects support full Agent Teams for parallel PDCA execution:
| Role | Agents | PDCA Phases |
|------|--------|-------------|
| architect | enterprise-expert, infra-architect | Design |
| developer | bkend-expert | Do, Act |
| qa | qa-monitor, gap-detector | Check |
| reviewer | code-analyzer, design-validator | Check, Act |
**To enable:**
1. Set environment: `HMCMKIT_EXPERIMENTAL_AGENT_TEAMS=1`
2. Start team mode: `/pdca team {feature}`
3. Monitor progress: `/pdca team status`
### Agent Memory (Auto-Active)
All hmcmkit agents automatically remember project context across sessions.
Enterprise agents use `project` scope memory, ensuring architecture decisions
and infrastructure patterns persist across development sessions.
@@ -0,0 +1,291 @@
---
name: hmcmkit-rules
classification: workflow
classification-reason: Process automation persists regardless of model advancement
deprecation-risk: none
description: |
Core rules for hmcmkit — PDCA methodology, level detection, agent triggering, quality standards.
Triggers: hmcmkit rules, core rules, methodology, 핵심 규칙, PDCA 규칙.
imports:
- ${PLUGIN_ROOT}/templates/shared/naming-conventions.md
# hooks: Managed by hooks/hooks.json (pre-write.js, unified-write-post.js) - GitHub #9354 workaround
user-invocable: false
---
# hmcmkit Core Rules
> Automatically applied rules that don't require user commands.
## 1. PDCA Auto-Apply Rules
**No Guessing**: If unsure, check docs → If not in docs, ask user
**SoR Priority**: Code > agents.md > docs/ design documents
| Request Type | AI Agent Behavior |
|--------------|-----------------|
| New feature | Check `docs/02-design/` → Design first if missing |
| Bug fix | Compare code + design → Fix |
| Refactoring | Current analysis → Plan → Update design → Execute |
| Implementation complete | Suggest Gap analysis |
### Template References
| Document Type | Template Path |
|---------------|---------------|
| Plan | `${HMCMKIT_PLUGIN_ROOT}/templates/plan.template.md` |
| Design | `${HMCMKIT_PLUGIN_ROOT}/templates/design.template.md` |
| Analysis | `${HMCMKIT_PLUGIN_ROOT}/templates/analysis.template.md` |
| Report | `${HMCMKIT_PLUGIN_ROOT}/templates/report.template.md` |
---
## 2. Level Auto-Detection
### Detection Order
1. Check agents.md for explicit Level declaration
2. File structure based detection
### Enterprise (2+ conditions met)
- infra/terraform/ folder
- infra/k8s/ or kubernetes/ folder
- services/ folder (2+ services)
- turbo.json or pnpm-workspace.yaml
- docker-compose.yml
- .github/workflows/ (CI/CD)
### Dynamic (1+ conditions met)
- bkend settings in .mcp.json
- lib/bkend/ or src/lib/bkend/
- supabase/ folder
- firebase.json
### Starter
None of the above conditions met.
### Level-specific Behavior
| Aspect | Starter | Dynamic | Enterprise |
|--------|---------|---------|------------|
| Explanation | Friendly, avoid jargon | Technical but clear | Concise, use terms |
| Code comments | Detailed | Core logic only | Architecture only |
| Error handling | Step-by-step guide | Technical solutions | Brief cause + fix |
| PDCA docs | Simple | Feature-specific | Detailed architecture |
| Primary Agent | `starter-guide` | `bkend-expert` | `enterprise-expert` |
| Reference Skill | `starter` | `dynamic` | `enterprise` |
### Level Upgrade Signals
- Starter → Dynamic: "Add login", "Save data", "Admin page"
- Dynamic → Enterprise: "High traffic", "Microservices", "Own server"
### Hierarchical agents.md Rules
```
project/
├── agents.md # Project-wide (always reference)
├── services/agents.md # Backend work context
├── frontend/agents.md # Frontend work context
└── infra/agents.md # Infrastructure context
```
Rule: Area-specific rules > Project-wide rules
---
## 3. Agent Auto-Trigger Rules
### Level-Based Selection
When user requests feature development:
1. Detect project level
2. Invoke appropriate agent automatically
### Task-Based Selection
| User Intent | Auto-Invoke Agent |
|-------------|-------------------|
| "code review", "security scan" | `hmcmkit:code-analyzer` |
| "design review", "spec check" | `hmcmkit:design-validator` |
| "gap analysis" | `hmcmkit:gap-detector` |
| "report", "summary" | `hmcmkit:report-generator` |
| "QA", "log analysis" | `hmcmkit:qa-monitor` |
| "pipeline", "which phase" | `hmcmkit:pipeline-guide` |
### Proactive Suggestions
After completing major tasks, suggest relevant agents.
### Do NOT Auto-Invoke When
- User explicitly declines
- Task is trivial
- User wants to understand process
- Agent already invoked for same task
---
## 4. Code Quality Standards
### Pre-coding Checks
1. Does similar functionality exist? Search first
2. Check utils/, hooks/, components/ui/
3. Reuse if exists; create if not
### Core Principles
**DRY**: Extract to common function on 2nd use
**SRP**: One function, one responsibility
**No Hardcoding**: Use meaningful constants
**Extensibility**: Write in generalized patterns
### Self-Check After Coding
- Same logic exists elsewhere?
- Can function be reused?
- Hardcoded values present?
- Function does only one thing?
### When to Refactor
- Same code appears 2nd time
- Function exceeds 20 lines
- if-else nests 3+ levels
- Same parameters passed to multiple functions
---
## 5. Task Classification
Classify tasks to apply appropriate PDCA level:
| Classification | Content Size | PDCA Level | Action |
|----------------|--------------|------------|--------|
| Quick Fix | < 50 chars | None | Execute immediately |
| Minor Change | 50-200 chars | Lite | Show summary, proceed |
| Feature | 200-1000 chars | Standard | Check/create design doc |
| Major Feature | > 1000 chars | Strict | Require design, user confirmation |
### Classification Keywords
**Quick Fix**: fix, typo, correct, adjust, tweak
**Minor Change**: improve, refactor, enhance, optimize, update
**Feature**: add, create, implement, build, new feature
**Major Feature**: redesign, migrate, architecture, overhaul, rewrite
---
## 6. Output Style Auto-Selection (v1.5.1)
When project level is detected, automatically suggest the matching output style:
| Level | Suggested Style | Trigger Condition |
|-------|-----------------|-------------------|
| Starter | `hmcmkit-learning` | Level detected as Starter |
| Dynamic | `hmcmkit-pdca-guide` | Level detected as Dynamic |
| Enterprise | `hmcmkit-enterprise` | Level detected as Enterprise |
### Auto-Selection Rules
- On session start: Suggest output style matching detected level
- On `/starter init`, `/dynamic init`, `/enterprise init`: Auto-suggest style for that level
- On PDCA phase transitions: Suggest `hmcmkit-pdca-guide` if not already active
- User can override with `/output-style` at any time
### Available Output Styles
| Style | Best For | Key Features |
|-------|----------|-------------|
| `hmcmkit-learning` | Beginners, learning | Learning points, TODO(learner) markers, concept explanations |
| `hmcmkit-pdca-guide` | PDCA workflows | Status badges, checklists, phase progress, gap analysis suggestions |
| `hmcmkit-enterprise` | Architecture decisions | Tradeoff analysis, cost impact, deployment strategy, SOLID compliance |
---
## 7. Agent Teams Auto-Suggestion (v1.5.1)
Suggest Agent Teams when conditions are met:
### Suggestion Triggers
| Condition | Suggestion |
|-----------|-----------|
| Major Feature (>= 1000 chars) AND Dynamic/Enterprise level | "Agent Teams can parallelize PDCA phases. Try `/pdca team {feature}`" |
| Match Rate < 70% AND Dynamic/Enterprise level | "Consider Agent Teams for faster parallel Check-Act iteration" |
| Enterprise project init | "Your project supports 4-teammate Agent Teams mode" |
| Dynamic project init | "Your project supports 2-teammate Agent Teams mode" |
### Team Availability
| Level | Available | Teammates | Roles |
|-------|:---------:|:---------:|-------|
| Starter | No | - | - |
| Dynamic | Yes | 2 | developer, qa |
| Enterprise | Yes | 4 | architect, developer, qa, reviewer |
### Requirements
- Environment: `HMCMKIT_EXPERIMENTAL_AGENT_TEAMS=1`
- If env var not set: Suggest setting it when team mode would be beneficial
- Command: `/pdca team {feature}` to start team mode
---
## 8. Agent Memory Awareness (v1.5.1)
Agent Memory is automatically active for all hmcmkit agents. No user action required.
### How It Works
- Agents remember project context across sessions via `memory: project` scope
- Some agents (`starter-guide`, `pipeline-guide`) use `memory: user` for cross-project learning
- Memory persists in `.ai-agent/agent-memory/` (project) or `~/.ai-agent/agent-memory/` (user)
### Memory Scopes
| Scope | Agents Using | Persistence |
|-------|-------------|-------------|
| `project` | 9 agents (code-analyzer, gap-detector, pdca-iterator, etc.) | Per-project, across sessions |
| `user` | 2 agents (starter-guide, pipeline-guide) | Global, across all projects |
### Proactive Mention
- On session start: "Agent Memory is active — agents remember context across sessions"
- When agent is invoked: Agent may reference previous session context
- No configuration needed — fully automatic
## 9. Plugin Hot Reload (v1.6.0)
After modifying hmcmkit plugin files, use `/reload-plugins` to apply changes without restarting Antigravity Platform.
- No need to exit and re-enter the session
- Changes to skills, agents, hooks, and templates are reflected immediately
- Note: Changes to agents.md require `/clear` to fully refresh
## Wildcard Permissions (CC 2.1.0+)
CC 2.1.0+ supports `Bash(pattern*)` wildcard permissions.
### hmcmkit Recommended Patterns
- `Bash(npm *)` - Allow all npm commands
- `Bash(git log*)` - Allow git log variants
- `Bash(node *)` - Allow node execution
- `Bash(npx *)` - Allow npx execution
### Deny Recommendations
- `Bash(rm -rf*)` - Deny recursive delete (dangerous)
- `Bash(git push --force*)` - Deny force push
### Configuration
Add to `.ai-agent/settings.json`:
```json
{
"permissions": {
"allow": ["Bash(npm *)", "Bash(git log*)"],
"deny": ["Bash(rm -rf*)"]
}
}
```
@@ -0,0 +1,169 @@
---
name: hmcmkit-templates
classification: workflow
classification-reason: Process automation persists regardless of model advancement
deprecation-risk: none
description: |
PDCA document templates — Plan, Design, Analysis, Report with consistent structure.
Triggers: template, plan document, design template, 템플릿, 문서 양식.
user-invocable: false
---
# hmcmkit Document Templates
> Use these templates when generating PDCA documents.
## Available Templates
| Template | Path | Purpose |
|----------|------|---------|
| Plan | `${HMCMKIT_PLUGIN_ROOT}/templates/plan.template.md` | Feature planning |
| Design | `${HMCMKIT_PLUGIN_ROOT}/templates/design.template.md` | Technical design |
| Analysis | `${HMCMKIT_PLUGIN_ROOT}/templates/analysis.template.md` | Gap analysis |
| Report | `${HMCMKIT_PLUGIN_ROOT}/templates/report.template.md` | Completion report |
| Index | `${HMCMKIT_PLUGIN_ROOT}/templates/_INDEX.template.md` | Document index |
| CLAUDE | `${HMCMKIT_PLUGIN_ROOT}/templates/agents.template.md` | agents.md template |
## Template Usage
### Plan Template
For **P**lan phase - feature planning before design.
Key sections:
- Overview & Purpose
- Scope (In/Out)
- Requirements (Functional/Non-Functional)
- Success Criteria
- Risks & Mitigation
### Design Template
For **D**o phase - technical design before implementation.
Key sections:
- Architecture (diagrams, data flow)
- Data Model (entities, relationships)
- API Specification (endpoints, request/response)
- UI/UX Design (layouts, components)
- Error Handling
- Security Considerations
- Test Plan
- Implementation Guide
### Analysis Template
For **C**heck phase - gap analysis between design and implementation.
Key sections:
- Design vs Implementation comparison
- Missing features
- Inconsistencies
- Quality metrics
- Recommendations
### Report Template
For **A**ct phase - completion report and lessons learned.
Key sections:
- Summary of completed work
- Metrics (LOC, test coverage, etc.)
- Issues encountered
- Lessons learned
- Future improvements
## Document Output Paths
```
docs/
├── 01-plan/
│ └── features/
│ └── {feature}.plan.md
├── 02-design/
│ └── features/
│ └── {feature}.design.md
├── 03-analysis/
│ └── features/
│ └── {feature}.analysis.md
└── 04-report/
└── features/
└── {feature}.report.md
```
## Variable Substitution
Templates use `{variable}` syntax:
- `{feature}`: Feature name
- `{date}`: Creation date (YYYY-MM-DD)
- `{author}`: Document author
## Pipeline Templates
Additional templates for Development Pipeline phases:
- `${HMCMKIT_PLUGIN_ROOT}/templates/pipeline/` directory
---
## Document Standards
### File Naming Rules
```
{number}_{english_name}.md # 01_system_architecture.md
{number}-{english_name}.md # 01-system-architecture.md
{feature}.{type}.md # login.design.md
```
### Common Header
All documents should include:
```markdown
# {Document Title}
> **Summary**: {One-line description}
>
> **Author**: {Name}
> **Created**: {YYYY-MM-DD}
> **Last Modified**: {YYYY-MM-DD}
> **Status**: {Draft | Review | Approved | Deprecated}
---
```
### Version Control
Track changes within documents:
```markdown
## Version History
| Version | Date | Changes | Author |
|---------|------|---------|--------|
| 1.0 | 2024-12-01 | Initial draft | Kay |
| 1.1 | 2024-12-05 | Added API spec | Kay |
```
### Cross-References
Link related documents:
```markdown
## Related Documents
- Plan: [login.plan.md](../01-plan/features/login.plan.md)
- Design: [login.design.md](../02-design/features/login.design.md)
- Analysis: [login.analysis.md](../03-analysis/features/login.analysis.md)
```
### Status Tracking
Use _INDEX.md in each folder:
| Status | Meaning | AI Agent Behavior |
|--------|---------|-----------------|
| ✅ Approved | Use as reference | Follow as-is |
| 🔄 In Progress | Being written | Notify of changes |
| ⏸️ On Hold | Temporarily paused | Request confirmation |
| ❌ Deprecated | No longer valid | Ignore |
### Conflict Resolution
- **Code vs Design mismatch**: Code is truth, suggest document update
- **Multiple versions**: Reference only the latest version
@@ -0,0 +1,541 @@
---
name: mobile-app
classification: capability
classification-reason: Specialized domain knowledge with limited model overlap
deprecation-risk: low
description: |
Mobile app development guide — React Native, Flutter, Expo for cross-platform.
Triggers: mobile app, React Native, Flutter, Expo, iOS, Android, 모바일 앱.
agent: hmcmkit:pipeline-guide
allowed-tools:
- Read
- Write
- Edit
- Glob
- Grep
- Bash
- WebSearch
user-invocable: true
---
# Mobile App Development Expertise
## Overview
A guide for developing mobile apps based on web development experience.
Develop for iOS and Android simultaneously using cross-platform frameworks.
---
## Framework Selection Guide
### Framework Selection by Tier (v1.3.0)
| Framework | Tier | Recommendation | Use Case |
|-----------|------|----------------|----------|
| **React Native (Expo)** | Tier 1 | ⭐ Primary | TypeScript ecosystem, AI tools |
| **React Native CLI** | Tier 1 | Recommended | Native module needs |
| **Flutter** | Tier 2 | Supported | Multi-platform (6 OS), performance |
> **AI-Native Recommendation**: React Native with TypeScript
> - Full Copilot/AI Agent support
> - Extensive npm ecosystem
> - 20:1 developer availability vs Dart
> **Performance Recommendation**: Flutter
> - Impeller rendering engine
> - Single codebase for 6 platforms
> - Smaller bundles
### Level-wise Recommendations
```
Starter → Expo (React Native) [Tier 1]
- Simple setup, can leverage web knowledge
- Full AI tool support
Dynamic → Expo + EAS Build [Tier 1] or Flutter [Tier 2]
- Includes server integration, production build support
- Choose Flutter for multi-platform needs
Enterprise → React Native CLI [Tier 1] or Flutter [Tier 2]
- Complex native features, performance optimization needed
- Flutter for consistent cross-platform UI
```
---
## Expo (React Native) Guide
### Project Creation
```bash
# Install Expo CLI
npm install -g expo-cli
# Create new project
npx create-expo-app my-app
cd my-app
# Start development server
npx expo start
```
### Folder Structure
```
my-app/
├── app/ # Expo Router pages
│ ├── (tabs)/ # Tab navigation
│ │ ├── index.tsx # Home tab
│ │ ├── explore.tsx # Explore tab
│ │ └── _layout.tsx # Tab layout
│ ├── _layout.tsx # Root layout
│ └── +not-found.tsx # 404 page
├── components/ # Reusable components
├── hooks/ # Custom hooks
├── constants/ # Constants
├── assets/ # Images, fonts, etc.
├── app.json # Expo configuration
└── package.json
```
### Navigation Patterns
```typescript
// app/_layout.tsx - Stack navigation
import { Stack } from 'expo-router';
export default function RootLayout() {
return (
<Stack>
<Stack.Screen name="(tabs)" options={{ headerShown: false }} />
<Stack.Screen name="modal" options={{ presentation: 'modal' }} />
</Stack>
);
}
```
```typescript
// app/(tabs)/_layout.tsx - Tab navigation
import { Tabs } from 'expo-router';
import { Ionicons } from '@expo/vector-icons';
export default function TabLayout() {
return (
<Tabs>
<Tabs.Screen
name="index"
options={{
title: 'Home',
tabBarIcon: ({ color }) => <Ionicons name="home" color={color} size={24} />,
}}
/>
<Tabs.Screen
name="profile"
options={{
title: 'Profile',
tabBarIcon: ({ color }) => <Ionicons name="person" color={color} size={24} />,
}}
/>
</Tabs>
);
}
```
### Styling Patterns
```typescript
// Basic StyleSheet
import { StyleSheet, View, Text } from 'react-native';
export function MyComponent() {
return (
<View style={styles.container}>
<Text style={styles.title}>Hello</Text>
</View>
);
}
const styles = StyleSheet.create({
container: {
flex: 1,
padding: 16,
backgroundColor: '#fff',
},
title: {
fontSize: 24,
fontWeight: 'bold',
},
});
```
```typescript
// NativeWind (Tailwind for RN) - Recommended
import { View, Text } from 'react-native';
export function MyComponent() {
return (
<View className="flex-1 p-4 bg-white">
<Text className="text-2xl font-bold">Hello</Text>
</View>
);
}
```
### API Integration
```typescript
// hooks/useApi.ts
import { useState, useEffect } from 'react';
export function useApi<T>(endpoint: string) {
const [data, setData] = useState<T | null>(null);
const [loading, setLoading] = useState(true);
const [error, setError] = useState<Error | null>(null);
useEffect(() => {
const fetchData = async () => {
try {
const response = await fetch(`${process.env.EXPO_PUBLIC_API_URL}${endpoint}`);
if (!response.ok) throw new Error('API Error');
const json = await response.json();
setData(json);
} catch (e) {
setError(e as Error);
} finally {
setLoading(false);
}
};
fetchData();
}, [endpoint]);
return { data, loading, error };
}
```
### Authentication Pattern
```typescript
// context/AuthContext.tsx
import { createContext, useContext, useState, useEffect } from 'react';
import * as SecureStore from 'expo-secure-store';
interface AuthContextType {
user: User | null;
signIn: (email: string, password: string) => Promise<void>;
signOut: () => Promise<void>;
}
const AuthContext = createContext<AuthContextType | null>(null);
export function AuthProvider({ children }: { children: React.ReactNode }) {
const [user, setUser] = useState<User | null>(null);
useEffect(() => {
// Check for stored token on app start
const loadToken = async () => {
const token = await SecureStore.getItemAsync('authToken');
if (token) {
// Load user info with token
}
};
loadToken();
}, []);
const signIn = async (email: string, password: string) => {
const response = await fetch('/api/auth/login', {
method: 'POST',
body: JSON.stringify({ email, password }),
});
const { token, user } = await response.json();
await SecureStore.setItemAsync('authToken', token);
setUser(user);
};
const signOut = async () => {
await SecureStore.deleteItemAsync('authToken');
setUser(null);
};
return (
<AuthContext.Provider value={{ user, signIn, signOut }}>
{children}
</AuthContext.Provider>
);
}
export const useAuth = () => useContext(AuthContext)!;
```
---
## Flutter Guide
### Project Creation
```bash
# After installing Flutter SDK
flutter create my_app
cd my_app
# Start development server
flutter run
```
### Folder Structure
```
my_app/
├── lib/
│ ├── main.dart # App entry point
│ ├── app/
│ │ ├── app.dart # MaterialApp setup
│ │ └── routes.dart # Route definitions
│ ├── features/ # Feature-based folders
│ │ ├── auth/
│ │ │ ├── screens/
│ │ │ ├── widgets/
│ │ │ └── providers/
│ │ └── home/
│ ├── shared/
│ │ ├── widgets/ # Common widgets
│ │ ├── services/ # API services
│ │ └── models/ # Data models
│ └── core/
│ ├── theme/ # Theme settings
│ └── constants/ # Constants
├── assets/ # Images, fonts
├── pubspec.yaml # Dependency management
└── android/ & ios/ # Native code
```
### Basic Widget Patterns
```dart
// lib/features/home/screens/home_screen.dart
import 'package:flutter/material.dart';
class HomeScreen extends StatelessWidget {
const HomeScreen({super.key});
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Text('Home'),
),
body: const Center(
child: Text('Hello, Flutter!'),
),
floatingActionButton: FloatingActionButton(
onPressed: () {},
child: const Icon(Icons.add),
),
);
}
}
```
### State Management (Riverpod)
```dart
// lib/providers/counter_provider.dart
import 'package:flutter_riverpod/flutter_riverpod.dart';
final counterProvider = StateNotifierProvider<CounterNotifier, int>((ref) {
return CounterNotifier();
});
class CounterNotifier extends StateNotifier<int> {
CounterNotifier() : super(0);
void increment() => state++;
void decrement() => state--;
}
```
```dart
// Usage
class CounterScreen extends ConsumerWidget {
@override
Widget build(BuildContext context, WidgetRef ref) {
final count = ref.watch(counterProvider);
return Text('Count: $count');
}
}
```
---
## Web vs Mobile Differences
### UI/UX Differences
| Element | Web | Mobile |
|---------|-----|--------|
| Click | onClick | onPress |
| Scroll | overflow: scroll | ScrollView / FlatList |
| Input | input | TextInput |
| Links | a href | Link / navigation |
| Layout | div + CSS | View + StyleSheet |
### Navigation Differences
```
Web: URL-based (browser back button)
Mobile: Stack-based (screen stacking)
Web: /users/123
Mobile: navigation.navigate('User', { id: 123 })
```
### Storage Differences
```
Web: localStorage, sessionStorage, Cookie
Mobile: AsyncStorage, SecureStore, SQLite
⚠️ SecureStore is required for sensitive info on mobile!
```
---
## Build & Deployment
### Expo EAS Build
```bash
# Install EAS CLI
npm install -g eas-cli
# Login
eas login
# Configure build
eas build:configure
# iOS build
eas build --platform ios
# Android build
eas build --platform android
# Submit to stores
eas submit --platform ios
eas submit --platform android
```
### Environment Variables
```json
// app.json
{
"expo": {
"extra": {
"apiUrl": "https://api.example.com"
}
}
}
```
```typescript
// Usage
import Constants from 'expo-constants';
const apiUrl = Constants.expoConfig?.extra?.apiUrl;
```
---
## Mobile PDCA Checklist
### Phase 1: Schema
```
□ Identify data that needs offline caching
□ Define sync conflict resolution strategy
```
### Phase 3: Mockup
```
□ Follow iOS/Android native UX guidelines
□ Consider gestures (swipe, pinch, etc.)
□ Layout for different screen sizes (phone, tablet)
```
### Phase 6: UI
```
□ Keyboard handling (screen adjustment during input)
□ Safe Area handling (notch, home button area)
□ Handle platform-specific UI differences
```
### Phase 7: Security
```
□ Store sensitive info with SecureStore
□ Certificate Pinning (if needed)
□ App obfuscation settings
```
### Phase 9: Deployment
```
□ Follow App Store review guidelines
□ Prepare Privacy Policy URL
□ Prepare screenshots, app description
```
---
## Frequently Asked Questions
### Q: Can I convert a web project to an app?
```
A: Recommend separate project over full conversion
- APIs can be shared
- UI needs to be rewritten (for native UX)
- Business logic can be shared
```
### Q: Should I use Expo or React Native CLI?
```
A: Start with Expo!
- 90%+ of apps are sufficient with Expo
- Can eject later if needed
- Use CLI only when native modules are absolutely required
```
### Q: How long does app review take?
```
A:
- iOS: 1-7 days (average 2-3 days)
- Android: Few hours ~ 3 days
⚠️ First submission has high rejection possibility → Follow guidelines carefully!
```
---
## Requesting from AI Agent
### Project Creation
```
"Set up a [app description] app project with React Native + Expo.
Configure with 3 tab navigation (Home, Search, Profile)."
```
### Screen Implementation
```
"Implement [screen name] screen.
- Display [content] at the top
- Display [list/form/etc.] in the middle
- [Button/navigation] at the bottom"
```
### API Integration
```
"Implement screen integrating with [API endpoint].
- Show loading state
- Handle errors
- Support pull-to-refresh"
```
@@ -0,0 +1,223 @@
---
name: pdca-batch
classification: workflow
classification-reason: Batch PDCA management persists regardless of model advancement
deprecation-risk: none
description: |
Manage multiple PDCA features and batch operations.
Triggers: pdca-batch, batch, multiple features, 다중 기능, 배치.
argument-hint: "[status|plan|manage]"
user-invocable: true
allowed-tools:
- Read
- Write
- Glob
- Grep
- Bash
- Task
- TaskCreate
- TaskList
- AskUserQuestion
imports: []
next-skill: null
pdca-phase: null
task-template: "[Batch] {action}"
---
# PDCA Batch Skill
> User-invocable skill for managing multiple PDCA features and batch operations.
## Arguments
| Argument | Description | Example |
|----------|-------------|---------|
| (none) | Show all active features (same as `status`) | `/pdca-batch` |
| `status` | Show all active features and their PDCA status | `/pdca-batch status` |
| `plan <f1> <f2> ...` | Plan multiple features in sequence | `/pdca-batch plan auth search api` |
| `manage` | Interactive dashboard for parallel features | `/pdca-batch manage` |
## Action Details
### status (Default)
Show all active PDCA features and their current status.
1. Read `.hmcmkit/state/pdca-status.json`
2. Filter to active features (exclude archived/completed unless `--all` flag)
3. For each feature, display: phase, matchRate, iterationCount, last updated
4. Show summary: total active, total completed, total archived
5. Warn if approaching max parallel limit (3)
**Output Format**:
```
--- PDCA Feature Dashboard ------------------------
Active Features: 2/3 (max)
# Feature Phase Match% Iter Last Updated
1 user-auth check 85% 2/5 10 min ago
2 search-api design - 0/5 2 hours ago
- (1 slot available)
Completed (recent):
3 payment-flow archived 96% 3/5 2 days ago
---------------------------------------------------
Totals: 2 active | 1 completed | 0 stale
Tip: Use /pdca-batch manage for interactive control
```
### plan <feature1> <feature2> ...
Plan multiple features in a batch sequence.
1. Parse feature names from arguments (space-separated)
2. Validate: max 5 features per batch plan
3. Check current active feature count (max 3 concurrent)
4. For features exceeding the parallel limit, queue them
5. Display batch plan summary and ask for confirmation via AskUserQuestion
6. On confirmation, for each feature sequentially:
a. Initialize feature in `pdca-status.json` (state: idle)
b. Create Plan document using plan template
c. Record batch origin: `batchId` in feature metadata
7. Display batch plan results
**Batch Plan Output**:
```
--- Batch Plan Results ----------------------------
Batch ID: batch-1710842700000
Features planned: 3
Feature Status Plan Document
auth OK docs/01-plan/features/auth.plan.md
search OK docs/01-plan/features/search.plan.md
api-v2 QUEUED (waiting for slot, 2/3 active)
---------------------------------------------------
Next: Run /pdca design <feature> for each planned feature
```
**Constraints**:
- Maximum 5 features per batch plan command
- Maximum 3 features active simultaneously
- Features beyond the limit are queued with `phase: queued`
- Queued features auto-activate when a slot becomes available
### manage
Interactive dashboard for managing parallel features.
1. Read all active features from `pdca-status.json`
2. Display interactive-style management panel
3. Show available actions per feature
4. Accept user input for next action via AskUserQuestion
**Output Format**:
```
--- Feature Management Dashboard ------------------
Active Features: 2/3
[1] user-auth (check, 85%, iter 2/5)
Actions: [a]nalyze [i]terate [r]eport [p]ause
[2] search-api (design, -, iter 0/5)
Actions: [d]esign-review [n]ext [p]ause
[Q] user-input (queued, waiting for slot)
Actions: [c]ancel [p]rioritize
---------------------------------------------------
Global Actions:
[s] Switch active feature
[n] New feature (if slot available)
[r] Refresh dashboard
[x] Exit dashboard
---------------------------------------------------
Select feature number or action:
```
**Management Actions**:
| Action | Description |
|--------|-------------|
| Switch feature | Change which feature is "focused" for subsequent /pdca commands |
| Prioritize queued | Move a queued feature to next available slot |
| Pause feature | Temporarily halt a feature's PDCA progression |
| Cancel queued | Remove a feature from the queue |
| New feature | Start a new PDCA cycle if slot available |
## Parallel Feature Rules
1. **Maximum 3 concurrent features**: Prevents context overload and resource contention
2. **Independent state**: Each feature has its own phase, matchRate, and iteration count
3. **Shared guardrails**: Automation level and trust score are global (not per-feature)
4. **Queue system**: Features beyond limit are queued and auto-activated on slot availability
5. **Isolation**: Features do NOT share checkpoints or audit entries
## State File Schema
Features in `pdca-status.json` with batch support:
```json
{
"user-auth": {
"phase": "check",
"matchRate": 85,
"iterationCount": 2,
"batchId": "batch-1710842700000",
"queuePosition": null,
"lastUpdated": "2026-03-19T10:30:00.000Z"
},
"search-api": {
"phase": "design",
"matchRate": 0,
"iterationCount": 0,
"batchId": "batch-1710842700000",
"queuePosition": null,
"lastUpdated": "2026-03-19T08:30:00.000Z"
},
"api-v2": {
"phase": "queued",
"batchId": "batch-1710842700000",
"queuePosition": 1,
"lastUpdated": "2026-03-19T10:30:00.000Z"
}
}
```
## Module Dependencies
| Module | Function | Usage |
|--------|----------|-------|
| `lib/pdca/status.js` | `getPdcaStatus()` | Read all feature states |
| `lib/pdca/status.js` | `updatePdcaStatus()` | Update feature state |
| `lib/pdca/state-machine.js` | `createContext()` | Initialize new feature |
| `lib/pdca/lifecycle.js` | `activateQueuedFeature()` | Auto-activate from queue |
| `lib/audit/audit-logger.js` | `writeAuditLog()` | Record batch operations |
## Usage Examples
```bash
# View all features
/pdca-batch
# Plan multiple features
/pdca-batch plan user-auth search-api payment-flow
# Interactive management
/pdca-batch manage
```
## Integration with /pdca
The `/pdca-batch` skill complements the main `/pdca` skill:
| Scope | Use /pdca | Use /pdca-batch |
|-------|-----------|-----------------|
| Single feature operations | Yes | No |
| Multi-feature overview | No | Yes |
| Phase transitions | Yes | No (redirects to /pdca) |
| Batch planning | No | Yes |
| Feature switching | No | Yes (manage) |
When using `/pdca` commands, they operate on the currently "focused" feature.
Use `/pdca-batch manage` to switch the focused feature.
+669
View File
@@ -0,0 +1,669 @@
---
name: pdca
classification: workflow
classification-reason: PDCA process automation independent of model capability evolution
deprecation-risk: none
description: |
Unified PDCA cycle management — plan, design, do, analyze, iterate, report.
Triggers: pdca, plan, design, analyze, report, status, next, iterate, 계획, 설계, 분석, 보고서.
argument-hint: "[action] [feature]"
user-invocable: true
agents:
analyze: hmcmkit:gap-detector
iterate: hmcmkit:pdca-iterator
report: hmcmkit:report-generator
team: null
pm: null
default: null
allowed-tools:
- Read
- Write
- Edit
- Glob
- Grep
- Bash
- Task
- TaskCreate
- TaskUpdate
- TaskList
- AskUserQuestion
imports:
- ${PLUGIN_ROOT}/templates/plan.template.md
- ${PLUGIN_ROOT}/templates/design.template.md
- ${PLUGIN_ROOT}/templates/do.template.md
- ${PLUGIN_ROOT}/templates/analysis.template.md
- ${PLUGIN_ROOT}/templates/report.template.md
- ${PLUGIN_ROOT}/templates/iteration-report.template.md
next-skill: null
pdca-phase: null
task-template: "[PDCA] {feature}"
hooks:
Stop:
- type: command
command: "node ${HMCMKIT_PLUGIN_ROOT}/scripts/pdca-skill-stop.js"
timeout: 10000
---
# PDCA Skill
> Unified Skill for managing PDCA cycle. Supports the entire Plan → Design → Do → Check → Act flow.
## Arguments
| Argument | Description | Example |
|----------|-------------|---------|
| `pm [feature]` | Run PM Agent Team analysis (pre-Plan) | `/pdca pm user-auth` |
| `plan [feature]` | Create Plan document | `/pdca plan user-auth` |
| `design [feature]` | Create Design document | `/pdca design user-auth` |
| `do [feature]` | Do phase guide (start implementation) | `/pdca do user-auth` |
| `analyze [feature]` | Run Gap analysis (Check phase) | `/pdca analyze user-auth` |
| `iterate [feature]` | Auto improvement iteration (Act phase) | `/pdca iterate user-auth` |
| `report [feature]` | Generate completion report | `/pdca report user-auth` |
| `archive [feature]` | Archive completed PDCA documents | `/pdca archive user-auth` |
| `cleanup [feature]` | Cleanup archived features from status | `/pdca cleanup` |
| `team [feature]` | Start PDCA Team Mode (requires Agent Teams) | `/pdca team user-auth` |
| `team status` | Show Team status | `/pdca team status` |
| `team cleanup` | Cleanup Team resources | `/pdca team cleanup` |
| `status` | Show current PDCA status | `/pdca status` |
| `next` | Guide to next phase | `/pdca next` |
## Action Details
### pm (PM Analysis Phase)
Run PM Agent Team for product discovery and strategy analysis before Plan phase.
1. **Call pm-lead Agent** (orchestrates 4 sub-agents)
2. pm-lead runs Phase 1: Context Collection (project info, git history)
3. pm-lead runs Phase 2: Parallel Analysis (3 agents simultaneously)
- pm-discovery: Opportunity Solution Tree (Teresa Torres)
- pm-strategy: Value Proposition (JTBD 6-Part) + Lean Canvas
- pm-research: 3 Personas + 5 Competitors + TAM/SAM/SOM
4. pm-lead runs Phase 3: PRD Synthesis via pm-prd agent
- Beachhead Segment (Geoffrey Moore) + GTM Strategy
- 8-section PRD generation
5. Output PRD to `docs/00-pm/{feature}.prd.md`
6. Create Task: `[PM] {feature}`
7. Update .hmcmkit-memory.json: phase = "pm"
8. Guide user to next step: `/pdca plan {feature}`
**Output Path**: `docs/00-pm/{feature}.prd.md`
**Requirements**:
- Agent Teams enabled: `HMCMKIT_EXPERIMENTAL_AGENT_TEAMS=1`
- Project level: Dynamic or Enterprise (Starter not supported)
### plan (Plan Phase)
0. **PRD Auto-Reference**: Check if `docs/00-pm/{feature}.prd.md` exists
- If found: Read PRD and use as context for Plan document (improves quality significantly)
- If not found: Proceed normally (tip: run `/pdca pm {feature}` first for better results)
1. Check if `docs/01-plan/features/{feature}.plan.md` exists
2. If not, create based on `plan.template.md`
3. If exists, display content and suggest modifications
4. **Checkpoint 1 — Requirements Confirmation**: Present understanding of the feature (problem, scope, constraints) and use AskUserQuestion: "요구사항 이해가 맞나요? 빠진 건 없나요?" Wait for user confirmation before proceeding.
5. **Checkpoint 2 — Clarifying Questions**: Identify underspecified elements (edge cases, error handling, integration points, compatibility). Present organized question list. Wait for answers before generating the document.
6. Generate Plan document with user-confirmed requirements
7. Create Task: `[Plan] {feature}`
8. Update .hmcmkit-memory.json: phase = "plan"
9. Write `## Executive Summary` at document top with 4-perspective table (Problem/Solution/Function UX Effect/Core Value), each 1-2 sentences
10. **Context Anchor Generation**: After generating Plan document, extract Context Anchor (WHY/WHO/RISK/SUCCESS/SCOPE) from Executive Summary, Requirements, and Risk sections. Write as `## Context Anchor` table between Executive Summary and Section 1. This anchor propagates to Design/Do documents for cross-session context continuity.
11. **MANDATORY**: After completing the document, also output the Executive Summary table in your response so the user sees it immediately without opening the file
**Output Path**: `docs/01-plan/features/{feature}.plan.md`
> **Tip**: For features with ambiguous requirements or multiple implementation approaches,
> use `/plan-plus {feature}` instead. Plan Plus adds brainstorming phases (intent discovery,
> alternatives exploration, YAGNI review) before document generation for higher-quality plans.
### design (Design Phase)
1. Verify Plan document exists (required - suggest running plan first if missing)
2. Read Plan document to understand requirements and scope
3. **PRD Context Loading**: Check if `docs/00-pm/{feature}.prd.md` exists. If found, read the Executive Summary and Beachhead/GTM sections to inform architecture decisions with market context. This prevents strategic context loss at the Plan→Design handoff.
4. **Context Anchor Embed**: Copy Plan's `## Context Anchor` table to Design document top (between header metadata and ## 1. Overview). If Plan has no Context Anchor (legacy), skip this step gracefully.
5. **Generate 3 Architecture Options** (inspired by feature-dev Phase 4):
- **Option A — Minimal Changes**: Least modification, maximum reuse of existing code. Fast but potentially coupled.
- **Option B — Clean Architecture**: Best separation of concerns, most maintainable. More files, more refactoring.
- **Option C — Pragmatic Balance**: Good boundaries without over-engineering. Recommended default.
6. Present comparison table with trade-offs (complexity, maintainability, effort, risk)
7. **Checkpoint 3 — Architecture Selection**: Use AskUserQuestion: "3가지 설계안 중 어떤 걸 선택하시겠습니까?" Include recommendation. Wait for user selection.
8. Create `docs/02-design/features/{feature}.design.md` using selected architecture
9. Use `design.template.md` structure + reference Plan content
10. **Session Guide Generation**: Analyze Design's `## 11. Implementation Guide` structure to generate Module Map and Recommended Session Plan. Add as `### 11.3 Session Guide` within Implementation Guide section. This enables `/pdca do {feature} --scope module-N` for multi-session incremental implementation.
11. **Design Anchor Integration (Pencil MCP)**: If the feature involves UI and Pencil MCP is available:
- Suggest: "UI 컨셉 페이지를 1-2개 먼저 만든 후 `/design-anchor capture {feature}` 로 디자인 토큰을 잠그세요"
- If Design Anchor already exists (`docs/02-design/styles/{feature}.design-anchor.md`), embed it in the Design document as `## Design Anchor` section
- This ensures design tokens (colors, typography, spacing) are locked before implementation
12. Create Task: `[Design] {feature}` (blockedBy: Plan task)
13. Update .hmcmkit-memory.json: phase = "design"
**Output Path**: `docs/02-design/features/{feature}.design.md`
### do (Do Phase)
1. Verify Design document exists (required)
2. **Read Design document FULLY** (read the entire document, not just a summary. This is critical — full context reload ensures each session starts with complete architectural context)
3. **Full Upstream Context Loading (Phase 2+3)**: Load the COMPLETE upstream document chain:
- Read PRD (`docs/00-pm/{feature}.prd.md`) — extract WHY context (JTBD, value proposition, market positioning)
- Read Plan (`docs/01-plan/features/{feature}.plan.md`) — extract Context Anchor, Success Criteria, Requirements
- This ensures implementation decisions are guided by strategic intent from PRD→Plan→Design, not just the Design spec
4. **Decision Record Chain Display**: Extract and display key decisions from PRD→Plan→Design as a unified chain. Format:
```
📋 Decision Record Chain
[PRD] Target: {market/user segment} — {rationale}
[Plan] Architecture: {selected option} — {rationale}
[Design] State Mgmt: {selected approach} — {rationale}
```
5. **Success Criteria Tracking**: Extract Success Criteria from Plan document. Display as implementation checklist — each criterion must be addressed during implementation. Mark criteria that are covered by the current --scope.
6. **Parse --scope parameter**: If arguments contain `--scope <value>`, extract module list (comma-separated scope keys). Match against Design's Session Guide Module Map. Filter implementation items to show only matching modules.
7. **Display Context Anchor**: Show the Context Anchor table from Design document header. Format: "📌 Context Anchor" + WHY/WHO/RISK/SUCCESS/SCOPE table. This reminds the user WHY we're building this feature.
8. **Session Guide Display**:
- If no --scope: Show full Module Map from Design + recommend session split + proceed with full implementation guide
- If --scope provided: Show only the selected modules' implementation items
9. Summarize implementation scope:
- Files to create: N
- Files to modify: M
- Estimated changes: ~X lines
10. **Checkpoint 4 — Implementation Approval**: Present scope summary and use AskUserQuestion: "이 범위로 구현을 시작해도 되겠습니까?" **DO NOT START IMPLEMENTATION WITHOUT USER APPROVAL.**
11. After approval, provide implementation guide based on `do.template.md`
12. Reference implementation order from Design document (filtered by --scope if provided)
13. **Code Comment Convention (Phase 3)**: During implementation, add Design reference comments for key architectural decisions:
- At module/file level: `// Design Ref: §{section} — {decision rationale}`
- At critical logic: `// Plan SC: {success criteria being addressed}`
- These comments create traceable links from code back to design decisions
14. Create Task: `[Do] {feature}` (blockedBy: Design task)
15. Update .hmcmkit-memory.json: phase = "do"
**--scope Parameter**:
```
/pdca do feature # Full scope (backward compatible) + session guide
/pdca do feature --scope module-1 # Only module-1
/pdca do feature --scope module-1,module-2 # Multiple modules
```
**Guide Provided**:
- Context Anchor (WHY/WHO/RISK/SUCCESS/SCOPE)
- Session scope (filtered or full)
- Implementation order checklist
- Key files/components list
- Dependency installation commands
### analyze (Check Phase)
1. Verify Do completion status (implementation code exists)
2. **Full Upstream Context Loading (Phase 2+3)**: Load the COMPLETE upstream document chain for comprehensive evaluation:
- Read PRD (`docs/00-pm/{feature}.prd.md`) — verify strategic alignment (was the right problem solved?)
- Read Plan (`docs/01-plan/features/{feature}.plan.md`) — verify Requirements fulfillment + Success Criteria
- Read Design (`docs/02-design/features/{feature}.design.md`) — verify structural implementation match
- This 3-layer verification catches gaps that single-document comparison misses
3. **Context Anchor Embed**: Copy Context Anchor from Design to Analysis document header.
4. **Strategic Alignment Check (Phase 3)**: Before structural gap analysis, verify:
- Does the implementation address the PRD's core problem (WHY)?
- Are Plan Success Criteria met or on track?
- Were key Design decisions (architecture, data model, API) followed?
- Flag strategic misalignments as Critical regardless of structural match rate
5. **Plan Success Criteria Reference**: Evaluate each Success Criteria from Plan:
- Mark as ✅ Met / ⚠️ Partial / ❌ Not Met
- Include evidence (file:line or test result)
- Criteria violations are automatically Critical severity
6. **Call gap-detector Agent** (v2.3.0: Static Analysis + Runtime Verification Plan)
- gap-detector performs static analysis (Structural + Functional + Contract)
- gap-detector outputs a **Runtime Verification Plan** (L1/L2/L3 test specs)
7. Compare Design document vs implementation code on 3 static axes:
- **Structural Match**: File existence, route coverage, component list
- **Functional Depth**: Placeholder detection, Page UI Checklist verification, actual logic completeness
- **API Contract**: 3-way verification (Design §4 ↔ Server route.ts ↔ Client fetch calls)
8. **Runtime Verification (v2.3.0)**: After gap-detector completes, execute runtime tests.
- **Preferred**: Run existing tests from `tests/e2e/{feature}.spec.ts` (written during Do phase)
- **Fallback**: If no test file exists, generate from gap-detector's Runtime Verification Plan
- Test scenarios are defined in Design §8 Test Plan, implemented during Do phase, executed here
**L1 — API Endpoint Tests** (always run if server is available):
- Execute each curl command from gap-detector's L1 plan
- Check: HTTP status code matches expected
- Check: Response JSON shape matches expected (has .data, .error, .pagination)
- Check: Auth guard returns 401 for protected endpoints
- Check: Zod validation returns 400 with fieldErrors for invalid input
- Check: Rate limiting returns 429 after threshold
- Detect server: `curl -s -o /dev/null -w "%{http_code}" http://localhost:3000/`
- If no server running: skip L1, warn user, use static-only formula
**L2 — UI Action Tests** (run if Playwright is installed):
- Generate Playwright test file from gap-detector's L2 plan
- Write to `tests/e2e/{feature}-actions.spec.ts`
- Run: `npx playwright test tests/e2e/{feature}-actions.spec.ts`
- Each test: navigate to page → perform action → assert result
- Check: API calls triggered by UI match expected endpoints
- If Playwright not installed: skip L2, suggest `pnpm add -D @playwright/test`
**L3 — E2E Scenario Tests** (run if Playwright is installed):
- Generate Playwright test file from gap-detector's L3 plan
- Write to `tests/e2e/{feature}-e2e.spec.ts`
- Run: `npx playwright test tests/e2e/{feature}-e2e.spec.ts`
- Full user journey: multi-page flows with state persistence
- Check: complete flow from start to end without errors
**Match Rate Formula (v2.3.0)**:
```
If runtime executed:
Overall = (Structural × 0.15) + (Functional × 0.25)
+ (Contract × 0.25) + (Runtime × 0.35)
If static only (no server):
Overall = (Structural × 0.2) + (Functional × 0.4) + (Contract × 0.4)
```
9. Calculate Match Rate and generate Gap list. Report all rates separately.
10. **Decision Record Verification (Phase 3)**: Check if key decisions from Decision Record Chain were followed in implementation. Flag deviations.
11. **Checkpoint 5 — Review Decision**: Present issues by severity (Critical/Important only, confidence ≥80%). Use AskUserQuestion with options:
- "지금 모두 수정" — proceed to iterate
- "Critical만 수정" — iterate critical only
- "그대로 진행" — accept current state
Wait for user decision before proceeding.
12. Create Task: `[Check] {feature}` (blockedBy: Do task)
13. Update .hmcmkit-memory.json: phase = "check", matchRate
**Output Path**: `docs/03-analysis/{feature}.analysis.md`
### iterate (Act Phase)
1. Check results (when matchRate < 90%)
2. **Call pdca-iterator Agent**
3. Auto-fix code based on Gap list
4. Auto re-run Check after fixes
5. Create Task: `[Act-N] {feature}` (N = iteration count)
6. Stop when >= 90% reached or max iterations (5) hit
**Iteration Rules**:
- Max iterations: 5 (adjustable via hmcmkit.config.json)
- Stop conditions: matchRate >= 90% or maxIterations reached
### report (Completion Report)
1. Verify Check >= 90% (warn if below)
2. **Full Upstream Context Loading (Phase 2+3)**: Load ALL upstream documents for comprehensive reporting:
- Read PRD — compare original value proposition vs delivered value
- Read Plan — compare planned Requirements/Success Criteria vs actual results
- Read Design — note architecture decisions and deviations
- Read Analysis — include final Match Rate and resolved gaps
- This ensures the report reflects the FULL journey from PRD→Code
3. **Call report-generator Agent**
4. Integrated report of PRD, Plan, Design, Implementation, Analysis
5. **Decision Record Summary (Phase 3)**: Include section "Key Decisions & Outcomes":
- List decisions from PRD→Plan→Design chain
- For each: was it followed? what was the outcome?
- This creates a learnable record for future PDCA cycles
6. **Success Criteria Final Status**: Include Plan Success Criteria with final status:
- Each criterion: ✅ Met (with evidence) / ❌ Not Met (with reason)
- Overall Success Rate: X/Y criteria met
7. Include `## Executive Summary` with `### 1.3 Value Delivered` reflecting actual results (4 perspectives with metrics)
8. **MANDATORY**: After completing the report, also output the Executive Summary table in your response
9. Create Task: `[Report] {feature}`
10. Update .hmcmkit-memory.json: phase = "completed"
**Output Path**: `docs/04-report/{feature}.report.md`
### team (Team Mode) - v1.5.1
Start PDCA Team Mode using Antigravity Platform Agent Teams (requires `HMCMKIT_EXPERIMENTAL_AGENT_TEAMS=1`).
#### team [feature] - Start Team Mode
1. Check if Agent Teams is available: call `isTeamModeAvailable()` from `lib/team/coordinator.js`
2. If not available, display: "Agent Teams is not enabled. Set `HMCMKIT_EXPERIMENTAL_AGENT_TEAMS=1` to enable."
3. Detect project level via `detectLevel()` - Starter projects cannot use Team Mode
4. Generate team strategy via `generateTeamStrategy(level)`:
- Dynamic: 3 teammates (developer, frontend, qa) — CTO Lead orchestrates
- Enterprise: 5 teammates (architect, developer, qa, reviewer, security) — CTO Lead orchestrates
5. CTO Lead (cto-lead agent, leader-agent) automatically:
- Sets technical direction and selects orchestration pattern
- Distributes tasks to teammates based on PDCA phase
- Enforces quality gates (90% Match Rate threshold)
6. Show strategy and confirm with AskUserQuestion before starting
7. Assign PDCA tasks to teammates via `assignNextTeammateWork()`
#### team status - Show Team Status
1. Call `formatTeamStatus()` from `lib/team/coordinator.js`
2. Display: Team availability, enabled state, display mode, teammate count
3. Show current PDCA feature progress per teammate if active
**Output Example**:
```
📊 PDCA Team Status
─────────────────────────────
Agent Teams: Available ✅
Display Mode: in-process
Teammates: 4 / 4 (Enterprise)
─────────────────────────────
Feature: user-auth
architect: [Design] in progress
developer: [Do] waiting
qa: idle
reviewer: idle
```
#### team cleanup - Cleanup Team Resources
1. Stop all active teammates
2. Record `team_session_ended` in PDCA history via `addPdcaHistory()`
3. Return to single-session PDCA mode
4. Display: "Returning to single-session mode"
**Required Environment**: `HMCMKIT_EXPERIMENTAL_AGENT_TEAMS=1`
**Level Requirements**:
| Level | Available | Teammates | CTO Lead |
|-------|:---------:|:---------:|:--------:|
| Starter | No | - | - |
| Dynamic | Yes | 3 | cto-lead (leader-agent) |
| Enterprise | Yes | 5 | cto-lead (leader-agent) |
### archive (Archive Phase)
1. Verify Report completion status (phase = "completed" or matchRate >= 90%)
2. Verify PDCA documents exist (plan, design, analysis, report)
3. Create `docs/archive/YYYY-MM/{feature}/` folder
4. Move documents (delete from original location)
5. Update Archive Index (`docs/archive/YYYY-MM/_INDEX.md`)
6. Update .pdca-status.json: phase = "archived", record archivedTo path
7. Remove feature from status (or preserve summary with `--summary` option)
**Arguments**:
| Argument | Description | Example |
|----------|-------------|---------|
| `archive {feature}` | Archive with complete cleanup (default) | `/pdca archive user-auth` |
| `archive {feature} --summary` | Archive with summary preservation (FR-04) | `/pdca archive user-auth --summary` |
**Output Path**: `docs/archive/YYYY-MM/{feature}/`
**Documents to Archive**:
- `docs/01-plan/features/{feature}.plan.md`
- `docs/02-design/features/{feature}.design.md`
- `docs/03-analysis/{feature}.analysis.md`
- `docs/04-report/features/{feature}.report.md`
**FR-04: Summary Preservation Option** (v1.4.8):
When using `--summary` (or `--preserve-summary`, `-s`), the feature data in `.pdca-status.json`
is converted to a lightweight summary instead of being deleted:
```json
// Summary format (70% size reduction)
{
"my-feature": {
"phase": "archived",
"matchRate": 100,
"iterationCount": 2,
"startedAt": "2026-01-15T10:00:00Z",
"archivedAt": "2026-01-20T15:30:00Z",
"archivedTo": "docs/archive/2026-01/my-feature/"
}
}
```
Use `--summary` when you need:
- Historical statistics and metrics
- Project duration tracking
- PDCA efficiency analysis
**Important Notes**:
- Cannot archive before Report completion
- Documents are deleted from original location after move (irreversible)
- Feature name must match exactly
- Default behavior: complete deletion from status
- Use `--summary` to preserve metrics for future reference
### cleanup (Cleanup Phase) - v1.4.8
Clean up archived features from `.pdca-status.json` to reduce file size.
1. Read archived features from `.pdca-status.json`
2. Display list with timestamps and archive paths
3. Ask user for confirmation via AskUserQuestion (FR-06)
4. Delete selected features from status using `cleanupArchivedFeatures()`
5. Report cleanup results
**Arguments**:
| Argument | Description | Example |
|----------|-------------|---------|
| `cleanup` | Interactive cleanup (shows list) | `/pdca cleanup` |
| `cleanup all` | Delete all archived features | `/pdca cleanup all` |
| `cleanup {feature}` | Delete specific feature | `/pdca cleanup old-feature` |
**Output Example**:
```
🧹 PDCA Cleanup
─────────────────────────────
Archived features found: 3
1. feature-a (archived: 2026-01-15)
2. feature-b (archived: 2026-01-20)
3. feature-c (archived: 2026-01-25)
Select features to cleanup:
[ ] All archived features
[ ] Select specific features
[ ] Cancel
```
**Related Functions** (`lib/pdca/status.js`):
- `getArchivedFeatures()` - Get list of archived features
- `cleanupArchivedFeatures(features?)` - Cleanup specific or all archived
- `deleteFeatureFromStatus(feature)` - Delete single feature
- `enforceFeatureLimit(max=50)` - Auto cleanup when limit exceeded
**Notes**:
- Only archived/completed features can be deleted
- Active features are protected from deletion
- Archive documents remain in `docs/archive/` (only status is cleaned)
### status (Status Check)
1. Read `.hmcmkit-memory.json`
2. Display current feature, PDCA phase, Task status
3. Visualize progress
**Output Example**:
```
📊 PDCA Status
─────────────────────────────
Feature: user-authentication
Phase: Check (Gap Analysis)
Match Rate: 85%
Iteration: 2/5
─────────────────────────────
[Plan] ✅ → [Design] ✅ → [Do] ✅ → [Check] 🔄 → [Act] ⏳
```
### next (Next Phase)
1. Check current PDCA phase
2. Suggest next phase guide and commands
3. Confirm with user via AskUserQuestion
**Phase Guide**:
| Current | Next | Suggestion |
|---------|------|------------|
| None | pm | `/pdca pm [feature]` (recommended) or `/pdca plan [feature]` |
| pm | plan | `/pdca plan [feature]` (PRD auto-referenced) |
| plan | design | `/pdca design [feature]` |
| design | do | Implementation start guide |
| do | check | `/pdca analyze [feature]` |
| check (<90%) | act | `/pdca iterate [feature]` |
| check (>=90%) | report | `/pdca report [feature]` |
| report | archive | `/pdca archive [feature]` |
## Template References
Templates loaded from imports are used when executing each action:
| Action | Template | Purpose |
|--------|----------|---------|
| plan | `plan.template.md` | Plan document structure |
| design | `design.template.md` | Design document structure |
| do | `do.template.md` | Implementation guide structure |
| analyze | `analysis.template.md` | Analysis report structure |
| report | `report.template.md` | Completion report structure |
## Task Integration
Each PDCA phase automatically integrates with Task System:
```
Task Creation Pattern:
┌────────────────────────────────────────┐
│ [PM] {feature} │
│ ↓ (optional, pre-Plan) │
│ [Plan] {feature} │
│ ↓ (blockedBy) │
│ [Design] {feature} │
│ ↓ (blockedBy) │
│ [Do] {feature} │
│ ↓ (blockedBy) │
│ [Check] {feature} │
│ ↓ (blockedBy, Check < 90%) │
│ [Act-1] {feature} │
│ ↓ (on iteration) │
│ [Act-N] {feature} │
│ ↓ (Check >= 90%) │
│ [Report] {feature} │
│ ↓ (after Report completion) │
│ [Archive] {feature} │
└────────────────────────────────────────┘
```
## Agent Integration
| Action | Agent | Role |
|--------|-------|------|
| pm | pm-lead | Orchestrate PM Agent Team (4 sub-agents) |
| analyze | gap-detector | Compare Design vs Implementation |
| iterate | pdca-iterator | Auto code fix and re-verification |
| report | report-generator | Generate completion report |
## Usage Examples
```bash
# Run PM analysis (recommended before planning)
/pdca pm user-authentication
# Start new feature
/pdca plan user-authentication
# Create design document
/pdca design user-authentication
# Implementation guide
/pdca do user-authentication
# Gap analysis after implementation
/pdca analyze user-authentication
# Auto improvement (if needed)
/pdca iterate user-authentication
# Completion report
/pdca report user-authentication
# Check current status
/pdca status
# Guide to next phase
/pdca next
```
## Legacy Commands Mapping
| Legacy Command | PDCA Skill |
|----------------|------------|
| `/pdca-plan` | `/pdca plan` |
| `/pdca-design` | `/pdca design` |
| `/pdca-analyze` | `/pdca analyze` |
| `/pdca-iterate` | `/pdca iterate` |
| `/pdca-report` | `/pdca report` |
| `/pdca-status` | `/pdca status` |
| `/pdca-next` | `/pdca next` |
| `/archive` | `/pdca archive` |
## Output Style Integration (v1.5.1)
PDCA workflows benefit from the `hmcmkit-pdca-guide` output style:
```
/output-style hmcmkit-pdca-guide
```
This provides PDCA-specific response formatting:
- Phase status badges: `[Plan] -> [Design] -> [Do] -> [Check] -> [Act]`
- Gap analysis suggestions after code changes
- Next-phase guidance with checklists
- Feature usage report integration
When running PDCA commands, suggest this style if not already active.
## Agent Teams Integration (v1.5.1)
For Dynamic/Enterprise projects, PDCA phases can run in parallel using Agent Teams:
```
/pdca team {feature} Start parallel PDCA
/pdca team status Monitor teammate progress
/pdca team cleanup End team session
```
Suggest Agent Teams when:
- Feature is classified as Major Feature (>= 1000 chars)
- Match Rate < 70% (parallel iteration can speed up fixes)
- Project level is Dynamic or Enterprise
CTO-Led Team Orchestration Patterns:
| Level | Plan | Design | Do | Check | Act |
|-------|------|--------|-----|-------|-----|
| Dynamic | leader | leader | swarm | council | leader |
| Enterprise | leader | council | swarm | council | watchdog |
## Auto Triggers
Auto-suggest related action when detecting these keywords:
| Keyword | Suggested Action |
|---------|------------------|
| "pm", "product discovery", "PRD", "market analysis" | pm |
| "plan", "planning", "roadmap" | plan |
| "design", "architecture", "spec" | design |
| "implement", "develop", "build" | do |
| "verify", "analyze", "check" | analyze |
| "improve", "iterate", "fix" | iterate |
| "complete", "report", "summary" | report |
| "archive", "store" | archive |
| "cleanup", "clean", "remove old" | cleanup |
## Slash Invoke Pattern (CC 2.1.0+)
Skills 2.0 enables direct slash invocation for all PDCA commands:
- `/pdca plan [feature]` — Create Plan document
- `/pdca design [feature]` — Create Design document
- `/pdca do [feature]` — Implementation guide
- `/pdca analyze [feature]` — Gap analysis (Check phase)
- `/pdca iterate [feature]` — Auto-improvement (Act phase)
- `/pdca report [feature]` — Completion report
- `/pdca status` — Current PDCA status
- `/pdca next` — Next phase guide
- `/plan-plus [feature]` — Brainstorming-enhanced planning
Hot reload: SKILL.md changes reflect without session restart (CC 2.1.0+).
## PDCA Auto-Monitoring (CC v2.1.71+)
CC v2.1.71 introduces `/loop` command and Cron tools for automated monitoring.
### Usage Examples
- `/loop 5m /pdca status` - Check PDCA status every 5 minutes
- `/loop 10m /pdca analyze [feature]` - Run Gap analysis every 10 minutes
- Use Cron tools for session-level scheduled checks
### CTO Team Integration
- Long CTO Team sessions benefit from `/loop` for progress monitoring
- stdin freeze fixed in v2.1.71 ensures reliable long sessions
- Background agent recovery (v2.1.71) makes `background: true` agents reliable
@@ -0,0 +1,143 @@
---
name: phase-1-schema
classification: capability
classification-reason: Pattern guidance may overlap with model's built-in knowledge as it improves
deprecation-risk: medium
description: |
Define project terminology, data structures, entities, and relationships.
Triggers: schema, data model, entity, terminology, 스키마, 데이터 모델, 용어.
agent: hmcmkit:pipeline-guide
allowed-tools:
- Read
- Write
- Glob
- Grep
user-invocable: false
imports:
- ${PLUGIN_ROOT}/templates/pipeline/phase-1-schema.template.md
- ${PLUGIN_ROOT}/templates/shared/naming-conventions.md
next-skill: phase-2-convention
pdca-phase: plan
task-template: "[Phase-1] {feature}"
---
# Phase 1: Schema/Terminology Definition
> Define terminology and data structures used throughout the project
## Purpose
Unify the language of the project. Ensure all team members (or AI) communicate using the same terms and clearly understand data structures.
## What to Do in This Phase
1. **Build Glossary**: Map business terms + global standards
2. **Identify Entities**: Determine what "things" exist
3. **Define Relationships**: Relationships between entities
4. **Design Schema**: Define data structures
## Glossary
### Why is it Needed?
**Explaining business terms to Antigravity Platform every time is tedious**.
Creating a glossary allows:
- AI Agent to automatically reference for context understanding
- Team communication consistency
- Reduced onboarding time for new team members/AI
### Term Categories
| Category | Description | Example |
|----------|-------------|---------|
| **Business Terms** | Internal proprietary terms | "Caddy" (golf booking assistant) |
| **Global Standards** | Industry common or technical standard terms | "OAuth", "REST API" |
| **Mapping** | Business ↔ Global correspondence | "Member" = User, "Payment" = Payment |
### Glossary Template
```markdown
## Business Terms (Internal Terms)
| Term | English | Definition | Global Standard Mapping |
|------|---------|------------|------------------------|
| Caddy | Caddy | AI assistant that helps book golf rounds | Booking Assistant |
| Round | Round | One 18-hole golf play | Session, Booking |
| Green Fee | Green Fee | Golf course usage fee | Usage Fee |
## Global Standards
| Term | Definition | Reference |
|------|------------|-----------|
| OAuth 2.0 | Authentication protocol | RFC 6749 |
| REST | API architecture style | - |
| UUID | Universal Unique Identifier | RFC 4122 |
## Term Usage Rules
1. Use **English** in code (`Caddy`, `Round`)
2. Use **local language** in UI/docs (Caddy, Round)
3. API responses prioritize **global standards** (`booking_assistant`)
```
### Antigravity Platform Auto-Reference Setup
To have AI Agent automatically reference the glossary:
**Method 1**: Include in agents.md
```markdown
## Term Reference
For this project's term definitions, see `docs/01-plan/glossary.md`.
```
**Method 2**: Add term rules to project agents.md
```markdown
<!-- Add to agents.md -->
Project terms are defined in docs/01-plan/glossary.md.
Always reference when using business terms.
```
## Deliverables
```
docs/01-plan/
├── glossary.md # Glossary (recommended new)
│ ├── Business Terms
│ ├── Global Standards
│ └── Mapping Table
├── schema.md # Data schema
├── terminology.md # (existing) → recommend merging into glossary.md
└── domain-model.md # Domain model
```
## PDCA Application
- **Plan**: Identify what entities/terms are needed
- **Design**: Design schema structure, relationships
- **Do**: Write documentation
- **Check**: Review for omissions/contradictions
- **Act**: Finalize and proceed to Phase 2
## Level-wise Application
| Level | Application Level |
|-------|------------------|
| Starter | Simple (core terms only) |
| Dynamic | Detailed (all entities) |
| Enterprise | Detailed (per microservice) |
## Example Questions
```
"What are the core 'things' this project deals with?"
"What are the relationships between users, products, orders...?"
"Are 'member' and 'user' the same or different?"
```
## Template
See `templates/pipeline/phase-1-schema.template.md`
## Next Phase
Phase 2: Coding Convention → Now that terms are defined, define code rules
@@ -0,0 +1,609 @@
---
name: phase-2-convention
classification: workflow
classification-reason: Process automation persists regardless of model advancement
deprecation-risk: none
description: |
Define coding rules, conventions, and standards for AI collaboration.
Triggers: convention, coding style, lint, rules, 코딩 규칙, 컨벤션.
agent: hmcmkit:pipeline-guide
allowed-tools:
- Read
- Write
- Glob
- Grep
user-invocable: false
imports:
- ${PLUGIN_ROOT}/templates/pipeline/phase-2-convention.template.md
- ${PLUGIN_ROOT}/templates/shared/naming-conventions.md
next-skill: phase-3-mockup
pdca-phase: plan
task-template: "[Phase-2] {feature}"
---
# Phase 2: Coding Convention
> Define code writing rules
## Purpose
Maintain consistent code style. Especially important when collaborating with AI - clarify what style AI should use when writing code.
## What to Do in This Phase
1. **Naming Rules**: Variables, functions, files, folder names
2. **Code Style**: Indentation, quotes, semicolons, etc.
3. **Structure Rules**: Folder structure, file separation criteria
4. **Pattern Definition**: Frequently used code patterns
## Deliverables
```
Project Root/
├── CONVENTIONS.md # Full conventions
└── docs/01-plan/
├── naming.md # Naming rules
└── structure.md # Structure rules
```
## PDCA Application
- **Plan**: Identify necessary convention items
- **Design**: Design detailed rules
- **Do**: Write convention documents
- **Check**: Review consistency/practicality
- **Act**: Finalize and proceed to Phase 3
## Level-wise Application
| Level | Application Level |
|-------|------------------|
| Starter | Basic (essential rules only) |
| Dynamic | Extended (including API, state management) |
| Enterprise | Extended (per-service rules) |
## Core Convention Items
### Naming
- Components: PascalCase
- Functions: camelCase
- Constants: UPPER_SNAKE_CASE
- Files: kebab-case or PascalCase
### Folder Structure
```
src/
├── components/ # Reusable components
├── features/ # Feature modules
├── hooks/ # Custom hooks
├── utils/ # Utilities
└── types/ # Type definitions
```
---
## Environment Variable Convention
### Why Define at Design Stage?
```
❌ Organizing env vars just before deployment
→ Missing variables, naming inconsistency, deployment delays
✅ Establish convention at design stage
→ Consistent naming, clear categorization, fast deployment
```
### Environment Variable Naming Rules
| Prefix | Purpose | Exposure Scope | Example |
|--------|---------|----------------|---------|
| `NEXT_PUBLIC_` | Client-exposed | Browser | `NEXT_PUBLIC_API_URL` |
| `DB_` | Database | Server only | `DB_HOST`, `DB_PASSWORD` |
| `API_` | External API keys | Server only | `API_STRIPE_SECRET` |
| `AUTH_` | Authentication | Server only | `AUTH_SECRET`, `AUTH_GOOGLE_ID` |
| `SMTP_` | Email service | Server only | `SMTP_HOST`, `SMTP_PASSWORD` |
| `STORAGE_` | File storage | Server only | `STORAGE_S3_BUCKET` |
```
⚠️ Security Principles
- Never expose anything except NEXT_PUBLIC_* to client
- API keys and passwords must be server-only variables
- Never commit sensitive info in .env files
```
### .env File Structure
```
Project Root/
├── .env.example # Template (in Git, values empty)
├── .env.local # Local development (Git ignored)
├── .env.development # Development env defaults
├── .env.staging # Staging env defaults
├── .env.production # Production defaults (no sensitive info)
└── .env.test # Test environment
```
### .env.example Template
```bash
# .env.example - This file is included in Git
# Set actual values in .env.local
# ===== App Settings =====
NODE_ENV=development
NEXT_PUBLIC_APP_URL=http://localhost:3000
# ===== Database =====
DB_HOST=
DB_PORT=5432
DB_NAME=
DB_USER=
DB_PASSWORD=
# ===== Authentication =====
AUTH_SECRET= # openssl rand -base64 32
AUTH_GOOGLE_ID=
AUTH_GOOGLE_SECRET=
# ===== External Services =====
NEXT_PUBLIC_API_URL=
API_STRIPE_SECRET=
SMTP_HOST=
SMTP_USER=
SMTP_PASSWORD=
```
### Environment-wise Value Classification
| Variable Type | .env.example | .env.local | CI/CD Secrets |
|---------------|:------------:|:----------:|:-------------:|
| App URL | Template | Local value | Per-env value |
| API endpoints | Template | Local/dev | Per-env value |
| DB password | Empty | Local value | ✅ Secrets |
| API keys | Empty | Test key | ✅ Secrets |
| JWT Secret | Empty | Local value | ✅ Secrets |
### Environment Variable Validation
```typescript
// lib/env.ts - Validate env vars at app startup
import { z } from 'zod';
const envSchema = z.object({
// Required
DATABASE_URL: z.string().url(),
AUTH_SECRET: z.string().min(32),
// Optional (with defaults)
NODE_ENV: z.enum(['development', 'staging', 'production']).default('development'),
// Client-exposed
NEXT_PUBLIC_APP_URL: z.string().url(),
});
// Validation and type inference
export const env = envSchema.parse(process.env);
// Type-safe usage
// env.DATABASE_URL ← autocomplete supported
```
### Environment Variable Checklist
- [ ] **Naming Consistency**
- [ ] Follow prefix rules (NEXT_PUBLIC_, DB_, API_, etc.)
- [ ] Use UPPER_SNAKE_CASE
- [ ] **File Structure**
- [ ] Create .env.example (template)
- [ ] Register .env.local in .gitignore
- [ ] Separate .env files per environment
- [ ] **Security**
- [ ] Classify sensitive info
- [ ] Verify client-exposed variables
- [ ] Organize Secrets list (for Phase 9 deployment)
---
## Clean Architecture Principles
### Why Define at Design Stage?
```
Clean Architecture = Code resilient to change
❌ Developing without architecture
→ Spaghetti code, multiple file changes for each modification
✅ Define layers at design stage
→ Separation of concerns, easy testing, easy maintenance
```
### 4-Layer Architecture (Recommended)
```
src/
├── presentation/ # or app/, pages/
│ ├── components/ # UI components
│ ├── hooks/ # State management hooks
│ └── pages/ # Page components
│
├── application/ # or services/, features/
│ ├── use-cases/ # Business use cases
│ └── services/ # API service wrappers
│
├── domain/ # or types/, entities/
│ ├── entities/ # Domain entities
│ ├── types/ # Type definitions
│ └── constants/ # Domain constants
│
└── infrastructure/ # or lib/, api/
├── api/ # API clients
├── db/ # Database connections
└── external/ # External services
```
### Layer Responsibilities and Rules
| Layer | Responsibility | Can Depend On | Cannot Depend On |
|-------|---------------|---------------|------------------|
| **Presentation** | UI rendering, user events | Application, Domain | Infrastructure directly |
| **Application** | Business logic orchestration | Domain, Infrastructure | Presentation |
| **Domain** | Core business rules, types | Nothing (independent) | All external layers |
| **Infrastructure** | External system connections | Domain | Application, Presentation |
### Dependency Rule
```typescript
// ❌ Bad: Presentation directly calls Infrastructure
// components/UserList.tsx
import { apiClient } from '@/lib/api/client'; // Direct import forbidden!
export function UserList() {
const users = apiClient.get('/users'); // ❌
}
// ✅ Good: Presentation → Application → Infrastructure
// hooks/useUsers.ts
import { userService } from '@/services/user.service';
export function useUsers() {
return useQuery({
queryKey: ['users'],
queryFn: userService.getList, // ✅ Call through Service
});
}
// components/UserList.tsx
import { useUsers } from '@/hooks/useUsers';
export function UserList() {
const { data: users } = useUsers(); // ✅ Call through Hook
}
```
### File Import Rules
```typescript
// ===== Allowed import directions =====
// In presentation/:
import { User } from '@/domain/types'; // ✅ Domain OK
import { useUsers } from '@/hooks/useUsers'; // ✅ Same layer OK
import { userService } from '@/services/user'; // ✅ Application OK
// In application/:
import { User } from '@/domain/types'; // ✅ Domain OK
import { apiClient } from '@/lib/api/client'; // ✅ Infrastructure OK
// In domain/:
// Minimize external imports (pure types/logic only)
// In infrastructure/:
import { User } from '@/domain/types'; // ✅ Domain OK
// ===== Forbidden imports =====
// In domain/:
import { apiClient } from '@/lib/api/client'; // ❌ Infrastructure forbidden
import { Button } from '@/components/ui/button'; // ❌ Presentation forbidden
// In infrastructure/:
import { useUsers } from '@/hooks/useUsers'; // ❌ Presentation forbidden
```
### Level-wise Application
| Level | Architecture Application |
|-------|-------------------------|
| **Starter** | Simple structure (components, lib) |
| **Dynamic** | 3-4 layer separation (recommended structure) |
| **Enterprise** | Strict layer separation + DI container |
### Starter Level Folder Structure
```
src/
├── components/ # UI components
├── lib/ # Utilities, API
└── types/ # Type definitions
```
### Dynamic Level Folder Structure
```
src/
├── components/ # Presentation
│ └── ui/
├── features/ # Feature modules (Application + Presentation)
│ ├── auth/
│ └── product/
├── hooks/ # Presentation (state management)
├── services/ # Application
├── types/ # Domain
└── lib/ # Infrastructure
└── api/
```
### Enterprise Level Folder Structure
```
src/
├── presentation/
│ ├── components/
│ ├── hooks/
│ └── pages/
├── application/
│ ├── use-cases/
│ └── services/
├── domain/
│ ├── entities/
│ └── types/
└── infrastructure/
├── api/
└── db/
```
---
## Phase Connection
Conventions defined in this Phase are verified in later Phases:
| Definition (Phase 2) | Verification (Phase 8) |
|----------------------|------------------------|
| Naming rules | Naming consistency check |
| Folder structure | Structure consistency check |
| Environment variable convention | Env var naming check |
| Clean architecture principles | Dependency direction check |
---
## Template
See `templates/pipeline/phase-2-convention.template.md`
## Next Phase
Phase 3: Mockup Development → Rules are set, now rapid prototyping
---
## 6. Reusability Principles
### 6.1 Function Design
#### Creating Generic Functions
```typescript
// ❌ Handles only specific case
function formatUserName(user: User) {
return `${user.firstName} ${user.lastName}`
}
// ✅ Generic
function formatFullName(firstName: string, lastName: string) {
return `${firstName} ${lastName}`
}
// Usage
formatFullName(user.firstName, user.lastName)
formatFullName(author.first, author.last)
```
#### Parameter Generalization
```typescript
// ❌ Tied to specific type
function calculateOrderTotal(order: Order) {
return order.items.reduce((sum, item) => sum + item.price, 0)
}
// ✅ Generalized with interface
interface HasPrice { price: number }
function calculateTotal<T extends HasPrice>(items: T[]) {
return items.reduce((sum, item) => sum + item.price, 0)
}
// Can be used in various places
calculateTotal(order.items)
calculateTotal(cart.products)
calculateTotal(invoice.lineItems)
```
### 6.2 Component Design
#### Composable Components
```tsx
// ❌ Hardcoded structure
function UserCard({ user }: { user: User }) {
return (
<div className="card">
<img src={user.avatar} />
<h3>{user.name}</h3>
<p>{user.email}</p>
</div>
)
}
// ✅ Composable
function Card({ children, className }: CardProps) {
return <div className={cn("card", className)}>{children}</div>
}
function Avatar({ src, alt }: AvatarProps) {
return <img src={src} alt={alt} className="avatar" />
}
// Use by combining
<Card>
<Avatar src={user.avatar} alt={user.name} />
<h3>{user.name}</h3>
<p>{user.email}</p>
</Card>
```
#### Props Extensibility
```tsx
// ❌ Limited props
interface ButtonProps {
label: string
onClick: () => void
}
// ✅ Extend HTML attributes
interface ButtonProps extends React.ButtonHTMLAttributes<HTMLButtonElement> {
variant?: 'default' | 'outline' | 'ghost'
size?: 'sm' | 'md' | 'lg'
}
// All button attributes available
<Button type="submit" disabled={isLoading}>
Save
</Button>
```
### 6.3 Extraction Criteria
#### When to Extract as Function
```
1. Same logic used 2+ times
2. Logic is complex enough to need a name
3. Logic that needs testing
4. Can be used in other files
```
#### When to Extract as Component
```
1. Same UI pattern repeats
2. Has independent state
3. Is a reusable unit
4. JSX over 50 lines
```
---
## 7. Extensibility Principles
### 7.1 Configuration-Based Design
```typescript
// ❌ Listing conditionals
function getStatusColor(status: string) {
if (status === 'active') return 'green'
if (status === 'pending') return 'yellow'
if (status === 'error') return 'red'
return 'gray'
}
// ✅ Configuration object
const STATUS_CONFIG = {
active: { color: 'green', label: 'Active' },
pending: { color: 'yellow', label: 'Pending' },
error: { color: 'red', label: 'Error' },
} as const
function getStatusConfig(status: keyof typeof STATUS_CONFIG) {
return STATUS_CONFIG[status] ?? { color: 'gray', label: status }
}
// Adding new status = just add config
```
### 7.2 Strategy Pattern
```typescript
// ❌ Listing switch statements
function processPayment(method: string, amount: number) {
switch (method) {
case 'card':
// Card payment logic
break
case 'bank':
// Bank transfer logic
break
}
}
// ✅ Strategy pattern
interface PaymentStrategy {
process(amount: number): Promise<Result>
}
const paymentStrategies: Record<string, PaymentStrategy> = {
card: new CardPayment(),
bank: new BankTransfer(),
}
function processPayment(method: string, amount: number) {
const strategy = paymentStrategies[method]
if (!strategy) throw new Error(`Unknown method: ${method}`)
return strategy.process(amount)
}
// Adding new payment method = just add strategy
```
### 7.3 Plugin Structure
```typescript
// Extensible system
interface Plugin {
name: string
init(): void
execute(data: unknown): unknown
}
class PluginManager {
private plugins: Plugin[] = []
register(plugin: Plugin) {
this.plugins.push(plugin)
}
executeAll(data: unknown) {
return this.plugins.reduce(
(result, plugin) => plugin.execute(result),
data
)
}
}
// New feature = add plugin
```
---
## 8. Duplication Prevention Checklist
### Before Writing Code
- [ ] Is there a similar function in utils/?
- [ ] Is there a similar component in components/?
- [ ] Is there a similar hook in hooks/?
- [ ] Did you search the entire project?
### After Writing Code
- [ ] Is the same code in 2+ places? → Extract
- [ ] Can this code be used elsewhere? → Move
- [ ] Are there hardcoded values? → Make constants
- [ ] Is it tied to a specific type? → Generalize
@@ -0,0 +1,336 @@
---
name: phase-3-mockup
classification: capability
classification-reason: Highly likely to be subsumed by model's native capabilities
deprecation-risk: high
description: |
Create UI/UX mockups and HTML/CSS/JS prototypes without a designer.
Triggers: mockup, prototype, wireframe, UI design, 목업, 프로토타입.
agents:
default: hmcmkit:pipeline-guide
frontend: hmcmkit:frontend-architect
allowed-tools:
- Read
- Write
- Edit
- Glob
- WebSearch
user-invocable: false
imports:
- ${PLUGIN_ROOT}/templates/pipeline/phase-3-mockup.template.md
next-skill: phase-4-api
pdca-phase: design
task-template: "[Phase-3] {feature}"
---
# Phase 3: Mockup Development
> Create trendy UI without a designer + Consider Next.js componentization
## Purpose
Quickly validate ideas before actual implementation. **Even without a designer**, research UI/UX trends to create high-quality prototypes, designed for easy conversion to Next.js components later.
## What to Do in This Phase
1. **Screen Mockups**: Implement UI with HTML/CSS
2. **Interactions**: Implement behavior with basic JavaScript
3. **Data Simulation**: Simulate API responses with JSON files
4. **Feature Validation**: Test user flows
## Deliverables
```
mockup/
├── pages/ # HTML pages
│ ├── index.html
│ ├── login.html
│ └── ...
├── styles/ # CSS
│ └── main.css
├── scripts/ # JavaScript
│ └── app.js
└── data/ # JSON mock data
├── users.json
└── products.json
docs/02-design/
└── mockup-spec.md # Mockup specification
```
## PDCA Application
- **Plan**: What screens/features to mock up
- **Design**: Screen structure, interaction design
- **Do**: Implement HTML/CSS/JS
- **Check**: Verify feature behavior
- **Act**: Apply feedback and proceed to Phase 4
## Level-wise Application
| Level | Application Method |
|-------|-------------------|
| Starter | This stage may be the final deliverable |
| Dynamic | For validation before next stages |
| Enterprise | For quick PoC |
## Core Principles
```
"Working prototype over perfect code"
- Pure HTML/CSS/JS without frameworks
- JSON files instead of APIs for data simulation
- Fast feedback loops
- Structure considering Next.js componentization
```
---
## UI/UX Trend Research Methods
### Creating Trendy UI Without a Designer
#### 1. Trend Research Sources
| Source | Purpose | URL |
|--------|---------|-----|
| **Dribbble** | UI design trends, color palettes | dribbble.com |
| **Behance** | Real project case studies | behance.net |
| **Awwwards** | Latest web trends from award winners | awwwards.com |
| **Mobbin** | Mobile app UI patterns | mobbin.com |
| **Godly** | Landing page references | godly.website |
| **Land-book** | Landing page gallery | land-book.com |
#### 2. 2025-2026 UI/UX Trends
```
🎨 Visual Trends
├── Bento Grid Layout
├── Glassmorphism
├── Gradient Mesh
├── 3D Elements (minimal 3D elements)
└── Micro-interactions
📱 UX Trends
├── Dark Mode First
├── Skeleton Loading
├── Progressive Disclosure
├── Thumb-friendly Mobile Design
└── Accessibility (WCAG 2.1)
🔤 Typography
├── Variable Fonts
├── Large Hero Text
└── Mixed Font Weights
```
#### 3. Quick UI Implementation Tools
| Tool | Purpose |
|------|---------|
| **v0.dev** | AI-based UI generation (shadcn/ui compatible) |
| **Tailwind UI** | High-quality component templates |
| **Heroicons** | Icons |
| **Lucide** | Icons (React compatible) |
| **Coolors** | Color palette generation |
| **Realtime Colors** | Real-time color preview |
#### 4. Pre-Mockup Checklist
```markdown
## UI Research Checklist
- [ ] Analyzed 3+ similar services
- [ ] Decided color palette (Primary, Secondary, Accent)
- [ ] Selected typography (Heading, Body)
- [ ] Chose layout pattern (Grid, Bento, etc.)
- [ ] Collected reference design screenshots
```
---
## Design for Next.js Componentization
### Mockup → Component Transition Strategy
Considering **component separation** from the mockup stage makes Next.js transition easier.
#### 1. Design HTML Structure in Component Units
```html
<!-- ❌ Bad: Monolithic HTML -->
<div class="page">
<header>...</header>
<main>
<div class="hero">...</div>
<div class="features">...</div>
</main>
<footer>...</footer>
</div>
<!-- ✅ Good: Separated by component units -->
<!-- components/Header.html -->
<header data-component="Header">
<nav data-component="Navigation">...</nav>
</header>
<!-- components/Hero.html -->
<section data-component="Hero">
<h1 data-slot="title">...</h1>
<p data-slot="description">...</p>
<button data-component="Button" data-variant="primary">...</button>
</section>
```
#### 2. Separate CSS by Component
```
mockup/
├── styles/
│ ├── base/
│ │ ├── reset.css
│ │ └── variables.css # CSS variables (design tokens)
│ ├── components/
│ │ ├── button.css
│ │ ├── card.css
│ │ ├── header.css
│ │ └── hero.css
│ └── pages/
│ └── home.css
```
#### 3. Create Component Mapping Document
```markdown
## Component Mapping (mockup → Next.js)
| Mockup File | Next.js Component | Props |
|-------------|------------------|-------|
| `components/button.html` | `components/ui/Button.tsx` | variant, size, disabled |
| `components/card.html` | `components/ui/Card.tsx` | title, description, image |
| `components/header.html` | `components/layout/Header.tsx` | user, navigation |
```
#### 4. Design Data Structure as Props
```javascript
// mockup/data/hero.json
{
"title": "Innovative Service",
"description": "We provide better experiences",
"cta": {
"label": "Get Started",
"href": "/signup"
},
"image": "/hero-image.png"
}
// → When transitioning to Next.js
// components/Hero.tsx
interface HeroProps {
title: string;
description: string;
cta: {
label: string;
href: string;
};
image: string;
}
```
### Next.js Transition Example
**Mockup (HTML)**:
```html
<!-- mockup/components/feature-card.html -->
<div class="feature-card" data-component="FeatureCard">
<div class="feature-card__icon">🚀</div>
<h3 class="feature-card__title">Fast Speed</h3>
<p class="feature-card__description">We provide optimized performance.</p>
</div>
```
**Next.js Component**:
```tsx
// components/FeatureCard.tsx
interface FeatureCardProps {
icon: string;
title: string;
description: string;
}
export function FeatureCard({ icon, title, description }: FeatureCardProps) {
return (
<div className="feature-card">
<div className="feature-card__icon">{icon}</div>
<h3 className="feature-card__title">{title}</h3>
<p className="feature-card__description">{description}</p>
</div>
);
}
```
---
## JSON Data Simulation Example
```javascript
// scripts/app.js
async function loadProducts() {
const response = await fetch('./data/products.json');
const products = await response.json();
renderProducts(products);
}
```
### JSON Structure → Use as API Schema
```json
// mockup/data/products.json
// This structure becomes the basis for Phase 4 API design
{
"data": [
{
"id": 1,
"name": "Product Name",
"price": 10000,
"image": "/products/1.jpg"
}
],
"pagination": {
"page": 1,
"limit": 10,
"total": 50
}
}
```
---
## Deliverables Checklist
- [ ] **UI Research**
- [ ] Collected reference designs (minimum 3)
- [ ] Decided color palette
- [ ] Selected fonts
- [ ] **Mockup Implementation**
- [ ] HTML separated by component units
- [ ] Design tokens defined with CSS variables
- [ ] Data simulated with JSON
- [ ] **Next.js Transition Preparation**
- [ ] Component mapping document created
- [ ] Props interfaces defined
- [ ] Verified reusable structure
---
## Template
See `templates/pipeline/phase-3-mockup.template.md`
## Next Phase
Phase 4: API Design/Implementation → Mockup is validated, now implement actual backend
@@ -0,0 +1,289 @@
---
name: phase-4-api
classification: capability
classification-reason: Pattern guidance may overlap with model's built-in knowledge as it improves
deprecation-risk: medium
description: |
Design and implement backend APIs with Zero Script QA validation.
Triggers: API design, REST API, backend, endpoint, 백엔드 API, API 설계.
imports:
- ${PLUGIN_ROOT}/templates/pipeline/phase-4-api.template.md
- ${PLUGIN_ROOT}/templates/shared/api-patterns.md
- ${PLUGIN_ROOT}/templates/shared/error-handling-patterns.md
hooks:
Stop:
- type: command
command: "node ${HMCMKIT_PLUGIN_ROOT}/scripts/phase4-api-stop.js"
timeout: 10000
agent: hmcmkit:qa-monitor
allowed-tools:
- Read
- Write
- Edit
- Glob
- Grep
- Bash
user-invocable: false
next-skill: phase-5-design-system
pdca-phase: do
task-template: "[Phase-4] {feature}"
---
# Phase 4: API Design/Implementation + Zero Script QA
> Backend API implementation and script-free QA
## Purpose
Implement backend APIs that can store and retrieve data. Validate with structured logs instead of test scripts.
## What to Do in This Phase
1. **API Design**: Define endpoints, requests/responses
2. **API Implementation**: Write actual backend code
3. **Zero Script QA**: Log-based validation
## Deliverables
```
docs/02-design/
└── api-spec.md # API specification
src/api/ # API implementation
├── routes/
├── controllers/
└── services/
docs/03-analysis/
└── api-qa.md # QA results
```
## PDCA Application
- **Plan**: Define required API list
- **Design**: Design endpoints, requests/responses
- **Do**: Implement APIs
- **Check**: Validate with Zero Script QA
- **Act**: Fix bugs and proceed to Phase 5
## Level-wise Application
| Level | Application Method |
|-------|-------------------|
| Starter | Skip this Phase (no API) |
| Dynamic | Use bkend.ai BaaS (see below) |
| Enterprise | Implement APIs directly |
### Dynamic Level: bkend.ai BaaS API Implementation
#### Step 1: MCP Setup
```bash
ai-agent mcp add bkend --transport http https://api.bkend.ai/mcp
```
#### Step 2: Table Design (via MCP tools)
Natural language request: "Create a users table with name(required), email(required, unique), age fields"
-> MCP `backend_table_create` auto-invoked
#### Step 3: Service API Integration
| Method | Endpoint | Description |
|--------|----------|-------------|
| GET | /v1/data/{table} | List (filter, sort, page) |
| POST | /v1/data/{table} | Create data |
| GET | /v1/data/{table}/{id} | Get single |
| PATCH | /v1/data/{table}/{id} | Partial update |
| DELETE | /v1/data/{table}/{id} | Delete |
Required Headers: x-project-id, x-environment, Authorization
#### Step 4: Auth Implementation
Reference MCP tools `3_howto_implement_auth` and `6_code_examples_auth`
#### Step 5: Zero Script QA
- Check bkend REST API call logs in browser DevTools Network tab
- Verify API behavior via response code/body
## What is Zero Script QA?
```
Instead of writing test scripts, validate with structured debug logs
[API] POST /api/users
[INPUT] { "email": "test@test.com", "name": "Test" }
[PROCESS] Email duplicate check → Passed
[PROCESS] Password hash → Complete
[PROCESS] DB save → Success
[OUTPUT] { "id": 1, "email": "test@test.com" }
[RESULT] ✅ Success
Advantages:
- Save test code writing time
- See actual behavior with your eyes
- Easy debugging
```
## RESTful API Principles
### What is REST?
**RE**presentational **S**tate **T**ransfer - an architecture style for designing web services.
### 6 Core Principles
| Principle | Description | Example |
|-----------|-------------|---------|
| **1. Client-Server** | Separation of concerns between client and server | UI ↔ Data storage separated |
| **2. Stateless** | Each request is independent, server doesn't store client state | Auth token included with each request |
| **3. Cacheable** | Responses must indicate if cacheable | `Cache-Control` header |
| **4. Uniform Interface** | Interact through consistent interface | Detailed below |
| **5. Layered System** | Allow layered system architecture | Load balancer, proxy |
| **6. Code on Demand** | (Optional) Server can send code to client | JavaScript delivery |
### Uniform Interface Details
The core of RESTful APIs is a **uniform interface**.
#### 1. Resource-Based URLs
```
✅ Good (nouns, plural)
GET /users # User list
GET /users/123 # Specific user
POST /users # Create user
PUT /users/123 # Update user
DELETE /users/123 # Delete user
❌ Bad (using verbs)
GET /getUsers
POST /createUser
POST /deleteUser/123
```
#### 2. HTTP Method Meanings
| Method | Purpose | Idempotent | Safe |
|--------|---------|:----------:|:----:|
| `GET` | Read | ✅ | ✅ |
| `POST` | Create | ❌ | ❌ |
| `PUT` | Full update | ✅ | ❌ |
| `PATCH` | Partial update | ❌ | ❌ |
| `DELETE` | Delete | ✅ | ❌ |
> **Idempotent**: Same result even if requested multiple times
> **Safe**: Doesn't change server state
#### 3. HTTP Status Codes
```
2xx Success
├── 200 OK # Success (read, update)
├── 201 Created # Creation success
└── 204 No Content # Success but no response body (delete)
4xx Client Error
├── 400 Bad Request # Invalid request (validation failure)
├── 401 Unauthorized # Authentication required
├── 403 Forbidden # No permission
├── 404 Not Found # Resource not found
└── 409 Conflict # Conflict (duplicate, etc.)
5xx Server Error
├── 500 Internal Error # Internal server error
└── 503 Service Unavailable # Service unavailable
```
#### 4. Consistent Response Format
```json
// Success response
{
"data": {
"id": 123,
"email": "user@example.com",
"name": "John Doe"
},
"meta": {
"timestamp": "2026-01-08T10:00:00Z"
}
}
// Error response
{
"error": {
"code": "VALIDATION_ERROR",
"message": "Email format is invalid.",
"details": [
{ "field": "email", "message": "Please enter a valid email" }
]
}
}
// List response (pagination)
{
"data": [...],
"pagination": {
"page": 1,
"limit": 20,
"total": 100,
"totalPages": 5
}
}
```
### URL Design Rules
```
1. Use lowercase
✅ /users/123/orders
❌ /Users/123/Orders
2. Use hyphens (-), avoid underscores (_)
✅ /user-profiles
❌ /user_profiles
3. Express hierarchical relationships
✅ /users/123/orders/456
4. Filtering via query parameters
✅ /users?status=active&sort=created_at
❌ /users/active/sort/created_at
5. Version management
✅ /api/v1/users
✅ Header: Accept: application/vnd.api+json;version=1
```
### API Documentation Tools
| Tool | Features |
|------|----------|
| **OpenAPI (Swagger)** | Industry standard, auto documentation |
| **Postman** | Testing + documentation |
| **Insomnia** | Lightweight API client |
---
## API Design Checklist
- [ ] **RESTful Principles Compliance**
- [ ] Resource-based URLs (nouns, plural)
- [ ] Appropriate HTTP methods
- [ ] Correct status codes
- [ ] Unified error response format
- [ ] Authentication/authorization method defined
- [ ] Pagination method defined
- [ ] Versioning method (optional)
## Templates
- `templates/pipeline/phase-4-api.template.md`
- `templates/pipeline/zero-script-qa.template.md`
## Next Phase
Phase 5: Design System → APIs are ready, now build UI components
@@ -0,0 +1,517 @@
---
name: phase-5-design-system
classification: capability
classification-reason: Pattern guidance may overlap with model's built-in knowledge as it improves
deprecation-risk: medium
description: |
Build platform-independent design systems and consistent component libraries.
Triggers: design system, component library, design tokens, 디자인 시스템, 컴포넌트.
imports:
- ${PLUGIN_ROOT}/templates/pipeline/phase-5-design-system.template.md
hooks:
Stop:
- type: command
command: "node ${HMCMKIT_PLUGIN_ROOT}/scripts/phase5-design-stop.js"
timeout: 10000
agents:
default: hmcmkit:pipeline-guide
frontend: hmcmkit:frontend-architect
allowed-tools:
- Read
- Write
- Edit
- Glob
- Bash
user-invocable: false
next-skill: phase-6-ui-integration
pdca-phase: do
task-template: "[Phase-5] {feature}"
---
# Phase 5: Design System
> Build platform-independent design system
## Purpose
Build a reusable UI component library. Enable consistent design and fast development.
---
## What is a Design System?
### Definition
A design system is **a collection of reusable components and clear standards** that enables building consistent user experiences at scale.
### Why is it Needed? (Framework Agnostic)
| Problem | Design System Solution |
|---------|----------------------|
| Designer-developer mismatch | Single Source of Truth |
| Duplicate component development | Reusable component library |
| Inconsistent UI/UX | Unified design tokens and rules |
| Increased maintenance cost | Centralized change management |
| Delayed new member onboarding | Documented component catalog |
### 3 Layers of Design System
```
┌─────────────────────────────────────────────────────┐
│ Design Tokens │
│ Color, Typography, Spacing, Radius, Shadow, ... │
├─────────────────────────────────────────────────────┤
│ Core Components │
│ Button, Input, Card, Dialog, Avatar, Badge, ... │
├─────────────────────────────────────────────────────┤
│ Composite Components │
│ Form, DataTable, Navigation, SearchBar, ... │
└─────────────────────────────────────────────────────┘
```
### Platform-specific Implementation Tools
| Platform | Recommended Tools | Design Token Method |
|----------|------------------|---------------------|
| **Web (React/Next.js)** | shadcn/ui, Radix | CSS Variables |
| **Web (Vue)** | Vuetify, PrimeVue | CSS Variables |
| **Flutter** | Material 3, Custom Theme | ThemeData |
| **iOS (SwiftUI)** | Native Components | Asset Catalog, Color Set |
| **Android (Compose)** | Material 3 | MaterialTheme |
| **React Native** | NativeBase, Tamagui | StyleSheet + Theme |
---
## What to Do in This Phase
1. **Install Base Components**: Button, Input, Card, etc.
2. **Customize**: Adjust to project style
3. **Composite Components**: Combine multiple base components
4. **Documentation**: Document component usage
## Deliverables
```
components/
└── ui/ # shadcn/ui components
├── button.tsx
├── input.tsx
├── card.tsx
└── ...
lib/
└── utils.ts # Utilities (cn function, etc.)
docs/02-design/
└── design-system.md # Design system specification
```
## PDCA Application
- **Plan**: Required component list
- **Design**: Component structure, variants design
- **Do**: Implement/customize components
- **Check**: Review consistency
- **Act**: Finalize and proceed to Phase 6
## Level-wise Application
| Level | Application Method |
|-------|-------------------|
| Starter | Optional (simple projects may skip) |
| Dynamic | Required |
| Enterprise | Required (including design tokens) |
## shadcn/ui Installation
```bash
# Initial setup
npx shadcn@latest init
# Add components
npx shadcn@latest add button
npx shadcn@latest add input
npx shadcn@latest add card
```
## Required Component List
### Basic
- Button, Input, Textarea
- Card, Badge, Avatar
- Dialog, Sheet, Popover
### Form
- Form, Label, Select
- Checkbox, Radio, Switch
### Navigation
- Navigation Menu, Tabs
- Breadcrumb, Pagination
## Custom Theme Building
### Design Token Override
shadcn/ui is CSS variable-based, so customize themes in `globals.css`.
```css
/* globals.css */
@layer base {
:root {
/* ===== Colors ===== */
--background: 0 0% 100%;
--foreground: 222.2 84% 4.9%;
--primary: 221.2 83.2% 53.3%; /* Brand main color */
--primary-foreground: 210 40% 98%;
--secondary: 210 40% 96.1%;
--accent: 210 40% 96.1%;
--destructive: 0 84.2% 60.2%;
--muted: 210 40% 96.1%;
--muted-foreground: 215.4 16.3% 46.9%;
/* ===== Typography ===== */
--font-sans: 'Pretendard', sans-serif;
--font-mono: 'JetBrains Mono', monospace;
/* ===== Spacing (rem units) ===== */
--spacing-xs: 0.25rem; /* 4px */
--spacing-sm: 0.5rem; /* 8px */
--spacing-md: 1rem; /* 16px */
--spacing-lg: 1.5rem; /* 24px */
--spacing-xl: 2rem; /* 32px */
/* ===== Border Radius ===== */
--radius: 0.5rem;
--radius-sm: 0.25rem;
--radius-lg: 0.75rem;
--radius-full: 9999px;
/* ===== Shadows ===== */
--shadow-sm: 0 1px 2px 0 rgb(0 0 0 / 0.05);
--shadow-md: 0 4px 6px -1px rgb(0 0 0 / 0.1);
--shadow-lg: 0 10px 15px -3px rgb(0 0 0 / 0.1);
}
.dark {
--background: 222.2 84% 4.9%;
--foreground: 210 40% 98%;
--primary: 217.2 91.2% 59.8%;
/* ... dark mode overrides */
}
}
```
### Tailwind Config Extension
```js
// tailwind.config.js
module.exports = {
theme: {
extend: {
colors: {
brand: {
50: 'hsl(var(--brand-50))',
500: 'hsl(var(--brand-500))',
900: 'hsl(var(--brand-900))',
},
},
fontFamily: {
sans: ['var(--font-sans)', 'system-ui'],
mono: ['var(--font-mono)', 'monospace'],
},
spacing: {
'xs': 'var(--spacing-xs)',
'sm': 'var(--spacing-sm)',
'md': 'var(--spacing-md)',
'lg': 'var(--spacing-lg)',
'xl': 'var(--spacing-xl)',
},
borderRadius: {
'sm': 'var(--radius-sm)',
'DEFAULT': 'var(--radius)',
'lg': 'var(--radius-lg)',
'full': 'var(--radius-full)',
},
},
},
}
```
### Design Token Documentation
Recommended to create `docs/02-design/design-tokens.md` per project:
| Token | Value | Purpose |
|-------|-------|---------|
| `--primary` | `221.2 83.2% 53.3%` | Brand main color |
| `--radius` | `0.5rem` | Default border-radius |
| `--font-sans` | `Pretendard` | Body font |
## Component Customization
```tsx
// Extend default button to project style
const Button = React.forwardRef<
HTMLButtonElement,
ButtonProps & { isLoading?: boolean }
>(({ isLoading, children, ...props }, ref) => {
return (
<ButtonPrimitive ref={ref} {...props}>
{isLoading ? <Spinner /> : children}
</ButtonPrimitive>
);
});
```
---
## Mobile App Design System
### Flutter: Custom Theme Building
Flutter defines design tokens through `ThemeData`.
```dart
// lib/theme/app_theme.dart
import 'package:flutter/material.dart';
class AppTheme {
// ===== Design Tokens =====
// Colors
static const Color primary = Color(0xFF3B82F6);
static const Color secondary = Color(0xFF64748B);
static const Color destructive = Color(0xFFEF4444);
static const Color background = Color(0xFFFFFFFF);
static const Color foreground = Color(0xFF0F172A);
// Spacing
static const double spacingXs = 4.0;
static const double spacingSm = 8.0;
static const double spacingMd = 16.0;
static const double spacingLg = 24.0;
static const double spacingXl = 32.0;
// Border Radius
static const double radiusSm = 4.0;
static const double radiusMd = 8.0;
static const double radiusLg = 12.0;
static const double radiusFull = 9999.0;
// ===== Theme Data =====
static ThemeData get lightTheme => ThemeData(
useMaterial3: true,
colorScheme: ColorScheme.fromSeed(
seedColor: primary,
brightness: Brightness.light,
),
fontFamily: 'Pretendard',
// Button Theme
elevatedButtonTheme: ElevatedButtonThemeData(
style: ElevatedButton.styleFrom(
padding: EdgeInsets.symmetric(
horizontal: spacingMd,
vertical: spacingSm,
),
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(radiusMd),
),
),
),
// Card Theme
cardTheme: CardTheme(
elevation: 2,
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(radiusLg),
),
),
// Input Theme
inputDecorationTheme: InputDecorationTheme(
border: OutlineInputBorder(
borderRadius: BorderRadius.circular(radiusMd),
),
contentPadding: EdgeInsets.all(spacingSm),
),
);
static ThemeData get darkTheme => ThemeData(
useMaterial3: true,
colorScheme: ColorScheme.fromSeed(
seedColor: primary,
brightness: Brightness.dark,
),
fontFamily: 'Pretendard',
// ... dark theme overrides
);
}
```
### Flutter: Reusable Components
```dart
// lib/components/app_button.dart
import 'package:flutter/material.dart';
import '../theme/app_theme.dart';
enum AppButtonVariant { primary, secondary, destructive, outline }
class AppButton extends StatelessWidget {
final String label;
final VoidCallback? onPressed;
final AppButtonVariant variant;
final bool isLoading;
const AppButton({
required this.label,
this.onPressed,
this.variant = AppButtonVariant.primary,
this.isLoading = false,
super.key,
});
@override
Widget build(BuildContext context) {
return ElevatedButton(
onPressed: isLoading ? null : onPressed,
style: _getStyle(),
child: isLoading
? SizedBox(
width: 20,
height: 20,
child: CircularProgressIndicator(strokeWidth: 2),
)
: Text(label),
);
}
ButtonStyle _getStyle() {
switch (variant) {
case AppButtonVariant.destructive:
return ElevatedButton.styleFrom(
backgroundColor: AppTheme.destructive,
);
case AppButtonVariant.outline:
return ElevatedButton.styleFrom(
backgroundColor: Colors.transparent,
side: BorderSide(color: AppTheme.primary),
);
default:
return ElevatedButton.styleFrom();
}
}
}
```
### Flutter: Project Structure
```
lib/
├── theme/
│ ├── app_theme.dart # ThemeData + Design Tokens
│ ├── app_colors.dart # Color constants
│ ├── app_typography.dart # TextStyle definitions
│ └── app_spacing.dart # Spacing constants
├── components/
│ ├── app_button.dart
│ ├── app_input.dart
│ ├── app_card.dart
│ └── app_dialog.dart
└── main.dart
```
---
## Cross-Platform Design Token Sharing
### Design Token JSON (Platform Independent)
Centrally manage tokens with Figma Tokens or Style Dictionary.
```json
// tokens/design-tokens.json
{
"color": {
"primary": { "value": "#3B82F6" },
"secondary": { "value": "#64748B" },
"destructive": { "value": "#EF4444" }
},
"spacing": {
"xs": { "value": "4px" },
"sm": { "value": "8px" },
"md": { "value": "16px" },
"lg": { "value": "24px" }
},
"radius": {
"sm": { "value": "4px" },
"md": { "value": "8px" },
"lg": { "value": "12px" }
},
"font": {
"family": { "value": "Pretendard" },
"size": {
"sm": { "value": "14px" },
"md": { "value": "16px" },
"lg": { "value": "18px" }
}
}
}
```
### Platform-specific Conversion
```bash
# Generate tokens for each platform with Style Dictionary
npx style-dictionary build
# Output:
# - build/css/variables.css (Web)
# - build/dart/app_tokens.dart (Flutter)
# - build/swift/AppTokens.swift (iOS)
# - build/kt/AppTokens.kt (Android)
```
---
## Design System Checklist (Platform Agnostic)
### Required Items
- [ ] **Design Tokens Definition**
- [ ] Colors (Primary, Secondary, Semantic)
- [ ] Typography (Font Family, Sizes, Weights)
- [ ] Spacing (xs, sm, md, lg, xl)
- [ ] Border Radius
- [ ] Shadows/Elevation
- [ ] **Core Components**
- [ ] Button (variants: primary, secondary, outline, destructive)
- [ ] Input/TextField
- [ ] Card
- [ ] Dialog/Modal
- [ ] Avatar
- [ ] Badge
- [ ] **Composite Components**
- [ ] Form (with validation)
- [ ] Navigation (Header, Sidebar, Bottom Nav)
- [ ] Data Display (Table, List)
- [ ] **Documentation**
- [ ] Component catalog (Storybook / Widgetbook)
- [ ] Usage guidelines
- [ ] Do's and Don'ts
---
## Template
See `templates/pipeline/phase-5-design-system.template.md`
## Next Phase
Phase 6: UI Implementation + API Integration → Components are ready, now implement actual screens
@@ -0,0 +1,710 @@
---
name: phase-6-ui-integration
classification: capability
classification-reason: Pattern guidance may overlap with model's built-in knowledge as it improves
deprecation-risk: medium
description: |
Implement frontend UI and integrate with backend APIs — state management and API clients.
Triggers: UI integration, frontend-backend, API client, 프론트엔드 통합, UI 구현.
imports:
- ${PLUGIN_ROOT}/templates/pipeline/phase-6-ui.template.md
hooks:
Stop:
- type: command
command: "node ${HMCMKIT_PLUGIN_ROOT}/scripts/phase6-ui-stop.js"
timeout: 10000
agents:
default: hmcmkit:pipeline-guide
frontend: hmcmkit:frontend-architect
allowed-tools:
- Read
- Write
- Edit
- Glob
- Grep
- Bash
user-invocable: false
next-skill: phase-7-seo-security
pdca-phase: do
task-template: "[Phase-6] {feature}"
---
# Phase 6: UI Implementation + API Integration
> Actual UI implementation and API integration
## Purpose
Implement actual screens using design system components and integrate with APIs.
## What to Do in This Phase
1. **Page Implementation**: Develop each screen
2. **State Management**: Handle client state
3. **API Integration**: Call backend APIs
4. **Error Handling**: Handle loading and error states
## Deliverables
```
src/
├── pages/ # Page components
│ ├── index.tsx
│ ├── login.tsx
│ └── ...
├── features/ # Feature-specific components
│ ├── auth/
│ ├── product/
│ └── ...
└── hooks/ # API call hooks
├── useAuth.ts
└── useProducts.ts
docs/03-analysis/
└── ui-qa.md # QA results
```
## PDCA Application
- **Plan**: Define screens/features to implement
- **Design**: Component structure, state management design
- **Do**: UI implementation + API integration
- **Check**: Zero Script QA
- **Act**: Fix bugs and proceed to Phase 7
## Level-wise Application
| Level | Application Method |
|-------|-------------------|
| Starter | Static UI only (no API integration) |
| Dynamic | Full integration |
| Enterprise | Full integration + optimization |
## API Client Architecture
### Why is a Centralized API Client Needed?
| Problem (Scattered API Calls) | Solution (Centralized Client) |
|------------------------------|------------------------------|
| Duplicate error handling logic | Common error handler |
| Distributed auth token handling | Automatic token injection |
| Inconsistent response formats | Standardized response types |
| Multiple changes when endpoint changes | Single point of management |
| Difficult testing/mocking | Easy mock replacement |
### 3-Layer API Client Structure
```
┌─────────────────────────────────────────────────────────┐
│ UI Components │
│ (pages, features, hooks) │
├─────────────────────────────────────────────────────────┤
│ Service Layer │
│ (Domain-specific API call functions) │
│ authService, productService, orderService, ... │
├─────────────────────────────────────────────────────────┤
│ API Client Layer │
│ (Common settings, interceptors, error handling) │
│ apiClient (axios/fetch wrapper) │
└─────────────────────────────────────────────────────────┘
```
### Folder Structure
```
src/
├── lib/
│ └── api/
│ ├── client.ts # API client (axios/fetch wrapper)
│ ├── interceptors.ts # Request/response interceptors
│ └── error-handler.ts # Error handling logic
├── services/
│ ├── auth.service.ts # Auth-related APIs
│ ├── product.service.ts # Product-related APIs
│ └── order.service.ts # Order-related APIs
├── types/
│ ├── api.types.ts # Common API types
│ ├── auth.types.ts # Auth domain types
│ └── product.types.ts # Product domain types
└── hooks/
├── useAuth.ts # Hooks using Service
└── useProducts.ts
```
---
## API Client Implementation
### 1. Basic API Client (lib/api/client.ts)
```typescript
// lib/api/client.ts
import { ApiError, ApiResponse } from '@/types/api.types';
const BASE_URL = process.env.NEXT_PUBLIC_API_URL || '/api';
interface RequestConfig extends RequestInit {
params?: Record<string, string>;
}
class ApiClient {
private baseUrl: string;
constructor(baseUrl: string) {
this.baseUrl = baseUrl;
}
private async request<T>(
endpoint: string,
config: RequestConfig = {}
): Promise<ApiResponse<T>> {
const { params, ...init } = config;
// URL parameter handling
const url = new URL(`${this.baseUrl}${endpoint}`);
if (params) {
Object.entries(params).forEach(([key, value]) => {
url.searchParams.append(key, value);
});
}
// Default header settings
const headers = new Headers(init.headers);
if (!headers.has('Content-Type')) {
headers.set('Content-Type', 'application/json');
}
// Automatic auth token injection
const token = this.getAuthToken();
if (token) {
headers.set('Authorization', `Bearer ${token}`);
}
try {
const response = await fetch(url.toString(), {
...init,
headers,
});
return this.handleResponse<T>(response);
} catch (error) {
throw this.handleNetworkError(error);
}
}
private async handleResponse<T>(response: Response): Promise<ApiResponse<T>> {
const data = await response.json();
if (!response.ok) {
throw new ApiError(
data.error?.code || 'UNKNOWN_ERROR',
data.error?.message || 'An error occurred',
response.status,
data.error?.details
);
}
return data as ApiResponse<T>;
}
private handleNetworkError(error: unknown): ApiError {
if (error instanceof TypeError && error.message === 'Failed to fetch') {
return new ApiError('NETWORK_ERROR', 'Please check your network connection.', 0);
}
return new ApiError('UNKNOWN_ERROR', 'An unknown error occurred.', 0);
}
private getAuthToken(): string | null {
if (typeof window === 'undefined') return null;
return localStorage.getItem('auth_token');
}
// HTTP method wrappers
get<T>(endpoint: string, params?: Record<string, string>) {
return this.request<T>(endpoint, { method: 'GET', params });
}
post<T>(endpoint: string, body?: unknown) {
return this.request<T>(endpoint, {
method: 'POST',
body: JSON.stringify(body),
});
}
put<T>(endpoint: string, body?: unknown) {
return this.request<T>(endpoint, {
method: 'PUT',
body: JSON.stringify(body),
});
}
patch<T>(endpoint: string, body?: unknown) {
return this.request<T>(endpoint, {
method: 'PATCH',
body: JSON.stringify(body),
});
}
delete<T>(endpoint: string) {
return this.request<T>(endpoint, { method: 'DELETE' });
}
}
export const apiClient = new ApiClient(BASE_URL);
```
### 2. Common Type Definitions (types/api.types.ts)
```typescript
// types/api.types.ts
// ===== Standard API Response Format (matches Phase 4) =====
/** Success response */
export interface ApiResponse<T> {
data: T;
meta?: {
timestamp: string;
requestId?: string;
};
}
/** Paginated response */
export interface PaginatedResponse<T> extends ApiResponse<T[]> {
pagination: {
page: number;
limit: number;
total: number;
totalPages: number;
};
}
/** Error response */
export interface ApiErrorResponse {
error: {
code: string;
message: string;
details?: Array<{
field: string;
message: string;
}>;
};
}
// ===== Error Class =====
export class ApiError extends Error {
constructor(
public code: string,
message: string,
public status: number,
public details?: Array<{ field: string; message: string }>
) {
super(message);
this.name = 'ApiError';
}
/** Check if validation error */
isValidationError(): boolean {
return this.code === 'VALIDATION_ERROR' && !!this.details;
}
/** Check if auth error */
isAuthError(): boolean {
return this.status === 401 || this.code === 'UNAUTHORIZED';
}
/** Check if forbidden error */
isForbiddenError(): boolean {
return this.status === 403 || this.code === 'FORBIDDEN';
}
/** Check if not found error */
isNotFoundError(): boolean {
return this.status === 404 || this.code === 'NOT_FOUND';
}
}
// ===== Common Error Codes =====
export const ERROR_CODES = {
// Client errors
VALIDATION_ERROR: 'VALIDATION_ERROR',
UNAUTHORIZED: 'UNAUTHORIZED',
FORBIDDEN: 'FORBIDDEN',
NOT_FOUND: 'NOT_FOUND',
CONFLICT: 'CONFLICT',
// Server errors
INTERNAL_ERROR: 'INTERNAL_ERROR',
SERVICE_UNAVAILABLE: 'SERVICE_UNAVAILABLE',
// Network errors
NETWORK_ERROR: 'NETWORK_ERROR',
TIMEOUT_ERROR: 'TIMEOUT_ERROR',
} as const;
export type ErrorCode = typeof ERROR_CODES[keyof typeof ERROR_CODES];
```
---
## Service Layer Pattern
### Domain-specific Service Separation
```typescript
// services/auth.service.ts
import { apiClient } from '@/lib/api/client';
import { User, LoginRequest, LoginResponse, SignupRequest } from '@/types/auth.types';
export const authService = {
/** Login */
login(credentials: LoginRequest) {
return apiClient.post<LoginResponse>('/auth/login', credentials);
},
/** Signup */
signup(data: SignupRequest) {
return apiClient.post<User>('/auth/signup', data);
},
/** Logout */
logout() {
return apiClient.post<void>('/auth/logout');
},
/** Get current user info */
getMe() {
return apiClient.get<User>('/auth/me');
},
/** Refresh token */
refreshToken() {
return apiClient.post<LoginResponse>('/auth/refresh');
},
};
// services/product.service.ts
import { apiClient } from '@/lib/api/client';
import { Product, ProductFilter, CreateProductRequest } from '@/types/product.types';
import { PaginatedResponse } from '@/types/api.types';
export const productService = {
/** Get product list */
getList(filter?: ProductFilter) {
const params = filter ? {
page: String(filter.page || 1),
limit: String(filter.limit || 20),
...(filter.category && { category: filter.category }),
...(filter.search && { search: filter.search }),
} : undefined;
return apiClient.get<PaginatedResponse<Product>>('/products', params);
},
/** Get product details */
getById(id: string) {
return apiClient.get<Product>(`/products/${id}`);
},
/** Create product */
create(data: CreateProductRequest) {
return apiClient.post<Product>('/products', data);
},
/** Update product */
update(id: string, data: Partial<CreateProductRequest>) {
return apiClient.patch<Product>(`/products/${id}`, data);
},
/** Delete product */
delete(id: string) {
return apiClient.delete<void>(`/products/${id}`);
},
};
```
---
## Error Handling Pattern
### Global Error Handler
```typescript
// lib/api/error-handler.ts
import { ApiError, ERROR_CODES } from '@/types/api.types';
import { toast } from 'sonner'; // or another toast library
interface ErrorHandlerOptions {
showToast?: boolean;
redirectOnAuth?: boolean;
customMessages?: Record<string, string>;
}
export function handleApiError(
error: unknown,
options: ErrorHandlerOptions = {}
): void {
const { showToast = true, redirectOnAuth = true, customMessages = {} } = options;
if (!(error instanceof ApiError)) {
console.error('Unexpected error:', error);
if (showToast) {
toast.error('An unknown error occurred.');
}
return;
}
// Use custom message if available
const message = customMessages[error.code] || error.message;
// Handle by error type
switch (error.code) {
case ERROR_CODES.UNAUTHORIZED:
if (redirectOnAuth && typeof window !== 'undefined') {
localStorage.removeItem('auth_token');
window.location.href = '/login';
}
break;
case ERROR_CODES.FORBIDDEN:
if (showToast) toast.error('You do not have permission.');
break;
case ERROR_CODES.NOT_FOUND:
if (showToast) toast.error('The requested resource was not found.');
break;
case ERROR_CODES.VALIDATION_ERROR:
// Validation errors are handled by form
break;
case ERROR_CODES.NETWORK_ERROR:
if (showToast) toast.error('Please check your network connection.');
break;
default:
if (showToast) toast.error(message);
}
// Error logging (development environment)
if (process.env.NODE_ENV === 'development') {
console.error(`[API Error] ${error.code}:`, {
message: error.message,
status: error.status,
details: error.details,
});
}
}
```
### Error Handling in Hooks
```typescript
// hooks/useProducts.ts
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query';
import { productService } from '@/services/product.service';
import { handleApiError } from '@/lib/api/error-handler';
import { ProductFilter } from '@/types/product.types';
export function useProducts(filter?: ProductFilter) {
return useQuery({
queryKey: ['products', filter],
queryFn: () => productService.getList(filter),
// Auto error handling
throwOnError: false,
meta: {
errorHandler: (error: unknown) => handleApiError(error),
},
});
}
export function useCreateProduct() {
const queryClient = useQueryClient();
return useMutation({
mutationFn: productService.create,
onSuccess: () => {
// Invalidate cache
queryClient.invalidateQueries({ queryKey: ['products'] });
},
onError: (error) => {
handleApiError(error, {
customMessages: {
CONFLICT: 'Product name already exists.',
},
});
},
});
}
```
---
## Client-Server Type Sharing
### Methods for Type Consistency
```
Method 1: Shared Package (Monorepo)
├── packages/
│ └── shared-types/ # Common types
│ ├── api.types.ts
│ ├── auth.types.ts
│ └── product.types.ts
├── apps/
│ ├── web/ # Frontend
│ └── api/ # Backend
Method 2: Auto-generate Types from API Spec
├── openapi.yaml # OpenAPI spec
└── scripts/
└── generate-types.ts # Type auto-generation script
Method 3: tRPC / GraphQL CodeGen
└── Auto-infer types from schema
```
### Type Definition Example
```typescript
// types/auth.types.ts (client-server shared)
export interface User {
id: string;
email: string;
name: string;
role: 'user' | 'admin';
createdAt: string;
updatedAt: string;
}
export interface LoginRequest {
email: string;
password: string;
}
export interface LoginResponse {
user: User;
token: string;
expiresAt: string;
}
export interface SignupRequest {
email: string;
password: string;
name: string;
termsAgreed: boolean;
}
```
---
## API Integration Patterns
### Basic Pattern (fetch)
```typescript
async function getProducts() {
const response = await fetch('/api/products');
if (!response.ok) throw new Error('Failed to fetch');
return response.json();
}
```
### React Query Pattern
```typescript
function useProducts() {
return useQuery({
queryKey: ['products'],
queryFn: getProducts,
});
}
```
### SWR Pattern
```typescript
function useProducts() {
return useSWR('/api/products', fetcher);
}
```
## State Management Guide
```
Server state (API data) → React Query / SWR
Client state (UI state) → useState / useReducer
Global state (auth, etc.) → Context / Zustand
Form state → React Hook Form
```
## Zero Script QA Application
```
Validate UI behavior with logs:
[UI] Login button clicked
[STATE] isLoading: true
[API] POST /api/auth/login
[RESPONSE] { token: "...", user: {...} }
[STATE] isLoading: false, isLoggedIn: true
[NAVIGATE] → /dashboard
[RESULT] ✅ Login successful
```
---
## API Integration Checklist
### Architecture
- [ ] **Build API client layer**
- [ ] Centralized API client (lib/api/client.ts)
- [ ] Automatic auth token injection
- [ ] Common header settings
- [ ] **Service Layer separation**
- [ ] Domain-specific service files (auth, product, order, etc.)
- [ ] Each service uses only apiClient
- [ ] **Type consistency**
- [ ] Common API type definitions (ApiResponse, ApiError)
- [ ] Domain-specific type definitions (Request, Response)
- [ ] Decide server-client type sharing method
### Error Handling
- [ ] **Error code standardization**
- [ ] Error codes matching Phase 4 API spec
- [ ] User messages defined per error code
- [ ] **Global error handler**
- [ ] Redirect on auth error
- [ ] Network error handling
- [ ] Toast notifications
- [ ] **Form validation error handling**
- [ ] Field-specific error message display
- [ ] Integration with server validation errors
### Coding Conventions
- [ ] **API call rules**
- [ ] No direct fetch in components
- [ ] Must follow hooks → services → apiClient order
- [ ] Prevent duplicate calls for same data (caching)
- [ ] **Naming rules**
- [ ] Services: `{domain}.service.ts`
- [ ] Hooks: `use{Domain}{Action}.ts`
- [ ] Types: `{domain}.types.ts`
---
## Template
See `templates/pipeline/phase-6-ui.template.md`
## Next Phase
Phase 7: SEO/Security → Features are complete, now optimize and strengthen security
@@ -0,0 +1,356 @@
---
name: phase-7-seo-security
classification: capability
classification-reason: Pattern guidance may overlap with model's built-in knowledge as it improves
deprecation-risk: medium
description: |
Enhance SEO (meta tags, semantic HTML) and security (vulnerability checks, hardening).
Triggers: SEO, security, meta tags, vulnerability, 검색 최적화, 보안.
imports:
- ${PLUGIN_ROOT}/templates/pipeline/phase-7-seo-security.template.md
agents:
default: hmcmkit:code-analyzer
security: hmcmkit:security-architect
allowed-tools:
- Read
- Edit
- Glob
- Grep
- WebSearch
user-invocable: false
next-skill: phase-8-review
pdca-phase: do
task-template: "[Phase-7] {feature}"
---
# Phase 7: SEO/Security
> Search optimization and security enhancement
## Purpose
Make the application discoverable through search and defend against security vulnerabilities.
## What to Do in This Phase
1. **SEO Optimization**: Meta tags, structured data, sitemap
2. **Performance Optimization**: Core Web Vitals improvement
3. **Security Enhancement**: Authentication, authorization, vulnerability defense
## Deliverables
```
docs/02-design/
├── seo-spec.md # SEO specification
└── security-spec.md # Security specification
src/
├── middleware/ # Security middleware
└── components/
└── seo/ # SEO components
```
## PDCA Application
- **Plan**: Define SEO/security requirements
- **Design**: Meta tags, security policy design
- **Do**: SEO/security implementation
- **Check**: Inspection and verification
- **Act**: Improve and proceed to Phase 8
## Level-wise Application
| Level | Application Method |
|-------|-------------------|
| Starter | SEO only (minimal security) |
| Dynamic | SEO + basic security |
| Enterprise | SEO + advanced security |
## SEO Checklist
### Basic
- [ ] Per-page title, description
- [ ] Open Graph meta tags
- [ ] Canonical URL
- [ ] sitemap.xml
- [ ] robots.txt
### Structured Data
- [ ] JSON-LD schema
- [ ] Breadcrumb
- [ ] Product/Review schema (if applicable)
### Performance
- [ ] Image optimization (next/image)
- [ ] Font optimization
- [ ] Code splitting
## Security Checklist
### Authentication/Authorization
- [ ] Secure session management
- [ ] CSRF protection
- [ ] Proper permission checks
### Data Protection
- [ ] Input validation
- [ ] SQL injection defense
- [ ] XSS defense
### Communication Security
- [ ] HTTPS enforcement
- [ ] Security header configuration
- [ ] CORS policy
---
## Security Architecture (Cross-Phase Connection)
### Security Layer Structure
```
┌─────────────────────────────────────────────────────────────┐
│ Client (Browser) │
├─────────────────────────────────────────────────────────────┤
│ Phase 6: UI Security │
│ - XSS defense (input escaping) │
│ - CSRF token inclusion │
│ - No sensitive info storage on client │
├─────────────────────────────────────────────────────────────┤
│ Phase 4/6: API Communication Security │
│ - HTTPS enforcement │
│ - Authorization header (Bearer Token) │
│ - Content-Type validation │
├─────────────────────────────────────────────────────────────┤
│ Phase 4: API Server Security │
│ - Input validation │
│ - Rate Limiting │
│ - Minimal error messages (prevent sensitive info exposure) │
├─────────────────────────────────────────────────────────────┤
│ Phase 2/9: Environment Variable Security │
│ - Secrets management │
│ - Environment separation │
│ - Client-exposed variable distinction │
└─────────────────────────────────────────────────────────────┘
```
### Security Responsibilities by Phase
| Phase | Security Responsibility | Verification Items |
|-------|------------------------|-------------------|
| **Phase 2** | Environment variable convention | NEXT_PUBLIC_* distinction, Secrets list |
| **Phase 4** | API security design | Auth method, error codes, input validation |
| **Phase 6** | Client security | XSS defense, token management, sensitive info |
| **Phase 7** | Security implementation/inspection | Full security checklist |
| **Phase 9** | Deployment security | Secrets injection, HTTPS, security headers |
---
## Client Security (Phase 6 Connection)
### XSS Defense Principles
```
⚠️ XSS (Cross-Site Scripting) Defense
1. Never use innerHTML directly
2. Always sanitize user input when rendering as HTML
3. Leverage React's automatic escaping
4. Use DOMPurify library when needed
```
### No Sensitive Information Storage
```typescript
// ❌ Forbidden: Sensitive info in localStorage
localStorage.setItem('password', password);
localStorage.setItem('creditCard', cardNumber);
// ✅ Allowed: Store only tokens (httpOnly cookies recommended)
localStorage.setItem('auth_token', token);
// ✅ More secure: httpOnly cookie (set by server)
// Set-Cookie: token=xxx; HttpOnly; Secure; SameSite=Strict
```
### CSRF Defense
```typescript
// Include CSRF token in API client
// lib/api/client.ts
private async request<T>(endpoint: string, config: RequestConfig = {}) {
const headers = new Headers(config.headers);
// Add CSRF token
const csrfToken = this.getCsrfToken();
if (csrfToken) {
headers.set('X-CSRF-Token', csrfToken);
}
// ...
}
```
---
## API Security (Phase 4 Connection)
### Input Validation (Server-side)
```typescript
// All input must be validated on the server
import { z } from 'zod';
const CreateUserSchema = z.object({
email: z.string().email(),
password: z.string().min(8).max(100),
name: z.string().min(1).max(50),
});
// Usage in API Route
export async function POST(req: Request) {
const body = await req.json();
const result = CreateUserSchema.safeParse(body);
if (!result.success) {
return Response.json({
error: {
code: 'VALIDATION_ERROR',
message: 'Input is invalid.',
details: result.error.flatten().fieldErrors,
}
}, { status: 400 });
}
const { email, password, name } = result.data;
}
```
### Error Message Security
```typescript
// ❌ Dangerous: Detailed error info exposure
{
message: 'User with email test@test.com not found',
stack: error.stack, // Stack trace exposed!
}
// ✅ Safe: Minimal information only
{
code: 'NOT_FOUND',
message: 'User not found.',
}
// Detailed logs only on server
console.error(`User not found: ${email}`, error);
```
### Rate Limiting
```typescript
// middleware.ts
import { Ratelimit } from '@upstash/ratelimit';
const ratelimit = new Ratelimit({
redis: Redis.fromEnv(),
limiter: Ratelimit.slidingWindow(10, '10 s'),
});
export async function middleware(request: NextRequest) {
const ip = request.ip ?? '127.0.0.1';
const { success } = await ratelimit.limit(ip);
if (!success) {
return new Response('Too Many Requests', { status: 429 });
}
}
```
---
## Environment Variable Security (Phase 2/9 Connection)
### Client Exposure Check
```typescript
// lib/env.ts
const serverEnvSchema = z.object({
DATABASE_URL: z.string(), // Server only
AUTH_SECRET: z.string(), // Server only
});
const clientEnvSchema = z.object({
NEXT_PUBLIC_APP_URL: z.string(), // Can be exposed to client
});
export const serverEnv = serverEnvSchema.parse(process.env);
export const clientEnv = clientEnvSchema.parse({
NEXT_PUBLIC_APP_URL: process.env.NEXT_PUBLIC_APP_URL,
});
```
### Security Header Configuration
```javascript
// next.config.js
const securityHeaders = [
{ key: 'Strict-Transport-Security', value: 'max-age=63072000' },
{ key: 'X-Frame-Options', value: 'SAMEORIGIN' },
{ key: 'X-Content-Type-Options', value: 'nosniff' },
{ key: 'Referrer-Policy', value: 'origin-when-cross-origin' },
];
module.exports = {
async headers() {
return [{ source: '/:path*', headers: securityHeaders }];
},
};
```
---
## Security Verification Checklist (Phase 8 Connection)
### Required (All Levels)
- [ ] HTTPS enforcement
- [ ] No sensitive info exposed to client
- [ ] Input validation (server-side)
- [ ] XSS defense
- [ ] No sensitive info in error messages
### Recommended (Dynamic and above)
- [ ] CSRF token applied
- [ ] Rate Limiting applied
- [ ] Security headers configured
- [ ] httpOnly cookies (auth token)
### Advanced (Enterprise)
- [ ] Content Security Policy (CSP)
- [ ] Security audit logs
- [ ] Regular security scans
## Next.js SEO Example
```tsx
// app/layout.tsx
export const metadata: Metadata = {
title: {
default: 'Site Name',
template: '%s | Site Name',
},
description: 'Site description',
openGraph: {
type: 'website',
locale: 'en_US',
url: 'https://example.com',
siteName: 'Site Name',
},
};
```
## Template
See `templates/pipeline/phase-7-seo-security.template.md`
## Next Phase
Phase 8: Review → After optimization, verify overall code quality
@@ -0,0 +1,540 @@
---
name: phase-8-review
classification: workflow
classification-reason: Process automation persists regardless of model advancement
deprecation-risk: none
description: |
Verify codebase quality — architecture consistency, convention compliance, gap analysis.
Triggers: code review, architecture check, quality, gap analysis, 코드 리뷰, 품질 검증.
imports:
- ${PLUGIN_ROOT}/templates/pipeline/phase-8-review.template.md
hooks:
Stop:
- type: command
command: "node ${HMCMKIT_PLUGIN_ROOT}/scripts/phase8-review-stop.js"
timeout: 10000
agents:
default: hmcmkit:code-analyzer
validate: hmcmkit:design-validator
gap: hmcmkit:gap-detector
qa: hmcmkit:qa-strategist
team: hmcmkit:cto-lead
allowed-tools:
- Read
- Glob
- Grep
- LSP
- Task
user-invocable: false
next-skill: phase-9-deployment
pdca-phase: check
task-template: "[Phase-8] {feature}"
---
# Phase 8: Architecture/Convention Review
> Overall codebase quality verification
## Purpose
Review the entire codebase before deployment. Identify architecture consistency, convention compliance, and potential issues.
## What to Do in This Phase
1. **Architecture Review**: Review structural consistency
2. **Convention Review**: Verify rule compliance
3. **Code Quality Review**: Duplication, complexity, potential bugs
4. **Refactoring**: Fix discovered issues
## Deliverables
```
docs/03-analysis/
├── architecture-review.md # Architecture review
├── convention-review.md # Convention review
└── refactoring-plan.md # Refactoring plan
```
## PDCA Application
- **Plan**: Define review scope/criteria
- **Design**: Design checklist
- **Do**: Execute code review
- **Check**: Analyze issues
- **Act**: Refactor and proceed to Phase 9
## Level-wise Application
| Level | Application Method |
|-------|-------------------|
| Starter | Can be skipped (simple projects) |
| Dynamic | Required |
| Enterprise | Required + security review |
---
## Full Phase Verification Matrix
### Cross-Phase Consistency Verification
Phase 8 verifies that **all Phase outputs and rules** are consistently applied.
```
┌─────────────────────────────────────────────────────────────────┐
│ Cross-Phase Dependency Flow │
├─────────────────────────────────────────────────────────────────┤
│ │
│ Phase 1 (Schema/Terminology) │
│ ↓ Glossary, entity definitions │
│ Phase 2 (Coding Convention) │
│ ↓ Naming rules, environment variable conventions │
│ Phase 3 (Mockup) │
│ ↓ Component structure, Props design │
│ Phase 4 (API) │
│ ↓ RESTful principles, response format, error codes │
│ Phase 5 (Design System) │
│ ↓ Design tokens, component variants │
│ Phase 6 (UI Implementation) │
│ ↓ API client, type sharing, error handling │
│ Phase 7 (SEO/Security) │
│ ↓ Security rules, metadata │
│ Phase 8 (Review) ← Current stage: Full verification │
│ ↓ │
│ Phase 9 (Deployment) │
│ │
└─────────────────────────────────────────────────────────────────┘
```
### Phase-specific Verification Checklist
#### Phase 1 → Verify: Terminology/Schema Consistency
```
□ Are glossary.md terms consistently used in code?
- Business terms → Code naming matching
- Global standard terms → API response field names matching
□ Do entity definitions match actual types?
□ Do relationship definitions match actual implementation?
```
#### Phase 2 → Verify: Convention Compliance
```
□ Naming rule compliance (PascalCase, camelCase, UPPER_SNAKE_CASE)
□ Folder structure rule compliance
□ Environment variable naming rule compliance (NEXT_PUBLIC_*, DB_*, API_*, etc.)
□ .env.example template completion
□ Environment variable validation logic (lib/env.ts) exists
```
#### Phase 4 → Verify: API Consistency
```
□ RESTful principle compliance
- Resource-based URLs (nouns, plural)
- Correct HTTP method usage
- Status code consistency
□ Response format consistency
- Success: { data, meta? }
- Error: { error: { code, message, details? } }
- Pagination: { data, pagination }
□ Error code standardization (matches ERROR_CODES constant)
```
#### Phase 5 → Verify: Design System Consistency
```
□ Are design tokens defined? (CSS Variables / ThemeData)
□ Do components use tokens? (no hardcoded colors)
□ Are component variants consistent?
□ Dark mode support (if defined)
```
#### Phase 6 → Verify: UI-API Integration Consistency
```
□ API client layer structure compliance
- Components → hooks → services → apiClient
- No direct fetch calls
□ Type consistency
- Phase 4 API spec types = Phase 6 client types
□ Error handling consistency
- Global error handler usage
- Error code-specific handling logic
□ State management pattern consistency
```
#### Phase 7 → Verify: Security/SEO Application
```
□ Authentication/authorization middleware applied
□ Input validation (server-side)
□ XSS, CSRF defense
□ No sensitive info exposed to client
□ SEO meta tags applied
```
#### Phase 9 → Verify: Deployment Readiness
```
□ Environment variable Secrets registered (based on Phase 2 list)
□ Environment separation (dev/staging/prod)
□ Build successful
□ Environment variable validation script passes
```
---
## Clean Architecture Verification
### Layer Separation Principles
```
┌─────────────────────────────────────────────────────────────┐
│ Presentation Layer │
│ (pages, components, hooks - UI concerns) │
├─────────────────────────────────────────────────────────────┤
│ Application Layer │
│ (services, use-cases - business logic) │
├─────────────────────────────────────────────────────────────┤
│ Domain Layer │
│ (entities, types - core domain models) │
├─────────────────────────────────────────────────────────────┤
│ Infrastructure Layer │
│ (api client, db, external services) │
└─────────────────────────────────────────────────────────────┘
Dependency direction: Outside → Inside (Presentation → Domain)
Inner layers must not know about outer layers
```
### Layer-specific Verification Checklist
#### Presentation Layer (UI)
```
□ Is there business logic in components?
□ Are there direct API calls? (should go through hooks)
□ Is state management properly separated?
□ Do components have single responsibility?
```
#### Application Layer (Services)
```
□ Are domain logic and infrastructure logic separated?
□ Are external dependencies abstracted?
□ Is the structure testable?
□ Are use cases clearly defined?
```
#### Domain Layer (Types/Entities)
```
□ Are there no external library dependencies?
□ Does it contain only pure business rules?
□ Do types match Phase 1 schema?
```
#### Infrastructure Layer (API Client)
```
□ Are external service calls abstracted?
□ Is error handling consistent?
□ Is configuration managed via environment variables?
```
---
## Architecture Review Checklist
### Structure
- [ ] Does folder structure match conventions
- [ ] Is separation of concerns well done
- [ ] Is dependency direction correct (outside → inside)
### Patterns
- [ ] Are consistent patterns used
- [ ] Is there unnecessary abstraction
- [ ] Is proper encapsulation done
## Convention Review Checklist
### Naming
- [ ] Does it follow Phase 2 defined rules
- [ ] Are meaningful names used
- [ ] Is there consistency
### Code Style
- [ ] Unified indentation, quotes, etc.
- [ ] Is file length appropriate
- [ ] Is function length appropriate
## Code Quality Checklist
- [ ] Is there duplicate code
- [ ] Are there highly complex functions
- [ ] Is error handling appropriate
- [ ] Is type safety ensured
## AI-Assisted Review
```
Request code review from AI Agent:
"Review this project's code.
- Does it follow CONVENTIONS.md rules
- Is there architecture consistency
- Are there potential bugs or improvements"
```
## Template
See `templates/pipeline/phase-8-review.template.md`
## Next Phase
Phase 9: Deployment → After review completion, deploy to production
---
## 6. In-Depth Code Quality Review
### 6.1 Duplicate Code Detection
#### Detection Methods
```bash
# 1. Search for similar function names
grep -r "function.*format" src/
grep -r "function.*calculate" src/
grep -r "function.*get.*By" src/
# 2. Search for similar patterns
grep -rn "reduce.*sum" src/
grep -rn "filter.*map" src/
grep -rn "useState.*useEffect" src/
```
#### Handling by Duplication Type
| Type | Example | Solution |
|------|---------|----------|
| Exact duplicate | Same code copy-paste | Extract to function |
| Structural similarity | Same logic, different data | Parameterize |
| Conceptual similarity | Different implementations for similar purpose | Integrate or interface |
#### Duplicate Code Checklist
```
□ Is the same logic in 2+ places?
□ Are there multiple functions with similar names?
□ Is the same data transformation repeated?
□ Are similar UI patterns repeated?
□ Is the same API call pattern repeated?
□ Is similar error handling repeated?
```
### 6.2 Reusability Assessment
#### Assessment Criteria
| Score | Criteria | Description |
|-------|----------|-------------|
| ⭐⭐⭐ | High | Can be used in other projects |
| ⭐⭐ | Medium | Can be used in multiple places within same project |
| ⭐ | Low | Used only for specific feature |
#### Reusability Checklist
```
Check for each function/component:
□ Is it tied to a specific domain?
□ Does it depend on external state?
□ Are parameters generic?
□ Is the return value predictable?
□ Are there side effects?
```
### 6.3 Extensibility Assessment
#### Extensibility Check
```
When new requirements come:
□ Can it be added without modifying existing code?
□ Can behavior be changed by configuration only?
□ Is adding new types/cases easy?
□ Can it be extended without adding conditionals?
```
#### Extensibility Anti-patterns
```typescript
// ❌ Requires modification for each extension
function process(type: string) {
if (type === 'a') { /* ... */ }
else if (type === 'b') { /* ... */ }
// Add else if for each new type...
}
// ❌ Hardcoded list
const ALLOWED_TYPES = ['a', 'b', 'c']
// ❌ Enumerated switch statements
switch (action.type) {
case 'ADD': // ...
case 'REMOVE': // ...
// Add case for each new action...
}
```
#### Good Extensibility Patterns
```typescript
// ✅ Registry pattern
const handlers: Record<string, Handler> = {}
function register(type: string, handler: Handler) {
handlers[type] = handler
}
function process(type: string, data: unknown) {
return handlers[type]?.(data)
}
// ✅ Configuration-based
const CONFIG = {
types: ['a', 'b', 'c'],
handlers: { ... }
}
// ✅ Plugin structure
interface Plugin { execute(data): Result }
const plugins: Plugin[] = []
```
### 6.4 Object-Oriented Principles Check
#### SOLID Principles Checklist
**S - Single Responsibility (SRP)**
```
□ Does the class/function change for only one reason?
□ Does the name clearly explain the role?
□ Is "and" in the name? → Needs separation
```
**O - Open/Closed (OCP)**
```
□ Is it open for extension? (new features can be added)
□ Is it closed for modification? (no existing code changes needed)
□ Are interfaces/abstractions used?
```
**L - Liskov Substitution (LSP)**
```
□ Can subtypes replace parent types?
□ Do overridden methods keep the contract?
```
**I - Interface Segregation (ISP)**
```
□ Is the interface too large?
□ Must unused methods be implemented?
□ Can the interface be split smaller?
```
**D - Dependency Inversion (DIP)**
```
□ Does it depend on abstractions instead of concrete classes?
□ Are dependencies injected? (DI)
□ Is the structure testable?
```
### 6.5 Refactoring Priority
```
Urgent (Required before deployment):
1. Duplication that can cause bugs
2. Security vulnerabilities
3. Performance bottlenecks
High (As soon as possible):
4. Same logic duplicated in 3+ places
5. Files over 200 lines
6. Nesting deeper than 5 levels
Medium (Next sprint):
7. Structure lacking extensibility
8. Naming inconsistencies
9. Structure difficult to test
Low (Backlog):
10. Style inconsistencies
11. Excessive comments
12. Unused code
```
---
## 7. AI Code Review Request Template
```markdown
Please review the code from these perspectives:
1. Duplicate Code
- Are there similar functions/components?
- Is there common logic that can be extracted?
2. Reusability
- Can it be used generically?
- Is it tied to a specific domain?
3. Extensibility
- Can it flexibly respond to new requirements?
- Are there hardcoded parts?
4. SOLID Principles
- Does it follow single responsibility?
- Is it open for extension and closed for modification?
5. Convention Compliance
- Does it follow CONVENTIONS.md rules?
- Is naming consistent?
Please identify parts that need refactoring and their priority.
```
---
## 8. Gap Analysis (Design vs Implementation)
### Gap Analysis Report Template
```markdown
# Gap Analysis Report
## Analysis Target
- Design document: docs/02-design/{feature}.design.md
- Implementation path: src/features/{feature}/
## Results by Category
### API Endpoints
| Design | Implementation | Status |
|--------|----------------|--------|
| POST /api/users | POST /api/users | ✅ Match |
| GET /api/users/:id | - | ❌ Not implemented |
| - | DELETE /api/users/:id | ⚠️ Missing from design |
### Data Model
| Design Entity | Implementation | Status |
|---------------|----------------|--------|
| User | types/user.ts | ✅ Match |
| UserRole | - | ❌ Not implemented |
### Match Rate
- Total items: 10
- Matches: 7
- Not implemented: 2
- Missing from design: 1
- **Match Rate: 70%**
```
### Gap Types and Actions
| Gap Type | Meaning | Action |
|----------|---------|--------|
| ✅ Match | Design = Implementation | None |
| ❌ Not implemented | In design, not in code | Implement or update design |
| ⚠️ Missing from design | In code, not in design | Add to design document |
| 🔄 Different | Exists but different | Align (code is truth) |
### When to Run Gap Analysis
- After completing feature implementation
- Before deployment
- When design document is updated
- During code review
@@ -0,0 +1,453 @@
---
name: phase-9-deployment
classification: capability
classification-reason: Pattern guidance may overlap with model's built-in knowledge as it improves
deprecation-risk: medium
description: |
Deploy to production — CI/CD pipelines, environment config, deployment strategies.
Triggers: deployment, CI/CD, production, Vercel, 배포, 프로덕션.
imports:
- ${PLUGIN_ROOT}/templates/pipeline/phase-9-deployment.template.md
hooks:
Stop:
- type: command
command: "node ${HMCMKIT_PLUGIN_ROOT}/scripts/phase9-deploy-stop.js"
timeout: 10000
agent: hmcmkit:infra-architect
allowed-tools:
- Read
- Write
- Edit
- Glob
- Grep
- Bash
user-invocable: false
next-skill: null
pdca-phase: act
task-template: "[Phase-9] {feature}"
---
# Phase 9: Deployment
> Production deployment
## Purpose
Deliver the completed application to users.
## What to Do in This Phase
1. **Prepare Deployment Environment**: Infrastructure setup
2. **Build**: Create production build
3. **Execute Deployment**: Actual deployment
4. **Verification**: Post-deployment operation check
## Deliverables
```
docs/02-design/
└── deployment-spec.md # Deployment specification
docs/04-report/
└── deployment-report.md # Deployment report
(Infrastructure config files)
├── vercel.json # Vercel configuration
├── Dockerfile # Docker configuration
└── k8s/ # Kubernetes configuration
```
## PDCA Application
- **Plan**: Establish deployment plan
- **Design**: Design deployment configuration
- **Do**: Execute deployment
- **Check**: Verify deployment
- **Act**: Problem resolution and completion report
## Level-wise Application
| Level | Deployment Method |
|-------|-------------------|
| Starter | Static hosting (Netlify, GitHub Pages) |
| Dynamic | Vercel, Railway, etc. |
| Enterprise | Kubernetes, AWS ECS, etc. |
## Starter Deployment (Static Hosting)
```bash
# GitHub Pages
npm run build
# Deploy dist/ folder to gh-pages branch
# Netlify
# Configure netlify.toml then connect Git
```
## Dynamic Deployment (Vercel)
```bash
# Vercel CLI
npm i -g vercel
vercel
# Or auto-deploy via Git connection
```
## Enterprise Deployment (Kubernetes)
```yaml
# k8s/deployment.yaml
apiVersion: apps/v1
kind: Deployment
metadata:
name: my-app
spec:
replicas: 3
template:
spec:
containers:
- name: app
image: my-app:latest
```
---
## Environment Management
### Environment Configuration Overview
```
┌─────────────────────────────────────────────────────────────┐
│ Environment Variable Flow │
├─────────────────────────────────────────────────────────────┤
│ │
│ Development │
│ └── .env.local → Developer local machine │
│ │
│ Staging │
│ └── CI/CD Secrets → Preview/Staging environment │
│ │
│ Production │
│ └── CI/CD Secrets → Production environment │
│ └── Vault/Secrets Manager (Enterprise) │
│ │
└─────────────────────────────────────────────────────────────┘
```
### Environment Classification
| Environment | Purpose | Data | Variable Source |
|-------------|---------|------|-----------------|
| **Development** | Local development | Test data | `.env.local` |
| **Staging** | Pre-deployment verification | Test data | CI/CD Secrets |
| **Production** | Live service | Real data | CI/CD Secrets + Vault |
---
## CI/CD Environment Variable Configuration
### GitHub Actions
```yaml
# .github/workflows/deploy.yml
name: Deploy
on:
push:
branches: [main, staging]
jobs:
deploy:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- name: Set environment
run: |
if [ "${{ github.ref }}" == "refs/heads/main" ]; then
echo "DEPLOY_ENV=production" >> $GITHUB_ENV
else
echo "DEPLOY_ENV=staging" >> $GITHUB_ENV
fi
- name: Build
env:
# General environment variables (can be exposed)
NEXT_PUBLIC_APP_URL: ${{ vars.APP_URL }}
NEXT_PUBLIC_API_URL: ${{ vars.API_URL }}
# Secrets (sensitive info)
DATABASE_URL: ${{ secrets.DATABASE_URL }}
AUTH_SECRET: ${{ secrets.AUTH_SECRET }}
API_STRIPE_SECRET: ${{ secrets.API_STRIPE_SECRET }}
run: npm run build
- name: Deploy to Vercel
env:
VERCEL_TOKEN: ${{ secrets.VERCEL_TOKEN }}
run: |
npx vercel --prod --token=$VERCEL_TOKEN
```
### GitHub Secrets Configuration Guide
```
Repository Settings → Secrets and variables → Actions
1. Repository secrets (sensitive info)
├── DATABASE_URL
├── AUTH_SECRET
├── API_STRIPE_SECRET
└── VERCEL_TOKEN
2. Repository variables (general settings)
├── APP_URL
├── API_URL
└── NODE_ENV
3. Environment-specific secrets
├── production/
│ ├── DATABASE_URL (production DB)
│ └── API_STRIPE_SECRET (live key)
└── staging/
├── DATABASE_URL (staging DB)
└── API_STRIPE_SECRET (test key)
```
### Vercel Environment Variable Configuration
```
Project Settings → Environment Variables
┌─────────────────┬─────────────┬─────────────┬─────────────┐
│ Variable Name │ Development │ Preview │ Production │
├─────────────────┼─────────────┼─────────────┼─────────────┤
│ DATABASE_URL │ dev-db │ staging-db │ prod-db │
│ AUTH_SECRET │ dev-secret │ stg-secret │ prod-secret │
│ API_STRIPE_* │ test key │ test key │ live key │
└─────────────────┴─────────────┴─────────────┴─────────────┘
Configuration steps:
1. Project Settings → Environment Variables
2. Add New Variable
3. Select environment (Development / Preview / Production)
4. Check Sensitive (if sensitive info)
```
---
## Secrets Management Strategy
### Level-wise Secrets Management
| Level | Secrets Management Method | Tools |
|-------|--------------------------|-------|
| **Starter** | CI/CD platform Secrets | GitHub Secrets, Vercel |
| **Dynamic** | CI/CD + environment separation | GitHub Environments |
| **Enterprise** | Dedicated Secrets Manager | Vault, AWS Secrets Manager |
### Starter/Dynamic: CI/CD Secrets
```yaml
# Usage in GitHub Actions
- name: Deploy
env:
DB_PASSWORD: ${{ secrets.DB_PASSWORD }}
```
### Enterprise: HashiCorp Vault
```yaml
# Fetch Secrets from Vault
- name: Import Secrets from Vault
uses: hashicorp/vault-action@v2
with:
url: https://vault.company.com
token: ${{ secrets.VAULT_TOKEN }}
secrets: |
secret/data/myapp/production db_password | DB_PASSWORD ;
secret/data/myapp/production api_key | API_KEY
```
### Enterprise: AWS Secrets Manager
```typescript
// lib/secrets.ts
import { SecretsManagerClient, GetSecretValueCommand } from "@aws-sdk/client-secrets-manager";
const client = new SecretsManagerClient({ region: "ap-northeast-2" });
export async function getSecret(secretName: string): Promise<Record<string, string>> {
const command = new GetSecretValueCommand({ SecretId: secretName });
const response = await client.send(command);
if (response.SecretString) {
return JSON.parse(response.SecretString);
}
throw new Error(`Secret ${secretName} not found`);
}
// Usage
const dbSecrets = await getSecret("myapp/production/database");
// { host: "...", password: "...", ... }
```
---
## Environment-specific Build Configuration
### Next.js Environment Configuration
```javascript
// next.config.js
/** @type {import('next').NextConfig} */
const nextConfig = {
// Environment-specific settings
env: {
NEXT_PUBLIC_ENV: process.env.NODE_ENV,
},
// Environment-specific redirects
async redirects() {
if (process.env.NODE_ENV === 'production') {
return [
{ source: '/debug', destination: '/', permanent: false },
];
}
return [];
},
};
module.exports = nextConfig;
```
### Environment-specific API Endpoints
```typescript
// lib/config.ts
const config = {
development: {
apiUrl: 'http://localhost:3001',
debug: true,
},
staging: {
apiUrl: 'https://api-staging.myapp.com',
debug: true,
},
production: {
apiUrl: 'https://api.myapp.com',
debug: false,
},
} as const;
type Environment = keyof typeof config;
const env = (process.env.NODE_ENV || 'development') as Environment;
export const appConfig = config[env];
```
---
## Environment Variable Validation (Pre-deployment)
### Required Variable Check Script
```javascript
#!/usr/bin/env node
// scripts/check-env.js
const REQUIRED_VARS = [
'DATABASE_URL',
'AUTH_SECRET',
'NEXT_PUBLIC_APP_URL'
];
const missing = REQUIRED_VARS.filter(v => !process.env[v]);
if (missing.length > 0) {
console.error('❌ Missing required environment variables:');
missing.forEach(v => console.error(` - ${v}`));
process.exit(1);
}
console.log('✅ All required environment variables are set');
```
### Validation in CI/CD
```yaml
# GitHub Actions
- name: Validate Environment
run: node scripts/check-env.js
env:
DATABASE_URL: ${{ secrets.DATABASE_URL }}
AUTH_SECRET: ${{ secrets.AUTH_SECRET }}
NEXT_PUBLIC_APP_URL: ${{ vars.APP_URL }}
```
---
## Environment Variable Management Checklist
### Pre-deployment
- [ ] **Secrets Registration**
- [ ] DATABASE_URL (per environment)
- [ ] AUTH_SECRET (per environment)
- [ ] External API keys (per environment)
- [ ] **Environment Separation**
- [ ] Development / Staging / Production distinction
- [ ] Per-environment database separation
- [ ] Per-environment external service key separation (test/live)
- [ ] **Validation**
- [ ] Run required variable check script
- [ ] Build test
### Post-deployment
- [ ] **Operation Check**
- [ ] Verify environment variables are injected correctly
- [ ] External service integration test
- [ ] **Security Check**
- [ ] Verify no sensitive info in logs
- [ ] Verify no server-only variables exposed to client
---
## Deployment Checklist
### Preparation
- [ ] Environment variable configuration (see checklist above)
- [ ] Domain connection
- [ ] SSL certificate
### Deployment
- [ ] Build successful
- [ ] Deployment complete
- [ ] Health check passed
### Verification
- [ ] Major feature operation check
- [ ] Error log review
- [ ] Performance monitoring
## Rollback Plan
```
If problems occur:
1. Immediately rollback to previous version
2. Analyze root cause
3. Fix and redeploy
```
## Template
See `templates/pipeline/phase-9-deployment.template.md`
## After Completion
Project complete! Start new feature development cycle from Phase 1 as needed
@@ -0,0 +1,228 @@
---
name: plan-plus
classification: hybrid
classification-reason: Combines workflow automation with capability-dependent features
deprecation-risk: low
description: |
Brainstorming-enhanced PDCA planning with intent discovery and YAGNI review.
Triggers: plan-plus, brainstorm, plan plus, intent, 브레인스토밍, 플랜플러스.
argument-hint: "[feature]"
user-invocable: true
allowed-tools:
- Read
- Write
- Edit
- Glob
- Grep
- Bash
- Task
- TaskCreate
- TaskUpdate
- TaskList
- AskUserQuestion
imports:
- ${PLUGIN_ROOT}/templates/plan-plus.template.md
next-skill: pdca design
pdca-phase: plan
task-template: "[Plan Plus] {feature}"
hooks:
Stop:
- type: command
command: "node ${HMCMKIT_PLUGIN_ROOT}/scripts/plan-plus-stop.js"
timeout: 10000
---
# Plan Plus — Brainstorming-Enhanced PDCA Planning
> Combines brainstorming's intent discovery with hmcmkit PDCA's structured planning to produce
> higher-quality Plan documents through collaborative dialogue.
## Overview
Plan Plus enhances the standard `/pdca plan` by adding 4 brainstorming phases before document
generation. This ensures that user intent is fully understood, alternatives are explored,
and unnecessary features are removed before any implementation begins.
**When to use Plan Plus instead of `/pdca plan`:**
- The feature has ambiguous or complex requirements
- Multiple implementation approaches are possible
- You want to ensure YAGNI compliance from the start
- The feature involves significant architectural decisions
## HARD-GATE
<HARD-GATE>
Do NOT write any code, scaffold any project, or invoke any implementation skill
until this entire process is complete and the user has approved the Plan document.
This applies to EVERY feature regardless of perceived simplicity.
A "simple" feature still goes through this process — the design can be short,
but you MUST present it and get approval.
</HARD-GATE>
## Process Flow
```
Phase 0: Context Exploration (automatic)
↓
Phase 1: Intent Discovery (1 question at a time)
↓
Phase 2: Alternatives Exploration (2-3 approaches)
↓
Phase 3: YAGNI Review (multiSelect verification)
↓
Phase 4: Incremental Design Validation (section-by-section)
↓
Phase 5: Plan Document Generation (plan-plus.template.md)
↓
Phase 6: Next Steps → /pdca design {feature}
```
## Phase Details
### Phase 0: Project Context Exploration (Automatic)
Before asking any questions, explore the current project state:
1. Read agents.md, package.json, pom.xml, etc. for project information
2. Check recent 5 git commits (understand current work direction)
3. Check existing `docs/01-plan/` documents (prevent duplication)
4. Check `.hmcmkit-memory.json` (check ongoing PDCA status)
> Share exploration results briefly: "I've reviewed the current project state: ..."
### Phase 1: Intent Discovery (Brainstorming Style)
**Principle: One question at a time, prefer multiple choice**
Use `AskUserQuestion` tool to discover the following in order:
#### Q1. Core Purpose
"What is the core problem this feature solves?"
- Provide 3-4 choices (inferred from project context)
- Always include a custom input option
#### Q2. Target Users
"Who will primarily use this feature?"
- Admin / End user / Developer / External system
#### Q3. Success Criteria
"What criteria would indicate this feature is successful?"
- Derive specific, measurable criteria
#### Q4. Constraints (only when needed)
Conflicts with existing systems, performance requirements, technical constraints, etc.
> **Important**: Minimize questions. Clear features need only Q1-Q2.
> Only proceed to Q3-Q4 for ambiguous features.
### Phase 2: Alternatives Exploration (Brainstorming Core)
**Always propose 2-3 approaches** with trade-offs for each.
Format:
```
### Approach A: {name} — Recommended
- Pros: ...
- Cons: ...
- Best for: ...
### Approach B: {name}
- Pros: ...
- Cons: ...
- Best for: ...
### Approach C: {name} (optional)
- Pros: ...
- Cons: ...
```
> Present the recommended approach first with clear reasoning.
> Use AskUserQuestion to let the user choose.
### Phase 3: YAGNI Review (Brainstorming Core)
Perform a YAGNI (You Ain't Gonna Need It) review on the selected approach:
Use AskUserQuestion with `multiSelect: true`:
"Select only what is essential for the first version:"
List all features and move unselected items to Out of Scope.
**Principle**: Don't abstract what can be done in 3 lines.
Don't design for hypothetical future requirements.
### Phase 4: Incremental Design Validation (Brainstorming Style)
Present the design section by section, getting approval after each:
1. Architecture overview → "Does this direction look right?"
2. Key components/modules → "Does this structure look right?"
3. Data flow → "Does this flow look right?"
> If the user says "no" to any section, revise only that section and re-present.
### Phase 5: Plan Document Generation
Generate the Plan document using `plan-plus.template.md` with results from Phases 0-4.
**Additional sections** (not in standard plan.template.md):
- **User Intent Discovery** — Core problem, target users, success criteria from Phase 1
- **Alternatives Explored** — Approaches compared in Phase 2
- **YAGNI Review** — Included/deferred/removed items from Phase 3
- **Brainstorming Log** — Key decisions from Phases 1-4
- **Executive Summary** -- Auto-synthesize 4-perspective summary (Problem/Solution/Function UX Effect/Core Value) from Phases 1-4 results. Place at document top, before numbered sections.
- **Executive Summary Response** -- MANDATORY: After generating the Plan document, also output the Executive Summary table in your response so the user sees the summary immediately without opening the file.
**Output Path**: `docs/01-plan/features/{feature}.plan.md`
After document generation, update PDCA status:
- Create Task: `[Plan] {feature}`
- Update .hmcmkit-memory.json: phase = "plan"
### Phase 6: Next Steps
After Plan document generation:
```
Plan Plus completed
Document: docs/01-plan/features/{feature}.plan.md
Next step: /pdca design {feature}
```
## Key Principles
| Principle | Origin | Application |
|-----------|--------|-------------|
| One question at a time | Brainstorming | Sequential questions via AskUserQuestion |
| Explore alternatives | Brainstorming | Mandatory 2-3 approaches in Phase 2 |
| YAGNI ruthlessly | Brainstorming | multiSelect verification in Phase 3 |
| Incremental validation | Brainstorming | Section-by-section approval in Phase 4 |
| HARD-GATE | Brainstorming | No code before approval (entire process) |
| Context first | Brainstorming | Automatic exploration in Phase 0 |
## Integration with PDCA
Plan Plus produces the same output as `/pdca plan` and feeds seamlessly into the
standard PDCA cycle:
```
/plan-plus {feature} ← Enhanced planning with brainstorming
↓
/pdca design {feature} ← Standard PDCA continues
↓
/pdca do {feature}
↓
/pdca analyze {feature}
↓
/pdca report {feature}
```
## Usage Examples
```bash
# Start brainstorming-enhanced planning
/plan-plus user-authentication
# After Plan Plus completes, continue with standard PDCA
/pdca design user-authentication
/pdca do user-authentication
```
@@ -0,0 +1,112 @@
---
name: pm-discovery
classification: workflow
classification-reason: PM process orchestration independent of model capability evolution
deprecation-risk: none
description: |
PM Agent Team — automated product discovery, strategy, and PRD generation with 4 PM agents.
Triggers: pm, PRD, product discovery, PM 분석, 제품 기획, PM analysis.
argument-hint: "[feature]"
user-invocable: true
agents:
default: hmcmkit:pm-lead
allowed-tools:
- Read
- Write
- Edit
- Glob
- Grep
- Bash
- AskUserQuestion
imports:
- ${PLUGIN_ROOT}/templates/pm-prd.template.md
next-skill: pdca plan
pdca-phase: pm
task-template: "[PM] {feature}"
---
# PM Agent Team - Product Discovery & Strategy
> Automated PM analysis pipeline: Discovery + Strategy + Research -> PRD
> Based on [pm-skills](https://github.com/phuryn/pm-skills) by Pawel Huryn (MIT License)
## Overview
PM Agent Team provides AI-powered product management analysis for solo developers
and small teams without a dedicated PM. It runs before the PDCA Plan phase to ensure
you're building the right thing.
## How It Works
```
/pdca pm {feature}
|
v
PM Lead (leader-agent) - orchestrates
|
+-- pm-discovery --> Opportunity Solution Tree
+-- pm-strategy --> Value Proposition + Lean Canvas [parallel]
+-- pm-research --> Personas + Competitors + Market
|
v
pm-prd --> Beachhead + GTM + PRD (8-section)
|
v
docs/00-pm/{feature}.prd.md
|
v
Next: /pdca plan {feature} (PRD auto-referenced)
```
## Included PM Frameworks (8)
| Framework | Agent | Origin |
|-----------|-------|--------|
| Opportunity Solution Tree | pm-discovery | Teresa Torres |
| Value Proposition (JTBD 6-Part) | pm-strategy | Huryn & Abdul Rauf |
| Lean Canvas | pm-strategy | Ash Maurya |
| User Personas (JTBD) | pm-research | JTBD-based |
| Competitor Analysis | pm-research | Strategic positioning |
| Market Sizing (TAM/SAM/SOM) | pm-research | Dual-method |
| Beachhead Segment | pm-prd | Geoffrey Moore |
| GTM Strategy | pm-prd | Product Compass |
## Usage
```bash
# Run PM analysis
/pdca pm my-saas-app
# After PM analysis, continue with PDCA
/pdca plan my-saas-app # PRD auto-referenced
/pdca design my-saas-app
/pdca do my-saas-app
```
## Requirements
- Agent Teams enabled: `HMCMKIT_EXPERIMENTAL_AGENT_TEAMS=1`
- Project level: Dynamic or Enterprise (Starter not supported)
## PDCA Integration
```
[PM] --> [Plan] --> [Design] --> [Do] --> [Check] --> [Act] --> [Report]
^ ^
new PRD auto-referenced in Plan
```
When `/pdca plan {feature}` runs after PM analysis:
1. Checks for `docs/00-pm/{feature}.prd.md`
2. If found, reads PRD and uses as context for Plan document
3. Plan document quality is significantly improved with PM-backed data
## Output
PRD document saved to `docs/00-pm/{feature}.prd.md` containing:
- Executive Summary (4-perspective)
- Opportunity Solution Tree
- Value Proposition + Lean Canvas
- User Personas (3) + Competitor Analysis (5) + Market Sizing
- Beachhead Segment + GTM Strategy
- Product Requirements (8-section PRD)
+183
View File
@@ -0,0 +1,183 @@
---
name: rollback
classification: workflow
classification-reason: Checkpoint and rollback management persists regardless of model advancement
deprecation-risk: none
description: |
Manage PDCA checkpoints and rollback — create, list, restore for safe recovery.
Triggers: rollback, checkpoint, restore, undo, 롤백, 체크포인트, 복원.
argument-hint: "[list|to|phase|reset] [target]"
user-invocable: true
allowed-tools:
- Read
- Write
- Glob
- Grep
- Bash
- AskUserQuestion
imports: []
next-skill: null
pdca-phase: null
task-template: "[Rollback] {action}"
---
# Rollback Skill
> User-invocable skill for checkpoint management and PDCA state rollback.
## Arguments
| Argument | Description | Example |
|----------|-------------|---------|
| (none) | List available checkpoints (same as `list`) | `/rollback` |
| `list` | List all available checkpoints | `/rollback list` |
| `to <checkpoint-id>` | Restore to a specific checkpoint | `/rollback to cp-1710842700000` |
| `phase` | Rollback to previous PDCA phase | `/rollback phase` |
| `reset <feature>` | Reset feature to initial (idle) state | `/rollback reset user-auth` |
## Action Details
### list (Default)
List all available checkpoints for the current or specified feature.
1. Read checkpoint metadata from `.hmcmkit/checkpoints/`
2. Filter by current active feature (or show all if no active feature)
3. Sort by timestamp (newest first)
4. Display formatted checkpoint list
**Checkpoint Metadata Schema**:
```json
{
"id": "cp-1710842700000",
"feature": "user-auth",
"phase": "design",
"type": "auto",
"timestamp": "2026-03-19T10:30:00.000Z",
"description": "Auto-checkpoint before Do phase",
"pdcaStatus": { "phase": "design", "matchRate": 0, "iterationCount": 0 },
"files": ["docs/02-design/features/user-auth.design.md"]
}
```
**Output Format**:
```
--- Checkpoints: user-auth ------------------------
ID Phase Type Date Description
cp-1710842700000 design auto 2026-03-19 10:30 Before Do phase
cp-1710839100000 plan auto 2026-03-19 09:25 Before Design phase
cp-1710835500000 idle manual 2026-03-19 08:15 Manual save point
---------------------------------------------------
Total: 3 checkpoints
Usage: /rollback to cp-1710842700000
```
### to <checkpoint-id>
Restore state to a specific checkpoint.
1. Validate the checkpoint ID exists in `.hmcmkit/checkpoints/`
2. Read the checkpoint metadata and saved state
3. Display what will be restored (phase, files, status)
4. **Require user confirmation** via AskUserQuestion (always, regardless of automation level)
5. On confirmation:
a. Create a safety checkpoint of current state (before rollback)
b. Restore `pdca-status.json` to the checkpoint's saved state
c. Restore any saved file snapshots
d. Write audit log: `checkpoint_restored`
e. Display confirmation with restored state
6. On rejection: Cancel and display current state
**Safety Rule**: Rollback operations ALWAYS require user confirmation,
even at L4 (Full-Auto). This is a destructive operation.
### phase
Rollback to the previous PDCA phase.
1. Read current feature state from `.hmcmkit/state/pdca-status.json`
2. Determine previous phase using the PDCA phase order:
`idle <- pm <- plan <- design <- do <- check <- act <- report <- archived`
3. If current phase is `idle`, display: "Already at initial state. Nothing to rollback."
4. Display the phase transition that will occur
5. **Require user confirmation** via AskUserQuestion
6. On confirmation:
a. Create auto-checkpoint of current state
b. Use `state-machine.transition()` with `ROLLBACK` event
c. Update `pdca-status.json` with previous phase
d. Write audit log: `phase_rollback`
e. Display: "Rolled back from {current} to {previous}"
**Phase Rollback Map**:
| Current Phase | Rolls Back To |
|:-------------:|:-------------:|
| pm | idle |
| plan | pm (or idle if PM was skipped) |
| design | plan |
| do | design |
| check | do |
| act | check |
| report | check |
| archived | report |
### reset <feature>
Reset a feature to its initial (idle) state.
1. Validate the feature exists in `pdca-status.json`
2. Display current feature state and what will be lost
3. **Require user confirmation** via AskUserQuestion with warning:
"This will reset ALL PDCA progress for {feature}. Documents in docs/ will NOT be deleted."
4. On confirmation:
a. Create auto-checkpoint of current state
b. Use `state-machine.transition()` with `RESET` event
c. Clear feature from active features list
d. Reset all metrics (matchRate, iterationCount, etc.)
e. Write audit log: `feature_reset`
f. Display: "Feature {feature} reset to idle state. PDCA documents preserved in docs/."
**Important**: Reset does NOT delete documents from `docs/`. It only resets the
PDCA status tracking. Use `/pdca cleanup` to remove archived status entries.
## Checkpoint Types
| Type | Trigger | Description |
|------|---------|-------------|
| `auto` | Phase transition (Design->Do) | Automatic checkpoint at key transitions |
| `manual` | User command | User-created save point |
| `phase_transition` | Any phase change | Lightweight state snapshot |
| `pre_rollback` | Before rollback | Safety checkpoint before destructive operation |
## State Files
| File | Purpose |
|------|---------|
| `.hmcmkit/checkpoints/cp-{timestamp}.json` | Checkpoint metadata and state snapshot |
| `.hmcmkit/state/pdca-status.json` | Current PDCA status (modified on rollback) |
## Module Dependencies
| Module | Function | Usage |
|--------|----------|-------|
| `lib/control/checkpoint-manager.js` | `listCheckpoints()` | List available checkpoints |
| `lib/control/checkpoint-manager.js` | `createCheckpoint()` | Create new checkpoint |
| `lib/control/checkpoint-manager.js` | `restoreCheckpoint()` | Restore to checkpoint |
| `lib/pdca/state-machine.js` | `transition()` | Execute ROLLBACK/RESET events |
| `lib/audit/audit-logger.js` | `writeAuditLog()` | Record rollback operations |
## Usage Examples
```bash
# List checkpoints
/rollback
# Restore to specific checkpoint
/rollback to cp-1710842700000
# Rollback to previous phase
/rollback phase
# Reset feature completely
/rollback reset user-auth
```
@@ -0,0 +1,144 @@
---
name: skill-create
classification: workflow
classification-reason: "Interactive skill creation workflow with user prompts, file generation, and eval scaffolding. Multi-step process requiring user decisions."
deprecation-risk: none
description: |
Interactive skill creation workflow for project-local skills.
Triggers: skill-create, create skill, 스킬 생성, 스킬 만들기.
argument-hint: "/skill-create [name] | /skill-create from-btw {btw-id}"
user-invocable: true
allowed-tools:
- Read
- Write
- Edit
- Glob
- Grep
- Bash
---
# skill-create - Interactive Skill Creation Workflow
프로젝트 컨텍스트를 분석하여 project-local 스킬을 생성하는 워크플로우.
## Workflow Steps
### Step 1: Gather Information
If `/skill-create` (no args):
1. Ask user for skill name (kebab-case)
2. Ask user for skill purpose/description
3. Ask user for classification: workflow or capability
If `/skill-create {name}`:
1. Use provided name
2. Analyze project context to infer purpose
3. Ask user to confirm/modify
If `/skill-create from-btw {btw-id}`:
1. Read btw suggestion from `.hmcmkit/btw-suggestions.json`
2. Use suggestion text as seed for skill description
3. Use suggestion context for project context
### Step 2: Analyze Project Context
1. Read `agents.md` for project conventions
2. Scan project structure:
- Identify tech stack (Java/Spring, Next.js, Python, etc.)
- Find relevant patterns in source code
- Check existing project-local skills for overlap
3. Determine appropriate:
- Allowed tools for the skill
- Trigger keywords (Korean + English)
- Related files/patterns to reference
### Step 3: Generate SKILL.md
Create `.ai-agent/skills/project/{name}/SKILL.md` with:
```yaml
---
name: {name}
classification: {workflow|capability}
classification-reason: "{reason based on analysis}"
deprecation-risk: none
description: |
{Generated description}
Triggers: {trigger commands}
Keywords: {keywords in Korean and English}
argument-hint: "{usage hint}"
user-invocable: true
allowed-tools:
- Read
- Write
- Edit
- Glob
- Grep
- Bash
---
```
Body content includes:
- Purpose and when to use
- Step-by-step instructions for workflow skills
- Pattern reference for capability skills
- Code examples from actual project files
- Integration points with other skills
### Step 4: Generate Eval Files (optional)
Create `evals/{name}/` directory with:
```
evals/{name}/
eval.yaml - Test configuration
prompt.txt - Test prompt
expected.txt - Expected behavior description
```
**eval.yaml format:**
```yaml
name: "{name} skill eval"
skill: ".ai-agent/skills/project/{name}/SKILL.md"
tests:
- name: "basic trigger"
prompt: "{trigger command}"
expected:
- "{expected behavior 1}"
- "{expected behavior 2}"
- name: "edge case"
prompt: "{edge case prompt}"
expected:
- "{expected behavior}"
```
### Step 5: Confirm and Report
1. Show generated file paths
2. Show skill summary (name, classification, triggers)
3. Suggest: "Test with `/{name}` or review at `.ai-agent/skills/project/{name}/SKILL.md`"
## Project-Local Skill Location
All generated skills go to: `.ai-agent/skills/project/{name}/SKILL.md`
This location:
- Is git-trackable for team sharing
- Takes precedence over hmcmkit core skills (2-layer architecture)
- Is auto-loaded by Antigravity Platform's skill discovery
## Naming Conventions
| Pattern | Example | Use When |
|---------|---------|----------|
| `{project}-{domain}` | `hunikflow-model` | Domain-specific capability |
| `{action}-{target}` | `validate-entity` | Action-oriented workflow |
| `{tool}-{purpose}` | `proxy-guide` | Tool/pattern guide |
## From-BTW Integration
When creating from a /btw suggestion:
1. Read the suggestion's `context.file` to understand what code was being worked on
2. Read the suggestion's `context.feature` to understand the PDCA feature context
3. Use suggestion text as the primary description seed
4. After creation, update the btw suggestion's `promotedTo` field with the new skill name
@@ -0,0 +1,97 @@
---
name: skill-status
classification: workflow
classification-reason: "Reports loaded skill inventory across core and project layers. Read-only status check workflow."
deprecation-risk: none
description: |
Show loaded skill inventory — hmcmkit core vs project-local, conflicts, coverage gaps.
Triggers: skill-status, skill list, 스킬 상태, 스킬 목록.
argument-hint: "/skill-status [--detail] [--conflicts]"
user-invocable: true
allowed-tools:
- Read
- Glob
- Grep
- Bash
---
# skill-status - Skill Inventory Report
로드된 스킬 목록을 core(hmcmkit 기본)와 project-local로 구분하여 표시.
## Command: `/skill-status`
### Step 1: Scan Core Skills
1. Read hmcmkit core skills directory:
`~/.ai-agent/plugins/cache/hmcmkit-marketplace/hmcmkit/*/skills/`
2. For each skill directory, read SKILL.md frontmatter:
- name, classification, description (first line)
3. Count total core skills
### Step 2: Scan Project-Local Skills
1. Read project skills directory:
`.ai-agent/skills/project/*/SKILL.md`
2. For each skill, read frontmatter
3. Count total project skills
### Step 3: Detect Conflicts
1. Compare skill names between core and project
2. If same name exists in both: mark as "override" (project wins)
3. If project skill triggers overlap with core: mark as "shadow"
### Step 4: Display Report
```
Skill Status Report
====================
Layer: hmcmkit Core (v1.6.2)
Skills: 28 loaded
-----------------------------------------------
Name | Type | Classification
--------------------|------------|---------------
pdca | workflow | PDCA lifecycle
enterprise | workflow | Enterprise init
hmcmkit-rules | capability | Auto-apply rules
code-review | workflow | Code analysis
... (truncated)
Layer: Project-Local (hunikflow)
Skills: 8 loaded
-----------------------------------------------
Name | Type | Classification
--------------------|------------|---------------
btw | workflow | BTW suggestions
skill-create | workflow | Skill generator
skill-status | workflow | This report
hunikflow-model | capability | @Flow patterns
hunikflow-proxy | capability | DataProxy patterns
hunikflow-domain | capability | ERP domain logic
hunikflow-i18n | capability | i18n CSV guide
hunikflow-dynamic-api| capability | Dynamic API guide
Conflicts: 0 overrides, 0 shadows
Summary: 36 total skills (28 core + 8 project)
```
### Options
**`/skill-status --detail`**: Show full descriptions and trigger keywords for each skill.
**`/skill-status --conflicts`**: Show only skills with naming conflicts or trigger overlaps.
## Skill Layer Priority
```
Priority (high to low):
1. .ai-agent/skills/project/ (project-local, git-tracked)
2. ~/.ai-agent/plugins/.../skills/ (hmcmkit core, plugin-managed)
3. ~/.ai-agent/skills/ (user global, if any)
```
When a project skill has the same name as a core skill, the project skill takes precedence.
This is the "2-layer override" pattern.
+292
View File
@@ -0,0 +1,292 @@
---
name: starter
classification: capability
classification-reason: Pattern guidance may overlap with model's built-in knowledge as it improves
deprecation-risk: medium
description: |
Static web development for beginners — HTML/CSS/JS and Next.js App Router.
Triggers: static website, portfolio, landing page, beginner, 정적 웹, 초보자, init starter.
argument-hint: "[init|guide|help]"
agent: hmcmkit:starter-guide
allowed-tools:
- Read
- Write
- Edit
- Glob
- Grep
- WebSearch
- WebFetch
user-invocable: true
imports:
- ${PLUGIN_ROOT}/templates/design-starter.template.md
next-skill: phase-1-schema
pdca-phase: plan
task-template: "[Init-Starter] {feature}"
---
# Beginner (Starter) Skill
## Actions
| Action | Description | Example |
|--------|-------------|---------|
| `init` | Project initialization (/init-starter feature) | `/starter init my-portfolio` |
| `guide` | Display development guide | `/starter guide` |
| `help` | Beginner help | `/starter help` |
### init (Project Initialization)
1. Create project directory structure (HTML/CSS/JS or Next.js)
2. Generate package.json (when Next.js selected)
3. Create agents.md (Level: Starter specified)
4. Create docs/ folder structure (for PDCA documents)
5. Initialize .hmcmkit-memory.json
### guide (Development Guide)
- Analyze current project state
- Suggest next steps appropriate for Starter level
- Phase 1-3 focused Pipeline guide
### help (Beginner Help)
- Explain HTML/CSS/JS basic concepts
- Answer frequently asked questions
- Provide example code
## Target Audience
- Those learning programming for the first time
- Those who want to create a simple website
- Those who need a portfolio site
## Tech Stack
### Option A: Pure HTML/CSS/JS (For Complete Beginners)
```
HTML5 → Web page structure
CSS3 → Styling
JavaScript → Dynamic features (optional)
```
### Option B: Next.js (Using Framework)
```
Next.js 14+ → React-based framework
Tailwind CSS → Utility CSS
TypeScript → Type safety (optional)
```
### Language Tier Guidance (v1.3.0)
> **Recommended**: Tier 1 languages only (Python, TypeScript, JavaScript)
>
> Starter level focuses on AI-Native development with maximum AI tool support.
| Tier | Allowed | Reason |
|------|---------|--------|
| Tier 1 | ✅ Yes | Full AI support, Vibe Coding optimized |
| Tier 2 | ⚠️ Limited | Consider Dynamic level instead |
| Tier 3-4 | ❌ No | Upgrade to Dynamic/Enterprise |
## Project Structure
### Option A: HTML/CSS/JS
```
project/
├── index.html # Main page
├── about.html # About page
├── css/
│ └── style.css # Styles
├── js/
│ └── main.js # JavaScript
├── images/ # Image files
├── docs/ # PDCA documents
│ ├── 01-plan/
│ └── 02-design/
└── README.md
```
### Option B: Next.js
```
project/
├── src/
│ ├── app/
│ │ ├── layout.tsx # Common layout
│ │ ├── page.tsx # Main page
│ │ └── about/
│ │ └── page.tsx # About page
│ └── components/ # Reusable components
├── public/ # Static files
├── docs/ # PDCA documents
├── package.json
├── tailwind.config.js
└── README.md
```
## Core Concept Explanations
### HTML (Web Page Structure)
```html
<!-- Basic structure -->
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>My Website</title>
<link rel="stylesheet" href="css/style.css">
</head>
<body>
<header>Header</header>
<main>Main content</main>
<footer>Footer</footer>
</body>
</html>
```
### CSS (Styling Web Pages)
```css
/* Basic styles */
body {
font-family: 'Inter', sans-serif;
margin: 0;
padding: 0;
}
/* Center alignment */
.container {
max-width: 1200px;
margin: 0 auto;
padding: 20px;
}
/* Responsive (mobile support) */
@media (max-width: 768px) {
.container {
padding: 10px;
}
}
```
### Next.js App Router (Creating Pages)
```tsx
// app/page.tsx - Main page
export default function Home() {
return (
<main className="container mx-auto p-4">
<h1 className="text-3xl font-bold">
Welcome!
</h1>
</main>
);
}
// app/about/page.tsx - About page
// URL: /about
export default function About() {
return (
<div className="container mx-auto p-4">
<h1>About</h1>
<p>I am ...</p>
</div>
);
}
```
### Tailwind CSS (Quick Styling)
```tsx
// Frequently used classes
<div className="
container // Center alignment
mx-auto // Auto left/right margin
p-4 // Padding 16px
text-center // Center text
text-xl // Large text
font-bold // Bold text
bg-blue-500 // Blue background
text-white // White text
rounded-lg // Rounded corners
hover:bg-blue-600 // Color change on hover
">
```
## Deployment Methods
### GitHub Pages (Free)
```
1. Create GitHub repository
2. Push code
3. Settings → Pages → Source: main branch
4. Access at https://username.github.io/repo-name
```
### Vercel (Recommended for Next.js)
```
1. Sign up at vercel.com (GitHub integration)
2. "New Project" → Select repository
3. Click "Deploy"
4. URL automatically generated
```
## Limitations
```
❌ Login/Registration (requires server)
❌ Data storage (requires database)
❌ Admin pages (requires backend)
❌ Payment features (requires backend)
```
## When to Upgrade
Move to **Dynamic Level** if you need:
```
→ "I need login functionality"
→ "I want to store data"
→ "I need an admin page"
→ "I want users to communicate with each other"
```
## hmcmkit Features for Starter Level (v1.5.1)
### Output Style: hmcmkit-learning (Recommended)
For the best learning experience, activate the learning output style:
```
/output-style hmcmkit-learning
```
This provides:
- Learning points after each task explaining what you did and why
- TODO(learner) markers encouraging hands-on practice
- Concept explanations adjusted for beginner difficulty
### Agent Memory (Auto-Active)
hmcmkit agents automatically remember your learning progress across sessions.
No setup needed — your `starter-guide` agent uses `user` scope memory,
so learning context persists even across different projects.
### Agent Teams
Agent Teams is not available for Starter level projects.
When you upgrade to Dynamic level, you unlock 2-teammate parallel PDCA mode.
---
## Common Mistakes
| Mistake | Solution |
|---------|----------|
| Image not showing | Check path (`./images/photo.jpg`) |
| CSS not applied | Check link tag path |
| Page navigation not working | Check href path (`./about.html`) |
| Broken on mobile | Check `<meta name="viewport">` tag |
@@ -0,0 +1,704 @@
---
name: zero-script-qa
classification: workflow
classification-reason: Process automation persists regardless of model advancement
deprecation-risk: none
description: |
Zero Script QA — test without scripts using structured JSON logging and Docker monitoring.
Triggers: zero-script-qa, log testing, docker logs, QA, 제로 스크립트 QA.
context: fork
agent: hmcmkit:qa-monitor
user-invocable: true
hooks:
Stop:
- type: command
command: "node ${HMCMKIT_PLUGIN_ROOT}/scripts/qa-stop.js"
timeout: 10000
---
# Zero Script QA Expert Knowledge
## Overview
Zero Script QA is a methodology that verifies features through **structured logs** and **real-time monitoring** without writing test scripts.
```
Traditional: Write test code → Execute → Check results → Maintain
Zero Script: Build log infrastructure → Manual UX test → AI log analysis → Auto issue detection
```
## Core Principles
### 1. Log Everything
- All API calls (including 200 OK)
- All errors
- All important business events
- Entire flow trackable via Request ID
### 2. Structured JSON Logs
- Parseable JSON format
- Consistent fields (timestamp, level, request_id, message, data)
- Different log levels per environment
### 3. Real-time Monitoring
- Docker log streaming
- Antigravity Platform analyzes in real-time
- Immediate issue detection and documentation
---
## Logging Architecture
### JSON Log Format Standard
```json
{
"timestamp": "2026-01-08T10:30:00.000Z",
"level": "INFO",
"service": "api",
"request_id": "req_abc123",
"message": "API Request completed",
"data": {
"method": "POST",
"path": "/api/users",
"status": 200,
"duration_ms": 45
}
}
```
### Required Log Fields
| Field | Type | Description |
|-------|------|-------------|
| timestamp | ISO 8601 | Time of occurrence |
| level | string | DEBUG, INFO, WARNING, ERROR |
| service | string | Service name (api, web, worker, etc.) |
| request_id | string | Request tracking ID |
| message | string | Log message |
| data | object | Additional data (optional) |
### Log Level Policy
| Environment | Minimum Level | Purpose |
|-------------|---------------|---------|
| Local | DEBUG | Development and QA |
| Staging | DEBUG | QA and integration testing |
| Production | INFO | Operations monitoring |
---
## Request ID Propagation
### Concept
```
Client → API Gateway → Backend → Database
↓ ↓ ↓ ↓
req_abc req_abc req_abc req_abc
Trackable with same Request ID across all layers
```
### Implementation Patterns
#### 1. Request ID Generation (Entry Point)
```typescript
// middleware.ts
import { v4 as uuidv4 } from 'uuid';
export function generateRequestId(): string {
return `req_${uuidv4().slice(0, 8)}`;
}
// Propagate via header
headers['X-Request-ID'] = requestId;
```
#### 2. Request ID Extraction and Propagation
```typescript
// API client
const requestId = headers['X-Request-ID'] || generateRequestId();
// Include in all logs
logger.info('Processing request', { request_id: requestId });
// Include in header when calling downstream services
await fetch(url, {
headers: { 'X-Request-ID': requestId }
});
```
---
## Backend Logging (FastAPI)
### Logging Middleware
```python
# middleware/logging.py
import logging
import time
import uuid
import json
from fastapi import Request
class JsonFormatter(logging.Formatter):
def format(self, record):
log_record = {
"timestamp": self.formatTime(record),
"level": record.levelname,
"service": "api",
"request_id": getattr(record, 'request_id', 'N/A'),
"message": record.getMessage(),
}
if hasattr(record, 'data'):
log_record["data"] = record.data
return json.dumps(log_record)
class LoggingMiddleware:
async def __call__(self, request: Request, call_next):
request_id = request.headers.get('X-Request-ID', f'req_{uuid.uuid4().hex[:8]}')
request.state.request_id = request_id
start_time = time.time()
# Request logging
logger.info(
f"Request started",
extra={
'request_id': request_id,
'data': {
'method': request.method,
'path': request.url.path,
'query': str(request.query_params)
}
}
)
response = await call_next(request)
duration = (time.time() - start_time) * 1000
# Response logging (including 200 OK!)
logger.info(
f"Request completed",
extra={
'request_id': request_id,
'data': {
'status': response.status_code,
'duration_ms': round(duration, 2)
}
}
)
response.headers['X-Request-ID'] = request_id
return response
```
### Business Logic Logging
```python
# services/user_service.py
def create_user(data: dict, request_id: str):
logger.info("Creating user", extra={
'request_id': request_id,
'data': {'email': data['email']}
})
# Business logic
user = User(**data)
db.add(user)
db.commit()
logger.info("User created", extra={
'request_id': request_id,
'data': {'user_id': user.id}
})
return user
```
---
## Frontend Logging (Next.js)
### Logger Module
```typescript
// lib/logger.ts
type LogLevel = 'DEBUG' | 'INFO' | 'WARNING' | 'ERROR';
interface LogData {
request_id?: string;
[key: string]: any;
}
const LOG_LEVELS: Record<LogLevel, number> = {
DEBUG: 0,
INFO: 1,
WARNING: 2,
ERROR: 3,
};
const MIN_LEVEL = process.env.NODE_ENV === 'production' ? 'INFO' : 'DEBUG';
function log(level: LogLevel, message: string, data?: LogData) {
if (LOG_LEVELS[level] < LOG_LEVELS[MIN_LEVEL]) return;
const logEntry = {
timestamp: new Date().toISOString(),
level,
service: 'web',
request_id: data?.request_id || 'N/A',
message,
data: data ? { ...data, request_id: undefined } : undefined,
};
console.log(JSON.stringify(logEntry));
}
export const logger = {
debug: (msg: string, data?: LogData) => log('DEBUG', msg, data),
info: (msg: string, data?: LogData) => log('INFO', msg, data),
warning: (msg: string, data?: LogData) => log('WARNING', msg, data),
error: (msg: string, data?: LogData) => log('ERROR', msg, data),
};
```
### API Client Integration
```typescript
// lib/api-client.ts
import { logger } from './logger';
import { v4 as uuidv4 } from 'uuid';
export async function apiClient<T>(
endpoint: string,
options: RequestInit = {}
): Promise<T> {
const requestId = `req_${uuidv4().slice(0, 8)}`;
const startTime = Date.now();
logger.info('API Request started', {
request_id: requestId,
method: options.method || 'GET',
endpoint,
});
try {
const response = await fetch(`/api${endpoint}`, {
...options,
headers: {
'Content-Type': 'application/json',
'X-Request-ID': requestId,
...options.headers,
},
});
const duration = Date.now() - startTime;
const data = await response.json();
// Log 200 OK too!
logger.info('API Request completed', {
request_id: requestId,
status: response.status,
duration_ms: duration,
});
if (!response.ok) {
logger.error('API Request failed', {
request_id: requestId,
status: response.status,
error: data.error,
});
throw new ApiError(data.error);
}
return data;
} catch (error) {
logger.error('API Request error', {
request_id: requestId,
error: error instanceof Error ? error.message : 'Unknown error',
});
throw error;
}
}
```
---
## Nginx JSON Logging
### nginx.conf Configuration
```nginx
http {
log_format json_combined escape=json '{'
'"timestamp":"$time_iso8601",'
'"level":"INFO",'
'"service":"nginx",'
'"request_id":"$http_x_request_id",'
'"message":"HTTP Request",'
'"data":{'
'"remote_addr":"$remote_addr",'
'"method":"$request_method",'
'"uri":"$request_uri",'
'"status":$status,'
'"body_bytes_sent":$body_bytes_sent,'
'"request_time":$request_time,'
'"upstream_response_time":"$upstream_response_time",'
'"http_referer":"$http_referer",'
'"http_user_agent":"$http_user_agent"'
'}'
'}';
access_log /var/log/nginx/access.log json_combined;
}
```
---
## Docker-Based QA Workflow
### docker-compose.yml Configuration
```yaml
version: '3.8'
services:
api:
build: ./backend
environment:
- LOG_LEVEL=DEBUG
- LOG_FORMAT=json
logging:
driver: json-file
options:
max-size: "10m"
max-file: "3"
web:
build: ./frontend
environment:
- NODE_ENV=development
depends_on:
- api
nginx:
image: nginx:alpine
volumes:
- ./nginx/nginx.conf:/etc/nginx/nginx.conf
ports:
- "80:80"
depends_on:
- api
- web
```
### Real-time Log Monitoring
```bash
# Stream all service logs
docker compose logs -f
# Specific service only
docker compose logs -f api
# Filter errors only
docker compose logs -f | grep '"level":"ERROR"'
# Track specific Request ID
docker compose logs -f | grep 'req_abc123'
```
---
## QA Automation Workflow
### 1. Start Environment
```bash
# Start development environment
docker compose up -d
# Start log monitoring (Antigravity Platform monitors)
docker compose logs -f
```
### 2. Manual UX Testing
```
User tests actual features in browser:
1. Sign up attempt
2. Login attempt
3. Use core features
4. Test edge cases
```
### 3. Antigravity Platform Log Analysis
```
Antigravity Platform in real-time:
1. Monitor log stream
2. Detect error patterns
3. Detect abnormal response times
4. Track entire flow via Request ID
5. Auto-document issues
```
### 4. Issue Documentation
```markdown
# QA Issue Report
## Issues Found
### ISSUE-001: Insufficient error handling on login failure
- **Request ID**: req_abc123
- **Severity**: Medium
- **Reproduction path**: Login → Wrong password
- **Log**:
```json
{"level":"ERROR","message":"Login failed","data":{"error":"Invalid credentials"}}
```
- **Problem**: Error message not user-friendly
- **Recommended fix**: Add error code to message mapping
```
---
## Issue Detection Patterns
### 1. Error Detection
```json
{"level":"ERROR","message":"..."}
```
→ Report immediately
### 2. Slow Response Detection
```json
{"data":{"duration_ms":3000}}
```
→ Warning when exceeding 1000ms
### 3. Consecutive Failure Detection
```
3+ consecutive failures on same endpoint
```
→ Report potential system issue
### 4. Abnormal Status Codes
```json
{"data":{"status":500}}
```
→ Report 5xx errors immediately
---
## Phase Integration
| Phase | Zero Script QA Integration |
|-------|---------------------------|
| Phase 4 (API) | API response logging verification |
| Phase 6 (UI) | Frontend logging verification |
| Phase 7 (Security) | Security event logging verification |
| Phase 8 (Review) | Log quality review |
| Phase 9 (Deployment) | Production log level configuration |
---
## Iterative Test Cycle Pattern
Based on bkamp.ai notification feature development:
### Example: 8-Cycle Test Process
| Cycle | Pass Rate | Bug Found | Fix Applied |
|-------|-----------|-----------|-------------|
| 1st | 30% | DB schema mismatch | Schema migration |
| 2nd | 45% | NULL handling missing | Add null checks |
| 3rd | 55% | Routing error | Fix deeplinks |
| 4th | 65% | Type mismatch | Fix enum types |
| 5th | 70% | Calculation error | Fix count logic |
| 6th | 75% | Event missing | Add event triggers |
| 7th | 82% | Cache sync issue | Fix cache invalidation |
| 8th | **89%** | Stable | Final polish |
### Cycle Workflow
```
┌─────────────────────────────────────────────────────────────┐
│ Iterative Test Cycle │
├─────────────────────────────────────────────────────────────┤
│ │
│ Cycle N: │
│ 1. Run test script (E2E or manual) │
│ 2. AI Agent monitors logs in real-time │
│ 3. Record pass/fail results │
│ 4. AI Agent identifies root cause of failures │
│ 5. Fix code immediately (hot reload) │
│ 6. Document: Cycle N → Bug → Fix │
│ │
│ Repeat until acceptable pass rate (>85%) │
│ │
└─────────────────────────────────────────────────────────────┘
```
### E2E Test Script Template
```bash
#!/bin/bash
# E2E Test Script Template
API_URL="http://localhost:8000"
TOKEN="your-test-token"
PASS_COUNT=0
FAIL_COUNT=0
SKIP_COUNT=0
GREEN='\033[0;32m'
RED='\033[0;31m'
YELLOW='\033[0;33m'
NC='\033[0m'
test_feature_action() {
echo -n "Testing: Feature action... "
response=$(curl -s -X POST "$API_URL/api/v1/feature/action" \
-H "Authorization: Bearer $TOKEN" \
-H "Content-Type: application/json" \
-d '{"param": "value"}')
if [[ "$response" == *"expected_result"* ]]; then
echo -e "${GREEN}✅ PASS${NC}"
((PASS_COUNT++))
else
echo -e "${RED}❌ FAIL${NC}"
echo "Response: $response"
((FAIL_COUNT++))
fi
}
# Run all tests
test_feature_action
# ... more tests
# Summary
echo ""
echo "═══════════════════════════════════════"
echo "Test Results:"
echo -e " ${GREEN}✅ PASS: $PASS_COUNT${NC}"
echo -e " ${RED}❌ FAIL: $FAIL_COUNT${NC}"
echo -e " ${YELLOW}⏭️ SKIP: $SKIP_COUNT${NC}"
echo "═══════════════════════════════════════"
```
### Test Cycle Documentation Template
```markdown
# Feature Test Results - Cycle N
## Summary
- **Date**: YYYY-MM-DD
- **Feature**: {feature name}
- **Pass Rate**: N%
- **Tests**: X passed / Y total
## Results
| Test Case | Status | Notes |
|-----------|--------|-------|
| Test 1 | ✅ | |
| Test 2 | ❌ | {error description} |
| Test 3 | ⏭️ | {skip reason} |
## Bugs Found
### BUG-001: {Title}
- **Root Cause**: {description}
- **Fix**: {what was changed}
- **Files**: `path/to/file.py:123`
## Next Cycle Plan
- {what to test next}
```
---
## 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
---
## Auto-Apply Rules
### When Building Logging Infrastructure
When implementing API/Backend:
1. Suggest logging middleware creation
2. Suggest JSON format logger setup
3. Add Request ID generation/propagation logic
When implementing Frontend:
1. Suggest Logger module creation
2. Suggest logging integration with API client
3. Suggest including Request ID header
### When Performing QA
On test request:
1. Guide to run `docker compose logs -f`
2. Request manual UX testing from user
3. Real-time log monitoring
4. Document issues immediately when detected
5. Provide fix suggestions
### Issue Detection Thresholds
| Severity | Condition | Action |
|----------|-----------|--------|
| Critical | `level: ERROR` or `status: 5xx` | Immediate report |
| Critical | `duration_ms > 3000` | Immediate report |
| Critical | 3+ consecutive failures | Immediate report |
| Warning | `status: 401, 403` | Warning report |
| Warning | `duration_ms > 1000` | Warning report |
| Info | Missing log fields | Note for improvement |
| Info | Request ID not propagated | Note for improvement |
### Required Logging Locations
#### Backend (FastAPI/Express)
```
✅ Request start (method, path, params)
✅ Request complete (status, duration_ms)
✅ Major business logic steps
✅ Detailed info on errors
✅ Before/after external API calls
✅ DB queries (in development)
```
#### Frontend (Next.js/React)
```
✅ API call start
✅ API response received (status, duration)
✅ Detailed info on errors
✅ Important user actions
```