@wooojin/forgen 0.6.8 → 0.6.9

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (221) hide show
  1. package/.claude-plugin/plugin.json +1 -1
  2. package/CHANGELOG.md +17 -0
  3. package/README.ja.md +15 -10
  4. package/README.ko.md +15 -10
  5. package/README.md +19 -14
  6. package/README.zh.md +13 -8
  7. package/dist/checks/dangerous-response-pattern.d.ts +2 -1
  8. package/dist/checks/dangerous-response-pattern.js +27 -3
  9. package/dist/cli.js +133 -17
  10. package/dist/core/auto-compound-runner.js +502 -397
  11. package/dist/core/block-cli.js +7 -3
  12. package/dist/core/compound-consent.d.ts +18 -0
  13. package/dist/core/compound-consent.js +101 -6
  14. package/dist/core/compound-sweep-cli.d.ts +16 -0
  15. package/dist/core/compound-sweep-cli.js +67 -5
  16. package/dist/core/config-hooks.js +28 -10
  17. package/dist/core/correction-signals.d.ts +9 -0
  18. package/dist/core/correction-signals.js +37 -0
  19. package/dist/core/dev-cli.d.ts +1 -2
  20. package/dist/core/dev-cli.js +9 -28
  21. package/dist/core/doctor-verify.d.ts +35 -0
  22. package/dist/core/doctor-verify.js +502 -0
  23. package/dist/core/doctor.d.ts +4 -6
  24. package/dist/core/doctor.js +103 -184
  25. package/dist/core/explain-cli.js +8 -0
  26. package/dist/core/extraction-haiku.d.ts +64 -0
  27. package/dist/core/extraction-haiku.js +208 -0
  28. package/dist/core/extraction-queue.d.ts +68 -0
  29. package/dist/core/extraction-queue.js +300 -0
  30. package/dist/core/flow-status.d.ts +93 -0
  31. package/dist/core/flow-status.js +368 -0
  32. package/dist/core/harness.js +14 -42
  33. package/dist/core/inspect-cli.js +37 -13
  34. package/dist/core/lifecycle-classifier.d.ts +5 -1
  35. package/dist/core/lifecycle-classifier.js +13 -2
  36. package/dist/core/migrate-cli.d.ts +1 -1
  37. package/dist/core/migrate-cli.js +11 -11
  38. package/dist/core/migrate-tenetx.d.ts +1 -1
  39. package/dist/core/migrate-tenetx.js +2 -2
  40. package/dist/core/node-engine.d.ts +3 -0
  41. package/dist/core/node-engine.js +8 -0
  42. package/dist/core/observability-store.d.ts +15 -0
  43. package/dist/core/observability-store.js +73 -0
  44. package/dist/core/paths.d.ts +2 -0
  45. package/dist/core/paths.js +2 -0
  46. package/dist/core/rendered-rules-manifest.d.ts +7 -1
  47. package/dist/core/rendered-rules-manifest.js +45 -1
  48. package/dist/core/session-store.d.ts +13 -11
  49. package/dist/core/session-store.js +103 -119
  50. package/dist/core/settings-injector.d.ts +5 -2
  51. package/dist/core/settings-injector.js +21 -88
  52. package/dist/core/spawn.d.ts +9 -1
  53. package/dist/core/spawn.js +33 -33
  54. package/dist/core/stats-cli.d.ts +7 -0
  55. package/dist/core/stats-cli.js +66 -93
  56. package/dist/core/status-cli.d.ts +1 -1
  57. package/dist/core/status-cli.js +23 -4
  58. package/dist/core/statusline-cli.js +5 -0
  59. package/dist/core/statusline-install.d.ts +10 -2
  60. package/dist/core/statusline-install.js +27 -4
  61. package/dist/core/transcript-summary.d.ts +84 -9
  62. package/dist/core/transcript-summary.js +283 -49
  63. package/dist/core/uninstall.d.ts +4 -0
  64. package/dist/core/uninstall.js +68 -36
  65. package/dist/core/v1-bootstrap.d.ts +1 -1
  66. package/dist/core/v1-bootstrap.js +38 -9
  67. package/dist/engine/acted-on-evidence.d.ts +8 -0
  68. package/dist/engine/acted-on-evidence.js +38 -0
  69. package/dist/engine/block-judge.d.ts +3 -1
  70. package/dist/engine/block-judge.js +4 -3
  71. package/dist/engine/compound-cli.d.ts +26 -2
  72. package/dist/engine/compound-cli.js +143 -19
  73. package/dist/engine/compound-lifecycle.d.ts +36 -2
  74. package/dist/engine/compound-lifecycle.js +131 -11
  75. package/dist/engine/compound-loop.d.ts +4 -0
  76. package/dist/engine/compound-loop.js +93 -18
  77. package/dist/engine/correction-cluster-runner.d.ts +11 -1
  78. package/dist/engine/correction-cluster-runner.js +39 -15
  79. package/dist/engine/correction-clustering.d.ts +11 -0
  80. package/dist/engine/correction-clustering.js +20 -3
  81. package/dist/engine/lifecycle/lifecycle-cli.js +10 -3
  82. package/dist/engine/lifecycle/meta-reclassifier.d.ts +9 -0
  83. package/dist/engine/lifecycle/meta-reclassifier.js +15 -3
  84. package/dist/engine/lifecycle/orchestrator.js +3 -2
  85. package/dist/engine/lifecycle/signals.d.ts +19 -1
  86. package/dist/engine/lifecycle/signals.js +61 -2
  87. package/dist/engine/lifecycle/trigger-t1-correction.d.ts +1 -1
  88. package/dist/engine/lifecycle/trigger-t1-correction.js +9 -28
  89. package/dist/engine/lifecycle/trigger-t5-conflict.d.ts +8 -0
  90. package/dist/engine/lifecycle/trigger-t5-conflict.js +60 -2
  91. package/dist/engine/roi-demotion.d.ts +11 -0
  92. package/dist/engine/roi-demotion.js +50 -8
  93. package/dist/engine/rule-detectability.d.ts +39 -0
  94. package/dist/engine/rule-detectability.js +66 -0
  95. package/dist/engine/rule-project-cli.d.ts +25 -0
  96. package/dist/engine/rule-project-cli.js +148 -0
  97. package/dist/engine/rule-recovery-cli.d.ts +21 -0
  98. package/dist/engine/rule-recovery-cli.js +265 -0
  99. package/dist/engine/rule-toggle-cli.d.ts +14 -2
  100. package/dist/engine/rule-toggle-cli.js +94 -6
  101. package/dist/engine/skill-promoter.d.ts +14 -8
  102. package/dist/engine/skill-promoter.js +57 -85
  103. package/dist/engine/solution-format.d.ts +26 -1
  104. package/dist/engine/solution-format.js +65 -3
  105. package/dist/engine/solution-habit.d.ts +1 -0
  106. package/dist/engine/solution-habit.js +22 -0
  107. package/dist/engine/solution-index.d.ts +5 -0
  108. package/dist/engine/solution-index.js +32 -0
  109. package/dist/engine/solution-matcher-eval.js +4 -4
  110. package/dist/engine/solution-matcher.js +15 -13
  111. package/dist/engine/solution-scope.d.ts +11 -0
  112. package/dist/engine/solution-scope.js +19 -0
  113. package/dist/engine/solution-writer.d.ts +3 -1
  114. package/dist/engine/solution-writer.js +3 -2
  115. package/dist/engine/term-normalizer.js +49 -0
  116. package/dist/fgx.js +1 -1
  117. package/dist/forge/cli.js +51 -8
  118. package/dist/forge/evidence-processor.js +6 -0
  119. package/dist/hooks/context-guard.d.ts +0 -22
  120. package/dist/hooks/context-guard.js +22 -55
  121. package/dist/hooks/context-usage.d.ts +21 -0
  122. package/dist/hooks/context-usage.js +103 -0
  123. package/dist/hooks/dangerous-patterns.json +1 -16
  124. package/dist/hooks/db-guard.d.ts +1 -1
  125. package/dist/hooks/db-guard.js +21 -30
  126. package/dist/hooks/hook-config.d.ts +2 -0
  127. package/dist/hooks/hook-config.js +5 -1
  128. package/dist/hooks/hooks-generator.d.ts +4 -0
  129. package/dist/hooks/hooks-generator.js +10 -4
  130. package/dist/hooks/permission-handler.js +23 -3
  131. package/dist/hooks/post-tool-use.js +14 -10
  132. package/dist/hooks/pre-tool-use.d.ts +17 -3
  133. package/dist/hooks/pre-tool-use.js +143 -30
  134. package/dist/hooks/rate-limiter.js +12 -7
  135. package/dist/hooks/secret-filter.js +15 -4
  136. package/dist/hooks/session-end.d.ts +2 -2
  137. package/dist/hooks/session-end.js +13 -7
  138. package/dist/hooks/session-recovery.js +79 -50
  139. package/dist/hooks/shared/command-analyzer.d.ts +45 -0
  140. package/dist/hooks/shared/command-analyzer.js +972 -0
  141. package/dist/hooks/shared/command-parser.d.ts +5 -29
  142. package/dist/hooks/shared/command-parser.js +65 -35
  143. package/dist/hooks/shared/commit-guard.d.ts +15 -0
  144. package/dist/hooks/shared/commit-guard.js +176 -0
  145. package/dist/hooks/shared/hook-response.d.ts +6 -0
  146. package/dist/hooks/shared/hook-response.js +12 -0
  147. package/dist/hooks/shared/hook-timing.js +9 -3
  148. package/dist/hooks/shared/injection-caps.d.ts +32 -2
  149. package/dist/hooks/shared/injection-caps.js +73 -2
  150. package/dist/hooks/shared/is-main.d.ts +8 -0
  151. package/dist/hooks/shared/is-main.js +20 -0
  152. package/dist/hooks/shared/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
