@wooojin/forgen 0.6.7 → 0.6.9

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 (223) hide show
  1. package/.claude-plugin/plugin.json +1 -1
  2. package/CHANGELOG.md +23 -0
  3. package/README.ja.md +15 -10
  4. package/README.ko.md +15 -10
  5. package/README.md +19 -14
  6. package/README.zh.md +13 -8
  7. package/dist/checks/dangerous-response-pattern.d.ts +2 -1
  8. package/dist/checks/dangerous-response-pattern.js +27 -3
  9. package/dist/cli.js +133 -17
  10. package/dist/core/auto-compound-runner.js +502 -397
  11. package/dist/core/block-cli.js +7 -3
  12. package/dist/core/compound-consent.d.ts +18 -0
  13. package/dist/core/compound-consent.js +101 -6
  14. package/dist/core/compound-sweep-cli.d.ts +16 -0
  15. package/dist/core/compound-sweep-cli.js +67 -5
  16. package/dist/core/config-hooks.js +28 -10
  17. package/dist/core/correction-signals.d.ts +9 -0
  18. package/dist/core/correction-signals.js +37 -0
  19. package/dist/core/dev-cli.d.ts +1 -2
  20. package/dist/core/dev-cli.js +9 -28
  21. package/dist/core/doctor-verify.d.ts +35 -0
  22. package/dist/core/doctor-verify.js +502 -0
  23. package/dist/core/doctor.d.ts +4 -6
  24. package/dist/core/doctor.js +103 -184
  25. package/dist/core/explain-cli.js +8 -0
  26. package/dist/core/extraction-haiku.d.ts +64 -0
  27. package/dist/core/extraction-haiku.js +208 -0
  28. package/dist/core/extraction-queue.d.ts +68 -0
  29. package/dist/core/extraction-queue.js +300 -0
  30. package/dist/core/flow-status.d.ts +93 -0
  31. package/dist/core/flow-status.js +368 -0
  32. package/dist/core/harness.js +14 -42
  33. package/dist/core/inspect-cli.js +37 -13
  34. package/dist/core/lifecycle-classifier.d.ts +5 -1
  35. package/dist/core/lifecycle-classifier.js +13 -2
  36. package/dist/core/migrate-cli.d.ts +1 -1
  37. package/dist/core/migrate-cli.js +11 -11
  38. package/dist/core/migrate-tenetx.d.ts +1 -1
  39. package/dist/core/migrate-tenetx.js +2 -2
  40. package/dist/core/node-engine.d.ts +3 -0
  41. package/dist/core/node-engine.js +8 -0
  42. package/dist/core/observability-store.d.ts +15 -0
  43. package/dist/core/observability-store.js +73 -0
  44. package/dist/core/paths.d.ts +2 -0
  45. package/dist/core/paths.js +2 -0
  46. package/dist/core/rendered-rules-manifest.d.ts +7 -1
  47. package/dist/core/rendered-rules-manifest.js +45 -1
  48. package/dist/core/session-store.d.ts +13 -11
  49. package/dist/core/session-store.js +103 -119
  50. package/dist/core/settings-injector.d.ts +5 -2
  51. package/dist/core/settings-injector.js +21 -88
  52. package/dist/core/spawn.d.ts +9 -1
  53. package/dist/core/spawn.js +33 -33
  54. package/dist/core/stats-cli.d.ts +7 -0
  55. package/dist/core/stats-cli.js +66 -93
  56. package/dist/core/status-cli.d.ts +1 -1
  57. package/dist/core/status-cli.js +23 -4
  58. package/dist/core/statusline-cli.js +5 -0
  59. package/dist/core/statusline-install.d.ts +10 -2
  60. package/dist/core/statusline-install.js +27 -4
  61. package/dist/core/transcript-summary.d.ts +84 -9
  62. package/dist/core/transcript-summary.js +283 -49
  63. package/dist/core/uninstall.d.ts +4 -0
  64. package/dist/core/uninstall.js +68 -36
  65. package/dist/core/v1-bootstrap.d.ts +1 -1
  66. package/dist/core/v1-bootstrap.js +38 -9
  67. package/dist/engine/acted-on-evidence.d.ts +8 -0
  68. package/dist/engine/acted-on-evidence.js +38 -0
  69. package/dist/engine/block-judge.d.ts +3 -1
  70. package/dist/engine/block-judge.js +4 -3
  71. package/dist/engine/compound-cli.d.ts +26 -2
  72. package/dist/engine/compound-cli.js +143 -19
  73. package/dist/engine/compound-lifecycle.d.ts +36 -2
  74. package/dist/engine/compound-lifecycle.js +131 -11
  75. package/dist/engine/compound-loop.d.ts +4 -0
  76. package/dist/engine/compound-loop.js +93 -18
  77. package/dist/engine/correction-cluster-runner.d.ts +11 -1
  78. package/dist/engine/correction-cluster-runner.js +39 -15
  79. package/dist/engine/correction-clustering.d.ts +11 -0
  80. package/dist/engine/correction-clustering.js +20 -3
  81. package/dist/engine/lifecycle/lifecycle-cli.js +10 -3
  82. package/dist/engine/lifecycle/meta-reclassifier.d.ts +9 -0
  83. package/dist/engine/lifecycle/meta-reclassifier.js +15 -3
  84. package/dist/engine/lifecycle/orchestrator.js +3 -2
  85. package/dist/engine/lifecycle/signals.d.ts +19 -1
  86. package/dist/engine/lifecycle/signals.js +61 -2
  87. package/dist/engine/lifecycle/trigger-t1-correction.d.ts +1 -1
  88. package/dist/engine/lifecycle/trigger-t1-correction.js +9 -28
  89. package/dist/engine/lifecycle/trigger-t5-conflict.d.ts +8 -0
  90. package/dist/engine/lifecycle/trigger-t5-conflict.js +60 -2
  91. package/dist/engine/roi-demotion.d.ts +11 -0
  92. package/dist/engine/roi-demotion.js +50 -8
  93. package/dist/engine/rule-detectability.d.ts +39 -0
  94. package/dist/engine/rule-detectability.js +66 -0
  95. package/dist/engine/rule-project-cli.d.ts +25 -0
  96. package/dist/engine/rule-project-cli.js +148 -0
  97. package/dist/engine/rule-recovery-cli.d.ts +21 -0
  98. package/dist/engine/rule-recovery-cli.js +265 -0
  99. package/dist/engine/rule-toggle-cli.d.ts +14 -2
  100. package/dist/engine/rule-toggle-cli.js +94 -6
  101. package/dist/engine/skill-promoter.d.ts +14 -8
  102. package/dist/engine/skill-promoter.js +57 -85
  103. package/dist/engine/solution-format.d.ts +26 -1
  104. package/dist/engine/solution-format.js +65 -3
  105. package/dist/engine/solution-habit.d.ts +1 -0
  106. package/dist/engine/solution-habit.js +22 -0
  107. package/dist/engine/solution-index.d.ts +5 -0
  108. package/dist/engine/solution-index.js +32 -0
  109. package/dist/engine/solution-matcher-eval.js +4 -4
  110. package/dist/engine/solution-matcher.js +15 -13
  111. package/dist/engine/solution-scope.d.ts +11 -0
  112. package/dist/engine/solution-scope.js +19 -0
  113. package/dist/engine/solution-writer.d.ts +3 -1
  114. package/dist/engine/solution-writer.js +3 -2
  115. package/dist/engine/term-normalizer.js +49 -0
  116. package/dist/fgx.js +1 -1
  117. package/dist/forge/cli.js +51 -8
  118. package/dist/forge/evidence-processor.js +6 -0
  119. package/dist/hooks/context-guard.d.ts +0 -22
  120. package/dist/hooks/context-guard.js +22 -55
  121. package/dist/hooks/context-usage.d.ts +21 -0
  122. package/dist/hooks/context-usage.js +103 -0
  123. package/dist/hooks/dangerous-patterns.json +1 -16
  124. package/dist/hooks/db-guard.d.ts +1 -1
  125. package/dist/hooks/db-guard.js +21 -30
  126. package/dist/hooks/hook-config.d.ts +2 -0
  127. package/dist/hooks/hook-config.js +5 -1
  128. package/dist/hooks/hooks-generator.d.ts +4 -0
  129. package/dist/hooks/hooks-generator.js +10 -4
  130. package/dist/hooks/permission-handler.js +23 -3
  131. package/dist/hooks/post-tool-use.js +14 -10
  132. package/dist/hooks/pre-tool-use.d.ts +17 -3
  133. package/dist/hooks/pre-tool-use.js +143 -30
  134. package/dist/hooks/rate-limiter.js +12 -7
  135. package/dist/hooks/secret-filter.js +15 -4
  136. package/dist/hooks/session-end.d.ts +2 -2
  137. package/dist/hooks/session-end.js +13 -7
  138. package/dist/hooks/session-recovery.js +79 -50
  139. package/dist/hooks/shared/command-analyzer.d.ts +45 -0
  140. package/dist/hooks/shared/command-analyzer.js +972 -0
  141. package/dist/hooks/shared/command-parser.d.ts +5 -29
  142. package/dist/hooks/shared/command-parser.js +65 -35
  143. package/dist/hooks/shared/commit-guard.d.ts +15 -0
  144. package/dist/hooks/shared/commit-guard.js +176 -0
  145. package/dist/hooks/shared/hook-response.d.ts +6 -0
  146. package/dist/hooks/shared/hook-response.js +12 -0
  147. package/dist/hooks/shared/hook-timing.js +9 -3
  148. package/dist/hooks/shared/injection-caps.d.ts +32 -2
  149. package/dist/hooks/shared/injection-caps.js +73 -2
  150. package/dist/hooks/shared/is-main.d.ts +8 -0
  151. package/dist/hooks/shared/is-main.js +20 -0
  152. package/dist/hooks/shared/stop-triggers.d.ts +1 -1
  153. package/dist/hooks/shared/stop-triggers.js +2 -1
  154. package/dist/hooks/shared/tool-response.d.ts +6 -0
  155. package/dist/hooks/shared/tool-response.js +30 -0
  156. package/dist/hooks/slop-detector.js +6 -3
  157. package/dist/hooks/solution-injector.d.ts +23 -0
  158. package/dist/hooks/solution-injector.js +102 -101
  159. package/dist/hooks/stop-guard.d.ts +11 -1
  160. package/dist/hooks/stop-guard.js +28 -11
  161. package/dist/hooks/subagent-stop-guard.js +2 -1
  162. package/dist/hooks/subagent-tracker.js +2 -1
  163. package/dist/host/capabilities-codex.js +1 -0
  164. package/dist/host/claude-shim.d.ts +24 -0
  165. package/dist/host/claude-shim.js +68 -0
  166. package/dist/host/codex-hook-shim.d.ts +3 -1
  167. package/dist/host/codex-hook-shim.js +7 -5
  168. package/dist/host/codex-notify.js +1 -1
  169. package/dist/host/codex-rules-context.d.ts +6 -4
  170. package/dist/host/codex-rules-context.js +11 -24
  171. package/dist/host/exec-host.d.ts +5 -1
  172. package/dist/host/exec-host.js +15 -4
  173. package/dist/host/install-claude.d.ts +47 -14
  174. package/dist/host/install-claude.js +302 -155
  175. package/dist/host/install-codex.d.ts +20 -0
  176. package/dist/host/install-codex.js +32 -1
  177. package/dist/host/install-opencode.d.ts +3 -1
  178. package/dist/host/install-opencode.js +6 -3
  179. package/dist/host/install-orchestrator.js +14 -1
  180. package/dist/host/opencode/translate.d.ts +1 -1
  181. package/dist/host/opencode/translate.js +5 -3
  182. package/dist/host/projection.d.ts +9 -1
  183. package/dist/host/projection.js +19 -2
  184. package/dist/mcp/server.js +5 -0
  185. package/dist/mcp/solution-reader.d.ts +5 -5
  186. package/dist/mcp/solution-reader.js +13 -35
  187. package/dist/mcp/tools.js +18 -1
  188. package/dist/renderer/inspect-renderer.js +4 -2
  189. package/dist/renderer/render-report.d.ts +22 -0
  190. package/dist/renderer/render-report.js +29 -0
  191. package/dist/renderer/rule-renderer.d.ts +28 -2
  192. package/dist/renderer/rule-renderer.js +91 -76
  193. package/dist/store/evidence-store.js +34 -6
  194. package/dist/store/rule-lifecycle.d.ts +3 -1
  195. package/dist/store/rule-lifecycle.js +10 -0
  196. package/dist/store/rule-scope.d.ts +7 -0
  197. package/dist/store/rule-scope.js +54 -0
  198. package/dist/store/rule-store.d.ts +29 -3
  199. package/dist/store/rule-store.js +110 -26
  200. package/dist/store/types.d.ts +22 -2
  201. package/dist/way/cli.d.ts +1 -0
  202. package/dist/way/cli.js +313 -0
  203. package/dist/way/compile.d.ts +22 -0
  204. package/dist/way/compile.js +408 -0
  205. package/dist/way/conflict.d.ts +2 -0
  206. package/dist/way/conflict.js +18 -0
  207. package/dist/way/draft.d.ts +43 -0
  208. package/dist/way/draft.js +335 -0
  209. package/dist/way/extract.d.ts +17 -0
  210. package/dist/way/extract.js +172 -0
  211. package/dist/way/io.d.ts +79 -0
  212. package/dist/way/io.js +425 -0
  213. package/dist/way/similar.d.ts +2 -0
  214. package/dist/way/similar.js +30 -0
  215. package/dist/way/types.d.ts +98 -0
  216. package/dist/way/types.js +2 -0
  217. package/package.json +1 -1
  218. package/plugin.json +1 -1
  219. package/scripts/postinstall.js +78 -900
  220. package/dist/core/health-cli.d.ts +0 -25
  221. package/dist/core/health-cli.js +0 -90
  222. package/dist/host/parity-harness.d.ts +0 -70
  223. package/dist/host/parity-harness.js +0 -287
