@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
@@ -1,105 +1,101 @@
1
1
  /**
2
- * Claude InstallPlan — feat/codex-support Phase 1 (P1-2)
2
+ * Claude InstallPlan — `forgen install claude` 와 npm postinstall 이 공유하는 단일 설치 경로 (D1 설치 일원화).
3
3
  *
4
- * `npm install` postinstall.js 의 *Claude 측* 5 작업을 module 로 분리.
5
- * `forgen install claude` CLI 가 호출 + (P1-6 에서) postinstall.js 도 위임.
4
+ * 작업:
5
+ * 1. 고정 shim: <FORGEN_HOME>/bin/forgen-run 작성 (node·패키지 경로는 shim 내용에만)
6
+ * 2. Slash commands: ~/.claude/commands/forgen/*.md (forgen-managed marker)
7
+ * 3. settings.json: hook 전체 + statusLine 을 shim 경유로. 사용자 hook·statusLine 보존, 멱등, 구형 절대경로 교체,
8
+ * 래퍼가 남긴 FORGEN_* env 와 forgen@forgen-local 플러그인 잔재 정리
9
+ * 4. MCP: ~/.claude.json mcpServers.forgen-compound (shim 경유)
10
+ * 5. Dev-guide skills, verify skill, 전역 ch-* agents (~/.claude/agents, forgen 표식 있는 파일만 관리)
6
11
  *
7
- * 5 작업:
8
- * 1. Plugin cache: ~/.claude/plugins/cache/forgen-local/forgen/<ver>/ 작성 + installed_plugins.json 등록
9
- * 2. Slash commands: ~/.claude/commands/forgen/*.md 생성 (forgen-managed marker)
10
- * 3. Settings hooks injection: ~/.claude/settings.json 의 hooks 머지 (forgen entry idempotent)
11
- * 4. MCP register: ~/.claude.json 에 mcpServers.forgen-compound 추가
12
- * 5. Dev-guide skills: ~/.claude/skills/forgen-<stack>-<skill>/ 설치 (forgen-managed only)
13
- * 6. verify skill: ~/.claude/skills/verify/ 설치 (ADR-016 D3 — 사용자 소유면 보존)
14
- *
15
- * 사용자 비-forgen 자산 보존 + 재실행 idempotent.
12
+ * 플러그인 등록(캐시·installed_plugins·enabledPlugins)은 만들지 않는다 — 마켓플레이스가 없어 로드 실패하고 hook 만 겹쳤다.
13
+ * shim 을 못 쓰는 환경(Windows)은 기존 절대경로 유지. 한 단계가 실패해도 나머지는 진행하고 사유를 errors 로 돌려준다.
16
14
  */
17
15
  import * as fs from 'node:fs';
18
16
  import * as os from 'node:os';
19
17
  import * as path from 'node:path';
20
18
  import { generateHooksJson } from '../hooks/hooks-generator.js';
19
+ import { applyStatusLineAuto, forgenStatuslineCommand } from '../core/statusline-install.js';
20
+ import { ensureForgenRunShim, forgenRunShimPath, isForgenRunCommand, shimSupported } from './claude-shim.js';
21
21
  import { hasManagedSkillMarker, installSkillFile, removeOwnedDevGuideSkills } from './managed-marker.js';
22
+ import { refreshCronAfterUpgrade } from '../core/compound-sweep-cli.js';
23
+ import { HOOK_REGISTRY } from '../hooks/hook-registry.js';
24
+ import { FileLockError, withFileLockSync } from '../hooks/shared/file-lock.js';
22
25
  const PLUGIN_KEY = 'forgen@forgen-local';
23
26
  const FORGEN_MANAGED_MARKER = '<!-- forgen-managed -->';
