@wooojin/forgen 0.6.8 → 0.6.10

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 (221) hide show
  1. package/.claude-plugin/plugin.json +1 -1
  2. package/CHANGELOG.md +27 -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 +145 -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 +177 -0
  145. package/dist/hooks/shared/hook-response.d.ts +12 -2
  146. package/dist/hooks/shared/hook-response.js +19 -3
  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/tool-response.d.ts +6 -0
  153. package/dist/hooks/shared/tool-response.js +30 -0
  154. package/dist/hooks/slop-detector.js +6 -3
  155. package/dist/hooks/solution-injector.d.ts +23 -0
  156. package/dist/hooks/solution-injector.js +102 -101
  157. package/dist/hooks/stop-guard.d.ts +11 -1
  158. package/dist/hooks/stop-guard.js +28 -11
  159. package/dist/hooks/subagent-stop-guard.js +2 -1
  160. package/dist/hooks/subagent-tracker.js +2 -1
  161. package/dist/host/capabilities-codex.js +1 -0
  162. package/dist/host/claude-shim.d.ts +24 -0
  163. package/dist/host/claude-shim.js +68 -0
  164. package/dist/host/codex-hook-shim.d.ts +3 -1
  165. package/dist/host/codex-hook-shim.js +7 -5
  166. package/dist/host/codex-notify.js +1 -1
  167. package/dist/host/codex-rules-context.d.ts +6 -4
  168. package/dist/host/codex-rules-context.js +11 -24
  169. package/dist/host/exec-host.d.ts +5 -1
  170. package/dist/host/exec-host.js +15 -4
  171. package/dist/host/install-claude.d.ts +47 -14
  172. package/dist/host/install-claude.js +302 -155
  173. package/dist/host/install-codex.d.ts +20 -0
  174. package/dist/host/install-codex.js +32 -1
  175. package/dist/host/install-opencode.d.ts +3 -1
  176. package/dist/host/install-opencode.js +6 -3
  177. package/dist/host/install-orchestrator.js +14 -1
  178. package/dist/host/opencode/translate.d.ts +1 -1
  179. package/dist/host/opencode/translate.js +5 -3
  180. package/dist/host/projection.d.ts +9 -1
  181. package/dist/host/projection.js +19 -2
  182. package/dist/mcp/server.js +5 -0
  183. package/dist/mcp/solution-reader.d.ts +5 -5
  184. package/dist/mcp/solution-reader.js +13 -35
  185. package/dist/mcp/tools.js +18 -1
  186. package/dist/renderer/inspect-renderer.js +4 -2
  187. package/dist/renderer/render-report.d.ts +22 -0
  188. package/dist/renderer/render-report.js +29 -0
  189. package/dist/renderer/rule-renderer.d.ts +28 -2
  190. package/dist/renderer/rule-renderer.js +91 -76
  191. package/dist/store/evidence-store.js +34 -6
  192. package/dist/store/rule-lifecycle.d.ts +3 -1
  193. package/dist/store/rule-lifecycle.js +10 -0
  194. package/dist/store/rule-scope.d.ts +7 -0
  195. package/dist/store/rule-scope.js +54 -0
  196. package/dist/store/rule-store.d.ts +29 -3
  197. package/dist/store/rule-store.js +110 -26
  198. package/dist/store/types.d.ts +22 -2
  199. package/dist/way/cli.d.ts +1 -0
  200. package/dist/way/cli.js +313 -0
  201. package/dist/way/compile.d.ts +22 -0
  202. package/dist/way/compile.js +408 -0
  203. package/dist/way/conflict.d.ts +2 -0
  204. package/dist/way/conflict.js +18 -0
  205. package/dist/way/draft.d.ts +43 -0
  206. package/dist/way/draft.js +335 -0
  207. package/dist/way/extract.d.ts +17 -0
  208. package/dist/way/extract.js +172 -0
  209. package/dist/way/io.d.ts +79 -0
  210. package/dist/way/io.js +425 -0
  211. package/dist/way/similar.d.ts +2 -0
  212. package/dist/way/similar.js +30 -0
  213. package/dist/way/types.d.ts +98 -0
  214. package/dist/way/types.js +2 -0
  215. package/package.json +1 -1
  216. package/plugin.json +1 -1
  217. package/scripts/postinstall.js +76 -899
  218. package/dist/core/health-cli.d.ts +0 -25
  219. package/dist/core/health-cli.js +0 -90
  220. package/dist/host/parity-harness.d.ts +0 -70
  221. package/dist/host/parity-harness.js +0 -287
@@ -12,10 +12,11 @@
12
12
  * - forge overlay 없이 기본 스킬만 설치 (overlay는 harness 실행 시 적용)
13
13
  * - 사용자가 수정한 파일(<!-- forgen-managed --> 마커 없음)은 보존
14
14
  * - settings.json의 기존 non-forgen 설정은 보존
15
- * - 실패해도 npm install을 깨뜨리지 않음 (silent failure)
15
+ * - 실패해도 npm install을 깨뜨리지 않음 (사유는 출력)
16
+ * - Claude 설치는 dist/host/install-claude.js 의 planClaudeInstall 을 호출 (`forgen install claude` 와 동일 경로)
16
17
  */
17
18
 
18
- import { readFileSync, readdirSync, writeFileSync, mkdirSync, existsSync, rmSync, symlinkSync, cpSync, lstatSync, statSync, copyFileSync, renameSync, readlinkSync, unlinkSync, rmdirSync } from 'node:fs';
19
+ import { readdirSync, writeFileSync, mkdirSync, existsSync, symlinkSync, cpSync, lstatSync, statSync, copyFileSync, renameSync, readlinkSync, unlinkSync, rmdirSync } from 'node:fs';
19
20
  import { join, dirname } from 'node:path';
20
21
  import { homedir, platform } from 'node:os';
21
22
  import { execFileSync } from 'node:child_process';
@@ -24,6 +25,8 @@ import { fileURLToPath } from 'node:url';
24
25
  const __dirname = dirname(fileURLToPath(import.meta.url));
25
26
  const PKG_ROOT = join(__dirname, '..');
26
27
  const IS_WINDOWS = platform() === 'win32';
28
+ /** package.json engines.node 와 같게 유지 (tests/node-engine 이 대조). */
29
+ const MIN_NODE_MAJOR = 22;
27
30
 
28
31
  /** SUDO_USER 유효성 검증 — 커맨드 인젝션 방지 */
29
32
  const SAFE_USERNAME_RE = /^[a-zA-Z0-9_-]+$/;
