claude-automata 0__tar.gz

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.
Files changed (86) hide show
  1. claude_automata-0/.gitignore +10 -0
  2. claude_automata-0/LICENSE +21 -0
  3. claude_automata-0/PKG-INFO +9 -0
  4. claude_automata-0/README.md +59 -0
  5. claude_automata-0/copier.yml +16 -0
  6. claude_automata-0/create.py +41 -0
  7. claude_automata-0/design/components/cognitive-load-trigger.md +384 -0
  8. claude_automata-0/design/components/error-classifier.md +941 -0
  9. claude_automata-0/design/components/hook-system.md +1518 -0
  10. claude_automata-0/design/components/purpose-engine.md +806 -0
  11. claude_automata-0/design/components/self-improvement.md +624 -0
  12. claude_automata-0/design/components/session-manager.md +1148 -0
  13. claude_automata-0/design/components/slack-client.md +1102 -0
  14. claude_automata-0/design/components/state-manager.md +1709 -0
  15. claude_automata-0/design/components/supervisor.md +1289 -0
  16. claude_automata-0/design/components/tui.md +1529 -0
  17. claude_automata-0/design/data-model.md +1749 -0
  18. claude_automata-0/design/directory-structure.md +850 -0
  19. claude_automata-0/design/encapsulation.md +294 -0
  20. claude_automata-0/design/file-format-decisions.md +233 -0
  21. claude_automata-0/design/flows.md +1873 -0
  22. claude_automata-0/design/requirements-traceability.md +427 -0
  23. claude_automata-0/design/root.md +584 -0
  24. claude_automata-0/docs/autonomous-ai-system-definition.md +20 -0
  25. claude_automata-0/docs/claude-automata-requirements.md +108 -0
  26. claude_automata-0/docs/claude-code-automation-patterns.md +1023 -0
  27. claude_automata-0/docs/llm-persistent-agent-research.md +1063 -0
  28. claude_automata-0/docs/uv-and-claude-max-research.md +590 -0
  29. claude_automata-0/poc/README.md +53 -0
  30. claude_automata-0/poc/agent-hook-review/01-agent-hook-on-stop.md +152 -0
  31. claude_automata-0/poc/agent-hook-review/02-multiple-stop-hooks.md +221 -0
  32. claude_automata-0/poc/agent-hook-review/03-additional-context-delivery.md +208 -0
  33. claude_automata-0/poc/agent-hook-review/04-agent-hook-capabilities.md +189 -0
  34. claude_automata-0/poc/state_persistence/run_multi_session.py +338 -0
  35. claude_automata-0/poc/state_persistence/session_hook.sh +38 -0
  36. claude_automata-0/poc/state_persistence/settings.json +15 -0
  37. claude_automata-0/poc/state_persistence/state_manager.py +320 -0
  38. claude_automata-0/poc/stop_hook/check_continue.sh +112 -0
  39. claude_automata-0/poc/stop_hook/run.sh +105 -0
  40. claude_automata-0/poc/stop_hook/settings.json +15 -0
  41. claude_automata-0/poc/stop_hook/tasks.json +19 -0
  42. claude_automata-0/poc/supervisor_loop.py +566 -0
  43. claude_automata-0/pyproject.toml +20 -0
  44. claude_automata-0/src/.gitignore +10 -0
  45. claude_automata-0/src/.python-version +1 -0
  46. claude_automata-0/src/README.md +11 -0
  47. claude_automata-0/src/cli/__init__.py +0 -0
  48. claude_automata-0/src/cli/main.py +7 -0
  49. claude_automata-0/src/pyproject.toml +20 -0
  50. claude_automata-0/temp/claude-code-docs/1.md +238 -0
  51. claude_automata-0/temp/claude-code-docs/10.md +674 -0
  52. claude_automata-0/temp/claude-code-docs/11.md +144 -0
  53. claude_automata-0/temp/claude-code-docs/12.md +621 -0
  54. claude_automata-0/temp/claude-code-docs/13.md +234 -0
  55. claude_automata-0/temp/claude-code-docs/14.md +457 -0
  56. claude_automata-0/temp/claude-code-docs/15.md +193 -0
  57. claude_automata-0/temp/claude-code-docs/16.md +678 -0
  58. claude_automata-0/temp/claude-code-docs/17.md +239 -0
  59. claude_automata-0/temp/claude-code-docs/18.md +927 -0
  60. claude_automata-0/temp/claude-code-docs/19.md +404 -0
  61. claude_automata-0/temp/claude-code-docs/2.md +345 -0
  62. claude_automata-0/temp/claude-code-docs/20.md +1343 -0
  63. claude_automata-0/temp/claude-code-docs/21.md +432 -0
  64. claude_automata-0/temp/claude-code-docs/22.md +445 -0
  65. claude_automata-0/temp/claude-code-docs/23.md +693 -0
  66. claude_automata-0/temp/claude-code-docs/24.md +760 -0
  67. claude_automata-0/temp/claude-code-docs/25.md +290 -0
  68. claude_automata-0/temp/claude-code-docs/26.md +134 -0
  69. claude_automata-0/temp/claude-code-docs/27.md +174 -0
  70. claude_automata-0/temp/claude-code-docs/28.md +926 -0
  71. claude_automata-0/temp/claude-code-docs/29.md +114 -0
  72. claude_automata-0/temp/claude-code-docs/3.md +2453 -0
  73. claude_automata-0/temp/claude-code-docs/30.md +90 -0
  74. claude_automata-0/temp/claude-code-docs/31.md +124 -0
  75. claude_automata-0/temp/claude-code-docs/32.md +60 -0
  76. claude_automata-0/temp/claude-code-docs/33.md +319 -0
  77. claude_automata-0/temp/claude-code-docs/34.md +90 -0
  78. claude_automata-0/temp/claude-code-docs/35.md +2092 -0
  79. claude_automata-0/temp/claude-code-docs/36.md +778 -0
  80. claude_automata-0/temp/claude-code-docs/37.md +424 -0
  81. claude_automata-0/temp/claude-code-docs/4.md +261 -0
  82. claude_automata-0/temp/claude-code-docs/5.md +305 -0
  83. claude_automata-0/temp/claude-code-docs/6.md +375 -0
  84. claude_automata-0/temp/claude-code-docs/7.md +983 -0
  85. claude_automata-0/temp/claude-code-docs/8.md +590 -0
  86. claude_automata-0/temp/claude-code-docs/9.md +182 -0