24
- function readPkgVersion(pkgRoot) {
25
- try {
26
- const pkg = JSON.parse(fs.readFileSync(path.join(pkgRoot, 'package.json'), 'utf-8'));
27
- return pkg.version ?? '0.0.0';
28
- }
29
- catch {
30
- return '0.0.0';
31
- }
27
+ /** 래퍼가 과거에 settings.env 에 써 넣던 키. 이제는 자식 프로세스 env 로만 넘긴다. */
28
+ const LEGACY_WRAPPER_ENV_KEYS = ['FORGEN_HARNESS', 'FORGEN_CWD', 'FORGEN_V1', 'FORGEN_RUNTIME', 'FORGEN_SESSION_ID', 'COMPOUND_HARNESS', 'COMPOUND_CWD'];
29
+ function errMsg(e) {
30
+ return e instanceof Error ? e.message : String(e);
32
31
  }
33
- // ── 1. Plugin cache ────────────────────────────────────────────────────
34
- function writePluginCache(opts) {
35
- const { pkgRoot, cacheDir, pluginsDir, version, dryRun } = opts;
36
- if (dryRun)
37
- return false;
38
- const cacheParent = path.dirname(cacheDir);
39
- // 이전 잔재 제거 + 디렉토리 작성
32
+ /** JSON 객체 파일 읽기. 없으면 {}, 파싱 실패면 `.corrupt-<ts>` 로 보존하고 throw — 덮어써서 사용자 설정을 잃지 않는다. */
33
+ function readJsonObject(file) {
34
+ if (!fs.existsSync(file))
35
+ return {};
36
+ const raw = fs.readFileSync(file, 'utf-8');
40
37
  try {
41
- fs.rmSync(cacheParent, { recursive: true, force: true });
42
- }
43
- catch { /* ignore */ }
44
- fs.mkdirSync(cacheParent, { recursive: true });
45
- // 1차: symlink 시도 (개발 환경)
46
- // Why warn on fallback: Windows 비관리자 / macOS SIP 환경에서 symlink 가 EPERM
47
- // 으로 거부되면 조용히 cpSync 폴백을 탔는데, 사용자는 "왜 install 이 느리지"
48
- // 를 알 길이 없었다. 폴백 진입을 stderr 로 알려서 진단성 확보.
49
- let linked = false;
50
- let symlinkErr = null;
51
- try {
52
- fs.symlinkSync(pkgRoot, cacheDir, 'dir');
53
- linked = true;
38
+ const parsed = JSON.parse(raw);
39
+ if (parsed && typeof parsed === 'object' && !Array.isArray(parsed))
40
+ return parsed;
41
+ throw new Error('not a JSON object');
54
42
  }
55
43
  catch (e) {
56
- symlinkErr = e;
57
- }
58
- if (!linked && symlinkErr) {
59
- const code = symlinkErr.code ?? 'UNKNOWN';
60
- process.stderr.write(`[forgen] symlink ${pkgRoot} → ${cacheDir} failed (${code}); falling back to cpSync.\n`);
61
- }
62
- if (!linked) {
63
- fs.mkdirSync(cacheDir, { recursive: true });
64
- const copyDirs = ['.claude-plugin', 'hooks', 'skills', 'assets'];
65
- for (const dir of copyDirs) {
66
- const src = path.join(pkgRoot, dir);
67
- if (fs.existsSync(src))
68
- fs.cpSync(src, path.join(cacheDir, dir), { recursive: true });
44
+ const corrupt = `${file}.corrupt-${Date.now()}`;
45
+ try {
46
+ fs.copyFileSync(file, corrupt);
69
47
  }
70
- if (fs.existsSync(path.join(pkgRoot, 'dist'))) {
71
- fs.cpSync(path.join(pkgRoot, 'dist'), path.join(cacheDir, 'dist'), { recursive: true });
48
+ catch { /* best-effort */ }
49
+ throw new Error(`${file} failed to parse (${errMsg(e)}); left untouched, copy at ${corrupt}`);
50
+ }
51
+ }
52
+ /** 내용이 바뀐 경우에만 원자적으로 쓴다(tmp+rename). 바뀌지 않으면 파일을 건드리지 않는다. */
53
+ function writeJsonIfChanged(file, before, data) {
54
+ if (JSON.stringify(data) === before)
55
+ return false;
56
+ // 사용자가 읽기 전용으로 잠근 파일은 rename 으로 몰래 교체하지 않는다
57
+ if (fs.existsSync(file)) {
58
+ try {
59
+ fs.accessSync(file, fs.constants.W_OK);
72
60
  }
73
- // core deps
74
- const coreDeps = ['js-yaml', '@modelcontextprotocol', 'zod'];
75
- fs.mkdirSync(path.join(cacheDir, 'node_modules'), { recursive: true });
76
- for (const dep of coreDeps) {
77
- const depSrc = path.join(pkgRoot, 'node_modules', dep);
78
- if (fs.existsSync(depSrc)) {
79
- fs.cpSync(depSrc, path.join(cacheDir, 'node_modules', dep), { recursive: true });
80
- }
61
+ catch {
62
+ throw new Error(`${file} is read-only (EACCES); not modified`);
81
63
  }
82
64
  }
83
- // installed_plugins.json 등록
65
+ fs.mkdirSync(path.dirname(file), { recursive: true });
66
+ const tmp = `${file}.tmp-${process.pid}`;
67
+ fs.writeFileSync(tmp, `${JSON.stringify(data, null, 2)}\n`);
68
+ fs.renameSync(tmp, file);
69
+ return true;
70
+ }
71
+ // ── 1. 플러그인 잔재 정리 ──────────────────────────────────────────────
72
+ /** 과거 postinstall 이 만든 forgen@forgen-local 캐시·installed_plugins 항목을 지운다. 지운 것이 있으면 true. */
73
+ function cleanLegacyPluginFiles(homeDir) {
74
+ let cleaned = false;
75
+ const pluginsDir = path.join(homeDir, '.claude', 'plugins');
76
+ const cacheDir = path.join(pluginsDir, 'cache', 'forgen-local');
77
+ if (fs.existsSync(cacheDir) || isDanglingLink(cacheDir)) {
78
+ fs.rmSync(cacheDir, { recursive: true, force: true });
79
+ cleaned = true;
80
+ }
84
81
  const installedPath = path.join(pluginsDir, 'installed_plugins.json');
85
- let installed = { version: 2, plugins: {} };
86
82
  if (fs.existsSync(installedPath)) {
87
- try {
88
- installed = JSON.parse(fs.readFileSync(installedPath, 'utf-8'));
83
+ const data = JSON.parse(fs.readFileSync(installedPath, 'utf-8'));
84
+ if (data.plugins && PLUGIN_KEY in data.plugins) {
85
+ delete data.plugins[PLUGIN_KEY];
86
+ fs.writeFileSync(installedPath, `${JSON.stringify(data, null, 2)}\n`);
87
+ cleaned = true;
89
88
  }
90
- catch { /* ignore */ }
91
89
  }
92
- installed.plugins = installed.plugins ?? {};
93
- installed.plugins[PLUGIN_KEY] = [{
94
- scope: 'user',
95
- installPath: cacheDir,
96
- version,
97
- installedAt: new Date().toISOString(),
98
- lastUpdated: new Date().toISOString(),
99
- }];
100
- fs.mkdirSync(pluginsDir, { recursive: true });
101
- fs.writeFileSync(installedPath, `${JSON.stringify(installed, null, 2)}\n`);
102
- return true;
90
+ return cleaned;
91
+ }
92
+ function isDanglingLink(p) {
93
+ try {
94
+ return fs.lstatSync(p).isSymbolicLink();
95
+ }
96
+ catch {
97
+ return false;
98
+ }
103
99
  }
104
100
  // ── 2. Slash commands ──────────────────────────────────────────────────
105
101
  /** Build-time injected --with-codex shared snippet. Mirror of scripts/copy-assets.js. */
@@ -152,89 +148,143 @@ function writeSlashCommands(opts) {
152
148
  }
153
149
  return count;
154
150
  }
155
- // ── 3. Settings hooks injection ────────────────────────────────────────
156
- function injectHooksIntoSettings(opts) {
157
- const { pkgRoot, settingsPath, dryRun } = opts;
158
- // settings.json 컨텍스트는 ${CLAUDE_PLUGIN_ROOT} 미해석 — 절대 경로 박제 (postinstall.js 와 동일 노하우)
151
+ // ── 3. Settings (hooks · statusLine · 잔재 정리) ───────────────────────
152
+ let hookScriptsCache = null;
153
+ function forgenHookScripts() {
154
+ if (!hookScriptsCache) {
155
+ hookScriptsCache = new Set(HOOK_REGISTRY.map((h) => path.basename(h.script.split(/\s+/)[0]))); // script 에 인자가 붙을 수 있다(`hooks/x.js start`)
156
+ // 등록에서 빠졌지만 구버전 settings 에 남아 있을 수 있는 이름.
157
+ for (const legacy of ['pre-tool-use.js', 'post-tool-use.js', 'stop-guard.js', 'session-recovery.js'])
158
+ hookScriptsCache.add(legacy);
159
+ }
160
+ return hookScriptsCache;
161
+ }
162
+ /** settings.json hook 명령이 forgen 소유인가 — 새 shim 형식과 구형 절대경로·플러그인 변수 형식 모두. */
163
+ export function isForgenHookCommand(cmd, pkgRoot) {
164
+ if (isForgenRunCommand(cmd))
165
+ return true;
166
+ if (cmd.includes('/forgen-local/forgen/'))
167
+ return true;
168
+ // 다른 플러그인 hook 을 지우지 않게, forgen 이 실제로 쓰는 hook 스크립트 이름까지 일치해야 한다.
169
+ const script = /[\\/]dist[\\/]hooks[\\/]([^"\s\\/]+\.js)/.exec(cmd)?.[1];
170
+ if (!script || !(forgenHookScripts().has(script) || script.includes('forgen')))
171
+ return false;
172
+ if (cmd.includes('CLAUDE_PLUGIN_ROOT'))
173
+ return true;
174
+ return (cmd.includes(pkgRoot) || /@wooojin[\\/]forgen|[\\/]forgen[^\\/\s"]*[\\/]|tenetx|compound-harness/.test(cmd));
175
+ }
176
+ /**
177
+ * settings 객체에 forgen 설정을 제자리 반영한다(설치·래퍼 공용, 순수 함수).
178
+ * hook 은 forgen 것만 갈아끼우고 사용자 hook 은 그룹 안에서도 보존한다. 같은 입력이면 결과가 같아 멱등이다.
179
+ */
180
+ export function removeForgenHooks(hooksConfig, pkgRoot) {
181
+ for (const [event, groups] of Object.entries(hooksConfig)) {
182
+ if (!Array.isArray(groups))
183
+ continue;
184
+ const kept = [];
185
+ for (const g of groups) {
186
+ const group = g;
187
+ if (typeof group.command === 'string') {
188
+ if (!isForgenHookCommand(group.command, pkgRoot))
189
+ kept.push(g);
190
+ continue;
191
+ }
192
+ if (!Array.isArray(group.hooks)) {
193
+ kept.push(g);
194
+ continue;
195
+ }
196
+ const inner = group.hooks.filter((h) => !(typeof h.command === 'string' && isForgenHookCommand(h.command, pkgRoot)));
197
+ if (inner.length === group.hooks.length)
198
+ kept.push(g);
199
+ else if (inner.length > 0)
200
+ kept.push({ ...group, hooks: inner });
201
+ }
202
+ if (kept.length === 0)
203
+ delete hooksConfig[event];
204
+ else
205
+ hooksConfig[event] = kept;
206
+ }
207
+ }
208
+ export function applyForgenSettings(settings, pkgRoot, shimPath) {
209
+ const hooksConfig = settings.hooks ?? {};
210
+ removeForgenHooks(hooksConfig, pkgRoot);
211
+ // settings.json 컨텍스트는 ${CLAUDE_PLUGIN_ROOT} 를 풀지 않는다. shim 이 있으면 그 경로, 없으면 절대경로.
159
212
  const generated = generateHooksJson({
160
213
  pluginRoot: path.join(pkgRoot, 'dist'),
161
214
  runtime: 'claude',
162
215
  releaseMode: true,
216
+ ...(shimPath ? { shimPath } : {}),
163
217
  });
164
218
  let count = 0;
165
- for (const events of Object.values(generated.hooks)) {
166
- for (const group of events) {
167
- const g = group;
168
- if (Array.isArray(g.hooks))
169
- count += g.hooks.length;
170
- }
171
- }
172
- if (dryRun)
173
- return count;
174
- let settings = {};
175
- if (fs.existsSync(settingsPath)) {
176
- try {
177
- settings = JSON.parse(fs.readFileSync(settingsPath, 'utf-8'));
178
- }
179
- catch { /* fallthrough */ }
180
- }
181
- const hooksConfig = settings.hooks ?? {};
182
- // 기존 forgen hook 제거 (path 에 pkgRoot 또는 CLAUDE_PLUGIN_ROOT 포함된 entry)
183
- for (const [event, entries] of Object.entries(hooksConfig)) {
184
- if (!Array.isArray(entries))
185
- continue;
186
- const filtered = entries.filter((entry) => {
187
- const e = entry;
188
- if (!Array.isArray(e.hooks))
189
- return true;
190
- // forgen-managed entry 식별: pkgRoot 또는 CLAUDE_PLUGIN_ROOT 또는 'forgen' 포함
191
- return !e.hooks.some((h) => typeof h.command === 'string' &&
192
- (h.command.includes(pkgRoot) || h.command.includes('CLAUDE_PLUGIN_ROOT') || h.command.includes('/forgen-local/forgen/')));
193
- });
194
- if (filtered.length === 0)
195
- delete hooksConfig[event];
196
- else
197
- hooksConfig[event] = filtered;
198
- }
199
- // forgen 측 entry 추가
200
219
  for (const [event, entries] of Object.entries(generated.hooks)) {
201
220
  if (!hooksConfig[event])
202
221
  hooksConfig[event] = [];
203
222
  hooksConfig[event].push(...entries);
223
+ for (const g of entries)
224
+ count += g.hooks.length;
204
225
  }
205
226
  settings.hooks = hooksConfig;
206
- // enabledPlugins 등록
207
- const enabled = settings.enabledPlugins ?? {};
208
- enabled[PLUGIN_KEY] = true;
209
- settings.enabledPlugins = enabled;
210
- fs.mkdirSync(path.dirname(settingsPath), { recursive: true });
211
- fs.writeFileSync(settingsPath, `${JSON.stringify(settings, null, 2)}\n`);
212
- return count;
227
+ const statusLine = applyStatusLineAuto(settings, forgenStatuslineCommand(shimPath));
228
+ // 플러그인 등록 잔재와 래퍼가 남긴 env, 구형 settings.mcpServers 항목 정리
229
+ const enabled = settings.enabledPlugins;
230
+ if (enabled && PLUGIN_KEY in enabled) {
231
+ delete enabled[PLUGIN_KEY];
232
+ if (Object.keys(enabled).length === 0)
233
+ delete settings.enabledPlugins;
234
+ }
235
+ const env = settings.env;
236
+ if (env) {
237
+ for (const k of LEGACY_WRAPPER_ENV_KEYS)
238
+ delete env[k];
239
+ if (Object.keys(env).length === 0)
240
+ delete settings.env;
241
+ }
242
+ const legacyMcp = settings.mcpServers;
243
+ if (legacyMcp && 'forgen-compound' in legacyMcp) {
244
+ delete legacyMcp['forgen-compound'];
245
+ if (Object.keys(legacyMcp).length === 0)
246
+ delete settings.mcpServers;
247
+ }
248
+ return { hooks: count, statusLine };
213
249
  }
214
- function registerMcpInClaudeJson(opts) {
215
- const { pkgRoot, claudeJsonPath, dryRun } = opts;
216
- const serverPath = path.join(pkgRoot, 'dist', 'mcp', 'server.js');
217
- const desired = { command: 'node', args: [serverPath] };
218
- let claudeJson = {};
219
- if (fs.existsSync(claudeJsonPath)) {
220
- try {
221
- claudeJson = JSON.parse(fs.readFileSync(claudeJsonPath, 'utf-8'));
222
- }
223
- catch { /* ignore */ }
250
+ function installSettings(opts) {
251
+ const update = () => {
252
+ const settings = readJsonObject(opts.settingsPath);
253
+ const before = JSON.stringify(settings);
254
+ const r = applyForgenSettings(settings, opts.pkgRoot, opts.shimPath);
255
+ if (!opts.dryRun)
256
+ writeJsonIfChanged(opts.settingsPath, before, settings);
257
+ return r;
258
+ };
259
+ if (opts.dryRun)
260
+ return update();
261
+ // 래퍼·실행 중인 세션과 read-modify-write 가 겹치면 한쪽이 유실된다.
262
+ try {
263
+ return withFileLockSync(opts.settingsPath, update);
224
264
  }
265
+ catch (e) {
266
+ if (e instanceof FileLockError)
267
+ return update();
268
+ throw e;
269
+ }
270
+ }
271
+ function registerMcpInClaudeJson(opts) {
272
+ const { pkgRoot, claudeJsonPath, shimPath, dryRun } = opts;
273
+ const desired = shimPath
274
+ ? { command: shimPath, args: ['mcp/server.js'] }
275
+ : { command: 'node', args: [path.join(pkgRoot, 'dist', 'mcp', 'server.js')] };
276
+ const claudeJson = readJsonObject(claudeJsonPath);
277
+ const before = JSON.stringify(claudeJson);
225
278
  const mcpServers = claudeJson.mcpServers ?? {};
226
279
  const existing = mcpServers['forgen-compound'];
227
280
  const alreadyPresent = existing !== undefined &&
228
- existing.command === 'node' &&
229
- Array.isArray(existing.args) &&
281
+ existing.command === desired.command &&
230
282
  JSON.stringify(existing.args) === JSON.stringify(desired.args);
231
- if (dryRun) {
232
- return { registered: !alreadyPresent, alreadyPresent };
283
+ if (!dryRun && !alreadyPresent) {
284
+ mcpServers['forgen-compound'] = { ...(existing ?? {}), ...desired };
285
+ claudeJson.mcpServers = mcpServers;
286
+ writeJsonIfChanged(claudeJsonPath, before, claudeJson);
233
287
  }
234
- mcpServers['forgen-compound'] = desired;
235
- claudeJson.mcpServers = mcpServers;
236
- fs.mkdirSync(path.dirname(claudeJsonPath), { recursive: true });
237
- fs.writeFileSync(claudeJsonPath, `${JSON.stringify(claudeJson, null, 2)}\n`);
238
288
  return { registered: !alreadyPresent, alreadyPresent };
239
289
  }
240
290
  // ── 5. Dev-guide skills ────────────────────────────────────────────────
@@ -323,6 +373,67 @@ function installVerifySkill(opts) {
323
373
  fs.copyFileSync(src, path.join(dir, 'SKILL.md'));
324
374
  return 'installed';
325
375
  }
376
+ function ensureShimPathOnly(homeDir) {
377
+ return shimSupported() ? forgenRunShimPath(homeDir) : null;
378
+ }
379
+ // ── 7. 전역 ch-* agents ────────────────────────────────────────────────
380
+ /** 설치할 agent 내용 — frontmatter 바로 뒤에 forgen 표식을 넣는다(소유 판정은 hasManagedSkillMarker 와 같은 위치 규칙). */
381
+ function withManagedMarker(content) {
382
+ const text = content.replace(/\r\n/g, '\n');
383
+ const close = text.startsWith('---\n') ? text.indexOf('\n---\n', 3) : -1;
384
+ if (close === -1)
385
+ return text;
386
+ return `${text.slice(0, close + 5)}\n${FORGEN_MANAGED_MARKER}\n${text.slice(close + 5).replace(/^\n+/, '\n')}`;
387
+ }
388
+ /**
389
+ * assets/claude/agents/*.md → ~/.claude/agents/ch-*.md. 표식이 있는 forgen 파일만 갱신·정리하고,
390
+ * 사용자가 만들었거나 수정해 표식이 없는 파일, 심링크는 건드리지 않는다.
391
+ */
392
+ export function installGlobalAgents(opts) {
393
+ const { pkgRoot, agentsDir } = opts;
394
+ const dryRun = opts.dryRun ?? false;
395
+ const sourceDir = path.join(pkgRoot, 'assets', 'claude', 'agents');
396
+ if (!fs.existsSync(sourceDir))
397
+ return { installed: 0, removed: 0 };
398
+ const valid = new Set();
399
+ let installed = 0;
400
+ if (!dryRun)
401
+ fs.mkdirSync(agentsDir, { recursive: true });
402
+ for (const file of fs.readdirSync(sourceDir).filter((f) => f.endsWith('.md'))) {
403
+ const name = `ch-${file}`;
404
+ valid.add(name);
405
+ const dest = path.join(agentsDir, name);
406
+ const content = withManagedMarker(fs.readFileSync(path.join(sourceDir, file), 'utf-8'));
407
+ try {
408
+ if (fs.lstatSync(dest).isSymbolicLink())
409
+ continue;
410
+ const cur = fs.readFileSync(dest, 'utf-8');
411
+ if (cur === content)
412
+ continue;
413
+ if (!hasManagedSkillMarker(cur))
414
+ continue; // 사용자 파일
415
+ }
416
+ catch { /* 없음 — 설치 */ }
417
+ if (!dryRun)
418
+ fs.writeFileSync(dest, content);
419
+ installed += 1;
420
+ }
421
+ let removed = 0;
422
+ try {
423
+ for (const name of fs.readdirSync(agentsDir)) {
424
+ if (!name.startsWith('ch-') || !name.endsWith('.md') || valid.has(name))
425
+ continue;
426
+ const f = path.join(agentsDir, name);
427
+ if (fs.lstatSync(f).isSymbolicLink() || !hasManagedSkillMarker(fs.readFileSync(f, 'utf-8')))
428
+ continue;
429
+ if (!dryRun)
430
+ fs.unlinkSync(f);
431
+ removed += 1;
432
+ }
433
+ }
434
+ catch { /* 디렉토리 없음 */ }
435
+ return { installed, removed };
436
+ }
326
437
  // ── public ─────────────────────────────────────────────────────────────
327
438
  export function planClaudeInstall(opts) {
328
439
  if (!opts.pkgRoot || !fs.existsSync(opts.pkgRoot)) {
@@ -331,37 +442,73 @@ export function planClaudeInstall(opts) {
331
442
  const homeDir = opts.homeDir ?? os.homedir();
332
443
  const dryRun = opts.dryRun ?? false;
333
444
  const registerMcp = opts.registerMcp ?? true;
334
- const version = readPkgVersion(opts.pkgRoot);
445
+ const { pkgRoot } = opts;
335
446
  const claudeDir = path.join(homeDir, '.claude');
336
- const pluginsDir = path.join(claudeDir, 'plugins');
337
- const cacheDir = path.join(pluginsDir, 'cache', 'forgen-local', 'forgen', version);
338
447
  const slashCommandsDir = path.join(claudeDir, 'commands', 'forgen');
339
448
  const settingsPath = path.join(claudeDir, 'settings.json');
340
449
  const claudeJsonPath = path.join(homeDir, '.claude.json');
341
450
  const skillsDir = path.join(claudeDir, 'skills');
342
- const pluginCacheWritten = writePluginCache({ pkgRoot: opts.pkgRoot, cacheDir, pluginsDir, version, dryRun });
343
- const slashCommandsCount = writeSlashCommands({ pkgRoot: opts.pkgRoot, targetDir: slashCommandsDir, dryRun });
344
- const hooksInjected = injectHooksIntoSettings({ pkgRoot: opts.pkgRoot, settingsPath, dryRun });
451
+ const agentsDir = path.join(claudeDir, 'agents');
452
+ const errors = [];
453
+ const step = (label, fallback, fn) => {
454
+ try {
455
+ return fn();
456
+ }
457
+ catch (e) {
458
+ errors.push(`${label}: ${errMsg(e)}`);
459
+ return fallback;
460
+ }
461
+ };
462
+ // 1. shim (dry-run 이면 경로만 계산)
463
+ let shimPath = null;
464
+ let shimStatus = 'unsupported';
465
+ if (dryRun) {
466
+ const probe = ensureShimPathOnly(homeDir);
467
+ shimPath = probe;
468
+ shimStatus = probe ? 'dry-run' : 'unsupported';
469
+ }
470
+ else {
471
+ const shim = ensureForgenRunShim(pkgRoot, homeDir);
472
+ shimPath = shim.path;
473
+ shimStatus = shim.status;
474
+ if (shim.status === 'foreign' || shim.status === 'error') {
475
+ errors.push(`shim: ${shim.status === 'foreign' ? 'a user file already exists at the shim path' : 'could not write the shim'}; falling back to absolute paths`);
476
+ }
477
+ }
478
+ const legacyPluginCleaned = dryRun ? false : step('legacy plugin cleanup', false, () => cleanLegacyPluginFiles(homeDir));
479
+ const slashCommandsCount = step('slash commands', 0, () => writeSlashCommands({ pkgRoot, targetDir: slashCommandsDir, dryRun }));
480
+ const settings = step('settings.json', { hooks: 0, statusLine: 'unchanged' }, () => installSettings({ pkgRoot, settingsPath, shimPath, dryRun }));
345
481
  const mcp = registerMcp
346
- ? registerMcpInClaudeJson({ pkgRoot: opts.pkgRoot, claudeJsonPath, dryRun })
482
+ ? step('~/.claude.json MCP', { registered: false, alreadyPresent: false }, () => registerMcpInClaudeJson({ pkgRoot, claudeJsonPath, shimPath, dryRun }))
347
483
  : { registered: false, alreadyPresent: false };
348
- const skills = installDevGuideSkills({ pkgRoot: opts.pkgRoot, skillsDir, dryRun });
484
+ const skills = step('dev-guide skills', { skillsPath: skillsDir, skillsInstalled: 0, skillsRemoved: 0 }, () => installDevGuideSkills({ pkgRoot, skillsDir, dryRun }));
349
485
  const verifySkill = (opts.installVerifySkill ?? true)
350
- ? installVerifySkill({ pkgRoot: opts.pkgRoot, skillsDir, dryRun })
486
+ ? step('verify skill', 'skipped', () => installVerifySkill({ pkgRoot, skillsDir, dryRun }))
351
487
  : 'skipped';
488
+ const agents = step('agents', { installed: 0, removed: 0 }, () => installGlobalAgents({ pkgRoot, agentsDir, dryRun }));
489
+ // 이미 등록된 sweep cron 을 shim 경유로 옮긴다. postinstall·forgen install claude·doctor --repair 가 모두 여기를 지난다.
490
+ if (!dryRun && shimPath) {
491
+ refreshCronAfterUpgrade(homeDir);
492
+ }
352
493
  return {
353
494
  homeDir,
354
- pluginCachePath: cacheDir,
355
- pluginCacheWritten,
495
+ shimPath,
496
+ shimStatus,
356
497
  slashCommandsPath: slashCommandsDir,
357
498
  slashCommandsCount,
358
499
  settingsPath,
359
- hooksInjected,
500
+ hooksInjected: settings.hooks,
501
+ statusLine: settings.statusLine,
360
502
  mcpRegistered: mcp.registered,
361
503
  mcpAlreadyPresent: mcp.alreadyPresent,
362
504
  skillsPath: skills.skillsPath,
363
505
  skillsInstalled: skills.skillsInstalled,
364
506
  skillsRemoved: skills.skillsRemoved,
365
507
  verifySkill,
508
+ agentsPath: agentsDir,
509
+ agentsInstalled: agents.installed,
510
+ agentsRemoved: agents.removed,
511
+ legacyPluginCleaned,
512
+ errors,
366
513
  };
367
514
  }
@@ -60,6 +60,10 @@ export interface CodexInstallResult {
60
60
  /** P3-3: AGENTS.md (cwd) 에 forgen rule block 인젝션 여부 */
61
61
  agentsMdPath: string;
62
62
  agentsMdInjected: boolean;
63
+ /** 예전 설치가 cwd·홈에 남긴 forgen 블록을 걷어낸 파일들 (dryRun 이면 걷어낼 파일들). */
64
+ staleAgentsMdCleaned: string[];
65
+ /** 같은 위치에 AGENTS.override.md 가 있으면 Codex 는 그것만 읽는다 — 그 경로. */
66
+ agentsOverridePath?: string;
63
67
  /** v0.4.9: dev-guide skills (~/.codex/skills) 설치 결과 */
64
68
  devGuideSkillsPath: string;
65
69
  devGuideSkillsInstalled: number;
@@ -221,6 +225,22 @@ export declare function removeForgenRulesEverywhere(opts: {
221
225
  error: string;
222
226
  }>;
223
227
  };
228
+ /**
229
+ * 예전 설치가 cwd 나 ~/AGENTS.md 에 남긴 forgen 블록을 걷어낸다 (표식 블록만 — 사용자 글은 보존, 블록뿐인 파일은 삭제).
230
+ * 기록된 경로 + 지금 cwd 의 경로 + 홈의 AGENTS.md 가 대상이고, 새 설치 위치 자신은 건드리지 않는다.
231
+ */
232
+ export declare function cleanStaleAgentsMd(opts: {
233
+ hostDir: string;
234
+ targetPath: string;
235
+ pkgRoot: string;
236
+ dryRun: boolean;
237
+ }): {
238
+ cleaned: string[];
239
+ failed: Array<{
240
+ path: string;
241
+ error: string;
242
+ }>;
243
+ };
224
244
  /**
225
245
  * AGENTS.md 의 forgen 블록 제거 (uninstall). 블록뿐이던 파일은 삭제한다.
226
246
  * BEGIN/END 마커가 각각 한 줄로, 순서대로 있을 때만 동작한다 (블록이 여러 개면 전부 제거).
@@ -569,10 +569,14 @@ export function planCodexInstall(opts) {
569
569
  // 7) P3-3 (US-013): cwd/AGENTS.md 에 forgen rules block 인젝션 (managed marker)
570
570
  // Codex 가 AGENTS.md 를 자동 read (codex-rs/core/src/agents_md.rs 검증).
571
571
  // pkgRoot 의 git repo root 의 AGENTS.md, 또는 explicit override.
572
- const agentsMdPath = opts.agentsMdPath ?? resolveAgentsMdPath(opts.pkgRoot);
572
+ // E7: cwd 에 쓰지 않는다. Codex 전역 지침 파일은 $CODEX_HOME/AGENTS.md.
573
+ const agentsMdPath = opts.agentsMdPath ?? path.join(codexHome, 'AGENTS.md');
573
574
  const agentsResult = upsertForgenRulesInAgentsMd({ agentsMdPath, pkgRoot: opts.pkgRoot, dryRun: opts.dryRun ?? false });
575
+ const stale = opts.agentsMdPath ? { cleaned: [] } : cleanStaleAgentsMd({ hostDir: codexHome, targetPath: agentsMdPath, pkgRoot: opts.pkgRoot, dryRun: opts.dryRun ?? false });
574
576
  if (!opts.dryRun)
575
577
  recordAgentsMdInstall(codexHome, agentsMdPath);
578
+ const overridePath = path.join(path.dirname(agentsMdPath), 'AGENTS.override.md');
579
+ const agentsOverridePath = fs.existsSync(overridePath) ? overridePath : undefined;
576
580
  // 8) v0.4.9: dev-guide skills → ~/.codex/skills/forgen-<stack>-<skill>/SKILL.md
577
581
  const devGuideResult = installDevGuideSkillsToCodex({
578
582
  pkgRoot: opts.pkgRoot,
@@ -607,6 +611,8 @@ export function planCodexInstall(opts) {
607
611
  skillsPath,
608
612
  agentsMdPath,
609
613
  agentsMdInjected: agentsResult.injected,
614
+ staleAgentsMdCleaned: stale.cleaned,
615
+ agentsOverridePath,
610
616
  devGuideSkillsPath: devGuideResult.devGuideSkillsPath,
611
617
  devGuideSkillsInstalled: devGuideResult.devGuideSkillsInstalled,
612
618
  devGuideSkillsRemoved: devGuideResult.devGuideSkillsRemoved,
@@ -1182,6 +1188,31 @@ export function removeForgenRulesEverywhere(opts) {
1182
1188
  }
1183
1189
  return { cleaned, failed };
1184
1190
  }
1191
+ /**
1192
+ * 예전 설치가 cwd 나 ~/AGENTS.md 에 남긴 forgen 블록을 걷어낸다 (표식 블록만 — 사용자 글은 보존, 블록뿐인 파일은 삭제).
1193
+ * 기록된 경로 + 지금 cwd 의 경로 + 홈의 AGENTS.md 가 대상이고, 새 설치 위치 자신은 건드리지 않는다.
1194
+ */
1195
+ export function cleanStaleAgentsMd(opts) {
1196
+ const target = path.resolve(opts.targetPath);
1197
+ const candidates = [...new Set([...readAgentsMdInstalls(opts.hostDir), resolveAgentsMdPath(opts.pkgRoot), path.join(os.homedir(), 'AGENTS.md')].map((p) => path.resolve(p)))].filter((p) => p !== target);
1198
+ const cleaned = [];
1199
+ const failed = [];
1200
+ for (const p of candidates) {
1201
+ try {
1202
+ if (removeForgenRulesFromAgentsMd({ agentsMdPath: p, dryRun: opts.dryRun }).removed)
1203
+ cleaned.push(p);
1204
+ }
1205
+ catch (e) {
1206
+ failed.push({ path: p, error: e instanceof Error ? e.message : String(e) });
1207
+ }
1208
+ }
1209
+ if (!opts.dryRun) {
1210
+ clearAgentsMdInstalls(opts.hostDir);
1211
+ for (const f of failed)
1212
+ recordAgentsMdInstall(opts.hostDir, f.path); // 못 지운 곳은 기록에 남겨 uninstall 이 다시 시도한다
1213
+ }
1214
+ return { cleaned, failed };
1215
+ }
1185
1216
  /** 마커가 *한 줄을 통째로* 차지할 때만 블록 경계로 본다 — 본문에 마커 문자열을 인용한 줄과 구분. */
1186
1217
  function findAgentsBlocks(lines) {
1187
1218
  const blocks = [];
@@ -7,7 +7,7 @@
7
7
  * 2. MCP: 기존 config 파일(opencode.jsonc 우선, 없으면 opencode.json)에 mcp.forgen-compound
8
8
  * surgical 병합. **JSONC 파서(jsonc-parser)로 주석/trailing-comma 보존**, 쓰기 전 백업
9
9
  * (리뷰 HIGH: JSON.parse 가 공식 JSONC 를 clobber 하던 데이터 손실 수정).
10
- * 3. AGENTS.md: cwd 의 forgen rules block (Codex 헬퍼 재사용).
10
+ * 3. AGENTS.md: <config>/AGENTS.md 의 forgen rules block (Codex 헬퍼 재사용).
11
11
  */
12
12
  export declare const PLUGIN_FILENAME = "forgen.ts";
13
13
  export declare const PLUGIN_MARKER = "forgen-managed";
@@ -36,6 +36,8 @@ export interface OpencodeInstallResult {
36
36
  /** config 백업 경로(수정 전 .bak). */
37
37
  mcpBackupPath?: string;
38
38
  agentsMdInjected: boolean;
39
+ /** 예전 설치가 cwd·홈에 남긴 forgen 블록을 걷어낸 파일들. */
40
+ staleAgentsMdCleaned?: string[];
39
41
  }
40
42
  export declare function resolveOpencodeConfigDir(opts: OpencodeInstallOptions): string;
41
43
  /** 기존 config 파일 경로 감지 — opencode.jsonc 우선, 없으면 opencode.json (둘 다 없으면 .json 신규). */