@@ -0,0 +1,502 @@
1
+ /**
2
+ * doctor 의 "실제 실행" 검증 (D8).
3
+ *
4
+ * 파일이 있다/설정에 적혀 있다가 아니라, Claude Code 가 하는 그대로 settings.json 의 명령을 실행해
5
+ * shim → node → 대상 체인이 살아 있는지 본다.
6
+ * - hook: 빈 입력으로 실행 → rc 0 + stdout 이 유효 JSON 1개 (shim 의 "대상 없음" 경고 JSON 도 실패로 본다)
7
+ * - MCP: initialize 왕복
8
+ * - statusLine: 빈 JSON 입력으로 실행 → rc 0 + 출력 있음
9
+ * 프로브는 임시 FORGEN_HOME 에서 돌려 실제 상태 디렉터리에 기록을 남기지 않는다.
10
+ */
11
+ import * as fs from 'node:fs';
12
+ import * as os from 'node:os';
13
+ import * as path from 'node:path';
14
+ import { spawn } from 'node:child_process';
15
+ import { createRequire } from 'node:module';
16
+ import { generateHooksJson } from '../hooks/hooks-generator.js';
17
+ import { forgenRunShimPath, isForgenRunCommand, shimSupported } from '../host/claude-shim.js';
18
+ import { isForgenHookCommand } from '../host/install-claude.js';
19
+ import { isForgenStatusline } from './statusline-install.js';
20
+ import { scanRuleFiles } from '../store/rule-store.js';
21
+ function readJson(p) {
22
+ try {
23
+ const v = JSON.parse(fs.readFileSync(p, 'utf-8'));
24
+ if (!v || typeof v !== 'object' || Array.isArray(v))
25
+ return { error: 'JSON 객체가 아님' };
26
+ return { value: v };
27
+ }
28
+ catch (e) {
29
+ return { error: e instanceof Error ? e.message.split('\n')[0] : String(e) };
30
+ }
31
+ }
32
+ /** 프로세스 그룹 전체를 죽인다 (손자가 파이프를 쥐고 있어도 정리). */
33
+ function killTree(child) {
34
+ const pid = child.pid;
35
+ if (!pid)
36
+ return;
37
+ try {
38
+ if (process.platform === 'win32')
39
+ spawn('taskkill', ['/pid', String(pid), '/T', '/F'], { stdio: 'ignore' }).on('error', () => { });
40
+ else
41
+ process.kill(-pid, 'SIGKILL');
42
+ }
43
+ catch {
44
+ try {
45
+ child.kill('SIGKILL');
46
+ }
47
+ catch { /* 이미 종료 */ }
48
+ }
49
+ }
50
+ /** exit 뒤 파이프 flush 를 기다리는 유예. 손자가 파이프를 쥐고 있으면 close 가 영영 안 오므로 이 시간 뒤 확정한다. */
51
+ const EXIT_GRACE_MS = 250;
52
+ function spawnGroup(command, env, cwd) {
53
+ return spawn(command, { shell: true, env, cwd, stdio: ['pipe', 'pipe', 'pipe'], detached: process.platform !== 'win32' });
54
+ }
55
+ function runCommand(command, input, env, cwd, timeoutMs) {
56
+ return new Promise((resolve) => {
57
+ let stdout = '';
58
+ let stderr = '';
59
+ let timedOut = false;
60
+ let settled = false;
61
+ let rcSeen = null;
62
+ const child = spawnGroup(command, env, cwd);
63
+ const done = (r) => {
64
+ if (settled)
65
+ return;
66
+ settled = true;
67
+ clearTimeout(timer);
68
+ killTree(child); // 남은 손자 정리
69
+ child.stdout?.destroy();
70
+ child.stderr?.destroy();
71
+ resolve(r);
72
+ };
73
+ const timer = setTimeout(() => { timedOut = true; done({ rc: rcSeen, stdout, stderr, timedOut }); }, timeoutMs);
74
+ child.stdout?.on('data', (d) => { stdout += String(d); });
75
+ child.stderr?.on('data', (d) => { stderr += String(d); });
76
+ child.on('error', (e) => done({ rc: null, stdout, stderr, timedOut, spawnError: e.message }));
77
+ child.on('exit', (rc) => { rcSeen = rc; setTimeout(() => done({ rc, stdout, stderr, timedOut }), EXIT_GRACE_MS); });
78
+ child.on('close', (rc) => done({ rc, stdout, stderr, timedOut }));
79
+ child.stdin?.on('error', () => { });
80
+ child.stdin?.end(input);
81
+ });
82
+ }
83
+ async function mapLimit(items, limit, fn) {
84
+ const out = new Array(items.length);
85
+ let next = 0;
86
+ await Promise.all(Array.from({ length: Math.min(limit, items.length) }, async () => {
87
+ while (next < items.length) {
88
+ const i = next++;
89
+ out[i] = await fn(items[i]);
90
+ }
91
+ }));
92
+ return out;
93
+ }
94
+ /** settings.json 에서 이벤트별 forgen 소유 hook 명령을 모은다. */
95
+ function collectForgenHooks(settings, pkgRoot) {
96
+ const out = [];
97
+ const hooks = settings.hooks;
98
+ if (!hooks || typeof hooks !== 'object')
99
+ return out;
100
+ for (const [event, groups] of Object.entries(hooks)) {
101
+ if (!Array.isArray(groups))
102
+ continue;
103
+ for (const g of groups) {
104
+ const group = g;
105
+ const cmds = typeof group.command === 'string' ? [group.command] : (group.hooks ?? []).map((h) => h?.command);
106
+ for (const c of cmds)
107
+ if (typeof c === 'string' && isForgenHookCommand(c, pkgRoot))
108
+ out.push({ event, command: c });
109
+ }
110
+ }
111
+ return out;
112
+ }
113
+ /** `forgen config hooks` 용: 실제 settings.json 에 등록된 forgen hook 과 disableAllHooks 상태. */
114
+ export function readSettingsHooks(homeDir, pkgRoot) {
115
+ const r = readJson(path.join(homeDir, '.claude', 'settings.json'));
116
+ if (!r.value)
117
+ return { error: fs.existsSync(path.join(homeDir, '.claude', 'settings.json')) ? `settings.json 파싱 실패 (${r.error})` : 'settings.json 없음', disableAll: false, entries: [] };
118
+ return { disableAll: r.value.disableAllHooks === true, entries: collectForgenHooks(r.value, pkgRoot) };
119
+ }
120
+ function short(command) {
121
+ const m = command.match(/(hooks\/[\w.-]+\.js)"?(?:\s+"?(\w+)"?)?\s*$/);
122
+ return m ? (m[2] ? `${m[1]} ${m[2]}` : m[1]) : command.slice(-40);
123
+ }
124
+ function probeHookOutput(r) {
125
+ if (r.spawnError)
126
+ return `실행 실패: ${r.spawnError}`;
127
+ if (r.timedOut)
128
+ return '시간 초과';
129
+ if (r.rc !== 0)
130
+ return `rc ${r.rc}${r.stderr.trim() ? ` (${r.stderr.trim().split('\n')[0].slice(0, 80)})` : ''}`;
131
+ const out = r.stdout.trim();
132
+ if (!out)
133
+ return '출력 없음';
134
+ let parsed;
135
+ try {
136
+ parsed = JSON.parse(out);
137
+ }
138
+ catch {
139
+ return '출력이 JSON 1개가 아님';
140
+ }
141
+ const msg = parsed?.systemMessage;
142
+ if (typeof msg === 'string' && msg.includes('forgen hooks are not running'))
143
+ return 'shim 이 대상 또는 node 를 못 찾음';
144
+ return null;
145
+ }
146
+ function dangling(dir, depth = 1) {
147
+ const bad = [];
148
+ let entries;
149
+ try {
150
+ entries = fs.readdirSync(dir);
151
+ }
152
+ catch {
153
+ return bad;
154
+ }
155
+ for (const name of entries) {
156
+ const p = path.join(dir, name);
157
+ try {
158
+ const st = fs.lstatSync(p);
159
+ if (st.isSymbolicLink()) {
160
+ try {
161
+ fs.statSync(p);
162
+ }
163
+ catch {
164
+ bad.push(p);
165
+ }
166
+ }
167
+ else if (st.isDirectory() && depth > 0) {
168
+ bad.push(...dangling(p, depth - 1));
169
+ }
170
+ }
171
+ catch { /* race */ }
172
+ }
173
+ return bad;
174
+ }
175
+ /** 플랫폼별 셸 인용. POSIX 는 단일 인용, Windows(cmd) 는 큰따옴표. */
176
+ export function quoteShellArg(s, platform = process.platform) {
177
+ if (platform === 'win32')
178
+ return `"${s.replace(/"/g, '\\"')}"`;
179
+ return `'${s.replace(/'/g, `'\\''`)}'`;
180
+ }
181
+ /** forgen 이 설치된 호스트. 파일 하나가 아니라 설치 흔적(shim·hook·MCP·명령·statusLine) 중 하나라도 있으면 설치된 것으로 본다. */
182
+ export function detectHosts(homeDir, pkgRoot) {
183
+ let claude = false;
184
+ try {
185
+ if (shimSupported() && fs.existsSync(forgenRunShimPath(homeDir)))
186
+ claude = true;
187
+ }
188
+ catch { /* ignore */ }
189
+ const settings = readJson(path.join(homeDir, '.claude', 'settings.json')).value;
190
+ if (settings) {
191
+ if (collectForgenHooks(settings, pkgRoot).length > 0)
192
+ claude = true;
193
+ const sl = settings.statusLine?.command;
194
+ if (typeof sl === 'string' && sl.trim() && (isForgenStatusline(sl) || isForgenRunCommand(sl)))
195
+ claude = true;
196
+ }
197
+ const cj = readJson(path.join(homeDir, '.claude.json')).value;
198
+ if (cj?.mcpServers?.['forgen-compound'])
199
+ claude = true;
200
+ if (fs.existsSync(path.join(homeDir, '.claude', 'commands', 'forgen')))
201
+ claude = true;
202
+ let codex = false;
203
+ const codexHome = process.env.CODEX_HOME ?? path.join(homeDir, '.codex');
204
+ try {
205
+ if (/forgen/i.test(fs.readFileSync(path.join(codexHome, 'hooks.json'), 'utf-8')))
206
+ codex = true;
207
+ }
208
+ catch { /* 없음 */ }
209
+ try {
210
+ if (/forgen-compound/.test(fs.readFileSync(path.join(codexHome, 'config.toml'), 'utf-8')))
211
+ codex = true;
212
+ }
213
+ catch { /* 없음 */ }
214
+ return { claude, codex };
215
+ }
216
+ function shimTarget(shimPath) {
217
+ let why = 'shim 파일 없음';
218
+ try {
219
+ const content = fs.readFileSync(shimPath, 'utf-8');
220
+ const pkg = content.match(/^FORGEN_PKG='(.*)'$/m)?.[1];
221
+ if (pkg && fs.existsSync(path.join(pkg, 'dist', 'cli.js')))
222
+ return { ok: true, why: '' };
223
+ why = `shim 이 가리키는 패키지가 없음 (${pkg ?? '?'})`;
224
+ }
225
+ catch { /* 파일 없음 */ }
226
+ return { ok: false, why };
227
+ }
228
+ /** settings 명령 맨 앞의 forgen-run shim 경로 (인용 해제). */
229
+ function referencedShim(command) {
230
+ const m = command.match(/^"((?:[^"\\]|\\.)*[\\/]forgen-run)"/);
231
+ return m ? m[1].replace(/\\(.)/g, '$1') : null;
232
+ }
233
+ /** settings·shim·hook·MCP·statusLine·데이터 파일 전체 검증. 순서는 출력 순서. */
234
+ export async function collectProbes(opts) {
235
+ const probes = [];
236
+ const add = (p) => probes.push(p);
237
+ const { homeDir, forgenHome, pkgRoot } = opts;
238
+ const claudeDir = path.join(homeDir, '.claude');
239
+ const settingsPath = path.join(claudeDir, 'settings.json');
240
+ const claudeJsonPath = path.join(homeDir, '.claude.json');
241
+ const reinstall = 'forgen install claude (또는 forgen doctor --repair)';
242
+ const probeHome = fs.mkdtempSync(path.join(os.tmpdir(), 'forgen-doctor-'));
243
+ // HOME 도 격리한다. SessionStart hook 의 룰 파일 회수 같은 동작이 실제 홈을 건드리면 안 된다.
244
+ // FORGEN_DOCTOR_PROBE=1 은 hook 쪽의 부작용 경로(세션 상태 기록, auto-compound·lifecycle 스폰)를 끈다.
245
+ const probeEnv = { ...process.env, HOME: probeHome, USERPROFILE: probeHome, FORGEN_HOME: probeHome, FORGEN_CWD: probeHome, FORGEN_DOCTOR_PROBE: '1' };
246
+ delete probeEnv.FORGEN_NESTED_RUN;
247
+ try {
248
+ const hosts = detectHosts(homeDir, pkgRoot);
249
+ if (!hosts.claude) {
250
+ if (hosts.codex)
251
+ add({ section: 'Install', label: 'Claude Code 에는 설치되지 않음 (Codex 전용)', ok: true, info: true, hint: 'Claude 항목은 건너뜀. Claude 도 쓰려면: forgen install claude' });
252
+ else
253
+ add({ section: 'Install', label: 'forgen 이 어느 호스트(Claude Code·Codex)에도 설치되지 않음', ok: false, hint: 'Fix: forgen install claude (Codex 는 forgen install codex)' });
254
+ }
255
+ if (hosts.claude) {
256
+ const shimPath = shimSupported() ? forgenRunShimPath(homeDir) : null;
257
+ const envHome = !!process.env.FORGEN_HOME;
258
+ // FORGEN_HOME 이 지정된 환경에선 settings 의 shim 경로가 달라도 같은 hook 으로 본다 (실제 실행 성공 여부는 아래 실행 프로브가 판정).
259
+ const canon = (c) => (envHome ? c.replace(/^"[^"]*forgen-run"/, '"<shim>"') : c);
260
+ // ── settings.json 읽기 ──
261
+ const sRes = readJson(settingsPath);
262
+ const settings = sRes.value;
263
+ const actual = settings ? collectForgenHooks(settings, pkgRoot) : [];
264
+ // ── shim ──
265
+ if (shimPath) {
266
+ const t = shimTarget(shimPath);
267
+ const other = envHome ? [...new Set(actual.map((a) => referencedShim(a.command)).filter((x) => !!x && x !== shimPath))].find((r) => shimTarget(r).ok) : undefined;
268
+ if (!t.ok && other) {
269
+ add({ section: 'Install', label: `settings 의 shim (${other}) 이 FORGEN_HOME 의 shim 과 다름`, ok: true, info: true, hint: '지정한 FORGEN_HOME 에는 shim 이 없지만 settings 가 가리키는 shim 은 살아 있음. 실행 결과는 아래 Execution 참고' });
270
+ }
271
+ else {
272
+ add({ section: 'Install', label: 'hook/MCP shim (~/.forgen/bin/forgen-run) → forgen package', ok: t.ok, hint: `${t.why}. Fix: ${reinstall}` });
273
+ }
274
+ }
275
+ // ── hook 등록 ──
276
+ if (!settings) {
277
+ add({ section: 'Install', label: 'settings.json 읽기', ok: false, hint: `${fs.existsSync(settingsPath) ? `파싱 실패 (${sRes.error})` : '파일 없음'} — hook·statusLine 이 연결되지 않음. Fix: ${reinstall}` });
278
+ }
279
+ else {
280
+ const disabled = settings.disableAllHooks === true;
281
+ add({ section: 'Install', label: 'disableAllHooks 꺼짐', ok: !disabled, hint: 'settings.json 에 disableAllHooks:true — 모든 hook 이 꺼져 있음. 값을 지우세요' });
282
+ const expectedJson = generateHooksJson({
283
+ pluginRoot: path.join(pkgRoot, 'dist'), runtime: 'claude', releaseMode: true, ...(shimPath ? { shimPath } : {}),
284
+ });
285
+ const expected = [];
286
+ for (const [event, groups] of Object.entries(expectedJson.hooks))
287
+ for (const g of groups)
288
+ for (const h of g.hooks)
289
+ expected.push({ event, command: h.command });
290
+ const same = (a, e) => a.event === e.event && canon(a.command) === canon(e.command);
291
+ const count = (list, e) => list.filter((a) => same(a, e)).length;
292
+ const missing = expected.filter((e) => count(actual, e) === 0);
293
+ const dup = expected.filter((e) => count(actual, e) > 1);
294
+ const stale = actual.filter((a) => !expected.some((e) => same(a, e)));
295
+ add({
296
+ section: 'Install', label: `settings hook 등록 ${expected.length - missing.length}/${expected.length}`, ok: missing.length === 0,
297
+ hint: `누락: ${missing.slice(0, 4).map((m) => `${m.event}:${short(m.command)}`).join(', ')}${missing.length > 4 ? ` 외 ${missing.length - 4}` : ''}. Fix: ${reinstall}`,
298
+ });
299
+ add({
300
+ section: 'Install', label: 'hook 이중 등록 없음', ok: dup.length === 0,
301
+ hint: `중복 ${dup.length}개 (${dup.slice(0, 3).map((m) => short(m.command)).join(', ')}) — 같은 hook 이 두 번 돌아 출력이 겹침. Fix: ${reinstall}`,
302
+ });
303
+ add({
304
+ section: 'Install', label: '구형·다른 경로 forgen hook 없음', ok: stale.length === 0,
305
+ hint: `${stale.length}개 (${stale.slice(0, 2).map((m) => m.command.slice(0, 60)).join(' | ')}) — 현재 shim 이 아닌 경로를 가리킴. Fix: ${reinstall}`,
306
+ });
307
+ // 실제 실행 — 등록된 forgen hook 전부 (중복 제거)
308
+ if (!opts.skipExec) {
309
+ const uniq = [...new Map(actual.map((a) => [`${a.event}\0${a.command}`, a])).values()];
310
+ const results = await mapLimit(uniq, 6, async (h) => ({ h, r: await runCommand(h.command, '', probeEnv, probeHome, 15_000) }));
311
+ const failed = results.map(({ h, r }) => ({ h, why: probeHookOutput(r) })).filter((x) => x.why);
312
+ add({
313
+ section: 'Execution', label: `hook 실행 ${uniq.length - failed.length}/${uniq.length} (빈 입력 → 유효 JSON, rc 0)`, ok: failed.length === 0 && uniq.length > 0,
314
+ hint: uniq.length === 0 ? '실행할 forgen hook 이 settings 에 없음' : `${failed.slice(0, 3).map((f) => `${f.h.event}:${short(f.h.command)} → ${f.why}`).join('; ')}${failed.length > 3 ? ` 외 ${failed.length - 3}` : ''}`,
315
+ });
316
+ }
317
+ // ── statusLine ──
318
+ const sl = settings.statusLine?.command;
319
+ if (!sl || !sl.trim()) {
320
+ add({ section: 'Statusline', label: 'statusLine 없음', ok: true, info: true, hint: '의도적으로 비웠다면 정상. forgen HUD 를 쓰려면: forgen statusline install' });
321
+ }
322
+ else if (!isForgenStatusline(sl) && !isForgenRunCommand(sl)) {
323
+ add({ section: 'Statusline', label: `statusLine 은 다른 명령 (${sl.slice(0, 50)})`, ok: true, info: true, hint: 'forgen HUD 로 바꾸려면: forgen statusline install --force' });
324
+ }
325
+ else {
326
+ add({ section: 'Statusline', label: 'statusLine 이 shim 또는 절대경로 (nvm-safe)', ok: !/^forgen(\s|$)/.test(sl.trim()), hint: 'PATH 의존 `forgen statusline` 은 nvm 버전에 따라 달라짐. Fix: forgen statusline install' });
327
+ if (!opts.skipExec) {
328
+ // 체인(`… statusline --after '<원본>'`)이면 forgen 부분만 실행해 판정한다. 사용자 원본 명령의 실패는 forgen 의 책임이 아니다.
329
+ const chainAt = sl.search(/\sstatusline\s+--after\s/);
330
+ const forgenPart = chainAt >= 0 ? sl.slice(0, chainAt + ' statusline'.length) : sl;
331
+ const r = await runCommand(forgenPart, '{}', probeEnv, probeHome, 15_000);
332
+ const why = r.spawnError ? r.spawnError : r.timedOut ? '시간 초과' : r.rc !== 0 ? `rc ${r.rc}` : !r.stdout.trim() ? '출력 없음' : /forgen: not found|forgen hooks are not running/.test(r.stdout) ? 'shim 이 대상 cli.js 를 못 찾음' : null;
333
+ add({ section: 'Statusline', label: `statusLine 실행 (빈 JSON 입력 → 출력)${chainAt >= 0 ? ' — forgen 부분만' : ''}`, ok: !why, hint: `${why}. Fix: forgen statusline install` });
334
+ }
335
+ }
336
+ }
337
+ // ── MCP ──
338
+ const cj = readJson(claudeJsonPath);
339
+ const mcp = (cj.value?.mcpServers?.['forgen-compound']);
340
+ if (!cj.value) {
341
+ add({ section: 'Execution', label: '~/.claude.json 읽기', ok: false, hint: `${fs.existsSync(claudeJsonPath) ? `파싱 실패 (${cj.error})` : '파일 없음'} — MCP 등록을 확인할 수 없음. Fix: ${reinstall}` });
342
+ }
343
+ else if (!mcp?.command) {
344
+ add({ section: 'Execution', label: 'MCP forgen-compound 등록', ok: false, hint: `~/.claude.json 에 forgen-compound 가 없음. Fix: ${reinstall}` });
345
+ }
346
+ else if (!opts.skipExec) {
347
+ const cmd = [mcp.command, ...(mcp.args ?? [])].map((s) => quoteShellArg(s)).join(' ');
348
+ const why = await mcpInitialize(cmd, probeEnv, probeHome);
349
+ add({ section: 'Execution', label: 'MCP forgen-compound initialize 왕복', ok: !why, hint: `${why}. Fix: ${reinstall}` });
350
+ }
351
+ if (opts.skipExec)
352
+ add({ section: 'Execution', label: '실행 검증 생략 (--quick)', ok: true, info: true, hint: 'hook·MCP·statusLine 을 실제로 실행해 보려면: forgen doctor' });
353
+ // ── 설치 자산 ──
354
+ const cmdDir = path.join(claudeDir, 'commands', 'forgen');
355
+ const cmdCount = fs.existsSync(cmdDir) ? fs.readdirSync(cmdDir).filter((f) => f.endsWith('.md')).length : 0;
356
+ add({ section: 'Install', label: `슬래시 명령 설치 (${cmdCount})`, ok: cmdCount > 0, hint: `~/.claude/commands/forgen 이 비었거나 없음. Fix: ${reinstall}` });
357
+ const skillsDir = path.join(claudeDir, 'skills');
358
+ let skillCount = 0;
359
+ try {
360
+ skillCount = fs.readdirSync(skillsDir).filter((f) => f.startsWith('forgen-') || f === 'verify').length;
361
+ }
362
+ catch { /* 없음 */ }
363
+ add({ section: 'Install', label: `forgen 스킬 설치 (${skillCount})`, ok: skillCount > 0, hint: `~/.claude/skills 에 forgen-* 스킬 없음. Fix: ${reinstall}` });
364
+ const broken = [skillsDir, path.join(claudeDir, 'commands'), path.join(claudeDir, 'agents'), forgenHome].flatMap((d) => dangling(d));
365
+ add({ section: 'Install', label: '끊긴 심링크 없음', ok: broken.length === 0, hint: `${broken.length}개: ${broken.slice(0, 3).join(', ')}` });
366
+ }
367
+ // ── 데이터 파일 (파싱까지) ──
368
+ const profile = path.join(forgenHome, 'me', 'forge-profile.json');
369
+ if (!fs.existsSync(profile))
370
+ add({ section: 'Data', label: '프로필 없음 (me/forge-profile.json)', ok: true, info: true, hint: '룰은 동작함. forgen 으로 온보딩하면 4축 프로필을 사용' });
371
+ else {
372
+ const r = readJson(profile);
373
+ add({ section: 'Data', label: 'Profile 파싱 (me/forge-profile.json)', ok: !!r.value, hint: `깨짐 (${r.error}). 복구: forgen forge --reset 후 온보딩` });
374
+ }
375
+ for (const rel of ['forge-profile.json', 'config.json', 'hook-config.json']) {
376
+ const p = path.join(forgenHome, rel);
377
+ if (!fs.existsSync(p))
378
+ continue;
379
+ const r = readJson(p);
380
+ add({ section: 'Data', label: `${rel} 파싱`, ok: !!r.value, hint: `깨짐 (${r.error}) — ${p}` });
381
+ }
382
+ const dbPath = path.join(forgenHome, 'sessions.db');
383
+ if (fs.existsSync(dbPath))
384
+ add({ section: 'Data', label: 'sessions.db 열기', ok: sqliteOk(dbPath), hint: 'SQLite 파일이 아니거나 손상됨. 백업 후 삭제하면 새로 만들어짐' });
385
+ const scan = scanRuleFiles();
386
+ if (scan.dirError)
387
+ add({ section: 'Data', label: '룰 디렉터리 읽기', ok: false, hint: `읽을 수 없음: ${scan.dirError}` });
388
+ else
389
+ add({ section: 'Data', label: `룰 파일 ${scan.rules.length + scan.broken.length}개 파싱 (깨진 ${scan.broken.length}개)`, ok: scan.broken.length === 0, hint: `깨진 룰: ${scan.broken.slice(0, 3).map((b) => b.file).join(', ')}${scan.broken.length > 3 ? ' …' : ''}` });
390
+ const solDir = path.join(forgenHome, 'me', 'solutions');
391
+ if (fs.existsSync(solDir)) {
392
+ let badSol = 0;
393
+ let totalSol = 0;
394
+ try {
395
+ for (const f of fs.readdirSync(solDir).filter((x) => x.endsWith('.md'))) {
396
+ totalSol++;
397
+ const head = fs.readFileSync(path.join(solDir, f), 'utf-8').slice(0, 200);
398
+ if (!head.startsWith('---') || head.includes('\0'))
399
+ badSol++;
400
+ }
401
+ }
402
+ catch {
403
+ badSol = -1;
404
+ }
405
+ add({ section: 'Data', label: `솔루션 ${totalSol}개 frontmatter 확인`, ok: badSol === 0, hint: badSol < 0 ? '솔루션 디렉터리를 읽을 수 없음' : `${badSol}개 frontmatter 깨짐` });
406
+ }
407
+ // ── 최근 hook 오류 (24h) ──
408
+ try {
409
+ const errPath = path.join(forgenHome, 'state', 'hook-errors.jsonl');
410
+ if (fs.existsSync(errPath)) {
411
+ const cutoff = Date.now() - 24 * 3600_000;
412
+ const byHook = new Map();
413
+ for (const line of fs.readFileSync(errPath, 'utf-8').split('\n')) {
414
+ if (!line.trim())
415
+ continue;
416
+ try {
417
+ const e = JSON.parse(line);
418
+ if (Date.parse(e.timestamp ?? '') >= cutoff)
419
+ byHook.set(e.hook ?? '?', (byHook.get(e.hook ?? '?') ?? 0) + 1);
420
+ }
421
+ catch { /* skip */ }
422
+ }
423
+ const noisy = [...byHook.entries()].filter(([, n]) => n >= 3);
424
+ add({ section: 'Hook Health', label: '최근 24h hook 오류 3회 미만', ok: noisy.length === 0, hint: noisy.map(([h, n]) => `${h}: ${n}회`).join(', ') });
425
+ }
426
+ }
427
+ catch { /* 읽기 실패는 아래 Hook Health 출력에서 표시 */ }
428
+ }
429
+ finally {
430
+ try {
431
+ fs.rmSync(probeHome, { recursive: true, force: true });
432
+ }
433
+ catch { /* ignore */ }
434
+ }
435
+ // 예전 버전에서 활성 룰로 남지 못한 교정. npm 은 postinstall 출력을 숨기므로 여기서 알린다. 실패로 세지 않는다.
436
+ try {
437
+ const { findLostCorrections } = await import('../engine/rule-recovery-cli.js');
438
+ const lost = findLostCorrections().length;
439
+ if (lost > 0)
440
+ add({ section: 'Rules', label: `활성 룰로 남지 못한 교정 ${lost}건`, ok: false, info: true, hint: '확인: forgen rule recover' });
441
+ }
442
+ catch { /* 안내일 뿐 */ }
443
+ return probes;
444
+ }
445
+ function sqliteOk(dbPath) {
446
+ try {
447
+ const fd = fs.openSync(dbPath, 'r');
448
+ const buf = Buffer.alloc(16);
449
+ fs.readSync(fd, buf, 0, 16, 0);
450
+ fs.closeSync(fd);
451
+ if (buf.toString('utf-8', 0, 15) !== 'SQLite format 3')
452
+ return false;
453
+ }
454
+ catch {
455
+ return false;
456
+ }
457
+ try {
458
+ const require = createRequire(import.meta.url);
459
+ const { DatabaseSync } = require('node:sqlite');
460
+ const db = new DatabaseSync(dbPath, { readOnly: true });
461
+ try {
462
+ return Object.values(db.prepare('PRAGMA quick_check').get())[0] === 'ok';
463
+ }
464
+ finally {
465
+ db.close();
466
+ }
467
+ }
468
+ catch {
469
+ return true; // node:sqlite 없음(Node 20) — 헤더 확인까지만
470
+ }
471
+ }
472
+ function mcpInitialize(command, env, cwd) {
473
+ return new Promise((resolve) => {
474
+ let buf = '';
475
+ let stderr = '';
476
+ let settled = false;
477
+ const child = spawnGroup(command, env, cwd);
478
+ const finish = (why) => { if (settled)
479
+ return; settled = true; clearTimeout(timer); killTree(child); child.stdout?.destroy(); child.stderr?.destroy(); resolve(why); };
480
+ const timer = setTimeout(() => finish('initialize 응답 시간 초과'), 12_000);
481
+ child.stdout?.on('data', (d) => {
482
+ buf += String(d);
483
+ for (const line of buf.split('\n')) {
484
+ if (!line.trim())
485
+ continue;
486
+ try {
487
+ const msg = JSON.parse(line);
488
+ if (msg.id === 1)
489
+ return finish(msg.result?.serverInfo ? null : 'initialize 응답에 serverInfo 없음');
490
+ }
491
+ catch { /* 다음 줄 */ }
492
+ }
493
+ });
494
+ child.stderr?.on('data', (d) => { stderr += String(d); });
495
+ child.on('error', (e) => finish(`실행 실패: ${e.message}`));
496
+ const ended = (rc) => finish(`응답 없이 종료 (rc ${rc}${stderr.trim() ? `: ${stderr.trim().split('\n')[0].slice(0, 80)}` : ''})`);
497
+ child.on('exit', (rc) => { setTimeout(() => ended(rc), EXIT_GRACE_MS); });
498
+ child.on('close', ended);
499
+ child.stdin?.on('error', () => { });
500
+ child.stdin?.write(`${JSON.stringify({ jsonrpc: '2.0', id: 1, method: 'initialize', params: { protocolVersion: '2024-11-05', capabilities: {}, clientInfo: { name: 'forgen-doctor', version: '1' } } })}\n`);
501
+ });
502
+ }
@@ -16,15 +16,13 @@ export interface DoctorOptions {
16
16
  * Initialization Status) for fast onboarding verification. ~10 lines output. */
17
17
  quick?: boolean;
18
18
  /** W1-1 (ADR-010): tenetx/legacy 규칙 스프롤 스캔 (dry-run — 삭제는
19
- * `forgen migrate tenetx` 가 수행). native /doctor 가 비용을 flag 하면
19
+ * `forgen dev migrate tenetx` 가 수행). native /doctor 가 비용을 flag 하면
20
20
  * forgen 이 provenance 로 안전하게 회수하는 보완 관계. */
21
21
  reclaim?: boolean;
22
22
  /** W2-1 (ADR-010): hook timing 표 등 상세 진단 표시. slow-hook 감지는
23
23
  * native /doctor 영역이라 기본 출력에서 강등됨 (수집은 유지). */
24
24
  verbose?: boolean;
25
25
  }
26
- /** plugin cache 디렉토리에 버전 엔트리가 하나 이상 있는가 (check + repair 재검증 공용) */
27
- export declare function pluginCacheOk(): boolean;
28
- /** installed_plugins.json 의 forgen entry 가 존재하며 installPath 가 살아있는가 */
29
- export declare function pluginRegisteredOk(): boolean;
30
- export declare function runDoctor(opts?: DoctorOptions): Promise<void>;
26
+ /** 고정 shim 이 가리키는 패키지가 살아 있는가 (collectProbes 의 shim 항목과 같은 판정). */
27
+ export declare function shimTargetOk(homeDir?: string): boolean;
28
+ export declare function runDoctor(opts?: DoctorOptions): Promise<number>;