@@ -0,0 +1,10 @@
1
+ # 개발 전용
2
+ .claude/settings.local.json
3
+
4
+ # Python
5
+ __pycache__/
6
+ .venv/
7
+
8
+ # OS
9
+ .DS_Store
10
+ CLAUDE.md
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 clomia
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1,9 @@
1
+ Metadata-Version: 2.4
2
+ Name: claude-automata
3
+ Version: 0
4
+ Summary: Autonomous AI System — 목적을 가지고 AI를 영속적으로 실행시키는 재귀적 자기개선 시스템
5
+ Project-URL: Repository, https://github.com/clomia/claude-automata
6
+ License-Expression: MIT
7
+ License-File: LICENSE
8
+ Requires-Python: >=3.10
9
+ Requires-Dist: copier>=9.0
@@ -0,0 +1,59 @@
1
+ # Autonomous AI System
2
+
3
+ **목적을 가지고 AI를 영속적으로 실행시키는 재귀적 자기개선 시스템**
4
+
5
+ ## 목적을 가지고
6
+
7
+ 목적이란 종료 조건이 없으며 나아가야 하는 방향을 뜻한다.
8
+ 시스템은 스스로 소유자로부터 목적을 구성한다.
9
+
10
+ ## AI를 영속적으로 실행시키는
11
+
12
+ 여기서 AI란 Foundation Model을 내포한 도구를 총칭한다.
13
+ 시스템은 컨텍스트 보존 메커니즘을 가지며 이를 통해 AI를 계속 실행시킨다.
14
+
15
+ ## 재귀적 자기개선 시스템
16
+
17
+ 시스템은 AI가 목적을 위해 시스템을 계속 개선하도록 유도한다.
18
+ 개선 동작 자체를 포함한 모든 구성 요소가 개선 대상이다.
19
+
20
+ # Claude Automata
21
+
22
+ claude-automata는 위 자율 AI 시스템의 구현체이다. Claude Code를 AI 엔진으로 사용하며, macOS에서 영속적으로 동작한다. 소유자는 Slack을 통해 시스템과 비동기로 소통한다.
23
+
24
+ ## 사용
25
+
26
+ **Prerequisites**: [uv](https://docs.astral.sh/uv/)
27
+
28
+ 시스템을 설치할 디렉토리 경로를 지정하여 실행한다. 이 디렉토리가 자율 시스템의 작업 공간이 된다.
29
+
30
+ ```bash
31
+ # 원하는 경로에 프로젝트 생성
32
+ uv run https://raw.githubusercontent.com/clomia/claude-automata/main/create.py ~/my-agent
33
+
34
+ # 생성된 디렉토리로 이동 후 설정 및 시작
35
+ cd ~/my-agent
36
+ uv sync
37
+ uv run automata configure
38
+ uv run automata start
39
+ ```
40
+
41
+ `automata configure`에서 Slack 토큰과 시스템의 목적을 입력하면 자율 운영이 시작된다.
42
+
43
+ ## 개발
44
+
45
+ 이 프로젝트는 Claude Code로 개발한다. `src/` 디렉토리가 제품 코드이며, copier가 사용자에게 `src/` 내용만 배포한다.
46
+
47
+ ### 개발 환경 격리
48
+
49
+ `src/` 안에는 제품용 Claude Code 설정(`.claude/settings.json`, `CLAUDE.md`)이 포함된다. 개발 세션이 이 설정에 오염되지 않도록 `.claude/settings.local.json`에 `claudeMdExcludes`가 설정되어 있다.
50
+
51
+ 주의사항:
52
+
53
+ - `src/CLAUDE.md`는 gitignore되어 있고, 제품의 Initialization Session이 런타임에 생성한다. 개발 중에는 존재하지 않는 것이 정상이다.
54
+ - `src/.claude/settings.json`은 프로젝트 루트가 아닌 하위 디렉토리이므로 개발 세션에 로드되지 않는다.
55
+ - `src/.claude/skills/`는 Claude Code가 하위 디렉토리에서도 on-demand 탐색하므로, `claudeMdExcludes`로 차단한다.
56
+
57
+ ### 설계 문서
58
+
59
+ 설계 문서는 `design/` 디렉토리에 있다. `design/root.md`가 루트 문서이다.
@@ -0,0 +1,16 @@
1
+ _subdirectory: src
2
+ _min_copier_version: "9.0.0"
3
+ _vcs_ref: HEAD
4
+
5
+ _exclude:
6
+ - "*.pyc"
7
+ - "__pycache__"
8
+ - ".DS_Store"
9
+ - "run/"
10
+ - "logs/"
11
+ - "state/archive/"
12
+
13
+ _tasks:
14
+ - "git init"
15
+ - "git add -A"
16
+ - "git commit -m 'claude-automata 초기 스캐폴드'"
@@ -0,0 +1,41 @@
1
+ # /// script
2
+ # dependencies = ["copier>=9.0"]
3
+ # requires-python = ">=3.10"
4
+ # ///
5
+ """
6
+ claude-automata 프로젝트 생성.
7
+
8
+ 사용법:
9
+ uv run create.py [디렉토리]
10
+ uv run https://raw.githubusercontent.com/clomia/claude-automata/main/create.py [디렉토리]
11
+ """
12
+ import sys
13
+ from pathlib import Path
14
+
15
+ def main():
16
+ dest = Path.cwd() / (sys.argv[1] if len(sys.argv) > 1 else "claude-automata")
17
+
18
+ if dest.exists():
19
+ print(f"오류: '{dest}' 디렉토리가 이미 존재합니다.")
20
+ sys.exit(1)
21
+
22
+ from copier import run_copy
23
+
24
+ run_copy(
25
+ src_path="https://github.com/clomia/claude-automata.git",
26
+ dst_path=str(dest),
27
+ defaults=True,
28
+ unsafe=True,
29
+ )
30
+
31
+ print()
32
+ print(f"'{dest.name}' 프로젝트가 생성되었습니다.")
33
+ print()
34
+ print("다음 단계:")
35
+ print(f" cd {dest.name}")
36
+ print(f" uv sync")
37
+ print(f" uv run automata configure")
38
+ print(f" uv run automata start")
39
+
40
+ if __name__ == "__main__":
41
+ main()
@@ -0,0 +1,384 @@
1
+ # 인지 부하 트리거 컴포넌트 설계
2
+
3
+ > **목적**: 모델에게 최대한의 유의미한 인지적 부하를 주어 추론 품질을 극대화한다 (Q-3).
4
+
5
+ ---
6
+
7
+ ## 1. 개요
8
+
9
+ 모델은 지시된 범위 내에서 최소한의 부하로 완료를 선언하는 경향이 있다. 인간 검수자는 작업을 대강 훑고 의심 패턴을 찾아 모델이 탐색하지 않은 확률 분포를 트리거한다. 이 컴포넌트는 그 기능을 시스템적으로 구현한다.
10
+
11
+ 두 계층의 인지 부하를 제공한다:
12
+
13
+ | 계층 | 메커니즘 | 원칙 준수 | 시점 |
14
+ |------|---------|----------|------|
15
+ | **자기 주도** | 미션 프롬프트의 다단계 프로토콜 | Q-4a, Q-4b, Q-4c, Q-4d | 세션 내 연속 |
16
+ | **외부 주입** | Stop hook agent가 패턴 분석 후 방향 제시 | Q-4a~Q-4e 전체 | 세션 종료 시도 시 |
17
+
18
+ 자기 주도 계층은 모든 세션에서 기본 수준의 인지 부하를 보장한다. 외부 주입 계층은 수행자의 맹점을 외부 관점에서 보완한다.
19
+
20
+ ---
21
+
22
+ ## 2. 자기 주도 계층: 미션 프롬프트 프로토콜
23
+
24
+ ### 2.1 구조
25
+
26
+ Supervisor가 미션 프롬프트를 생성할 때, 다단계 실행 프로토콜을 포함한다:
27
+
28
+ ```
29
+ ## 미션: {mission.id} {mission.title}
30
+
31
+ ### 목표
32
+ {mission.description}
33
+
34
+ ### 성공 기준
35
+ {mission.success_criteria — 항목별}
36
+
37
+ ### 실행 프로토콜
38
+
39
+ 이 미션을 다음 단계로 실행하라. 각 단계를 건너뛰지 마라.
40
+
41
+ **1단계 — 실행**: 성공 기준을 달성하라.
42
+
43
+ **2단계 — 검증**: 성공 기준 각 항목을 개별적으로 대조 확인하라.
44
+ 달성 여부가 불확실한 항목이 있으면 추가 작업하라.
45
+ {인지 부하 모듈이 생성한 미션 특화 검증 지시}
46
+
47
+ **3단계 — 미탐색 영역**: 이 접근법의 약점 3가지를 식별하고 대응하라.
48
+ {인지 부하 모듈이 생성한 미션 특화 확장 지시}
49
+
50
+ **4단계 — 요약**: state/session-summary.md에 다음을 기록하라:
51
+ - 가장 불확실했던 결정 3가지와 근거
52
+ - 검토했지만 채택하지 않은 대안
53
+ - 타협한 부분과 이유
54
+ ```
55
+
56
+ ### 2.2 미션 특화 지시 생성
57
+
58
+ 인지 부하 모듈(`system/cognitive_load.py`)이 2~3단계의 미션 특화 내용을 생성한다. Python 기반 결정론적 생성이다:
59
+
60
+ ```python
61
+ class CognitiveLoadTrigger:
62
+ """미션 프롬프트의 인지 부하 내용을 생성하고, 트리거 효과를 추적한다."""
63
+
64
+ def generate_mission_protocol(
65
+ self,
66
+ mission: dict,
67
+ health_metrics: dict,
68
+ friction_history: list[dict],
69
+ ) -> dict[str, list[str]]:
70
+ """미션 특화 검증/확장 지시를 생성한다."""
71
+ phase2 = []
72
+ phase3 = []
73
+
74
+ # 유사 미션의 friction 이력 기반
75
+ related = [f for f in friction_history
76
+ if self._is_related(f, mission)]
77
+ if related:
78
+ types = set(f["type"] for f in related)
79
+ phase2.append(
80
+ f"유사 미션에서 {', '.join(types)} friction이 발생한 이력이 있다. "
81
+ f"이 영역을 특히 주의하여 검증하라."
82
+ )
83
+
84
+ # 건강 메트릭 기반
85
+ if health_metrics.get("friction_trend") == "increasing":
86
+ phase3.append(
87
+ "시스템 friction이 증가 추세이다. "
88
+ "이 미션의 결과가 friction을 줄이는 방향인지 확인하라."
89
+ )
90
+
91
+ stalled = health_metrics.get("stalled_mission_id")
92
+ if stalled == mission.get("id"):
93
+ phase2.append(
94
+ "이 미션이 이전 세션에서 정체되었다. "
95
+ "이전과 다른 접근법을 시도하라."
96
+ )
97
+
98
+ return {"phase2": phase2, "phase3": phase3}
99
+ ```
100
+
101
+ ### 2.3 원칙 준수
102
+
103
+ 자기 주도 계층은 Q-4e(컨텍스트 분리)를 충족하지 않는다 — 수행자 자신이 지시를 수행하므로 같은 컨텍스트이다. Q-4a(작업 기반 — friction 이력), Q-4b(미탐색 — 약점 식별 지시), Q-4c(비처방 — 방향 제시), Q-4d(컨텍스트 내)는 충족한다. Q-4e는 외부 주입 계층이 담당한다.
104
+
105
+ ---
106
+
107
+ ## 3. 외부 주입 계층: Stop Hook Agent
108
+
109
+ ### 3.1 작동 원리
110
+
111
+ 수행자가 세션 종료를 시도하면 Stop hook이 발동한다. `type: "agent"` 훅이 **별도 컨텍스트**에서 실행되어 수행자의 작업 패턴을 분석하고 방향을 제시한다.
112
+
113
+ ```
114
+ 수행자: 작업 완료, 종료 시도
115
+
116
+
117
+ Stop hook agent (별도 컨텍스트, opus):
118
+ │ 읽는 것:
119
+ │ 1. run/session-analysis.json ← 작업 패턴 (객관적 사실)
120
+ │ 2. 변경된 파일들 ← 실제 결과물
121
+ │ 3. 미션 success_criteria
122
+ │ 4. state/trigger-effectiveness.jsonl ← 이전 트리거의 효과 기록
123
+
124
+ │ 읽지 않는 것:
125
+ │ - 수행자의 추론, 해석, 계획, 설명
126
+
127
+ │ 분석 → 방향 생성
128
+
129
+
130
+ ok: false, reason: "탐색하라: ..."
131
+
132
+
133
+ 수행자: 같은 컨텍스트에서 방향을 받고 추가 작업
134
+ │ (1~4단계의 전체 작업 기억 보존)
135
+
136
+
137
+ 수행자: 추가 완료 → stop_hook_active: true → 세션 종료
138
+ ```
139
+
140
+ ### 3.2 session-analysis.json (작업 패턴 기록)
141
+
142
+ Supervisor의 StreamAnalyzer가 stream-json에서 실시간 추출하는 객관적 기록이다.
143
+
144
+ ```python
145
+ class StreamAnalyzer:
146
+ """stream-json 이벤트를 실시간 분석하여 작업 패턴을 기록한다."""
147
+
148
+ def __init__(self):
149
+ self.tool_calls: list[dict] = []
150
+ self.errors: list[dict] = []
151
+ self.files_read: set[str] = set()
152
+ self.files_written: set[str] = set()
153
+ self.bash_commands: list[dict] = []
154
+ self.start_time: float = time.time()
155
+
156
+ def process_event(self, event: dict) -> None:
157
+ """각 stream-json 이벤트를 처리한다."""
158
+ if event.get("type") == "tool_use":
159
+ tool = event.get("tool", "")
160
+ target = event.get("target", "")
161
+ self.tool_calls.append({
162
+ "tool": tool,
163
+ "target": target,
164
+ "timestamp": time.time() - self.start_time,
165
+ })
166
+ if tool == "Read":
167
+ self.files_read.add(target)
168
+ elif tool in ("Edit", "Write"):
169
+ self.files_written.add(target)
170
+ elif tool == "Bash":
171
+ self.bash_commands.append({
172
+ "command": event.get("command", "")
173
+ })
174
+
175
+ elif event.get("type") == "tool_result" and event.get("is_error"):
176
+ self.errors.append({
177
+ "tool": self.tool_calls[-1]["tool"] if self.tool_calls else "unknown",
178
+ "error": str(event.get("text", ""))[:300],
179
+ "timestamp": time.time() - self.start_time,
180
+ })
181
+
182
+ def write_analysis(self, path: Path) -> None:
183
+ """작업 패턴을 파일에 기록한다."""
184
+ analysis = {
185
+ "tool_call_count": len(self.tool_calls),
186
+ "tool_distribution": dict(Counter(
187
+ tc["tool"] for tc in self.tool_calls
188
+ )),
189
+ "files_read": sorted(self.files_read),
190
+ "files_written": sorted(self.files_written),
191
+ "files_read_not_written": sorted(
192
+ self.files_read - self.files_written
193
+ ),
194
+ "errors": self.errors,
195
+ "error_count": len(self.errors),
196
+ "tests_executed": any(
197
+ "pytest" in cmd.get("command", "")
198
+ or "test" in cmd.get("command", "")
199
+ for cmd in self.bash_commands
200
+ ),
201
+ "bash_commands": [
202
+ cmd["command"][:100] for cmd in self.bash_commands
203
+ ],
204
+ "duration_minutes": round(
205
+ (time.time() - self.start_time) / 60, 1
206
+ ),
207
+ "topic_areas": self._extract_topic_areas(),
208
+ }
209
+ atomic_write(path, json.dumps(
210
+ analysis, ensure_ascii=False, indent=2
211
+ ))
212
+
213
+ def _extract_topic_areas(self) -> dict[str, int]:
214
+ """파일 경로에서 작업 영역을 추출한다."""
215
+ areas: dict[str, int] = {}
216
+ for f in self.files_read | self.files_written:
217
+ parts = Path(f).parts
218
+ if len(parts) >= 2:
219
+ area = str(Path(*parts[:2]))
220
+ areas[area] = areas.get(area, 0) + 1
221
+ return areas
222
+ ```
223
+
224
+ **포함**: tool call 목록, 파일 접근 기록, 에러, bash 명령, 시간 분포, 작업 영역.
225
+ **제외**: assistant 텍스트, 도구 결과 내용, 수행자의 추론/해석.
226
+
227
+ ### 3.3 Stop Hook Agent Prompt
228
+
229
+ `.claude/settings.json`에 등록한다. prompt는 5개 독립 설계에서 도출된 분석 기법을 통합한다:
230
+
231
+ ```json
232
+ {
233
+ "Stop": [
234
+ {
235
+ "hooks": [
236
+ {
237
+ "type": "agent",
238
+ "model": "opus",
239
+ "timeout": 120,
240
+ "tools": ["Read", "Glob", "Grep", "Bash"],
241
+ "prompt": "당신은 인지 부하 트리거 생성자이다.\n\n메인 에이전트가 미션을 수행하고 완료를 선언했다. 당신의 역할은 메인 에이전트가 탐색하지 않았을 가능성이 높은 방향을 식별하는 것이다.\n\n## 입력\n\n다음 파일들을 읽어라:\n1. run/session-analysis.json — 수행된 작업의 객관적 패턴 기록\n2. state/missions.json에서 status가 in_progress인 미션의 success_criteria\n3. session-analysis.json의 files_written에 나열된 파일들\n4. state/trigger-effectiveness.jsonl (존재하면)\n\n## 분석 방법\n\n다음 렌즈로 작업 패턴을 분석하라:\n\n**부재 분석**: success_criteria에 있지만 작업 기록에 반영되지 않은 것은 무엇인가? 접근되지 않은 파일, 실행되지 않은 명령, 탐색되지 않은 영역은?\n\n**접근법 다양성**: 수행자가 하나의 도구 유형이나 하나의 작업 패턴만 사용했는가? 읽기만 하고 테스트하지 않았는가? 작성만 하고 검증하지 않았는가?\n\n**에러 무시 패턴**: 에러가 발생한 후 수행자가 조사하지 않고 넘어간 것이 있는가?\n\n**깊이 비대칭**: 어떤 영역은 깊이 탐색하고 다른 영역은 피상적으로만 다룬 것이 있는가?\n\n**수렴 패턴**: 작업이 점점 좁은 범위로 수렴했는가? 초기 탐색에서 발견했지만 후속 작업에 반영하지 않은 것은?\n\n## 이전 트리거 효과\n\ntrigger-effectiveness.jsonl이 존재하면 읽어라. 효과가 높았던 분석 유형을 우선시하라. 효과가 낮았던 유형은 다른 접근을 시도하라.\n\n## 출력 규칙\n\n- 결론을 내리거나 해법을 처방하지 마라. 탐색 방향만 제시하라.\n- 각 방향은 session-analysis.json의 구체적 패턴을 근거로 들어라.\n- 수행자가 이미 충분히 다룬 영역은 반복하지 마라.\n- 최대 3개 방향을 제시하라.\n- $ARGUMENTS의 last_assistant_message는 수행자의 해석이다. 무시하고 객관적 패턴만 참조하라."
242
+ }
243
+ ]
244
+ }
245
+ ]
246
+ }
247
+ ```
248
+
249
+ ### 3.4 원칙 준수
250
+
251
+ | 원칙 | 충족 방식 |
252
+ |------|----------|
253
+ | Q-4a 작업 기반 | session-analysis.json(작업 패턴)과 실제 파일을 읽음 |
254
+ | Q-4b 미탐색 지향 | 분석 방법이 "부재", "미탐색", "미접근"을 명시적으로 탐색. effectiveness 이력으로 반복 방지 |
255
+ | Q-4c 비처방 | "결론을 내리지 마라. 방향만 제시하라" 명시 |
256
+ | Q-4d 컨텍스트 내 전달 | Stop hook reason이 메인 세션에 주입. 수행자의 전체 작업 기억 보존 |
257
+ | Q-4e 컨텍스트 분리 | 별도 컨텍스트에서 실행. session-analysis.json은 사실만 포함. assistant 텍스트 제외 |
258
+
259
+ ---
260
+
261
+ ## 4. 효과 추적 (자기개선의 씨앗)
262
+
263
+ ### 4.1 목적
264
+
265
+ 트리거가 수행자의 행동을 실제로 변화시켰는지 측정한다. 이 데이터가 없으면 트리거 시스템은 영원히 정적이다. 이 데이터가 있으면 자기개선이 "어떤 유형의 트리거가 효과적인가?"를 판단할 수 있다.
266
+
267
+ ### 4.2 측정
268
+
269
+ ```
270
+ 트리거 전: session-analysis.json 스냅샷 저장 (pre_snapshot)
271
+ 트리거 주입: Stop hook reason 전달
272
+ 수행자: 추가 작업
273
+ 세션 종료: session-analysis.json 최종 상태 (post_snapshot)
274
+
275
+ 효과 = post_snapshot - pre_snapshot
276
+ ```
277
+
278
+ ```python
279
+ def compute_effectiveness(pre: dict, post: dict) -> str:
280
+ new_files = len(
281
+ set(post["files_read"] + post["files_written"])
282
+ - set(pre["files_read"] + pre["files_written"])
283
+ )
284
+ new_areas = len(
285
+ set(post.get("topic_areas", {}))
286
+ - set(pre.get("topic_areas", {}))
287
+ )
288
+ calls_after = post["tool_call_count"] - pre["tool_call_count"]
289
+
290
+ if new_files >= 3 or new_areas >= 1:
291
+ return "high"
292
+ elif new_files >= 1 or calls_after >= 5:
293
+ return "medium"
294
+ else:
295
+ return "low"
296
+ ```
297
+
298
+ ### 4.3 기록
299
+
300
+ `state/trigger-effectiveness.jsonl` (append-only, Git 추적):
301
+
302
+ ```jsonl
303
+ {"mission_id":"M-042","trigger_directions":["에러 처리 경로 탐색","테스트 커버리지 확인"],"effectiveness":"high","new_files":5,"new_areas":2,"timestamp":"2026-03-27T10:00:00Z"}
304
+ ```
305
+
306
+ Stop hook agent의 prompt가 이 파일을 읽도록 지시되어 있다. 미션이 축적될수록 agent hook이 효과적인 분석 유형을 우선시하게 된다.
307
+
308
+ ---
309
+
310
+ ## 5. 컨텍스트 흐름
311
+
312
+ ```
313
+ 세션 시작 (미션 프롬프트 + 4단계 프로토콜)
314
+
315
+ ├── 1단계: 실행 (turns 1~N)
316
+ │ Supervisor: stream-json → session-analysis.json 실시간 갱신
317
+
318
+ ├── 2단계: 검증 (1단계 컨텍스트 위에서)
319
+
320
+ ├── 3단계: 미탐색 영역 (1+2단계 컨텍스트 위에서)
321
+
322
+ ├── 4단계: 요약 (1+2+3단계 컨텍스트 위에서)
323
+
324
+
325
+ 수행자 "완료" → Stop hook 발동
326
+ │ Supervisor: pre_trigger 스냅샷 저장
327
+
328
+
329
+ Stop hook agent (opus, 120s, 별도 컨텍스트)
330
+ │ 분석 → 방향 생성
331
+
332
+ ok: false, reason: [방향들]
333
+
334
+
335
+ 수행자: 추가 작업 (전체 컨텍스트 보존)
336
+
337
+
338
+ stop_hook_active: true → 세션 종료
339
+ │ Supervisor: post_trigger 스냅샷
340
+ │ 효과 측정 → trigger-effectiveness.jsonl에 기록
341
+
342
+ Supervisor: 다음 세션
343
+ ```
344
+
345
+ ---
346
+
347
+ ## 6. 구성 요소
348
+
349
+ | 구성 요소 | 위치 | 역할 |
350
+ |----------|------|------|
351
+ | CognitiveLoadTrigger | `system/cognitive_load.py` | 미션 특화 지시 생성 + 효과 추적 |
352
+ | StreamAnalyzer | `system/cognitive_load.py` | stream-json → session-analysis.json |
353
+ | Stop hook agent | `.claude/settings.json` | 외부 컨텍스트에서 패턴 분석 → 방향 생성 |
354
+ | session-analysis.json | `run/` | 작업 패턴의 객관적 기록 |
355
+ | trigger-effectiveness.jsonl | `state/` | 트리거 효과 이력 |
356
+
357
+ ---
358
+
359
+ ## 7. 자기개선 경로
360
+
361
+ 이 컴포넌트의 모든 부분은 자기개선 대상이다 (S-4):
362
+
363
+ | 대상 | 방법 |
364
+ |------|------|
365
+ | Stop hook agent prompt | `.claude/settings.json` 수정. 분석 방법 추가/변경 |
366
+ | 미션 프로토콜 | `system/cognitive_load.py`의 generate_mission_protocol() 수정 |
367
+ | StreamAnalyzer | 새 패턴 추출 로직 추가 |
368
+ | 효과 측정 로직 | 새 효과 지표 추가 |
369
+ | 4단계 프로토콜 구조 | 단계 추가/변경 |
370
+
371
+ trigger-effectiveness.jsonl이 자기개선의 데이터 기반이다. AI가 이 데이터를 분석하여 "absence 분석의 효과가 높고 convergence 분석은 낮다"를 발견하면, Stop hook prompt를 수정하여 absence 분석을 강화한다.
372
+
373
+ ---
374
+
375
+ ## 8. Q-3/Q-4 준수 검증
376
+
377
+ | 요구사항 | 충족 |
378
+ |----------|------|
379
+ | Q-3 최대 인지 부하 | 자기 주도(4단계) + 외부 주입(Stop hook agent) = 5회 이상 인지 전환, 같은 컨텍스트에서 축적 |
380
+ | Q-4a 작업 기반 | session-analysis.json + 실제 파일 읽기 |
381
+ | Q-4b 미탐색 지향 | 부재/다양성/에러무시/비대칭/수렴 분석. effectiveness 이력으로 반복 방지 |
382
+ | Q-4c 비처방 | prompt에 "방향만 제시" 명시 |
383
+ | Q-4d 컨텍스트 내 전달 | Stop hook reason이 동일 세션에 주입 |
384
+ | Q-4e 컨텍스트 분리 | 별도 컨텍스트. 사실만 입력. 해석 제외 |