@@ -10,6 +10,7 @@
10
10
  * - hard strength rule 은 cli 로도 suppress 불가 (ADR-002 불변 원칙).
11
11
  */
12
12
  import { loadAllRules, saveRule } from '../store/rule-store.js';
13
+ import { withStatusChange } from '../store/rule-lifecycle.js';
13
14
  export async function handleSuppressRule(args) {
14
15
  const partial = args[0];
15
16
  if (!partial) {
@@ -40,14 +41,14 @@ export async function handleSuppressRule(args) {
40
41
  console.log(`Rule ${rule.rule_id} is already suppressed.`);
41
42
  return;
42
43
  }
43
- saveRule({ ...rule, status: 'suppressed' });
44
+ saveRule(withStatusChange(rule, 'suppressed', 'user: suppress-rule', 'cli'));
44
45
  console.log(`✓ Suppressed rule ${rule.rule_id}`);
45
46
  console.log(` Policy: ${rule.policy.slice(0, 80)}`);
46
47
  console.log(` Re-activate with: forgen activate-rule ${rule.rule_id}`);
47
48
  }
48
49
  /**
49
- * ADR-017 D1: enforce_mode 전환. `advise` = 차단 대신 기록만(precision 자동 강등과 같은 상태),
50
- * `enforce` = 차단 복귀(자동 강등 해제 — 사용자 명시). 하드 룰은 advise 로 내릴 수 없다.
50
+ * ADR-017 D1: enforce_mode 전환. `advise` = 차단 대신 기록만, `enforce` = 차단 켬(사용자 명시).
51
+ * 의미 룰(self_check)은 기본이 기록만이라 `enforce` 로 켠 것만 차단한다. 하드 룰은 advise 로 내릴 수 없다.
51
52
  */
52
53
  export async function handleEnforceMode(args, mode) {
53
54
  const { loadAllRules, saveRule } = await import('../store/rule-store.js');
@@ -70,10 +71,16 @@ export async function handleEnforceMode(args, mode) {
70
71
  console.log(`✗ [forgen] hard rule ${rule.rule_id.slice(0, 8)} cannot be set to advise`);
71
72
  return;
72
73
  }
73
- const prev = rule.enforce_mode ?? 'block';
74
+ const { ruleEnforced } = await import('./rule-detectability.js');
75
+ if (mode === 'block' && !(rule.enforce_via ?? []).some((s) => !!s.verifier)) {
76
+ console.log(`✗ [forgen] ${rule.rule_id.slice(0, 8)} 에는 판정기가 없어 차단할 수 없습니다. 주입만 됩니다.`);
77
+ process.exitCode = 1;
78
+ return;
79
+ }
80
+ const prev = rule.enforce_mode ?? (ruleEnforced(rule) ? 'block' : 'advise');
74
81
  rule.enforce_mode = mode;
75
82
  saveRule(rule);
76
- console.log(`✓ [forgen] ${rule.rule_id.slice(0, 8)} enforce_mode: ${prev} → ${mode}${mode === 'block' ? ' (차단 복귀 — 자동 강등 해제)' : ' (기록만, 차단 안 함)'}`);
83
+ console.log(`✓ [forgen] ${rule.rule_id.slice(0, 8)} enforce_mode: ${prev} → ${mode}${mode === 'block' ? ' (차단 켬)' : ' (기록만, 차단 안 함)'}`);
77
84
  }
78
85
  export async function handleActivateRule(args) {
79
86
  const partial = args[0];
@@ -100,7 +107,88 @@ export async function handleActivateRule(args) {
100
107
  console.error(`Cannot activate rule with status=${rule.status}. Edit the rule file directly.`);
101
108
  process.exit(1);
102
109
  }
103
- saveRule({ ...rule, status: 'active' });
110
+ saveRule(withStatusChange(rule, 'active', 'user: activate-rule', 'cli'));
104
111
  console.log(`✓ Activated rule ${rule.rule_id}`);
105
112
  console.log(` Policy: ${rule.policy.slice(0, 80)}`);
106
113
  }
114
+ /**
115
+ * D12-C: precision 판정으로 advise 강등된 룰을 한꺼번에 복구한다.
116
+ * 강등의 근거였던 오탐 판정 중 상당수는 "무관한 룰이 무관한 완료 보고를 막은" 주제 게이트 이전 오탐이었다.
117
+ * 기본은 목록만 보여주고(--apply 로 실행), 실행하면 enforce_mode 를 block 으로 되돌리고
118
+ * 게이트 이전 stop-guard 판정이 정밀도 계산에 다시 쓰이지 않도록 epoch 를 기록한다.
119
+ */
120
+ export async function handleRestoreDemoted(args) {
121
+ const apply = args.includes('--apply');
122
+ const { loadAllRules, saveRule } = await import('../store/rule-store.js');
123
+ const { lastDemotion } = await import('./block-judge.js');
124
+ const { writeRuleEpoch } = await import('./lifecycle/signals.js');
125
+ // precision 자동 강등으로 기록된 룰만(강등 기록 = 이전 모드·사유가 남은 것). 사용자가 직접 advise 로 둔 룰은 건드리지 않는다.
126
+ const { stopBlocks } = await import('./rule-detectability.js');
127
+ // 의미 룰은 지금 정책의 기본이 기록만이다. 일괄 복구로 차단을 켜지 않는다(켜려면 forgen rule enforce).
128
+ const semantic = (r) => (r.enforce_via ?? []).some((s) => s.hook === 'Stop' && !!s.verifier) && !stopBlocks({ ...r, enforce_mode: undefined });
129
+ const demoted = loadAllRules().filter((r) => r.status === 'active' && r.enforce_mode === 'advise' && lastDemotion(r.rule_id) && !semantic(r));
130
+ if (demoted.length === 0) {
131
+ console.log('복구할 자동 강등 룰이 없습니다.');
132
+ return;
133
+ }
134
+ console.log(`자동 강등(advise) 룰 ${demoted.length}개${apply ? ' — 복구합니다' : ' (미리보기. --apply 로 복구)'}`);
135
+ for (const r of demoted) {
136
+ const d = lastDemotion(r.rule_id);
137
+ console.log(` ${r.rule_id.slice(0, 8)} [${r.strength}] ${d ? `${d.at.slice(0, 10)} 정밀도 ${Math.round(d.precision * 100)}% (판정 ${d.judged}건, 이전 모드 ${d?.prev_mode ?? 'block'}${d?.reason ? `, 사유 ${d.reason}` : ''})` : ''} ${r.policy.slice(0, 60)}`);
138
+ if (apply) {
139
+ r.enforce_mode = d?.prev_mode ?? 'block';
140
+ saveRule(r);
141
+ writeRuleEpoch(r.rule_id); // 이 룰의 과거 판정만 기준에서 제외 — 다른 룰의 정밀도 기록은 그대로
142
+ }
143
+ }
144
+ if (apply)
145
+ console.log('✓ 복구 완료 — 복구한 룰의 이전 판정만 정밀도 기준에서 제외됩니다(다른 룰 기록은 유지).');
146
+ }
147
+ /**
148
+ * R9: explicit 교정 룰 병합은 자동으로 적용하지 않는다 — 제안만 쌓이고, 여기서 목록을 보고 --apply 로 확인한다.
149
+ * (적용 후에도 `forgen rule unmerge <id>` 로 원본 복구 가능.)
150
+ */
151
+ export async function handleMergeExplicit(args) {
152
+ const applyIdx = args.indexOf('--apply');
153
+ const apply = applyIdx >= 0;
154
+ // `--apply <id...>`: 미리보기에 표시된 제안 ID 만 적용한다 (ID 없는 --apply 는 거부 — 처음 보는 제안을 통째로 적용하지 않는다).
155
+ const ids = apply ? args.slice(applyIdx + 1).filter((a) => !a.startsWith('--')) : [];
156
+ const { runCorrectionClustering, MERGE_PROPOSALS_PATH } = await import('./correction-cluster-runner.js');
157
+ const { loadAllRules } = await import('../store/rule-store.js');
158
+ // 최신 제안을 보려면 먼저 제안 모드로 한 번 계산한다(변경 없음).
159
+ await runCorrectionClustering();
160
+ const fs = await import('node:fs');
161
+ let proposals = [];
162
+ try {
163
+ proposals = JSON.parse(fs.readFileSync(MERGE_PROPOSALS_PATH, 'utf-8')).proposals ?? [];
164
+ }
165
+ catch { /* none */ }
166
+ if (proposals.length === 0) {
167
+ console.log('병합 제안이 없습니다.');
168
+ return;
169
+ }
170
+ const byId = new Map(loadAllRules().map((r) => [r.rule_id, r]));
171
+ console.log(`explicit 룰 병합 제안 ${proposals.length}건${apply ? '' : ' (미리보기. 적용: forgen rule merge-explicit --apply <제안ID...>)'}`);
172
+ proposals.forEach((p) => {
173
+ console.log(` [${p.id ?? '?'}] → ${p.strength}: ${p.representative_policy.slice(0, 80)}`);
174
+ for (const id of p.members)
175
+ console.log(` - ${id.slice(0, 8)} ${byId.get(id)?.policy.slice(0, 70) ?? ''}`);
176
+ });
177
+ if (!apply)
178
+ return;
179
+ if (ids.length === 0) {
180
+ console.log('✗ 적용할 제안 ID 를 지정하세요: forgen rule merge-explicit --apply <제안ID...> (위 목록의 [ ] 안 값)');
181
+ process.exitCode = 1;
182
+ return;
183
+ }
184
+ // 룰이 바뀌면 ID 가 달라진다 → 미리보기 때와 달라졌으면 하나도 적용하지 않고 중단.
185
+ const fresh = new Set(proposals.map((p) => p.id));
186
+ const stale = ids.filter((id) => !fresh.has(id));
187
+ if (stale.length > 0) {
188
+ console.log(`✗ 중단: 제안 ${stale.join(', ')} 이(가) 현재 룰 상태와 맞지 않습니다(룰이 바뀌었거나 ID 오타). 미리보기를 다시 확인하세요. 아무것도 적용하지 않았습니다.`);
189
+ process.exitCode = 1;
190
+ return;
191
+ }
192
+ const merges = await runCorrectionClustering({ confirmed: true, only: ids });
193
+ console.log(`✓ ${merges.length}건 병합. 되돌리기: forgen rule unmerge <id>`);
194
+ }
@@ -1,20 +1,26 @@
1
1
  /**
2
2
  * Forgen — Skill Promoter
3
3
  *
4
- * verified/mature 솔루션을 .forgen/me/skills/ 스킬로 승격.
5
- * 솔루션(선언적 지식) → 스킬(절차적 지식) 변환.
4
+ * verified/mature 솔루션을 표준 SKILL.md(agentskills.io) 디렉터리로 승격한다. 변환은 Way 컴파일러(target: skill)가 한다.
5
+ * 기본 : ~/.forgen/me/skills/<name>/SKILL.md
6
+ * --install : ~/.claude/skills/<name>/SKILL.md (Claude Code 개인 스킬)
7
+ * --out <dir> : <dir>/<name>/SKILL.md
8
+ * `compound --verify` 게이트는 그대로다. 내용이 빈 솔루션은 거부한다.
6
9
  */
7
10
  export interface PromoteResult {
8
11
  success: boolean;
9
- skillPath?: string;
12
+ paths?: string[];
10
13
  reason?: string;
11
14
  }
12
- /** 솔루션을 스킬로 승격 */
13
- export declare function promoteSolution(solutionName: string, triggers?: string[]): PromoteResult;
14
- /** 스킬 목록 조회 */
15
+ export interface PromoteOptions {
16
+ install?: boolean;
17
+ out?: string;
18
+ force?: boolean;
19
+ }
20
+ export declare function promoteSolution(solutionName: string, opts?: PromoteOptions): PromoteResult;
21
+ /** 스킬 목록 조회 (SKILL.md 디렉터리 + 구 형식 .md) */
15
22
  export declare function listSkills(): Array<{
16
23
  name: string;
17
24
  status: string;
18
- promotedFrom?: string;
19
- triggers: string[];
25
+ description: string;
20
26
  }>;
@@ -1,112 +1,84 @@
1
1
  /**
2
2
  * Forgen — Skill Promoter
3
3
  *
4
- * verified/mature 솔루션을 .forgen/me/skills/ 스킬로 승격.
5
- * 솔루션(선언적 지식) → 스킬(절차적 지식) 변환.
4
+ * verified/mature 솔루션을 표준 SKILL.md(agentskills.io) 디렉터리로 승격한다. 변환은 Way 컴파일러(target: skill)가 한다.
5
+ * 기본 : ~/.forgen/me/skills/<name>/SKILL.md
6
+ * --install : ~/.claude/skills/<name>/SKILL.md (Claude Code 개인 스킬)
7
+ * --out <dir> : <dir>/<name>/SKILL.md
8
+ * `compound --verify` 게이트는 그대로다. 내용이 빈 솔루션은 거부한다.
6
9
  */
7
10
  import * as fs from 'node:fs';
8
11
  import * as path from 'node:path';
9
12
  import { parseSolutionV3 } from './solution-format.js';
10
13
  import { createLogger } from '../core/logger.js';
11
14
  import { ME_SOLUTIONS, ME_SKILLS, CLAUDE_DIR } from '../core/paths.js';
15
+ import { compile } from '../way/compile.js';
16
+ import { readSolutions } from '../way/extract.js';
17
+ import { writeFiles } from '../way/io.js';
18
+ import { WAY_SCHEMA } from '../way/types.js';
12
19
  const log = createLogger('skill-promoter');
13
- // Claude Code가 자동 인식하는 글로벌 스킬 경로 (~/.claude/skills)
14
- const CLAUDE_SKILLS = path.join(CLAUDE_DIR, 'skills');
15
- // 일반적인 태그 제외 (트리거로 부적합)
16
- const GENERIC_TAGS = new Set([
17
- 'typescript', 'javascript', 'react', 'node', 'error', 'fix', 'code',
18
- 'pattern', 'solution', 'decision', 'troubleshoot', 'project', 'file',
19
- ]);
20
- /** 솔루션을 스킬로 승격 */
21
- export function promoteSolution(solutionName, triggers) {
22
- // 1. 솔루션 찾기
20
+ export function promoteSolution(solutionName, opts = {}) {
21
+ if (!/^[\w.-]+$/.test(solutionName))
22
+ return { success: false, reason: `Invalid solution name: ${solutionName}` };
23
23
  const solPath = path.join(ME_SOLUTIONS, `${solutionName}.md`);
24
- if (!fs.existsSync(solPath)) {
24
+ if (!fs.existsSync(solPath))
25
25
  return { success: false, reason: `Solution not found: ${solutionName}` };
26
- }
27
- const content = fs.readFileSync(solPath, 'utf-8');
28
- const parsed = parseSolutionV3(content);
29
- if (!parsed) {
26
+ const parsed = parseSolutionV3(fs.readFileSync(solPath, 'utf-8'));
27
+ if (!parsed)
30
28
  return { success: false, reason: `Failed to parse solution: ${solutionName}` };
31
- }
32
- // 2. 자격 검증: verified 이상만
33
29
  if (!['verified', 'mature'].includes(parsed.frontmatter.status)) {
34
30
  return {
35
31
  success: false,
36
32
  reason: `Only verified/mature solutions can be promoted. Current: ${parsed.frontmatter.status}. Use 'forgen compound --verify ${solutionName}' first.`,
37
33
  };
38
34
  }
39
- // 3. 중복 체크
40
- const skillPath = path.join(ME_SKILLS, `${solutionName}.md`);
41
- if (fs.existsSync(skillPath)) {
42
- return { success: false, reason: `Skill already exists: ${solutionName}` };
43
- }
44
- // 4. 트리거 결정
45
- const effectiveTriggers = triggers ?? deriveTriggersFromTags(parsed.frontmatter.tags);
46
- if (effectiveTriggers.length === 0) {
47
- return { success: false, reason: 'No triggers could be derived. Provide --trigger manually.' };
35
+ if (!parsed.content.trim())
36
+ return { success: false, reason: `Solution has no content: ${solutionName}. A skill needs a procedure to carry.` };
37
+ const id = `solution:${solutionName}`;
38
+ const item = readSolutions().items.find((i) => i.id === id);
39
+ if (!item)
40
+ return { success: false, reason: `Solution is not exportable (habit log or invalid): ${solutionName}` };
41
+ const res = compile({ schema: WAY_SCHEMA, generator: 'forgen-way', generated_at: new Date().toISOString(), items: [item], stats: {} }, 'skill', { only: [id] });
42
+ if (!res.files.length)
43
+ return { success: false, reason: `Nothing to write for ${solutionName}` };
44
+ // 컴파일러 경로(.claude/skills/<name>/SKILL.md)에서 <name>/SKILL.md 만 취해 대상 폴더에 놓는다.
45
+ const files = res.files.map((f) => ({ ...f, path: f.path.replace(/^\.claude\/skills\//, '') }));
46
+ const base = opts.out ? path.resolve(opts.out) : opts.install ? path.join(CLAUDE_DIR, 'skills') : ME_SKILLS;
47
+ const { plan, written } = writeFiles(files, base, opts.force ?? false);
48
+ const blocked = plan.find((p) => p.action.startsWith('blocked'));
49
+ if (blocked) {
50
+ return { success: false, reason: blocked.action === 'blocked-foreign'
51
+ ? `${blocked.abs} exists and was not written by forgen. Not overwritten.`
52
+ : `${blocked.abs} already exists with different content. Use --force to overwrite.` };
48
53
  }
49
- // 5. 스킬 파일 생성
50
- const description = parsed.context
51
- ? parsed.context.split('\n')[0].slice(0, 100)
52
- : `${solutionName} 패턴 적용`;
53
- const skillContent = [
54
- '---',
55
- `name: ${solutionName}`,
56
- `description: ${description}`,
57
- 'triggers:',
58
- ...effectiveTriggers.map(t => ` - "${t}"`),
59
- `promoted_from: solution/${solutionName}`,
60
- `promoted_at: "${new Date().toISOString().split('T')[0]}"`,
61
- 'status: candidate',
62
- 'usage_count: 0',
63
- '---',
64
- '',
65
- '<Purpose>',
66
- parsed.context || `${solutionName} 패턴을 적용합니다.`,
67
- '</Purpose>',
68
- '',
69
- '<Steps>',
70
- parsed.content,
71
- '</Steps>',
72
- ].join('\n');
73
- fs.mkdirSync(ME_SKILLS, { recursive: true });
74
- fs.writeFileSync(skillPath, skillContent);
75
- // Claude Code 네이티브 스킬로도 등록 (~/.claude/skills/{name}/SKILL.md)
76
- const claudeSkillDir = path.join(CLAUDE_SKILLS, solutionName);
77
- fs.mkdirSync(claudeSkillDir, { recursive: true });
78
- fs.writeFileSync(path.join(claudeSkillDir, 'SKILL.md'), skillContent);
79
- log.debug(`스킬 승격 완료: ${solutionName} → ${skillPath} + ${claudeSkillDir}`);
80
- return { success: true, skillPath };
54
+ log.debug(`스킬 승격 완료: ${solutionName} → ${plan.map((p) => p.abs).join(', ')} (written ${written})`);
55
+ return { success: true, paths: plan.map((p) => p.abs) };
81
56
  }
82
- /** 태그에서 트리거 키워드 자동 추출 */
83
- function deriveTriggersFromTags(tags) {
84
- return tags
85
- .filter(t => t.length >= 3 && !GENERIC_TAGS.has(t.toLowerCase()))
86
- .slice(0, 3);
87
- }
88
- /** 스킬 목록 조회 */
57
+ /** 스킬 목록 조회 (SKILL.md 디렉터리 + 구 형식 .md) */
89
58
  export function listSkills() {
90
59
  if (!fs.existsSync(ME_SKILLS))
91
60
  return [];
92
- return fs.readdirSync(ME_SKILLS)
93
- .filter(f => f.endsWith('.md'))
94
- .map(f => {
61
+ const out = [];
62
+ for (const entry of fs.readdirSync(ME_SKILLS, { withFileTypes: true })) {
63
+ const file = entry.isDirectory() ? path.join(ME_SKILLS, entry.name, 'SKILL.md') : entry.name.endsWith('.md') ? path.join(ME_SKILLS, entry.name) : '';
64
+ if (!file || !fs.existsSync(file))
65
+ continue;
95
66
  try {
96
- const content = fs.readFileSync(path.join(ME_SKILLS, f), 'utf-8');
97
- const fmMatch = content.match(/^---\n([\s\S]*?)\n---/);
98
- if (!fmMatch)
99
- return null;
100
- const fm = fmMatch[1];
101
- const name = fm.match(/name:\s*(.+)/)?.[1]?.trim() ?? f.replace('.md', '');
102
- const status = fm.match(/status:\s*(.+)/)?.[1]?.trim() ?? 'unknown';
103
- const promotedFrom = fm.match(/promoted_from:\s*(.+)/)?.[1]?.trim();
104
- const triggers = [...fm.matchAll(/- "(.+)"/g)].map(m => m[1]);
105
- return { name, status, promotedFrom, triggers };
106
- }
107
- catch {
108
- return null;
67
+ const fm = /^---\n([\s\S]*?)\n---/.exec(fs.readFileSync(file, 'utf-8'))?.[1];
68
+ if (!fm)
69
+ continue;
70
+ const name = fm.match(/^name:\s*(.+)$/m)?.[1]?.trim() ?? entry.name.replace(/\.md$/, '');
71
+ const status = entry.isDirectory() ? 'standard' : (fm.match(/^status:\s*(.+)$/m)?.[1]?.trim() ?? 'legacy');
72
+ let description = fm.match(/^description:\s*(.+)$/m)?.[1]?.trim() ?? '';
73
+ if (description.startsWith('"')) {
74
+ try {
75
+ description = JSON.parse(description);
76
+ }
77
+ catch { /* 그대로 */ }
78
+ }
79
+ out.push({ name, status, description: description.length > 80 ? `${description.slice(0, 79)}…` : description });
109
80
  }
110
- })
111
- .filter((s) => s !== null);
81
+ catch { /* 건너뜀 */ }
82
+ }
83
+ return out;
112
84
  }
@@ -21,7 +21,16 @@ export interface SolutionFrontmatter {
21
21
  updated: string;
22
22
  supersedes: string | null;
23
23
  extractedBy: 'auto' | 'manual';
24
+ /**
25
+ * 적용 프로젝트 키(룰의 `projects` 와 같은 키: git 저장소 폴더 이름 소문자). 없으면 전역.
26
+ * 구버전 파서는 모르는 키를 무시하므로 호환된다(검증이 추가 키를 거부하지 않는다).
27
+ */
28
+ projects?: string[];
29
+ /** 은퇴 사유 (D6). stale=기간 경과, contradicted=반증, manual=사용자 지정. 없으면 사유 미상(구버전 은퇴). */
30
+ retiredReason?: RetiredReason;
31
+ retiredAt?: string;
24
32
  }
33
+ export type RetiredReason = 'stale' | 'contradicted' | 'manual';
25
34
  export interface SolutionV3 {
26
35
  frontmatter: SolutionFrontmatter;
27
36
  context: string;
@@ -35,6 +44,8 @@ export interface SolutionIndexEntry {
35
44
  type: SolutionType;
36
45
  scope: 'me' | 'team' | 'project' | 'universal';
37
46
  tags: string[];
47
+ /** 적용 프로젝트 키 (없으면 전역). */
48
+ projects?: string[];
38
49
  /**
39
50
  * Pre-expanded tag set, computed at index build time via the term normalizer.
40
51
  * Contains `tags` plus every related match term from the canonical families
@@ -76,6 +87,16 @@ export declare function parseSolutionV3(content: string): SolutionV3 | null;
76
87
  export declare function serializeSolutionV3(solution: SolutionV3): string;
77
88
  /** Check if content is in V1 format (# Title + > Type: pattern) */
78
89
  export declare function isV1Format(content: string): boolean;
90
+ /**
91
+ * 솔루션 태그에서만 빼는 템플릿·메타 단어 (D5). "무엇: … 왜: … 어떻게: …" 형식과 설명문에서 태그로 새어 나오고, 대부분의 솔루션에 있어
92
+ * 변별력이 없다. 룰 클러스터링·룰 관련도 같은 다른 extractTags 소비자는 이 단어를 그대로 쓰므로 `solution: true` 일 때만 적용한다.
93
+ */
94
+ export declare const KO_TEMPLATE_WORDS: Set<string>;
95
+ /**
96
+ * 조사 제거가 어간을 자르는 명사 ("고빈도"→"고빈"). 끝 글자가 조사(도·이·가·의·과·와·만·로)와 같은 흔한 명사만 보호한다.
97
+ * 목록은 보수적으로 — 새 항목은 실제로 잘린 사례가 확인될 때만 추가한다.
98
+ */
99
+ export declare const KO_PROTECTED_NOUNS: Set<string>;
79
100
  /** 영어 불용어 */
80
101
  export declare const EN_STOPWORDS: Set<string>;
81
102
  /** 한국어 일반 조사/어미 — strip 대상 (긴 것부터 매칭)
@@ -106,7 +127,11 @@ export declare function stripKoSuffix(word: string): string;
106
127
  * representation of every existing solution, requiring an index rebuild and
107
128
  * a fresh `ROUND3_BASELINE` measurement on every downstream PR.
108
129
  */
109
- export declare function extractTags(text: string): string[];
130
+ export declare function extractTags(text: string, opts?: {
131
+ solution?: boolean;
132
+ }): string[];
133
+ /** 솔루션 태그 추출 (저장·질의 공통): extractTags + 템플릿 단어·활용형 제거. */
134
+ export declare function extractSolutionTags(text: string): string[];
110
135
  /**
111
136
  * Expand a solution tag list with hyphen-split alternatives.
112
137
  *
@@ -334,6 +334,50 @@ const KO_STOPWORDS = new Set([
334
334
  '다음',
335
335
  '최종',
336
336
  ]);
337
+ /**
338
+ * 솔루션 태그에서만 빼는 템플릿·메타 단어 (D5). "무엇: … 왜: … 어떻게: …" 형식과 설명문에서 태그로 새어 나오고, 대부분의 솔루션에 있어
339
+ * 변별력이 없다. 룰 클러스터링·룰 관련도 같은 다른 extractTags 소비자는 이 단어를 그대로 쓰므로 `solution: true` 일 때만 적용한다.
340
+ */
341
+ export const KO_TEMPLATE_WORDS = new Set([
342
+ '무엇',
343
+ '실제',
344
+ '실제로',
345
+ '파일',
346
+ '왜냐',
347
+ '주의',
348
+ '예시',
349
+ '대신',
350
+ '기존',
351
+ '해당',
352
+ '각각',
353
+ '항상',
354
+ '반드시',
355
+ '때문',
356
+ '위해',
357
+ '통해',
358
+ '경우',
359
+ '사용자에게',
360
+ '않는다',
361
+ '않다',
362
+ '있다',
363
+ '없다',
364
+ '말고',
365
+ '하지',
366
+ ]);
367
+ /** 동사 활용 꼴("나오면", "확인하려면", "반복되면") — 주제어가 아니다. "화면"·"표면" 같은 명사는 걸리지 않는 어미만 쓴다. */
368
+ const KO_VERBAL_NOISE_RE = /(?:으면|오면|우면|하면|되면|려면|라면|하거나|는지|은지)$/;
369
+ /**
370
+ * 조사 제거가 어간을 자르는 명사 ("고빈도"→"고빈"). 끝 글자가 조사(도·이·가·의·과·와·만·로)와 같은 흔한 명사만 보호한다.
371
+ * 목록은 보수적으로 — 새 항목은 실제로 잘린 사례가 확인될 때만 추가한다.
372
+ */
373
+ export const KO_PROTECTED_NOUNS = new Set([
374
+ '고빈도', '저빈도', '빈도', '강도', '속도', '정도', '온도', '밀도', '각도', '난이도', '신뢰도', '완성도', '정확도',
375
+ '중요도', '만족도', '유사도', '관련도', '해상도', '투명도', '적합도', '이해도', '인지도', '선호도', '활용도', '진척도',
376
+ '숙련도', '충실도', '채도', '명도', '습도', '농도', '연도', '제도', '태도', '지도', '정보밀도', '우선도', '가시도',
377
+ '차이', '사이', '아이', '높이', '길이', '깊이', '넓이', '나이', '다이', '라이', '모이', '세이',
378
+ '평가', '고가', '저가', '단가', '물가', '시가', '대가', '원가', '지가', '공과', '성과', '효과', '결과', '교과', '연과',
379
+ '의의', '회의', '합의', '동의', '논의', '심의', '건의', '주의', '계의',
380
+ ]);
337
381
  /** 영어 불용어 */
338
382
  export const EN_STOPWORDS = new Set([
339
383
  'the',
@@ -400,9 +444,19 @@ export const KO_SUFFIXES = [
400
444
  '합니다',
401
445
  '입니다',
402
446
  '됩니다',
447
+ '에서는',
448
+ '으로는',
449
+ '에게는',
403
450
  '에서',
404
451
  '까지',
405
452
  '으로',
453
+ '이랑',
454
+ '에게',
455
+ '한테',
456
+ '부터',
457
+ '처럼',
458
+ '보다',
459
+ '마다',
406
460
  '하는',
407
461
  '하고',
408
462
  '했다',
@@ -423,6 +477,8 @@ export const KO_SUFFIXES = [
423
477
  '로',
424
478
  ];
425
479
  export function stripKoSuffix(word) {
480
+ if (KO_PROTECTED_NOUNS.has(word))
481
+ return word;
426
482
  for (const suffix of KO_SUFFIXES) {
427
483
  if (word.endsWith(suffix) && word.length > suffix.length) {
428
484
  return word.slice(0, -suffix.length);
@@ -448,7 +504,7 @@ const MAX_TAGS = 8;
448
504
  * representation of every existing solution, requiring an index rebuild and
449
505
  * a fresh `ROUND3_BASELINE` measurement on every downstream PR.
450
506
  */
451
- export function extractTags(text) {
507
+ export function extractTags(text, opts = {}) {
452
508
  const cleaned = text.toLowerCase().replace(/[^가-힣a-z0-9\s]/g, ' ');
453
509
  const words = cleaned.split(/\s+/).filter(Boolean);
454
510
  const freq = new Map();
@@ -458,8 +514,10 @@ export function extractTags(text) {
458
514
  const base = normalizeColloquialKo(w);
459
515
  if (base === null)
460
516
  continue;
517
+ if (opts.solution && KO_VERBAL_NOISE_RE.test(base) && base.length >= 3)
518
+ continue;
461
519
  const stem = stripKoSuffix(base);
462
- if (stem.length >= 2 && !KO_STOPWORDS.has(stem)) {
520
+ if (stem.length >= 2 && !KO_STOPWORDS.has(stem) && !(opts.solution && KO_TEMPLATE_WORDS.has(stem))) {
463
521
  freq.set(stem, (freq.get(stem) ?? 0) + 1);
464
522
  }
465
523
  }
@@ -473,6 +531,10 @@ export function extractTags(text) {
473
531
  .slice(0, MAX_TAGS)
474
532
  .map(([tag]) => tag);
475
533
  }
534
+ /** 솔루션 태그 추출 (저장·질의 공통): extractTags + 템플릿 단어·활용형 제거. */
535
+ export function extractSolutionTags(text) {
536
+ return extractTags(text, { solution: true });
537
+ }
476
538
  // ── Compound-tag expansion (R4-T1) ──
477
539
  //
478
540
  // The matcher's tag intersection step compares solution.tags directly
@@ -608,7 +670,7 @@ export function expandQueryBigrams(tags) {
608
670
  * 쿼리 사이드만 확장하므로 인덱스 재구축·ROUND3_BASELINE 재측정이 불필요
609
671
  * (expandQueryBigrams와 같은 계약).
610
672
  */
611
- const KO_CONJUGATION_RE = /^([가-힣]{2,}?)(했|하|해|됐|되|돼)[가-힣]*$/;
673
+ const KO_CONJUGATION_RE = /^([가-힣]{2,}?)(했|하|해|됐|되|돼|할)[가-힣]*$/;
612
674
  export function expandQueryKoreanStems(tags) {
613
675
  const out = new Set(tags);
614
676
  for (const tag of tags) {
@@ -0,0 +1 @@
1
+ export declare function isHabitLog(name: string, rawContent: string): boolean;
@@ -0,0 +1,22 @@
1
+ /**
2
+ * 습관 로그 판정. `works-with-typescript` 류는 "주로 TypeScript 코드를 작성합니다" 한 줄뿐이라 다른 작업에 재사용할
3
+ * 지식이 아니고, 흔한 단어 때문에 주입 매치의 상당 부분을 차지했다(실측 31%). 솔루션이 아니라 behavior 로 취급한다.
4
+ *
5
+ * 판정 (extractedBy: auto 이고, 아래 둘 중 하나):
6
+ * - 이름이 제거된 추출기 접두사 (works-with-, writes-, edits-, uses-, prefers-) 이고 본문이 짧다(<=120자)
7
+ * - Context 가 "Detected from N … operations" (추출기가 남긴 표지)
8
+ */
9
+ import { parseSolutionV3 } from './solution-format.js';
10
+ const HABIT_NAME_RE = /^(works-with|writes|edits|uses|prefers)-/;
11
+ const HABIT_CONTEXT_RE = /^Detected from \d+ [a-z ]*operations?/i;
12
+ export function isHabitLog(name, rawContent) {
13
+ const parsed = parseSolutionV3(rawContent);
14
+ if (!parsed)
15
+ return false;
16
+ // 자동 생성 표식(extractedBy: auto)이 없으면 사용자가 쓴 솔루션이다. 이름·길이가 비슷해도 습관 로그로 취급하지 않는다.
17
+ if (parsed.frontmatter.extractedBy !== 'auto')
18
+ return false;
19
+ if (HABIT_CONTEXT_RE.test(parsed.context.trim()))
20
+ return true;
21
+ return HABIT_NAME_RE.test(name) && parsed.content.trim().length <= 120;
22
+ }
@@ -11,3 +11,8 @@ export interface SolutionIndex {
11
11
  export declare function isIndexStale(index: SolutionIndex): boolean;
12
12
  export declare function getOrBuildIndex(dirs: SolutionDirConfig[]): SolutionIndex;
13
13
  export declare function resetIndexCache(): void;
14
+ /**
15
+ * 기본 솔루션 디렉터리 목록 — hook 매칭과 MCP 검색이 **같은 목록**을 쓴다(경로 일치).
16
+ * 설치된 팩의 solutions/ 와 cwd 의 project 스코프를 포함한다. 이름순 정렬로 우선순위가 결정적이다.
17
+ */
18
+ export declare function defaultSolutionDirs(cwd?: string): SolutionDirConfig[];
@@ -6,6 +6,8 @@ import { withFileLockSync } from '../hooks/shared/file-lock.js';
6
6
  import { atomicWriteText } from '../hooks/shared/atomic-write.js';
7
7
  import { createLogger } from '../core/logger.js';
8
8
  import { recordQuarantine, diagnoseFromRawContent } from './solution-quarantine.js';
9
+ import { isHabitLog } from './solution-habit.js';
10
+ import { ME_SOLUTIONS, PACKS_DIR } from '../core/paths.js';
9
11
  const log = createLogger('solution-index');
10
12
  /**
11
13
  * Cache keyed by an order-preserving directory signature.
@@ -107,6 +109,7 @@ function buildIndex(dirs) {
107
109
  let droppedRetired = 0;
108
110
  let droppedIoError = 0;
109
111
  let droppedSymlink = 0;
112
+ let droppedHabit = 0;
110
113
  for (const file of files) {
111
114
  try {
112
115
  const filePath = path.join(dir, file);
@@ -172,6 +175,11 @@ function buildIndex(dirs) {
172
175
  droppedRetired++;
173
176
  continue;
174
177
  }
178
+ // 습관 로그(`works-with-typescript` 류)는 솔루션이 아니라 behavior 다 — 매처·검색 대상에서 뺀다.
179
+ if (isHabitLog(fm.name, content)) {
180
+ droppedHabit++;
181
+ continue;
182
+ }
175
183
  fileEntries.push({
176
184
  entry: {
177
185
  name: fm.name,
@@ -180,6 +188,7 @@ function buildIndex(dirs) {
180
188
  type: fm.type,
181
189
  scope: dirConfig.scope,
182
190
  tags: fm.tags,
191
+ ...(Array.isArray(fm.projects) && fm.projects.length ? { projects: fm.projects.filter((x) => typeof x === 'string').map((x) => x.toLowerCase()) } : {}),
183
192
  // T2: pre-expand via the shared term normalizer. Once per solution
184
193
  // per index build, not once per solution per query. Safe to
185
194
  // recompute on rebuild (cheap: O(N_tags) Map lookups).
@@ -219,6 +228,9 @@ function buildIndex(dirs) {
219
228
  else if (totalBad > 0) {
220
229
  log.debug(`${dir}: ${droppedMalformed} malformed, ${droppedIoError} i/o errors, ${droppedSymlink} symlinks skipped (${totalBad}/${totalScanned} files)`);
221
230
  }
231
+ if (droppedHabit > 0) {
232
+ log.debug(`${dir}: ${droppedHabit} habit-log entries excluded from matching (move with \`forgen compound habits --apply\`)`);
233
+ }
222
234
  if (droppedRetired > 0) {
223
235
  log.debug(`${dir}: ${droppedRetired} retired solutions filtered (expected)`);
224
236
  }
@@ -260,3 +272,23 @@ export function getOrBuildIndex(dirs) {
260
272
  export function resetIndexCache() {
261
273
  cachedIndexes.clear();
262
274
  }
275
+ /**
276
+ * 기본 솔루션 디렉터리 목록 — hook 매칭과 MCP 검색이 **같은 목록**을 쓴다(경로 일치).
277
+ * 설치된 팩의 solutions/ 와 cwd 의 project 스코프를 포함한다. 이름순 정렬로 우선순위가 결정적이다.
278
+ */
279
+ export function defaultSolutionDirs(cwd) {
280
+ const dirs = [{ dir: ME_SOLUTIONS, scope: 'me' }];
281
+ try {
282
+ if (fs.existsSync(PACKS_DIR)) {
283
+ for (const entry of fs.readdirSync(PACKS_DIR).sort()) {
284
+ const solDir = path.join(PACKS_DIR, entry, 'solutions');
285
+ if (fs.existsSync(solDir))
286
+ dirs.push({ dir: solDir, scope: 'team' });
287
+ }
288
+ }
289
+ }
290
+ catch { /* 팩 디렉터리 접근 실패는 무시 */ }
291
+ if (cwd)
292
+ dirs.push({ dir: path.join(cwd, '.compound', 'solutions'), scope: 'project' });
293
+ return dirs;
294
+ }