moai-adk 0.3.3__py3-none-any.whl → 0.3.7__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.

Potentially problematic release.


This version of moai-adk might be problematic. Click here for more details.

Files changed (46) hide show
  1. moai_adk/__init__.py +1 -1
  2. moai_adk/cli/commands/update.py +49 -30
  3. moai_adk/core/project/initializer.py +16 -5
  4. moai_adk/core/project/phase_executor.py +27 -3
  5. moai_adk/core/project/validator.py +46 -1
  6. moai_adk/core/template/processor.py +151 -11
  7. moai_adk/templates/.claude/agents/alfred/cc-manager.md +474 -0
  8. moai_adk/templates/.claude/agents/alfred/debug-helper.md +166 -0
  9. moai_adk/templates/.claude/agents/alfred/doc-syncer.md +175 -0
  10. moai_adk/templates/.claude/agents/alfred/git-manager.md +327 -0
  11. moai_adk/templates/.claude/agents/alfred/implementation-planner.md +311 -0
  12. moai_adk/templates/.claude/agents/alfred/project-manager.md +152 -0
  13. moai_adk/templates/.claude/agents/alfred/quality-gate.md +301 -0
  14. moai_adk/templates/.claude/agents/alfred/spec-builder.md +241 -0
  15. moai_adk/templates/.claude/agents/alfred/tag-agent.md +247 -0
  16. moai_adk/templates/.claude/agents/alfred/tdd-implementer.md +280 -0
  17. moai_adk/templates/.claude/agents/alfred/trust-checker.md +332 -0
  18. moai_adk/templates/.claude/commands/alfred/0-project.md +523 -0
  19. moai_adk/templates/.claude/commands/alfred/1-spec.md +530 -0
  20. moai_adk/templates/.claude/commands/alfred/2-build.md +430 -0
  21. moai_adk/templates/.claude/commands/alfred/3-sync.md +552 -0
  22. moai_adk/templates/.claude/hooks/alfred/README.md +230 -0
  23. moai_adk/templates/.claude/hooks/alfred/alfred_hooks.py +160 -0
  24. moai_adk/templates/.claude/hooks/alfred/core/__init__.py +79 -0
  25. moai_adk/templates/.claude/hooks/alfred/core/checkpoint.py +271 -0
  26. moai_adk/templates/.claude/hooks/alfred/core/context.py +110 -0
  27. moai_adk/templates/.claude/hooks/alfred/core/project.py +284 -0
  28. moai_adk/templates/.claude/hooks/alfred/core/tags.py +244 -0
  29. moai_adk/templates/.claude/hooks/alfred/handlers/__init__.py +21 -0
  30. moai_adk/templates/.claude/hooks/alfred/handlers/notification.py +25 -0
  31. moai_adk/templates/.claude/hooks/alfred/handlers/session.py +80 -0
  32. moai_adk/templates/.claude/hooks/alfred/handlers/tool.py +71 -0
  33. moai_adk/templates/.claude/hooks/alfred/handlers/user.py +41 -0
  34. moai_adk/templates/.claude/output-styles/alfred/agentic-coding.md +635 -0
  35. moai_adk/templates/.claude/output-styles/alfred/moai-adk-learning.md +691 -0
  36. moai_adk/templates/.claude/output-styles/alfred/study-with-alfred.md +469 -0
  37. moai_adk/templates/.claude/settings.json +134 -0
  38. moai_adk/templates/.moai/hooks/pre-push.sample +88 -0
  39. moai_adk/templates/.moai/memory/development-guide.md +1 -26
  40. moai_adk/templates/.moai/memory/gitflow-protection-policy.md +220 -0
  41. {moai_adk-0.3.3.dist-info → moai_adk-0.3.7.dist-info}/METADATA +783 -250
  42. moai_adk-0.3.7.dist-info/RECORD +89 -0
  43. moai_adk-0.3.3.dist-info/RECORD +0 -56
  44. {moai_adk-0.3.3.dist-info → moai_adk-0.3.7.dist-info}/WHEEL +0 -0
  45. {moai_adk-0.3.3.dist-info → moai_adk-0.3.7.dist-info}/entry_points.txt +0 -0
  46. {moai_adk-0.3.3.dist-info → moai_adk-0.3.7.dist-info}/licenses/LICENSE +0 -0