@@ -89,12 +92,7 @@ function fixOwnership(...paths) {
89
92
  const HOME = resolveHome();
90
93
 
91
94
  // ── Paths ──
92
- const SKILLS_DIR = join(PKG_ROOT, 'assets', 'claude', 'commands');
93
- const DIST_HOOKS = join(PKG_ROOT, 'dist', 'hooks');
94
- const COMMANDS_DIR = join(HOME, '.claude', 'commands', 'forgen');
95
95
  const CLAUDE_DIR = join(HOME, '.claude');
96
- const PLUGINS_DIR = join(CLAUDE_DIR, 'plugins');
97
- const SETTINGS_PATH = join(CLAUDE_DIR, 'settings.json');
98
96
  const COMPOUND_HOME = join(HOME, '.forgen');
99
97
 
100
98
  // ── 0.5. Migrate legacy storage (~/.tenetx/, ~/.compound/) → ~/.forgen/ ──
@@ -175,603 +173,6 @@ function installStarterPack() {
175
173
  return installed;
176
174
  }
177
175
 
178
- // ── 2. Register as Claude Code plugin ──
179
- // omc, claude-hud 등 동작하는 플러그인의 실제 구조를 그대로 따름:
180
- // .claude-plugin/plugin.json — 메타데이터 + skills 경로
181
- // hooks/hooks.json — ${CLAUDE_PLUGIN_ROOT} 기반 훅 정의
182
- // skills/{name}/SKILL.md — 스킬 파일 (서브디렉토리 구조)
183
- // commands/*.md — 슬래시 커맨드
184
- //
185
- // 설계 결정: 캐시 디렉토리를 PKG_ROOT로 symlink하여 dist/, node_modules/ 접근 보장.
186
- // symlink 실패 시 (sudo, cross-device 등) 필수 파일만 복사.
187
- function registerPlugin() {
188
- // .claude-plugin/plugin.json 필수 — 없으면 표준 구조가 아님
189
- if (!existsSync(join(PKG_ROOT, '.claude-plugin', 'plugin.json'))) return false;
190
-
191
- const pkg = JSON.parse(readFileSync(join(PKG_ROOT, 'package.json'), 'utf-8'));
192
- const version = pkg.version ?? '0.0.0';
193
-
194
- // skills/ 디렉토리 생성 (commands/*.md → skills/{name}/SKILL.md)
195
- generateSkillsDir();
196
-
197
- // 캐시 경로: ~/.claude/plugins/cache/forgen-local/forgen/{version}/
198
- const cacheParent = join(PLUGINS_DIR, 'cache', 'forgen-local', 'forgen');
199
- const CACHE_DIR = join(cacheParent, version);
200
-
201
- // 이전 잔재 완전 제거
202
- try { rmSync(cacheParent, { recursive: true, force: true }); } catch { /* ignore */ }
203
- mkdirSync(join(cacheParent), { recursive: true });
204
-
205
- // 1차: symlink (개발 환경, dist/node_modules 접근 가능)
206
- let linked = false;
207
- try {
208
- symlinkSync(PKG_ROOT, CACHE_DIR, 'dir');
209
- linked = true;
210
- } catch {
211
- // symlink 실패 → 복사 fallback
212
- }
213
-
214
- if (!linked) {
215
- // 2차: 필수 디렉토리 복사
216
- mkdirSync(CACHE_DIR, { recursive: true });
217
- const copyDirs = ['.claude-plugin', 'hooks', 'skills', 'assets'];
218
- for (const dir of copyDirs) {
219
- const src = join(PKG_ROOT, dir);
220
- if (existsSync(src)) {
221
- cpSync(src, join(CACHE_DIR, dir), { recursive: true });
222
- }
223
- }
224
- // dist/ 복사 (훅 실행에 필요)
225
- if (existsSync(join(PKG_ROOT, 'dist'))) {
226
- cpSync(join(PKG_ROOT, 'dist'), join(CACHE_DIR, 'dist'), { recursive: true });
227
- }
228
- // 핵심 의존성 복사 (symlink 실패 시 필요)
229
- const coreDeps = ['js-yaml', '@modelcontextprotocol', 'zod'];
230
- mkdirSync(join(CACHE_DIR, 'node_modules'), { recursive: true });
231
- for (const dep of coreDeps) {
232
- const depSrc = join(PKG_ROOT, 'node_modules', dep);
233
- if (existsSync(depSrc)) {
234
- cpSync(depSrc, join(CACHE_DIR, 'node_modules', dep), { recursive: true });
235
- }
236
- }
237
- }
238
-
239
- // installed_plugins.json에 등록
240
- const installedPath = join(PLUGINS_DIR, 'installed_plugins.json');
241
- let installed = { version: 2, plugins: {} };
242
- if (existsSync(installedPath)) {
243
- try { installed = JSON.parse(readFileSync(installedPath, 'utf-8')); } catch { /* ignore */ }
244
- }
245
-
246
- const pluginKey = 'forgen@forgen-local';
247
- installed.plugins = installed.plugins ?? {};
248
- installed.plugins[pluginKey] = [{
249
- scope: 'user',
250
- installPath: CACHE_DIR,
251
- version,
252
- installedAt: new Date().toISOString(),
253
- lastUpdated: new Date().toISOString(),
254
- }];
255
-
256
- mkdirSync(PLUGINS_DIR, { recursive: true });
257
- writeFileSync(installedPath, JSON.stringify(installed, null, 2));
258
-
259
- return true;
260
- }
261
-
262
- /** settings 객체에 enabledPlugins를 적용합니다 (settings.json 쓰기는 main에서 일괄 수행). */
263
- /**
264
- * statusLine 자동 등록 (2026-10-07, 오너 피드백 "설치 후 forgen install 을 또 해야 하는 게 불편").
265
- * - 없거나 forgen 소유(`forgen …` / `…/dist/cli.js statusline`) → 이 패키지의 **절대 경로**로 등록
266
- * (PATH 의존 `forgen statusline` 은 nvm 버전마다 다른 바이너리가 잡힌다 — 실측 0.4.8).
267
- * - 커스텀(claude-hud 등) → 건드리지 않고 안내만. 교체는 `forgen statusline install --force`.
268
- * 반환: 'installed' | 'updated' | 'unchanged' | 'custom'
269
- */
270
- function applyStatusLineAuto(settings) {
271
- const cmd = `"${process.execPath}" "${join(PKG_ROOT, 'dist', 'cli.js')}" statusline`;
272
- const existing = settings.statusLine && settings.statusLine.command;
273
- const owned = !existing || /^forgen(\s|$)/.test(String(existing).trim()) || /[\\/]dist[\\/]cli\.js"?\s+statusline(\s|$)/.test(String(existing));
274
- if (!owned) return 'custom';
275
- // 체인(`… statusline --after '<원본>'`)이면 forgen 경로만 갱신하고 --after 이후는 보존한다.
276
- const chainAt = existing ? String(existing).search(/\sstatusline\s+--after\s/) : -1;
277
- const next = chainAt >= 0 ? `${cmd}${String(existing).slice(chainAt + ' statusline'.length)}` : cmd;
278
- if (existing === next) return 'unchanged';
279
- settings.statusLine = { type: 'command', command: next };
280
- return existing ? 'updated' : 'installed';
281
- }
282
-
283
- function applyPluginSettings(settings) {
284
- const pluginKey = 'forgen@forgen-local';
285
- const enabled = settings.enabledPlugins ?? {};
286
- enabled[pluginKey] = true;
287
- settings.enabledPlugins = enabled;
288
- }
289
-
290
- /**
291
- * 설치된 다른 플러그인을 감지하여 겹치는 스킬 목록을 반환.
292
- * Returns Map<skillName, pluginName>.
293
- *
294
- * 설계 결정: 빌드 이전 postinstall 단계에서 실행되므로
295
- * TypeScript 소스 import 없이 순수 파일시스템 체크만 사용.
296
- */
297
- function detectPluginConflicts() {
298
- const conflicts = new Map();
299
-
300
- // oh-my-claudecode: ~/.omc 또는 .omc(프로젝트 루트) 존재 여부 확인
301
- const omcGlobal = join(HOME, '.omc');
302
- const omcLocal = join(process.cwd(), '.omc');
303
- if (existsSync(omcGlobal) || existsSync(omcLocal)) {
304
- const omcSkills = [
305
- 'autopilot', 'team', 'code-review', 'tdd', 'debug-detective',
306
- 'refactor', 'security-review', 'git-master', 'migrate', 'pipeline', 'ultrawork',
307
- ];
308
- for (const skill of omcSkills) {
309
- conflicts.set(skill, 'oh-my-claudecode');
310
- }
311
- }
312
-
313
- // claude-mem: ~/.claude-mem 존재 여부 확인
314
- const claudeMem = join(HOME, '.claude-mem');
315
- if (existsSync(claudeMem)) {
316
- // claude-mem과 겹치는 스킬이 추가되면 여기에 등록
317
- }
318
-
319
- // superpowers: ~/.codex/superpowers/ 존재 여부 확인
320
- const superpowers = join(HOME, '.codex', 'superpowers');
321
- if (existsSync(superpowers)) {
322
- for (const skill of ['tdd', 'debug-detective', 'refactor', 'code-review']) {
323
- conflicts.set(skill, 'superpowers');
324
- }
325
- }
326
-
327
- // feature-dev (official Anthropic plugin): ~/.claude/plugins/feature-dev/ 존재 여부 확인
328
- const featureDev = join(HOME, '.claude', 'plugins', 'feature-dev');
329
- if (existsSync(featureDev)) {
330
- conflicts.set('pipeline', 'feature-dev');
331
- }
332
-
333
- // code-review plugin (official Anthropic plugin): ~/.claude/plugins/code-review/ 존재 여부 확인
334
- const codeReviewPlugin = join(HOME, '.claude', 'plugins', 'code-review');
335
- if (existsSync(codeReviewPlugin)) {
336
- conflicts.set('code-review', 'code-review-plugin');
337
- }
338
-
339
- // commit-commands (official Anthropic plugin): ~/.claude/plugins/commit-commands/ 존재 여부 확인
340
- const commitCommands = join(HOME, '.claude', 'plugins', 'commit-commands');
341
- if (existsSync(commitCommands)) {
342
- conflicts.set('git-master', 'commit-commands');
343
- }
344
-
345
- return conflicts;
346
- }
347
-
348
- /**
349
- * commands/*.md → skills/{name}/SKILL.md 변환.
350
- * Claude Code 플러그인은 skills/{name}/SKILL.md 구조로 스킬을 인식.
351
- */
352
- function generateSkillsDir() {
353
- const skillsSrc = join(PKG_ROOT, 'assets', 'claude', 'commands');
354
- const skillsDst = join(PKG_ROOT, 'skills');
355
- if (!existsSync(skillsSrc)) return;
356
-
357
- // 기존 skills/ 제거 후 재생성
358
- try { rmSync(skillsDst, { recursive: true, force: true }); } catch { /* ignore */ }
359
-
360
- const conflicts = detectPluginConflicts();
361
- let skipped = 0;
362
-
363
- for (const file of readdirSync(skillsSrc).filter(f => f.endsWith('.md'))) {
364
- const name = file.replace('.md', '');
365
-
366
- // 다른 플러그인이 동일 스킬을 제공하면 건너뜀
367
- if (conflicts.has(name)) {
368
- const pluginName = conflicts.get(name);
369
- console.log(`[forgen] Skipping skill "${name}" — provided by ${pluginName}`);
370
- skipped++;
371
- continue;
372
- }
373
-
374
- const raw = readFileSync(join(skillsSrc, file), 'utf-8');
375
-
376
- // description 추출
377
- const descMatch = raw.match(/description:\s*(.+)/);
378
- const desc = descMatch?.[1]?.trim() ?? name;
379
-
380
- // frontmatter 이후 본문 추출
381
- const bodyMatch = raw.match(/^---\n[\s\S]*?\n---\n([\s\S]*)$/);
382
- const body = bodyMatch?.[1]?.trim() ?? raw;
383
-
384
- // skills/{name}/SKILL.md 생성 (Claude Code 표준)
385
- const skillDir = join(skillsDst, name);
386
- mkdirSync(skillDir, { recursive: true });
387
- writeFileSync(join(skillDir, 'SKILL.md'), `---\nname: ${name}\ndescription: ${desc}\n---\n\n${body}\n`);
388
- }
389
-
390
- if (skipped > 0) {
391
- console.log(`[forgen] ${skipped} overlapping skills skipped. Compound knowledge engine remains active.`);
392
- }
393
- }
394
-
395
- // ── 3. Generate hooks/hooks.json dynamically ──
396
-
397
- /**
398
- * HOOK_REGISTRY — hooks/hook-registry.json에서 로드.
399
- * 단일 소스 오브 트루스: hook-registry.ts와 동일 파일을 읽습니다.
400
- * 중복/불일치 완전 제거.
401
- */
402
- let HOOK_REGISTRY = [];
403
- try {
404
- HOOK_REGISTRY = JSON.parse(readFileSync(join(PKG_ROOT, 'assets', 'shared', 'hook-registry.json'), 'utf-8'));
405
- } catch {
406
- console.warn('[forgen] hook-registry.json not found, skipping hook generation');
407
- }
408
-
409
- /**
410
- * hook-config.ts의 isHookEnabled 로직 인라인 구현.
411
- * 우선순위: 개별 훅 > 티어 > 레거시 > 기본값 true
412
- * compound-core 훅은 tier 설정으로 비활성화 불가.
413
- */
414
- function isHookEnabledFromConfig(hookName, hookTier, config) {
415
- if (!config) return true;
416
-
417
- const hooksSection = config['hooks'];
418
- // 1) 개별 훅 설정 (v2: hooks 섹션)
419
- if (hooksSection?.[hookName]?.['enabled'] === false) return false;
420
- if (hooksSection?.[hookName]?.['enabled'] === true) return true;
421
-
422
- // 2) 티어 설정 — compound-core는 tier 비활성화 무시
423
- if (hookTier !== 'compound-core') {
424
- const tiers = config['tiers'];
425
- if (tiers?.[hookTier]?.['enabled'] === false) return false;
426
- }
427
-
428
- // 3) 레거시 형식 (최상위 hookName.enabled)
429
- if (config[hookName]?.['enabled'] === false) return false;
430
-
431
- return true;
432
- }
433
-
434
- /**
435
- * 플러그인별 충돌 훅 목록 (plugin-detector.ts의 overlappingHooks와 동기화 필요).
436
- * 다른 플러그인이 감지되어도 이 목록에 있는 훅만 자동 비활성화.
437
- */
438
- const PLUGIN_HOOK_CONFLICTS = {
439
- 'oh-my-claudecode': ['intent-classifier', 'keyword-detector', 'skill-injector'],
440
- };
441
-
442
- /**
443
- * hooks/hooks.json을 동적으로 생성합니다.
444
- *
445
- * 동작:
446
- * 1. ~/.compound/hook-config.json 로드 (없으면 모두 활성화)
447
- * 2. detectPluginConflicts()로 다른 플러그인 존재 여부 판별
448
- * 3. 활성 훅을 이벤트별 그룹으로 변환하여 hooks.json 작성
449
- *
450
- * 설계 결정:
451
- * - compound-core 훅은 절대 자동 비활성화 안 함
452
- * - script 필드에 공백이 있으면 파일 경로와 인수로 분리
453
- * 예: "hooks/subagent-tracker.js stop" →
454
- * node "${CLAUDE_PLUGIN_ROOT}/dist/hooks/subagent-tracker.js" stop
455
- * - 다른 플러그인이 감지되어도 해당 플러그인과 실제 충돌하는 훅만 비활성
456
- * (plugin-detector.ts의 overlappingHooks와 동일한 좁은 기준)
457
- */
458
- function generateAndWriteHooksJson() {
459
- const pluginRoot = '${CLAUDE_PLUGIN_ROOT}/dist';
460
- const hooksJsonPath = join(PKG_ROOT, 'hooks', 'hooks.json');
461
-
462
- // hook-config.json 로드 (실패 시 null → 모두 기본 활성)
463
- let hookConfig = null;
464
- const hookConfigPath = join(COMPOUND_HOME, 'hook-config.json');
465
- if (existsSync(hookConfigPath)) {
466
- try { hookConfig = JSON.parse(readFileSync(hookConfigPath, 'utf-8')); } catch { /* ignore */ }
467
- }
468
-
469
- // detectPluginConflicts()는 skill→plugin Map이므로, 플러그인 집합을 추출해 훅 충돌 구성
470
- const skillConflicts = detectPluginConflicts();
471
- const hasOtherPlugins = skillConflicts.size > 0;
472
- const detectedPluginNames = new Set(skillConflicts.values());
473
- const hookConflicts = new Map();
474
- for (const [plugin, hooks] of Object.entries(PLUGIN_HOOK_CONFLICTS)) {
475
- if (detectedPluginNames.has(plugin)) {
476
- for (const h of hooks) hookConflicts.set(h, plugin);
477
- }
478
- }
479
-
480
- // 활성 훅 필터링
481
- const activeHooks = HOOK_REGISTRY.filter(hook => {
482
- // 1) hook-config.json 기반 개별/티어 비활성화
483
- if (!isHookEnabledFromConfig(hook.name, hook.tier, hookConfig)) return false;
484
-
485
- // 2) 다른 플러그인과 실제 충돌하는 workflow 훅만 비활성 (compound-critical 제외)
486
- // hooks-generator.ts의 hookConflicts.has(hook.name) 조건과 동일한 좁은 기준
487
- if (hasOtherPlugins && hook.tier === 'workflow' && hookConflicts.has(hook.name) && !hook.compoundCritical) return false;
488
-
489
- return true;
490
- });
491
-
492
- // 이벤트별 그룹핑 (registry 순서 유지)
493
- const byEvent = new Map();
494
- for (const hook of activeHooks) {
495
- if (!byEvent.has(hook.event)) byEvent.set(hook.event, []);
496
- byEvent.get(hook.event).push(hook);
497
- }
498
-
499
- // hooks.json 구조 조립 — matcher별 그룹핑 (best practice: 도구별 필터링)
500
- const hooks = {};
501
- for (const [event, entries] of byEvent) {
502
- const byMatcher = new Map();
503
- for (const h of entries) {
504
- const m = h.matcher || '*';
505
- if (!byMatcher.has(m)) byMatcher.set(m, []);
506
- byMatcher.get(m).push(h);
507
- }
508
- hooks[event] = [...byMatcher.entries()].map(([matcher, matcherEntries]) => ({
509
- matcher,
510
- hooks: matcherEntries.map(h => {
511
- const spaceIdx = h.script.indexOf(' ');
512
- let command;
513
- if (spaceIdx === -1) {
514
- command = `node "${pluginRoot}/${h.script}"`;
515
- } else {
516
- const scriptPath = h.script.slice(0, spaceIdx);
517
- const args = h.script.slice(spaceIdx + 1);
518
- command = `node "${pluginRoot}/${scriptPath}" ${args}`;
519
- }
520
- return { type: 'command', command, timeout: h.timeout };
521
- }),
522
- }));
523
- }
524
-
525
- const total = HOOK_REGISTRY.length;
526
- const active = activeHooks.length;
527
- const result = {
528
- description: `Forgen harness hooks (auto-generated, ${active}/${total} active)`,
529
- hooks,
530
- };
531
-
532
- mkdirSync(join(PKG_ROOT, 'hooks'), { recursive: true });
533
- writeFileSync(hooksJsonPath, JSON.stringify(result, null, 2) + '\n');
534
-
535
- return { active, total };
536
- }
537
-
538
- // ── 4. Install slash commands ──
539
- /** Build-time injected --with-codex shared snippet. Mirror of scripts/copy-assets.js. */
540
- const WITH_CODEX_SNIPPET = `
541
-
542
- ---
543
-
544
- ## \`--with-codex\` flag (cross-model review)
545
-
546
- If \`$ARGUMENTS\` contains any of \`--with-codex\`, \`--코덱스\`, \`with codex\`, \`코덱스 검토\`, \`코덱스로 검토\`,
547
- then after completing the primary skill work, perform a cross-model review pass:
548
-
549
- 1. Save your primary output text to a temp file (e.g., \`/tmp/forgen-with-codex-$(date +%s).md\`).
550
- 2. Invoke codex via Bash:
551
- \`\`\`bash
552
- codex exec --json --ignore-user-config --ignore-rules --ephemeral \\
553
- -s read-only -c approval_policy="never" --skip-git-repo-check \\
554
- "$(printf 'You are a second-opinion reviewer for another AI assistant\\\\u0027s output. Read the work product below and report ONLY:\\n1. Defects, gaps, or risks the original work missed\\n2. Specific disagreements with the original\\n3. Topics that should have been covered but were not\\n\\nOutput format: prioritized bullet list (max 15 items, severity-sorted, no prose intro). If you find nothing material, say "No critical issues found."\\n\\n<work>\\n%s\\n</work>' "$(cat /tmp/forgen-with-codex-*.md)")"
555
- \`\`\`
556
- 3. Append the codex output under heading \`## Codex Cross-Review (--with-codex)\` in your final response.
557
- 4. If codex flags critical issues, briefly acknowledge + suggest follow-up.
558
- 5. If \`codex: command not found\`, note in response and skip the review pass (do not fail).
559
-
560
- OPT-IN per invocation. Without the flag, skip this entire section.
561
- `;
562
-
563
- function buildCommandContent(skillContent, skillName) {
564
- const descMatch = skillContent.match(/description:\s*(.+)/);
565
- const desc = descMatch?.[1]?.trim() ?? skillName;
566
- return `# ${desc}\n\n<!-- forgen-managed -->\n\nActivate Forgen "${skillName}" mode for the task: $ARGUMENTS\n\n${skillContent}${WITH_CODEX_SNIPPET}`;
567
- }
568
-
569
- function safeWriteCommand(cmdPath, content) {
570
- if (existsSync(cmdPath)) {
571
- const existing = readFileSync(cmdPath, 'utf-8');
572
- if (!existing.includes('<!-- forgen-managed -->')) return false;
573
- }
574
- writeFileSync(cmdPath, content);
575
- return true;
576
- }
577
-
578
- function installSlashCommands() {
579
- if (!existsSync(SKILLS_DIR)) return 0;
580
- mkdirSync(COMMANDS_DIR, { recursive: true });
581
-
582
- const skills = readdirSync(SKILLS_DIR).filter((f) => f.endsWith('.md'));
583
- let installed = 0;
584
-
585
- for (const file of skills) {
586
- const skillName = file.replace('.md', '');
587
- const skillContent = readFileSync(join(SKILLS_DIR, file), 'utf-8');
588
- const cmdContent = buildCommandContent(skillContent, skillName);
589
- if (safeWriteCommand(join(COMMANDS_DIR, file), cmdContent)) {
590
- installed++;
591
- }
592
- }
593
- return installed;
594
- }
595
-
596
- // ── 3. Inject hooks into settings.json ──
597
-
598
- /** 훅 경로가 forgen dist/hooks를 가리키는지 판별 (Windows \ 와 Unix / 모두 처리) */
599
- function isForgenHook(entry) {
600
- // [\\/] 패턴으로 양쪽 구분자 모두 매칭 (harness.ts와 동일 전략)
601
- const HOOK_PATTERN = /[\\/]dist[\\/]hooks[\\/].*\.js/;
602
- const check = (cmd) => HOOK_PATTERN.test(cmd) && (cmd.includes(PKG_ROOT) || cmd.includes('forgen') || cmd.includes('tenetx'));
603
- if (typeof entry.command === 'string' && check(entry.command)) return true;
604
- if (Array.isArray(entry.hooks)) {
605
- return entry.hooks.some((h) => typeof h.command === 'string' && check(h.command));
606
- }
607
- return false;
608
- }
609
-
610
- /**
611
- * settings.json에 forgen 훅을 절대 경로로 직접 등록합니다.
612
- *
613
- * 설계 결정:
614
- * - 플러그인 hooks.json의 ${CLAUDE_PLUGIN_ROOT}는 Claude Code 버전에 따라
615
- * 해석되지 않을 수 있으므로, settings.json에 절대 경로로 직접 등록.
616
- * - PKG_ROOT는 npm i -g 시 글로벌 node_modules 경로,
617
- * npm link 시 개발 디렉토리 경로로 자동 해석.
618
- * - 기존 non-forgen 훅은 보존.
619
- */
620
- function applyHookSettings(settings) {
621
- if (!existsSync(DIST_HOOKS)) return false;
622
-
623
- // 1) 기존 forgen 훅 제거 (이전 버전 잔재 + 현재 버전 모두)
624
- const hooksConfig = settings.hooks ?? {};
625
- for (const [event, entries] of Object.entries(hooksConfig)) {
626
- if (Array.isArray(entries)) {
627
- hooksConfig[event] = entries.filter(h => !isForgenHook(h));
628
- if (hooksConfig[event].length === 0) delete hooksConfig[event];
629
- }
630
- }
631
-
632
- // 2) hook-registry.json 기반으로 활성 훅을 settings.json에 등록
633
- // registry의 script 필드는 "hooks/xxx.js" 형식 → dist/ 기준으로 join
634
- const distDir = join(PKG_ROOT, 'dist');
635
-
636
- let hookConfig = null;
637
- const hookConfigPath = join(COMPOUND_HOME, 'hook-config.json');
638
- if (existsSync(hookConfigPath)) {
639
- try { hookConfig = JSON.parse(readFileSync(hookConfigPath, 'utf-8')); } catch { /* ignore */ }
640
- }
641
-
642
- const skillConflicts = detectPluginConflicts();
643
- const detectedPluginNames = new Set(skillConflicts.values());
644
- const hookConflicts = new Map();
645
- for (const [plugin, hooks] of Object.entries(PLUGIN_HOOK_CONFLICTS)) {
646
- if (detectedPluginNames.has(plugin)) {
647
- for (const h of hooks) hookConflicts.set(h, plugin);
648
- }
649
- }
650
-
651
- const activeHooks = HOOK_REGISTRY.filter(hook => {
652
- if (!isHookEnabledFromConfig(hook.name, hook.tier, hookConfig)) return false;
653
- if (skillConflicts.size > 0 && hook.tier === 'workflow' && hookConflicts.has(hook.name) && !hook.compoundCritical) return false;
654
- return true;
655
- });
656
-
657
- // 이벤트별 그룹핑
658
- const byEvent = new Map();
659
- for (const hook of activeHooks) {
660
- if (!byEvent.has(hook.event)) byEvent.set(hook.event, []);
661
- byEvent.get(hook.event).push(hook);
662
- }
663
-
664
- // settings.json hooks 구조 조립 (절대 경로 사용)
665
- for (const [event, entries] of byEvent) {
666
- const byMatcher = new Map();
667
- for (const h of entries) {
668
- const m = h.matcher || '';
669
- if (!byMatcher.has(m)) byMatcher.set(m, []);
670
- byMatcher.get(m).push(h);
671
- }
672
-
673
- if (!hooksConfig[event]) hooksConfig[event] = [];
674
-
675
- for (const [matcher, matcherEntries] of byMatcher) {
676
- hooksConfig[event].push({
677
- matcher,
678
- hooks: matcherEntries.map(h => {
679
- const spaceIdx = h.script.indexOf(' ');
680
- let command;
681
- if (spaceIdx === -1) {
682
- command = `node "${join(distDir, h.script)}"`;
683
- } else {
684
- const scriptPath = h.script.slice(0, spaceIdx);
685
- const args = h.script.slice(spaceIdx + 1);
686
- command = `node "${join(distDir, scriptPath)}" ${args}`;
687
- }
688
- return { type: 'command', command, timeout: h.timeout };
689
- }),
690
- });
691
- }
692
- }
693
-
694
- settings.hooks = hooksConfig;
695
-
696
- // env에 COMPOUND_HARNESS 마커 설정
697
- const env = settings.env ?? {};
698
- env.COMPOUND_HARNESS = '1';
699
- settings.env = env;
700
-
701
- return true;
702
- }
703
-
704
- // ── MCP Server Registration ──
705
-
706
- /**
707
- * ~/.claude.json의 mcpServers에 forgen-compound MCP 서버를 등록합니다.
708
- *
709
- * 설계 결정 (실증 검증 완료):
710
- * - Claude Code는 settings.json의 mcpServers를 읽지 않음
711
- * - MCP 서버는 반드시 ~/.claude.json에 등록해야 Claude Code가 인식
712
- * - context7 등 동작하는 MCP 서버와 동일한 등록 경로
713
- * - npm bin 경로(forgen-mcp) 우선, 없으면 node + 절대 경로 fallback
714
- */
715
- function applyMcpToClaudeJson() {
716
- const mcpServerPath = join(PKG_ROOT, 'dist', 'mcp', 'server.js');
717
- if (!existsSync(mcpServerPath)) return false;
718
-
719
- // W-V3: 항상 node + 절대경로 사용 — PATH 변경/nvm 전환에도 안정적
720
- const mcpCommand = 'node';
721
- const mcpArgs = [mcpServerPath];
722
-
723
- const claudeJsonPath = join(HOME, '.claude.json');
724
- let claudeJson = {};
725
- if (existsSync(claudeJsonPath)) {
726
- try {
727
- claudeJson = JSON.parse(readFileSync(claudeJsonPath, 'utf-8'));
728
- } catch (e) {
729
- // Audit fix #10 (2026-04-21): silent parse-failure used to let the
730
- // merged write below overwrite the user's malformed-but-original
731
- // ~/.claude.json, wiping all their other plugin configs. Preserve
732
- // and skip instead.
733
- const corruptPath = `${claudeJsonPath}.corrupt-${Date.now()}`;
734
- try { copyFileSync(claudeJsonPath, corruptPath); } catch { /* best-effort */ }
735
- console.error(
736
- `[forgen] ${claudeJsonPath} failed to parse; preserved at ${corruptPath}. ` +
737
- `Skipping MCP registration.`,
738
- );
739
- return false;
740
- }
741
- }
742
-
743
- const mcpServers = claudeJson.mcpServers ?? {};
744
- mcpServers['forgen-compound'] = {
745
- command: mcpCommand,
746
- args: mcpArgs,
747
- };
748
- claudeJson.mcpServers = mcpServers;
749
-
750
- // Atomic write — tmp file + rename so a partial write never leaves
751
- // ~/.claude.json in a torn state for any concurrent reader.
752
- const tmpPath = `${claudeJsonPath}.tmp.${process.pid}`;
753
- writeFileSync(tmpPath, JSON.stringify(claudeJson, null, 2));
754
- renameSync(tmpPath, claudeJsonPath);
755
- fixOwnership(claudeJsonPath);
756
- return true;
757
- }
758
-
759
- /** settings.json에서 레거시 mcpServers 항목 정리 (더 이상 사용하지 않음) */
760
- function cleanLegacyMcpFromSettings(settings) {
761
- if (settings.mcpServers?.['forgen-compound']) {
762
- delete settings.mcpServers['forgen-compound'];
763
- if (Object.keys(settings.mcpServers).length === 0) {
764
- delete settings.mcpServers;
765
- }
766
- }
767
- }
768
-
769
- /**
770
- * dev-guide 스킬 14개 자동 설치 — assets/dev-guide/{fe,be}/skills/{stack}/{skill}/SKILL.md
771
- * → ~/.claude/skills/forgen-<stack>-<skill>/SKILL.md
772
- *
773
- * forgen- prefix 로 사용자 own skills 와 격리. idempotent 재실행 시 forgen-* 만 정리 후 재설치.
774
- */
775
176
  /**
776
177
  * forgen 이 설치한 dev-guide 스킬만 정리한다 (src/host/managed-marker.ts 의 removeOwnedDevGuideSkills 와 같은 규칙).
777
178
  *
@@ -838,45 +239,6 @@ function installSkillFile(src, skillsDir, name) {
838
239
  }
839
240
  }
840
241
 
841
- function installDevGuideSkills(home) {
842
- const devGuideRoot = join(PKG_ROOT, 'assets', 'dev-guide');
843
- if (!existsSync(devGuideRoot)) {
844
- console.log('[forgen] dev-guide assets not found — skipping skill install');
845
- return 0;
846
- }
847
-
848
- const userSkillsDir = join(home, '.claude', 'skills');
849
- mkdirSync(userSkillsDir, { recursive: true });
850
-
851
- // 1. forgen 이 설치한 dev-guide 스킬 정리 (사용자가 만든 forgen-* 스킬은 보존)
852
- const removed = removeOwnedDevGuideSkills(userSkillsDir, devGuideRoot);
853
-
854
- // 2. assets/dev-guide/{side}/skills/{stack}/{skill}/SKILL.md 수집
855
- let installed = 0;
856
- for (const side of ['fe', 'be']) {
857
- const sideSkillsDir = join(devGuideRoot, side, 'skills');
858
- if (!existsSync(sideSkillsDir)) continue;
859
- for (const stack of readdirSync(sideSkillsDir)) {
860
- const stackDir = join(sideSkillsDir, stack);
861
- if (!statSync(stackDir).isDirectory()) continue;
862
- for (const skill of readdirSync(stackDir)) {
863
- const skillSrc = join(stackDir, skill);
864
- const skillFile = join(skillSrc, 'SKILL.md');
865
- if (!existsSync(skillFile)) continue;
866
-
867
- // 대상: ~/.claude/skills/forgen-<stack>-<skill>/SKILL.md (이미 있는 사용자 것은 덮어쓰지 않는다)
868
- if (installSkillFile(skillFile, userSkillsDir, `forgen-${stack}-${skill}`)) installed++;
869
- }
870
- }
871
- }
872
-
873
- // 3. sudo 케이스 ownership 회복
874
- fixOwnership(userSkillsDir);
875
-
876
- console.log(`[forgen] dev-guide skills: ${installed} installed${removed > 0 ? ` (${removed} stale removed)` : ''}`);
877
- return installed;
878
- }
879
-
880
242
  /**
881
243
  * v0.4.9: dev-guide 14 skills → ~/.codex/skills/forgen-<stack>-<skill>/SKILL.md
882
244
  * forgen 자체 commands(forgen-compound 등) 와 prefix 겹치지 않도록
@@ -922,111 +284,57 @@ function installDevGuideSkillsToCodex(home) {
922
284
  // ── Main ──
923
285
 
924
286
  /**
925
- * settings.json을 한 번 읽고, 모든 변경을 적용한 후, 한 번만 씁니다.
926
- * 이전 방식(3곳에서 각각 read-modify-write)은 중간에 다른 프로세스가
927
- * settings.json을 수정하면 데이터 유실 가능성이 있었습니다.
287
+ * 한 번에 설치 완료: Claude(hook·MCP·statusLine·commands·skills·verify·agents)는 dist 의 planClaudeInstall 을 호출해
288
+ * `forgen install claude` 와 같은 경로를 쓴다. hook/MCP/statusLine 은 고정 shim(~/.forgen/bin/forgen-run)만 가리키므로
289
+ * Node 전환·재설치 때 settings 는 바뀌지 않는다. 어떤 단계가 실패해도 npm install 은 성공으로 끝내되 사유를 출력한다.
928
290
  */
929
291
  async function main() {
930
- // W-V2: 로컬 설치 시 전역 설정 수정 방지
931
- if (!process.env.npm_config_global && process.env.INIT_CWD && process.env.INIT_CWD !== PKG_ROOT) {
932
- // npm install (로컬) — postinstall 스킵
292
+ if (process.env.FORGEN_SKIP_POSTINSTALL === '1') return;
293
+ // 저장소 체크아웃에서 `npm install` 하면 INIT_CWD 가 PKG_ROOT 와 같아진다. 개발자 실제 홈을 바꾸면 안 된다.
294
+ if (existsSync(join(PKG_ROOT, '.git')) && process.env.FORGEN_FORCE_POSTINSTALL !== '1') {
295
+ console.log('[forgen] 저장소 체크아웃이라 사용자 설정을 건드리지 않습니다. 설치하려면: forgen install claude');
933
296
  return;
934
297
  }
935
- migrateLegacyStorage();
936
- ensureDirectories();
937
-
938
- // ── 0. 기존 forgen entry 감지 (마이그레이션 모드 분기) ──
939
- //
940
- // feat/codex-support (P1-6, 2026-04-27): postinstall 이 호스트 인젝션을 *자동*
941
- // 으로 하던 v0.4.x 동작을 변경. 새로운 정책:
942
- // - 기존 사용자 (settings.json 에 forgen hook entry 있음): 그대로 갱신 (행동
943
- // 변화 없음 — 마이그레이션 안전). default_host 자동 설정 안내 banner 출력.
944
- // - 신규 사용자 (forgen entry 없음): host 인젝션 자동 안 함. "Run `forgen
945
- // install`" banner 만 출력. 사용자가 어느 host (Claude/Codex/Both) 에 등록할지
946
- // 명시 선택.
947
- //
948
- // 사용자 의도와 무관한 Claude bias (postinstall 이 ~/.claude/ 자동 인젝션) 제거.
949
- let isExistingForgenUser = false;
950
- if (existsSync(SETTINGS_PATH)) {
951
- try {
952
- const probe = JSON.parse(readFileSync(SETTINGS_PATH, 'utf-8'));
953
- const hooks = probe?.hooks ?? {};
954
- for (const arr of Object.values(hooks)) {
955
- if (!Array.isArray(arr)) continue;
956
- for (const grp of arr) {
957
- if (!grp?.hooks) continue;
958
- for (const h of grp.hooks) {
959
- const cmd = typeof h?.command === 'string' ? h.command : '';
960
- // P1-6b detection: forgen hook command path 식별. cross-platform (POSIX + Windows)
961
- // 및 다양한 install 위치 (npm global, plugin cache, dev) 커버.
962
- if (
963
- cmd.includes('CLAUDE_PLUGIN_ROOT') ||
964
- cmd.includes('/forgen-local/forgen/') ||
965
- cmd.includes('\\forgen-local\\forgen\\') ||
966
- cmd.includes('/forgen/dist/hooks/') ||
967
- cmd.includes('\\forgen\\dist\\hooks\\') ||
968
- cmd.includes('/@wooojin/forgen/') ||
969
- cmd.includes('\\@wooojin\\forgen\\')
970
- ) {
971
- isExistingForgenUser = true;
972
- }
973
- }
974
- if (isExistingForgenUser) break;
975
- }
976
- if (isExistingForgenUser) break;
977
- }
978
- } catch { /* settings.json 손상 시 fall-through, 단계 1 의 corrupt handling 이 처리 */ }
298
+ // pnpm·yarn 전역 설치는 npm_config_global 이 없다. 패키지 위치로 판별한다.
299
+ const globalByPath = /[\\/](pnpm[\\/]global|\.pnpm-global|yarn[\\/]global|\.config[\\/]yarn[\\/]global)[\\/]/.test(PKG_ROOT);
300
+ // W-V2: 프로젝트 의존성으로 설치할 때는 사용자 홈에 hook 을 심지 않는다.
301
+ if (!process.env.npm_config_global && !globalByPath && process.env.INIT_CWD && process.env.INIT_CWD !== PKG_ROOT) {
302
+ console.log('[forgen] 프로젝트 의존성으로 설치되어 hook 을 등록하지 않았습니다. 등록하려면: npx forgen install claude');
303
+ return;
979
304
  }
305
+ const problems = [];
306
+ const attempt = (label, fn) => {
307
+ try { return fn(); } catch (err) { problems.push(`${label}: ${err?.message ?? err}`); return undefined; }
308
+ };
980
309
 
981
- // ── 1. settings.json 한 번 읽기 ──
982
- //
983
- // Audit finding #2/#10 (2026-04-21): prior `catch { settings = {} }`
984
- // silently swallowed parse failures and let the merged write below
985
- // clobber the user's malformed-but-original settings.json — a data
986
- // loss path triggered by any partial edit or external corruption.
987
- // Now: preserve the corrupt file as `.corrupt-<ts>`, abort the
988
- // settings write (and subsequent MCP registration + ownership fix
989
- // that also touches ~/.claude.json), surface the warning via npm's
990
- // postinstall output. The outer try/catch at the bottom ensures
991
- // `npm install` still succeeds; only the settings mutation is
992
- // skipped.
993
- let settings = {};
994
- if (existsSync(SETTINGS_PATH)) {
995
- try {
996
- settings = JSON.parse(readFileSync(SETTINGS_PATH, 'utf-8'));
997
- } catch (e) {
998
- const corruptPath = `${SETTINGS_PATH}.corrupt-${Date.now()}`;
999
- try { copyFileSync(SETTINGS_PATH, corruptPath); } catch { /* best-effort */ }
1000
- throw new Error(
1001
- `[forgen] ${SETTINGS_PATH} failed to parse: ${e?.message ?? e}. ` +
1002
- `Preserved corrupt copy at ${corruptPath}. Skipping settings injection to avoid data loss.`,
1003
- );
1004
- }
310
+ // Node 엔진 미달 경고 (설치는 막지 않는다)
311
+ if (Number(process.versions.node.split('.')[0]) < MIN_NODE_MAJOR) {
312
+ console.error(`[forgen] WARNING: Node ${process.versions.node} is below the supported range (>=${MIN_NODE_MAJOR}). Some features may fail; use: nvm install ${MIN_NODE_MAJOR} && nvm use ${MIN_NODE_MAJOR}`);
1005
313
  }
1006
314
 
1007
- // ── 2. 플러그인 등록 (installed_plugins.json + skills) ──
1008
- // P1-6b (옵션 Y): 신규 사용자에게는 자동 install 안 함. 기존 forgen 사용자만 갱신.
1009
- // 사용자 host 선택 권한 보장 (1원칙 = Claude bias 제거).
1010
- let plugin = false;
1011
- if (isExistingForgenUser) {
1012
- try {
1013
- plugin = registerPlugin();
1014
- if (plugin) applyPluginSettings(settings);
1015
- } catch (err) {
1016
- console.error(`[forgen] plugin registration failed: ${err?.message ?? err}`);
1017
- }
315
+ attempt('legacy storage migration', migrateLegacyStorage);
316
+ attempt('directories', ensureDirectories);
317
+
318
+ // ── Claude: 단일 설치 경로 ──
319
+ let claude = null;
320
+ try {
321
+ const mod = await import(join(PKG_ROOT, 'dist', 'host', 'install-claude.js'));
322
+ claude = mod.planClaudeInstall({ pkgRoot: PKG_ROOT, homeDir: HOME });
323
+ for (const e of claude.errors) problems.push(e);
324
+ } catch (err) {
325
+ problems.push(`claude install: ${err?.message ?? err} (is dist/ built?)`);
1018
326
  }
1019
327
 
1020
- // ── 2.4. Codex 훅 shim 갱신 — 이미 쓰고 있으면 새 node/패키지 경로로 내용만 재작성(hooks.json 불변 → trust 유지) ──
328
+ // ── Codex 훅 shim 갱신 — 이미 쓰고 있으면 새 node/패키지 경로로 내용만 재작성(hooks.json 불변 → trust 유지) ──
1021
329
  try {
1022
330
  const shimMod = await import(join(PKG_ROOT, 'dist', 'host', 'codex-hook-shim.js'));
1023
- const shimFile = shimMod.codexHookShimPath(process.env.CODEX_HOME || join(HOME, '.codex'));
331
+ const codexHome = process.env.CODEX_HOME || join(HOME, '.codex');
332
+ const shimFile = shimMod.codexHookShimPath(codexHome);
1024
333
  if (existsSync(shimFile)) {
1025
334
  const r = shimMod.writeCodexHookShim(PKG_ROOT, process.execPath, shimFile);
1026
335
  if (r === 'written') console.log('[forgen] Codex hook shim updated → no /hooks re-trust needed.');
1027
336
  } else {
1028
337
  // 이전 형식(node + 절대경로) forgen 훅 → shim 형식으로 자동 전환 (forgen 훅 명령만, 순서·사용자 훅 보존).
1029
- const codexHome = process.env.CODEX_HOME || join(HOME, '.codex');
1030
338
  const r = shimMod.migrateCodexHooksToShim(codexHome, PKG_ROOT, process.execPath);
1031
339
  if (r.status === 'migrated') {
1032
340
  console.log(`[forgen] Codex: ${r.rewritten} forgen hooks switched to a stable shim (backup: hooks.json.bak-pre-shim).`);
@@ -1035,7 +343,7 @@ async function main() {
1035
343
  }
1036
344
  } catch { /* dist 없음(dev) 또는 실패 — 다음 forgen install codex 가 처리 */ }
1037
345
 
1038
- // ── 2.4b. Stop 룰 발동 조건 재조정 1회 마이그레이션 (2026-10-07, v0.6.7~) ──
346
+ // ── Stop 룰 발동 조건 재조정 1회 마이그레이션 (2026-10-07, v0.6.7~) ──
1039
347
  // 룰별 발동 조건·critic 실행 증거 판정은 룰 파일에 구워져 있어 업그레이드만으론 반영되지 않는다.
1040
348
  // 사용자 룰만 대상(프로젝트 룰은 git 소스라 건드리지 않음). 마커로 1회만.
1041
349
  try {
@@ -1053,185 +361,54 @@ async function main() {
1053
361
  }
1054
362
  } catch (err) { console.error(`[forgen] Stop rule retune skipped: ${err?.message ?? err}`); }
1055
363
 
1056
- // ── 2.5. statusLine 자동 등록 (settings 단일 쓰기에 포함) ──
1057
- let statusLineResult = 'unchanged';
1058
- try { statusLineResult = applyStatusLineAuto(settings); } catch (err) { console.error(`[forgen] statusLine setup skipped: ${err?.message ?? err}`); }
1059
-
1060
- // ── 3. hooks.json 동적 생성 ──
1061
- //
1062
- // A4 guard (2026-04-09): skip regeneration when running inside the
1063
- // forgen source tree itself. Pre-A4 fix, every `npm install` /
1064
- // `npm audit fix` run from the dev checkout clobbered the package's
1065
- // own committed `hooks/hooks.json` with a file reflecting the
1066
- // developer's LOCAL plugin state (which usually has `oh-my-claudecode`
1067
- // or similar installed for testing). That 17/19-active file then
1068
- // shipped in the next npm tarball and broke keyword-detector for
1069
- // every user whose postinstall didn't complete (sudo issues,
1070
- // read-only FS, etc.). The checked-in file should always be the
1071
- // pristine 19/19 baseline; per-user plugin conflict resolution is
1072
- // handled at runtime via `forgen config hooks`. Detect "we're in the
1073
- // source tree" via the presence of a sibling `.git/` directory next
1074
- // to the package root — a regular npm install never has that.
1075
- let hooksJsonResult = null;
1076
- const isSourceCheckout = existsSync(join(PKG_ROOT, '.git'));
1077
- if (isSourceCheckout) {
1078
- // no-op in dev: leave the committed file untouched
1079
- } else {
1080
- try {
1081
- hooksJsonResult = generateAndWriteHooksJson();
1082
- } catch (err) {
1083
- console.error(`[forgen] hooks.json generation failed: ${err?.message ?? err}`);
1084
- }
1085
- }
1086
-
1087
- // ── 4. 슬래시 커맨드 설치 ── (기존 사용자만)
1088
- let commands = 0;
1089
- if (isExistingForgenUser) {
1090
- try {
1091
- commands = installSlashCommands();
1092
- } catch (err) {
1093
- console.error(`[forgen] slash commands failed: ${err?.message ?? err}`);
1094
- }
1095
- }
1096
-
1097
- // ── 5. settings에 훅 설정 적용 ── (기존 사용자만)
1098
- let hooks = false;
1099
- if (isExistingForgenUser) {
1100
- try {
1101
- hooks = applyHookSettings(settings);
1102
- } catch (err) {
1103
- console.error(`[forgen] hooks settings failed: ${err?.message ?? err}`);
1104
- }
1105
- }
1106
-
1107
- // ── 6. MCP 서버 ~/.claude.json 등록 ── (기존 사용자만)
1108
- let mcp = false;
1109
- if (isExistingForgenUser) {
1110
- try {
1111
- mcp = applyMcpToClaudeJson();
1112
- cleanLegacyMcpFromSettings(settings);
1113
- } catch (err) {
1114
- console.error(`[forgen] MCP server registration failed: ${err?.message ?? err}`);
1115
- }
1116
- }
1117
-
1118
- // ── 7. settings.json 한 번 쓰기 (atomic) ──
1119
- //
1120
- // Audit fix #10 (2026-04-21): prior direct writeFileSync could leave
1121
- // settings.json truncated / partially-written if the process was
1122
- // interrupted (sudo shell SIGINT, npm exit). Tmp + rename is atomic
1123
- // on POSIX within the same directory. Lock is NOT acquired here —
1124
- // postinstall is serialized by npm and we don't want to introduce a
1125
- // cross-module dependency from a build-time script.
1126
- try {
1127
- mkdirSync(dirname(SETTINGS_PATH), { recursive: true });
1128
- const tmpPath = `${SETTINGS_PATH}.tmp.${process.pid}`;
1129
- writeFileSync(tmpPath, JSON.stringify(settings, null, 2));
1130
- renameSync(tmpPath, SETTINGS_PATH);
1131
- } catch (err) {
1132
- console.error(`[forgen] settings.json write failed: ${err?.message ?? err}`);
1133
- }
1134
-
1135
- // ── 8. Starter Knowledge Pack 설치 (솔루션 < 5개일 때만) ──
1136
- let starterInstalled = 0;
1137
- try {
1138
- starterInstalled = installStarterPack();
1139
- } catch (err) {
1140
- console.error(`[forgen] starter pack failed: ${err?.message ?? err}`);
1141
- }
1142
-
1143
- // ── 8b. dev-guide 스킬 자동 설치 (claude) ──
1144
- try {
1145
- installDevGuideSkills(HOME);
1146
- } catch (e) {
1147
- // postinstall 의 "fail-open" 원칙 — npm install 깨뜨리지 않음
1148
- console.log(`[forgen] dev-guide skills 설치 스킵 (${e?.message ?? e})`);
1149
- }
364
+ // ── Starter Knowledge Pack (솔루션 < 5개일 때만) ──
365
+ const starterInstalled = attempt('starter pack', installStarterPack) ?? 0;
1150
366
 
1151
- // ── 8c. dev-guide 스킬 자동 설치 (codex) ──
1152
- try {
1153
- installDevGuideSkillsToCodex(HOME);
1154
- } catch (e) {
1155
- console.log(`[forgen] codex dev-guide skills 설치 스킵 (${e?.message ?? e})`);
1156
- }
367
+ // ── dev-guide 스킬 (codex) ──
368
+ attempt('codex dev-guide skills', () => installDevGuideSkillsToCodex(HOME));
1157
369
 
1158
370
  // sudo 실행 시 파일 소유권을 실제 유저로 변경
1159
- fixOwnership(join(HOME, '.claude'), join(HOME, '.forgen'));
371
+ fixOwnership(join(HOME, '.claude'), join(HOME, '.forgen'), join(HOME, '.claude.json'));
1160
372
 
1161
- // ── 9. Self-check: 설치 산출물이 현재 Node 에서 실제로 로드되는지 확인 ──
1162
- //
1163
- // Why: 0.4.4 이전 빌드는 `import ... with { type: 'json' }` 를 사용해 Node
1164
- // 20.0-20.9 에서 모든 훅이 SyntaxError 로 깨졌다. 사용자는 npm i -g 가 정상
1165
- // 종료된 직후에야 "각종 훅들이 에러난다"는 증상을 보았다. self-check 가 있었
1166
- // 다면 install 시점에 즉시 실패를 노출했을 것.
1167
- //
1168
- // 동작: dist/hooks/hook-registry.js 를 dynamic import 로 로드 → HOOK_REGISTRY
1169
- // 배열에 entry 가 있는지 확인. 실패 시 stderr 로 구체적 원인 + Node 버전을
1170
- // 알리고 npm install 자체는 깨뜨리지 않음 (postinstall 정책 유지).
1171
- let selfCheckOk = false;
373
+ // ── Self-check: 설치 산출물이 현재 Node 에서 실제로 로드되는지 확인 ──
374
+ // 0.4.4 이전 빌드는 Node 20.0-20.9 에서 모든 훅이 SyntaxError 로 깨졌다. 설치 직후에 노출하기 위한 점검.
1172
375
  let selfCheckErr = '';
1173
376
  try {
1174
- const registryUrl = new URL('../dist/hooks/hook-registry.js', import.meta.url);
1175
- const mod = await import(registryUrl.href);
1176
- if (Array.isArray(mod?.HOOK_REGISTRY) && mod.HOOK_REGISTRY.length > 0) {
1177
- selfCheckOk = true;
1178
- } else {
1179
- selfCheckErr = 'HOOK_REGISTRY is empty or not an array';
1180
- }
377
+ const mod = await import(new URL('../dist/hooks/hook-registry.js', import.meta.url).href);
378
+ if (!Array.isArray(mod?.HOOK_REGISTRY) || mod.HOOK_REGISTRY.length === 0) selfCheckErr = 'HOOK_REGISTRY is empty or not an array';
1181
379
  } catch (err) {
1182
380
  selfCheckErr = err?.message ?? String(err);
1183
381
  }
1184
- if (!selfCheckOk) {
1185
- console.error('');
1186
- console.error(`[forgen] WARNING: hook self-check FAILED on Node ${process.version}.`);
1187
- console.error(`[forgen] reason: ${selfCheckErr}`);
1188
- console.error('[forgen] 훅이 Claude Code 실행 시 로드 실패할 수 있습니다.');
1189
- console.error('[forgen] Node 20.10+ 또는 22.x 사용을 권장합니다.');
1190
- console.error('[forgen] 문제 지속 시: https://github.com/forgen-team/forgen/issues');
1191
- console.error('');
1192
- }
1193
-
1194
- const parts = [];
1195
- if (plugin) parts.push('plugin');
1196
- if (hooksJsonResult) parts.push(`hooks.json (${hooksJsonResult.active}/${hooksJsonResult.total} active)`);
1197
- if (commands > 0) parts.push(`${commands} slash commands`);
1198
- if (hooks) parts.push('hooks');
1199
- if (mcp) parts.push('MCP compound');
1200
- if (starterInstalled > 0) parts.push(`${starterInstalled} starter solutions`);
1201
- if (parts.length > 0) {
382
+ if (selfCheckErr) problems.push(`hook self-check failed on Node ${process.version}: ${selfCheckErr}`);
383
+
384
+ // ── 요약 ──
385
+ if (claude) {
386
+ const parts = [
387
+ claude.shimPath ? `shim ${claude.shimPath}` : 'absolute-path hooks (no shim)',
388
+ `${claude.hooksInjected} hooks`,
389
+ claude.mcpAlreadyPresent || claude.mcpRegistered ? 'MCP' : null,
390
+ `statusLine ${claude.statusLine}`,
391
+ `${claude.slashCommandsCount} commands`,
392
+ `${claude.skillsInstalled} skills`,
393
+ `verify ${claude.verifySkill}`,
394
+ `${claude.agentsInstalled} agents`,
395
+ starterInstalled > 0 ? `${starterInstalled} starter solutions` : null,
396
+ ].filter(Boolean);
1202
397
  console.log(`[forgen] Installed: ${parts.join(', ')} → ${HOME}`);
398
+ if (claude.statusLine === 'custom') {
399
+ console.log('[forgen] statusLine is set to another command (e.g. claude-hud) — left untouched.');
400
+ console.log('[forgen] To switch to forgen (backup kept in statusLine_backup): forgen statusline install --force');
401
+ console.log('[forgen] To keep it AND show forgen\'s line after it (chain, original kept in statusLine_backup): forgen statusline install --chain');
402
+ }
1203
403
  }
1204
- if (statusLineResult === 'installed' || statusLineResult === 'updated') {
1205
- console.log('[forgen] statusLine registered (absolute path) — running sessions pick it up on the next message.');
1206
- } else if (statusLineResult === 'custom') {
1207
- console.log('[forgen] statusLine is set to another command (e.g. claude-hud) — left untouched.');
1208
- console.log('[forgen] To switch to forgen (backup kept in statusLine_backup): forgen statusline install --force');
1209
- console.log('[forgen] To keep it AND show forgen\'s line after it (chain, original kept in statusLine_backup): forgen statusline install --chain');
1210
- }
1211
-
1212
- // First-run banner (신규 사용자 안내) — feat/codex-support P1-6
1213
- if (!isExistingForgenUser) {
1214
- console.log('');
1215
- console.log(' ╭─ forgen — setup checklist ────────────────────────────────╮');
1216
- console.log(' │ │');
1217
- console.log(' │ 1. Register on a host: │');
1218
- console.log(' │ $ forgen install claude (or codex / both) │');
1219
- console.log(' │ │');
1220
- console.log(' │ 2. Complete onboarding (4 questions): │');
1221
- console.log(' │ $ forgen │');
1222
- console.log(' │ │');
1223
- console.log(' │ 3. Verify setup: │');
1224
- console.log(' │ $ forgen doctor --quick │');
1225
- console.log(' │ │');
1226
- console.log(' ╰────────────────────────────────────────────────────────────╯');
1227
- console.log('');
404
+ if (problems.length > 0) {
405
+ console.error('');
406
+ console.error('[forgen] Setup was incomplete — the package itself is installed:');
407
+ for (const p of problems) console.error(`[forgen] - ${p}`);
408
+ console.error('[forgen] Retry after fixing the cause: forgen install claude');
409
+ console.error('');
1228
410
  } else {
1229
- // 기존 사용자: default_host 안내
1230
- console.log('');
1231
- console.log(' [forgen] Multi-host support added. Existing forgen entry preserved.');
1232
- console.log(' Optional: `forgen config default-host {claude|codex|ask}` to set fgx default.');
1233
- console.log(' Optional: `forgen install codex` to register on Codex too.');
1234
- console.log('');
411
+ console.log('[forgen] Next: run `forgen` to finish onboarding, then `forgen doctor --quick`. Codex: `forgen install codex`.');
1235
412
  }
1236
413
  }
1237
414