@@ -0,0 +1,230 @@
1
+ # Alfred Hooks System
2
+
3
+ **Event-Driven Context Management for MoAI-ADK**
4
+
5
+ Alfred Hooks는 Claude Code의 이벤트 시스템과 통합되어 프로젝트 컨텍스트를 자동으로 관리하고, 위험한 작업 전에 checkpoint를 생성하며, JIT (Just-in-Time) 문서 로딩을 제공합니다.
6
+
7
+ ---
8
+
9
+ ## 📐 Architecture
10
+
11
+ ### Modular Design (9 Files, ≤284 LOC each)
12
+
13
+ ```
14
+ .claude/hooks/alfred/
15
+ ├── alfred_hooks.py # Main entry point (CLI router)
16
+ ├── core/ # Core business logic
17
+ │ ├── __init__.py # Type definitions (HookPayload, HookResult)
18
+ │ ├── project.py # Language detection, Git info, SPEC counting
19
+ │ ├── context.py # JIT retrieval, workflow context
20
+ │ ├── checkpoint.py # Event-driven checkpoint creation
21
+ │ └── tags.py # TAG search, verification, caching
22
+ └── handlers/ # Event handlers
23
+ ├── __init__.py # Handler exports
24
+ ├── session.py # SessionStart, SessionEnd
25
+ ├── user.py # UserPromptSubmit
26
+ ├── tool.py # PreToolUse, PostToolUse
27
+ └── notification.py # Notification, Stop, SubagentStop
28
+ ```
29
+
30
+ ### Design Principles
31
+
32
+ - **Single Responsibility**: 각 모듈은 하나의 명확한 책임
33
+ - **Separation of Concerns**: core (비즈니스 로직) vs handlers (이벤트 처리)
34
+ - **CODE-FIRST**: 중간 캐시 없이 코드 직접 스캔 (mtime 기반 무효화)
35
+ - **Context Engineering**: JIT Retrieval로 초기 컨텍스트 부담 최소화
36
+
37
+ ---
38
+
39
+ ## 🎯 Core Modules
40
+
41
+ ### `core/project.py` (284 LOC)
42
+
43
+ **프로젝트 메타데이터 및 언어 감지**
44
+
45
+ ```python
46
+ # Public API
47
+ detect_language(cwd: str) -> str
48
+ get_project_language(cwd: str) -> str
49
+ get_git_info(cwd: str) -> dict[str, Any]
50
+ count_specs(cwd: str) -> dict[str, int]
51
+ ```
52
+
53
+ **Features**:
54
+ - 20개 언어 자동 감지 (Python, TypeScript, Java, Go, Rust, etc.)
55
+ - `.moai/config.json` 우선, fallback to auto-detection
56
+ - Git 정보 조회 (branch, commit, changes)
57
+ - SPEC 진행도 계산 (total, completed, percentage)
58
+
59
+ ### `core/context.py` (110 LOC)
60
+
61
+ **JIT Context Retrieval 및 워크플로우 관리**
62
+
63
+ ```python
64
+ # Public API
65
+ get_jit_context(prompt: str, cwd: str) -> list[str]
66
+ save_phase_context(phase: str, data: Any, ttl: int = 600)
67
+ load_phase_context(phase: str, ttl: int = 600) -> Any | None
68
+ clear_workflow_context()
69
+ ```
70
+
71
+ **Features**:
72
+ - 프롬프트 분석 기반 문서 자동 추천
73
+ - `/alfred:1-spec` → `spec-metadata.md`
74
+ - `/alfred:2-build` → `development-guide.md`
75
+ - 워크플로우 단계별 컨텍스트 캐싱 (TTL 10분)
76
+ - Anthropic Context Engineering 원칙 준수
77
+
78
+ ### `core/checkpoint.py` (244 LOC)
79
+
80
+ **Event-Driven Checkpoint 자동화**
81
+
82
+ ```python
83
+ # Public API
84
+ detect_risky_operation(tool: str, args: dict, cwd: str) -> tuple[bool, str]
85
+ create_checkpoint(cwd: str, operation: str) -> str
86
+ log_checkpoint(cwd: str, branch: str, description: str)
87
+ list_checkpoints(cwd: str, max_count: int = 10) -> list[dict]
88
+ ```
89
+
90
+ **Features**:
91
+ - 위험한 작업 자동 감지:
92
+ - Bash: `rm -rf`, `git merge`, `git reset --hard`
93
+ - Edit/Write: `CLAUDE.md`, `config.json`
94
+ - MultiEdit: ≥10 files
95
+ - Git checkpoint 자동 생성: `checkpoint/before-{operation}-{timestamp}`
96
+ - checkpoint 이력 관리 및 복구 가이드
97
+
98
+ ### `core/tags.py` (244 LOC)
99
+
100
+ **CODE-FIRST TAG 시스템**
101
+
102
+ ```python
103
+ # Public API
104
+ search_tags(pattern: str, scope: list[str], cache_ttl: int = 60) -> list[dict]
105
+ verify_tag_chain(tag_id: str) -> dict[str, Any]
106
+ find_all_tags_by_type(tag_type: str) -> dict[str, list[str]]
107
+ suggest_tag_reuse(keyword: str) -> list[str]
108
+ get_library_version(library: str, cache_ttl: int = 86400) -> str | None
109
+ set_library_version(library: str, version: str)
110
+ ```
111
+
112
+ **Features**:
113
+ - ripgrep 기반 TAG 검색 (JSON 출력 파싱)
114
+ - mtime 기반 캐시 무효화 (CODE-FIRST 보장)
115
+ - TAG 체인 검증 (@SPEC → @TEST → @CODE 완전성 확인)
116
+ - 라이브러리 버전 캐싱 (TTL 24시간)
117
+
118
+ ---
119
+
120
+ ## 🎬 Event Handlers
121
+
122
+ ### `handlers/session.py`
123
+
124
+ **SessionStart, SessionEnd 핸들러**
125
+
126
+ - **SessionStart**: 프로젝트 정보 표시
127
+ - 언어, Git 상태, SPEC 진행도, 최근 checkpoint
128
+ - `systemMessage` 필드로 사용자에게 직접 표시
129
+ - **SessionEnd**: 정리 작업 (stub)
130
+
131
+ ### `handlers/user.py`
132
+
133
+ **UserPromptSubmit 핸들러**
134
+
135
+ - JIT Context 추천 문서 리스트 반환
136
+ - 사용자 프롬프트 패턴 분석 및 관련 문서 로드
137
+
138
+ ### `handlers/tool.py`
139
+
140
+ **PreToolUse, PostToolUse 핸들러**
141
+
142
+ - **PreToolUse**: 위험한 작업 감지 시 자동 checkpoint 생성
143
+ - **PostToolUse**: 후처리 작업 (stub)
144
+
145
+ ### `handlers/notification.py`
146
+
147
+ **Notification, Stop, SubagentStop 핸들러**
148
+
149
+ - 기본 구현 (stub, 향후 확장 가능)
150
+
151
+ ---
152
+
153
+ ## 🧪 Testing
154
+
155
+ ### Test Suite
156
+
157
+ ```bash
158
+ # Run all tests
159
+ uv run pytest tests/unit/test_alfred_hooks_*.py -v --no-cov
160
+
161
+ # Run specific module tests
162
+ uv run pytest tests/unit/test_alfred_hooks_core_tags.py -v
163
+ uv run pytest tests/unit/test_alfred_hooks_core_context.py -v
164
+ uv run pytest tests/unit/test_alfred_hooks_core_project.py -v
165
+ ```
166
+
167
+ ### Test Coverage (18 tests)
168
+
169
+ - ✅ **tags.py**: 7 tests (캐시, TAG 검증, 버전 관리)
170
+ - ✅ **context.py**: 5 tests (JIT, 워크플로우 컨텍스트)
171
+ - ✅ **project.py**: 6 tests (언어 감지, Git, SPEC 카운트)
172
+
173
+ ### Test Structure
174
+
175
+ ```python
176
+ # Dynamic module loading for isolated testing
177
+ def _load_{module}_module(module_name: str):
178
+ repo_root = Path(__file__).resolve().parents[2]
179
+ hooks_dir = repo_root / ".claude" / "hooks" / "alfred"
180
+ sys.path.insert(0, str(hooks_dir))
181
+
182
+ module_path = hooks_dir / "core" / "{module}.py"
183
+ spec = importlib.util.spec_from_file_location(module_name, module_path)
184
+ # ...
185
+ ```
186
+
187
+ ---
188
+
189
+ ## 🔄 Migration from moai_hooks.py
190
+
191
+ ### Before (Monolithic)
192
+
193
+ - **1 file**: 1233 LOC
194
+ - **Issues**:
195
+ - 모든 기능이 하나의 파일에 집중
196
+ - 테스트 어려움, 유지보수 복잡
197
+ - 책임 분리 불명확
198
+
199
+ ### After (Modular)
200
+
201
+ - **9 files**: ≤284 LOC each
202
+ - **Benefits**:
203
+ - 명확한 책임 분리 (SRP)
204
+ - 독립적인 모듈 테스트 가능
205
+ - 확장 용이, 유지보수 간편
206
+ - Context Engineering 원칙 준수
207
+
208
+ ### Breaking Changes
209
+
210
+ **없음** - 외부 API는 동일하게 유지됩니다.
211
+
212
+ ---
213
+
214
+ ## 📚 References
215
+
216
+ ### Internal Documents
217
+
218
+ - **CLAUDE.md**: MoAI-ADK 사용자 가이드
219
+ - **.moai/memory/development-guide.md**: SPEC-First TDD 워크플로우
220
+ - **.moai/memory/spec-metadata.md**: SPEC 메타데이터 표준
221
+
222
+ ### External Resources
223
+
224
+ - [Claude Code Hooks Documentation](https://docs.claude.com/en/docs/claude-code)
225
+ - [Anthropic Context Engineering](https://docs.anthropic.com/claude/docs/context-engineering)
226
+
227
+ ---
228
+
229
+ **Last Updated**: 2025-10-16
230
+ **Author**: @Alfred (MoAI-ADK SuperAgent)
@@ -0,0 +1,160 @@
1
+ #!/usr/bin/env python3
2
+ # @CODE:HOOKS-REFACTOR-001 | SPEC: SPEC-HOOKS-REFACTOR-001.md
3
+ """Alfred Hooks - Main entry point for MoAI-ADK Claude Code Hooks
4
+
5
+ Claude Code 이벤트를 적절한 핸들러로 라우팅하는 메인 진입점
6
+
7
+ Setup sys.path for package imports
8
+ """
9
+ import sys
10
+ from pathlib import Path
11
+
12
+ # Add the hooks directory to sys.path to enable package imports
13
+ HOOKS_DIR = Path(__file__).parent
14
+ if str(HOOKS_DIR) not in sys.path:
15
+ sys.path.insert(0, str(HOOKS_DIR))
16
+
17
+ # Now we can import from the package
18
+
19
+ """
20
+ Architecture:
21
+ ┌─────────────────────────────────────────────────────────────┐
22
+ │ alfred_hooks.py (Router) │
23
+ ├─────────────────────────────────────────────────────────────┤
24
+ │ - CLI argument parsing │
25
+ │ - JSON I/O (stdin/stdout) │
26
+ │ - Event routing to handlers │
27
+ └─────────────────────────────────────────────────────────────┘
28
+
29
+ ┌─────────────────────────────────────────────────────────────┐
30
+ │ handlers/ (Event Handlers) │
31
+ ├─────────────────────────────────────────────────────────────┤
32
+ │ - session.py: SessionStart, SessionEnd │
33
+ │ - user.py: UserPromptSubmit │
34
+ │ - tool.py: PreToolUse, PostToolUse │
35
+ │ - notification.py: Notification, Stop, SubagentStop │
36
+ └─────────────────────────────────────────────────────────────┘
37
+
38
+ ┌─────────────────────────────────────────────────────────────┐
39
+ │ core/ (Business Logic) │
40
+ ├─────────────────────────────────────────────────────────────┤
41
+ │ - project.py: Language detection, Git info, SPEC progress │
42
+ │ - context.py: JIT Retrieval, workflow context │
43
+ │ - checkpoint.py: Event-Driven Checkpoint system │
44
+ │ - tags.py: TAG search/verification, library version cache │
45
+ └─────────────────────────────────────────────────────────────┘
46
+
47
+ Usage:
48
+ python alfred_hooks.py <event_name> < payload.json
49
+
50
+ Supported Events:
51
+ - SessionStart: 세션 시작 (프로젝트 상태 표시)
52
+ - UserPromptSubmit: 프롬프트 제출 (JIT 문서 로딩)
53
+ - PreToolUse: Tool 사용 전 (Checkpoint 자동 생성)
54
+ - SessionEnd, PostToolUse, Notification, Stop, SubagentStop
55
+
56
+ Exit Codes:
57
+ - 0: 성공
58
+ - 1: 에러 (인수 없음, JSON 파싱 실패, 예외 발생)
59
+
60
+ TDD History:
61
+ - RED: 모듈 분리 설계, 이벤트 라우팅 테스트
62
+ - GREEN: 1233 LOC → 9개 모듈 분리 구현 (SRP 준수)
63
+ - REFACTOR: Import 최적화, 에러 처리 강화
64
+ """
65
+
66
+ import json
67
+
68
+ from core import HookResult
69
+ from handlers import (
70
+ handle_notification,
71
+ handle_post_tool_use,
72
+ handle_pre_tool_use,
73
+ handle_session_end,
74
+ handle_session_start,
75
+ handle_stop,
76
+ handle_subagent_stop,
77
+ handle_user_prompt_submit,
78
+ )
79
+
80
+
81
+ def main() -> None:
82
+ """메인 진입점 - Claude Code Hook 스크립트
83
+
84
+ CLI 인수로 이벤트명을 받고, stdin으로 JSON 페이로드를 읽습니다.
85
+ 이벤트에 맞는 핸들러를 호출하고, 결과를 JSON으로 stdout에 출력합니다.
86
+
87
+ Usage:
88
+ python alfred_hooks.py <event_name> < payload.json
89
+
90
+ Supported Events:
91
+ - SessionStart: 세션 시작 (프로젝트 상태 표시)
92
+ - UserPromptSubmit: 프롬프트 제출 (JIT 문서 로딩)
93
+ - SessionEnd, PreToolUse, PostToolUse, Notification, Stop, SubagentStop
94
+
95
+ Exit Codes:
96
+ - 0: 성공
97
+ - 1: 에러 (인수 없음, JSON 파싱 실패, 예외 발생)
98
+
99
+ Examples:
100
+ $ echo '{"cwd": "."}' | python alfred_hooks.py SessionStart
101
+ {"message": "🚀 MoAI-ADK Session Started\\n...", ...}
102
+
103
+ Notes:
104
+ - Claude Code가 자동으로 호출 (사용자 직접 실행 불필요)
105
+ - stdin/stdout으로 JSON I/O 처리
106
+ - stderr로 에러 메시지 출력
107
+ - UserPromptSubmit은 특별한 출력 스키마 사용 (hookEventName + additionalContext)
108
+
109
+ TDD History:
110
+ - RED: 이벤트 라우팅, JSON I/O, 에러 처리 테스트
111
+ - GREEN: 핸들러 맵 기반 라우팅 구현
112
+ - REFACTOR: 에러 메시지 명확화, exit code 표준화, UserPromptSubmit 스키마 분리
113
+ """
114
+ # Check for event argument
115
+ if len(sys.argv) < 2:
116
+ print("Usage: alfred_hooks.py <event>", file=sys.stderr)
117
+ sys.exit(1)
118
+
119
+ event_name = sys.argv[1]
120
+
121
+ try:
122
+ # Read JSON from stdin
123
+ input_data = sys.stdin.read()
124
+ data = json.loads(input_data)
125
+
126
+ cwd = data.get("cwd", ".")
127
+
128
+ # Route to appropriate handler
129
+ handlers = {
130
+ "SessionStart": handle_session_start,
131
+ "UserPromptSubmit": handle_user_prompt_submit,
132
+ "SessionEnd": handle_session_end,
133
+ "PreToolUse": handle_pre_tool_use,
134
+ "PostToolUse": handle_post_tool_use,
135
+ "Notification": handle_notification,
136
+ "Stop": handle_stop,
137
+ "SubagentStop": handle_subagent_stop,
138
+ }
139
+
140
+ handler = handlers.get(event_name)
141
+ result = handler({"cwd": cwd, **data}) if handler else HookResult()
142
+
143
+ # UserPromptSubmit은 특별한 출력 스키마 사용
144
+ if event_name == "UserPromptSubmit":
145
+ print(json.dumps(result.to_user_prompt_submit_dict()))
146
+ else:
147
+ print(json.dumps(result.to_dict()))
148
+
149
+ sys.exit(0)
150
+
151
+ except json.JSONDecodeError as e:
152
+ print(f"JSON parse error: {e}", file=sys.stderr)
153
+ sys.exit(1)
154
+ except Exception as e:
155
+ print(f"Unexpected error: {e}", file=sys.stderr)
156
+ sys.exit(1)
157
+
158
+
159
+ if __name__ == "__main__":
160
+ main()
@@ -0,0 +1,79 @@
1
+ #!/usr/bin/env python3
2
+ """Core module for Alfred Hooks
3
+
4
+ 공통 타입 정의 및 유틸리티 함수
5
+ """
6
+
7
+ from dataclasses import asdict, dataclass, field
8
+ from typing import Any, NotRequired, TypedDict
9
+
10
+
11
+ class HookPayload(TypedDict):
12
+ """Claude Code Hook 이벤트 페이로드 타입 정의
13
+
14
+ Claude Code가 Hook 스크립트에 전달하는 데이터 구조.
15
+ 이벤트에 따라 필드가 다를 수 있으므로 NotRequired 사용.
16
+ """
17
+
18
+ cwd: str
19
+ userPrompt: NotRequired[str] # UserPromptSubmit 이벤트만 포함
20
+ tool: NotRequired[str] # PreToolUse/PostToolUse 이벤트
21
+ arguments: NotRequired[dict[str, Any]] # Tool arguments
22
+
23
+
24
+ @dataclass
25
+ class HookResult:
26
+ """Hook 실행 결과"""
27
+
28
+ message: str | None = None
29
+ systemMessage: str | None = None # 사용자에게 직접 표시되는 메시지
30
+ blocked: bool = False
31
+ contextFiles: list[str] = field(default_factory=list)
32
+ suggestions: list[str] = field(default_factory=list)
33
+ exitCode: int = 0
34
+
35
+ def to_dict(self) -> dict[str, Any]:
36
+ """일반 Hook용 딕셔너리 변환"""
37
+ return asdict(self)
38
+
39
+ def to_user_prompt_submit_dict(self) -> dict[str, Any]:
40
+ """UserPromptSubmit Hook 전용 출력 형식
41
+
42
+ Claude Code는 UserPromptSubmit에 대해 특별한 스키마를 요구:
43
+ {
44
+ "hookEventName": "UserPromptSubmit",
45
+ "additionalContext": "string (required)"
46
+ }
47
+
48
+ Returns:
49
+ Claude Code UserPromptSubmit Hook 스키마에 맞는 딕셔너리
50
+
51
+ Examples:
52
+ >>> result = HookResult(contextFiles=["tests/"])
53
+ >>> result.to_user_prompt_submit_dict()
54
+ {'hookEventName': 'UserPromptSubmit', 'additionalContext': '📎 Context: tests/'}
55
+ """
56
+ # contextFiles를 additionalContext 문자열로 변환
57
+ if self.contextFiles:
58
+ context_str = "\n".join([f"📎 Context: {f}" for f in self.contextFiles])
59
+ else:
60
+ context_str = ""
61
+
62
+ # message가 있으면 추가
63
+ if self.message:
64
+ if context_str:
65
+ context_str = f"{self.message}\n\n{context_str}"
66
+ else:
67
+ context_str = self.message
68
+
69
+ # 빈 문자열이면 기본값 사용
70
+ if not context_str:
71
+ context_str = ""
72
+
73
+ return {
74
+ "hookEventName": "UserPromptSubmit",
75
+ "additionalContext": context_str
76
+ }
77
+
78
+
79
+ __all__ = ["HookPayload", "HookResult"]