@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
@@ -0,0 +1,335 @@
1
+ /**
2
+ * Way 초안 — 주제 하나에 대해 룰·솔루션·교정 원문을 모아 SKILL.md 또는 호스트 중립 워크플로우 초안을 쓴다.
3
+ * forgen way draft skill "<주제>" [--project k] [--out dir]
4
+ * forgen way draft workflow "<주제>" [--project k] [--out dir]
5
+ *
6
+ * 룰 하나를 옮긴 스킬은 제목과 절차가 같은 문장이라 쓸모가 없다. 여기서는 주제와 관련된 항목을 모아 격리된 Haiku 중첩 호출로
7
+ * 절차·판단 기준·실패 대응을 정리한다. 원문에 없는 절차를 지어내지 않도록 프롬프트가 못 박고, 근거 항목 id 는 초안 옆 파일에 남긴다.
8
+ * Haiku 를 쓸 수 없으면 모은 항목 묶음을 그대로(결정론) 출력하고 사유를 보여 준다.
9
+ *
10
+ * 전송 전: 비밀 마스킹(redactSecrets) + <private> 제거(stripPrivate). 통째로 private 인 항목은 보내지 않는다.
11
+ */
12
+ import * as fs from 'node:fs';
13
+ import * as crypto from 'node:crypto';
14
+ import * as path from 'node:path';
15
+ import { callHaiku, probeClaudeAvailability } from '../core/extraction-haiku.js';
16
+ import { resolveScope } from '../core/scope-resolver.js';
17
+ import { isFullyPrivate, stripPrivate } from '../engine/private-filter.js';
18
+ import { relevantRules } from '../engine/rule-relevance.js';
19
+ import { parseSolutionV3 } from '../engine/solution-format.js';
20
+ import { isHabitLog } from '../engine/solution-habit.js';
21
+ import { defaultSolutionDirs } from '../engine/solution-index.js';
22
+ import { defaultNormalizer } from '../engine/term-normalizer.js';
23
+ import { matchSolutions } from '../engine/solution-matcher.js';
24
+ import { redactSecrets } from '../hooks/secret-filter.js';
25
+ import { loadAllEvidence } from '../store/evidence-store.js';
26
+ import { ruleOrigin } from '../store/rule-origin.js';
27
+ import { loadAllRules } from '../store/rule-store.js';
28
+ const MAX_RULES = 8;
29
+ const MAX_SOLUTIONS = 6;
30
+ const MAX_CORRECTIONS = 6;
31
+ const CLIP_SOLUTION = 700;
32
+ const CLIP_RULE = 400;
33
+ const CLIP_CORRECTION = 300;
34
+ /** rule-relevance 점수만으로 채택하려면 이 점수 이상(일반 용어 4개 / 식별자급 2개). 그보다 낮으면 주제어가 본문에 실제로 있어야 한다. */
35
+ const RELEVANCE_ALONE = 2.0;
36
+ /** 같은 종류에서 최고 점수의 이 비율 미만은 버린다 (관련 없는 항목이 꼬리로 따라붙는 것 방지). */
37
+ const RELATIVE_CUT = 0.6;
38
+ function relativeCut(entries) {
39
+ const top = Math.max(0, ...entries.map((e) => e[1]));
40
+ return entries.filter((e) => e[1] >= top * RELATIVE_CUT);
41
+ }
42
+ function clean(text, max) {
43
+ if (isFullyPrivate(text))
44
+ return null;
45
+ const t = redactSecrets(stripPrivate(text).cleaned).redacted.replace(/\s+/g, ' ').trim();
46
+ if (!t)
47
+ return null;
48
+ return t.length > max ? `${t.slice(0, max - 1)}…` : t;
49
+ }
50
+ function inProject(projects, project) {
51
+ if (!project)
52
+ return true;
53
+ return !projects || projects.length === 0 || projects.includes(project);
54
+ }
55
+ /**
56
+ * 주제어 기반 보조 매칭. rule-relevance·매처는 긴 프롬프트용이라 "격리 검증" 같은 짧은 주제를 놓친다(한글 어미 `검증하라` 등).
57
+ * 주제의 낱말마다 동의어 계열(term-normalizer)까지 펴서 본문에 있는지 보고, 낱말 대부분(둘이면 둘 다)이 있어야 관련으로 본다.
58
+ */
59
+ function topicWords(topic) {
60
+ return [...new Set(topic.toLowerCase().split(/[\s,/·]+/).map((w) => w.replace(/[^\p{L}\p{N}-]/gu, '')).filter((w) => w.length >= 2))];
61
+ }
62
+ function termIn(term, lower) {
63
+ const t = term.toLowerCase();
64
+ if (/^[a-z0-9._-]+$/.test(t))
65
+ return new RegExp(`(^|[^a-z0-9])${t.replace(/[.]/g, '\\.')}`).test(lower);
66
+ return lower.includes(t);
67
+ }
68
+ export function topicScore(topic, text) {
69
+ const words = topicWords(topic);
70
+ if (words.length === 0)
71
+ return 0;
72
+ const lower = text.toLowerCase();
73
+ let hit = 0;
74
+ for (const w of words)
75
+ if (defaultNormalizer.normalizeTerms([w]).some((t) => termIn(t, lower)))
76
+ hit++;
77
+ const need = words.length <= 1 ? 1 : Math.ceil(words.length * 0.6);
78
+ return hit >= need ? Math.round((hit / words.length) * 100) / 100 : 0;
79
+ }
80
+ /** 주제와 관련된 룰(rule-relevance + 주제어), 솔루션(매처 + 주제어), 교정 원문(같은 기준)을 모은다. */
81
+ export function gatherSources(topic, opts = {}) {
82
+ const cwd = opts.cwd ?? process.cwd();
83
+ const project = opts.project?.toLowerCase();
84
+ const sources = [];
85
+ const have = new Set();
86
+ let excludedPrivate = 0;
87
+ const add = (s) => { if (!have.has(s.id)) {
88
+ have.add(s.id);
89
+ sources.push(s);
90
+ } };
91
+ // 1) 룰
92
+ const rules = loadAllRules().filter((r) => r.status === 'active' && inProject(r.projects, project));
93
+ const rank = new Map();
94
+ const topical = new Map();
95
+ for (const r of rules) {
96
+ const sc = topicScore(topic, `${r.trigger ?? ''} ${r.policy}`);
97
+ if (sc > 0)
98
+ topical.set(r.rule_id, sc);
99
+ }
100
+ for (const hit of relevantRules(topic, rules))
101
+ if (topical.has(hit.rule_id) || hit.score >= RELEVANCE_ALONE)
102
+ rank.set(hit.rule_id, hit.score + (topical.get(hit.rule_id) ?? 0));
103
+ for (const [id, sc] of topical)
104
+ rank.set(id, Math.max(rank.get(id) ?? 0, sc));
105
+ const byId = new Map(rules.map((r) => [r.rule_id, r]));
106
+ for (const [id, score] of relativeCut([...rank].sort((a, b) => b[1] - a[1]).slice(0, MAX_RULES))) {
107
+ const rule = byId.get(id);
108
+ if (!rule)
109
+ continue;
110
+ const text = clean(`${rule.trigger ? `[${rule.trigger}] ` : ''}${rule.policy}`, CLIP_RULE);
111
+ if (!text) {
112
+ excludedPrivate++;
113
+ continue;
114
+ }
115
+ const q = ruleOrigin(rule);
116
+ const quote = q?.quoteSource === 'user' ? clean(q.quote, CLIP_CORRECTION) ?? undefined : undefined;
117
+ add({ id: `rule:${rule.rule_id}`, kind: 'rule', text, quote, score });
118
+ }
119
+ // 2) 솔루션: 매처(주입과 같은 경로) + 주제어
120
+ const solCand = new Map();
121
+ try {
122
+ // 매처 후보는 태그 2개 이상 겹칠 때만 (짧은 주제에서 낱말 하나로 걸린 무관한 솔루션 방지)
123
+ for (const m of matchSolutions(topic, resolveScope(cwd), cwd))
124
+ if (m.status !== 'retired' && m.matchedTags.length >= 2)
125
+ solCand.set(m.name, { path: m.path, score: m.relevance });
126
+ }
127
+ catch { /* 매처 실패는 주제어 매칭만으로 진행 */ }
128
+ for (const { dir } of defaultSolutionDirs(cwd)) {
129
+ let files = [];
130
+ try {
131
+ files = fs.readdirSync(dir).filter((f) => f.endsWith('.md'));
132
+ }
133
+ catch {
134
+ continue;
135
+ }
136
+ for (const f of files) {
137
+ const fp = path.join(dir, f);
138
+ let raw = '';
139
+ try {
140
+ raw = fs.readFileSync(fp, 'utf-8');
141
+ }
142
+ catch {
143
+ continue;
144
+ }
145
+ const parsed = parseSolutionV3(raw);
146
+ if (!parsed || parsed.frontmatter.status === 'retired' || isHabitLog(parsed.frontmatter.name, raw))
147
+ continue;
148
+ const sc = topicScore(topic, `${parsed.frontmatter.name.replace(/-/g, ' ')} ${parsed.frontmatter.tags.join(' ')} ${parsed.context} ${parsed.content}`);
149
+ if (sc > 0)
150
+ solCand.set(parsed.frontmatter.name, { path: fp, score: Math.max(sc, solCand.get(parsed.frontmatter.name)?.score ?? 0) });
151
+ }
152
+ }
153
+ let taken = 0;
154
+ const solTop = Math.max(0, ...[...solCand.values()].map((c) => c.score));
155
+ for (const [name, c] of [...solCand].sort((a, b) => b[1].score - a[1].score)) {
156
+ if (taken >= MAX_SOLUTIONS)
157
+ break;
158
+ if (c.score < solTop * RELATIVE_CUT)
159
+ break;
160
+ let raw = '';
161
+ try {
162
+ raw = fs.readFileSync(c.path, 'utf-8');
163
+ }
164
+ catch {
165
+ continue;
166
+ }
167
+ const parsed = parseSolutionV3(raw);
168
+ if (!parsed || !inProject(parsed.frontmatter.projects, project))
169
+ continue;
170
+ const text = clean(`${name.replace(/-/g, ' ')}: ${parsed.content}`, CLIP_SOLUTION);
171
+ if (!text) {
172
+ excludedPrivate++;
173
+ continue;
174
+ }
175
+ add({ id: `solution:${name}`, kind: 'solution', text, score: c.score });
176
+ taken++;
177
+ }
178
+ // 3) 교정 원문: 룰이 되지 않은 것까지 포함해 같은 기준으로 고른다
179
+ try {
180
+ const quotes = [];
181
+ const pseudo = [];
182
+ for (const e of loadAllEvidence()) {
183
+ if (e.type !== 'explicit_correction')
184
+ continue;
185
+ const q = typeof e.raw_payload?.user_quote === 'string' ? e.raw_payload.user_quote : '';
186
+ if (!q)
187
+ continue;
188
+ pseudo.push({ rule_id: e.evidence_id, trigger: '', policy: q });
189
+ quotes.push({ id: e.evidence_id, q, score: topicScore(topic, q) });
190
+ }
191
+ for (const hit of relevantRules(topic, pseudo)) {
192
+ const x = quotes.find((k) => k.id === hit.rule_id);
193
+ if (x && (x.score > 0 || hit.score >= RELEVANCE_ALONE))
194
+ x.score = Math.max(x.score, hit.score);
195
+ }
196
+ const qTop = Math.max(0, ...quotes.map((k) => k.score));
197
+ for (const k of quotes)
198
+ if (k.score < qTop * RELATIVE_CUT)
199
+ k.score = 0;
200
+ const seenQuotes = new Set(sources.map((x) => x.quote).filter(Boolean));
201
+ let n = 0;
202
+ for (const x of quotes.filter((k) => k.score > 0).sort((a, b) => b.score - a.score)) {
203
+ if (n >= MAX_CORRECTIONS)
204
+ break;
205
+ const text = clean(x.q, CLIP_CORRECTION);
206
+ if (!text) {
207
+ excludedPrivate++;
208
+ continue;
209
+ }
210
+ if (seenQuotes.has(text))
211
+ continue;
212
+ add({ id: `correction:${x.id}`, kind: 'correction', text, score: x.score });
213
+ n++;
214
+ }
215
+ }
216
+ catch { /* 교정 읽기 실패는 무시 */ }
217
+ return { sources, excludedPrivate };
218
+ }
219
+ const KIND_LABEL = { rule: '룰', solution: '솔루션', correction: '교정 원문' };
220
+ function renderSources(sources) {
221
+ return sources.map((s, i) => `[${i + 1}] (${KIND_LABEL[s.kind]}) ${s.text}${s.quote ? `\n 사용자 발언: "${s.quote}"` : ''}`).join('\n');
222
+ }
223
+ export function buildDraftPrompt(kind, topic, sources) {
224
+ const common = [
225
+ '아래 [근거] 항목만 바탕으로 초안을 쓴다.',
226
+ '- 근거에 없는 절차·명령·파일 경로·도구 이름을 지어내지 않는다. 근거가 얇으면 그만큼만 쓰고 짧게 끝낸다.',
227
+ '- 일회성 내용(특정 날짜, 특정 파일·커밋, 한 번 있었던 사건의 경위)은 뺀다. 다음에도 통하는 판단 기준만 남긴다.',
228
+ '- 주제와 직접 관련 없는 근거(다른 주제의 규칙·솔루션이 섞여 들어올 수 있다)는 무시한다.',
229
+ '- 특정 프로젝트·제품 이름이 붙은 조건은 그 조건이 근거에 명시된 경우에만 "판단 기준"에 조건으로 쓰고, 그렇지 않으면 일반화하지 않는다.',
230
+ '- 비슷한 근거는 하나로 합친다. 근거를 그대로 나열하지 않는다.',
231
+ '- 근거끼리 충돌하면 충돌을 숨기지 말고 "판단 기준"에 어느 쪽을 언제 따르는지 적는다. 정할 수 없으면 그렇게 쓴다.',
232
+ '- 한국어로 쓴다. 파일 내용만 출력한다. 앞뒤 설명이나 코드펜스로 감싸지 않는다.',
233
+ ];
234
+ const format = kind === 'skill'
235
+ ? [
236
+ '출력 형식은 표준 SKILL.md 다.',
237
+ '---',
238
+ 'name: <소문자 영문·숫자·하이픈, 3~40자>',
239
+ 'description: <언제 쓰는지 트리거 문장. "~할 때 사용" 형태로, 사용자가 실제로 할 법한 요청 표현을 2~3개 넣는다. 스킬 내용 요약이 아니라 호출 조건이다. 한두 문장>',
240
+ '---',
241
+ '# <제목: 주제를 한 줄로>',
242
+ '## 절차 — 번호 목록. 각 단계는 무엇을 하고 어떻게 확인하는지 포함한다.',
243
+ '## 판단 기준 — 언제 이 방식을 쓰고 언제 쓰지 않는지, 갈림길마다 기준.',
244
+ '## 실패했을 때 — 단계가 실패하거나 확인이 안 될 때의 대응.',
245
+ ]
246
+ : [
247
+ '출력 형식은 호스트 중립 워크플로우 단계 체크리스트(Markdown)다. 특정 AI 도구·CLI 의 명령이나 기능 이름을 쓰지 않는다.',
248
+ '# <제목>',
249
+ '한 줄: 언제 이 워크플로우를 돌리는지.',
250
+ '## 단계 — `- [ ]` 체크리스트. 각 단계는 한 문장 행동 + 들여쓴 줄에 "확인:" (무엇을 보면 끝난 것인지).',
251
+ '## 갈림길 — 조건 → 어느 단계로/무엇을 할지.',
252
+ '## 실패 시 — 단계별 막혔을 때의 대응.',
253
+ ];
254
+ return [`주제: ${topic}`, '', ...common, '', ...format, '', '[근거]', renderSources(sources)].join('\n');
255
+ }
256
+ /** 모델이 감싼 코드펜스·앞말을 걷어낸다. */
257
+ export function stripWrapper(out) {
258
+ let t = out.trim();
259
+ const fence = t.match(/^```[a-z]*\n([\s\S]*?)\n```$/i);
260
+ if (fence)
261
+ t = fence[1].trim();
262
+ const fm = t.indexOf('\n---\n');
263
+ if (!t.startsWith('---') && fm >= 0 && /^name:/m.test(t.slice(fm)))
264
+ t = t.slice(fm + 1);
265
+ return t;
266
+ }
267
+ /** 결정론 출력: 관련 항목 묶음. 초안이 아니라 재료다. */
268
+ export function deterministicBundle(kind, topic, sources, reason) {
269
+ const out = [`# ${topic} — 관련 항목 묶음 (${kind === 'skill' ? '스킬' : '워크플로우'} 초안 아님)`, '', `> 초안을 쓰지 못했다: ${reason}`, '> 아래는 주제와 관련된 항목을 그대로 모은 것이다. 직접 정리하거나, Haiku 가 가능할 때 다시 실행한다.', ''];
270
+ for (const k of ['rule', 'correction', 'solution']) {
271
+ const list = sources.filter((s) => s.kind === k);
272
+ if (!list.length)
273
+ continue;
274
+ out.push(`## ${KIND_LABEL[k]}`, ...list.map((s) => `- ${s.text}${s.quote ? `\n - 사용자 발언: "${s.quote}"` : ''}`), '');
275
+ }
276
+ return `${out.join('\n')}\n`;
277
+ }
278
+ export function writeDraft(kind, topic, sources, opts = {}) {
279
+ if (sources.length === 0)
280
+ return { mode: 'deterministic', text: deterministicBundle(kind, topic, sources, '주제와 관련된 룰·솔루션·교정을 찾지 못함'), reason: '관련 항목 없음' };
281
+ if (opts.noLlm)
282
+ return { mode: 'deterministic', text: deterministicBundle(kind, topic, sources, '--no-llm'), reason: '--no-llm' };
283
+ const probe = probeClaudeAvailability();
284
+ if (!probe.available)
285
+ return { mode: 'deterministic', text: deterministicBundle(kind, topic, sources, probe.reason ?? 'claude 사용 불가'), reason: probe.reason };
286
+ const r = callHaiku('way-draft', buildDraftPrompt(kind, topic, sources), { cwd: opts.cwd ?? process.cwd() });
287
+ if (!r.ok)
288
+ return { mode: 'deterministic', text: deterministicBundle(kind, topic, sources, r.reason ?? r.outcome), reason: r.reason ?? r.outcome, ms: r.ms };
289
+ const text = redactSecrets(stripWrapper(r.output)).redacted;
290
+ return { mode: 'haiku', text: `${text.trimEnd()}\n`, ms: r.ms };
291
+ }
292
+ const MARK = '<!-- forgen-way: draft generated by `forgen way draft`. Edits are overwritten on regenerate. -->';
293
+ /** 초안 텍스트에서 SKILL.md 이름을 안전한 ASCII 로 뽑는다 (없거나 이상하면 주제에서 만든다). */
294
+ export function skillNameFor(text, topic) {
295
+ const m = text.match(/^name:\s*["']?([a-z0-9][a-z0-9-]{1,62})["']?\s*$/m);
296
+ if (m)
297
+ return m[1].replace(/-+$/g, '');
298
+ const ascii = topic.toLowerCase().replace(/[^a-z0-9]+/g, '-').replace(/^-+|-+$/g, '').slice(0, 40);
299
+ return ascii.length >= 3 ? ascii : `way-draft-${crypto.createHash('sha1').update(topic).digest('hex').slice(0, 8)}`;
300
+ }
301
+ function sourcesFile(topic, kind, outcome, sources, excludedPrivate) {
302
+ return [
303
+ MARK, `# 근거 항목 — ${topic}`, '',
304
+ `종류: ${kind}, 방식: ${outcome.mode}${outcome.reason ? ` (${outcome.reason})` : ''}, 항목 ${sources.length}개${excludedPrivate ? `, private 제외 ${excludedPrivate}` : ''}`, '',
305
+ ...sources.map((s) => `- \`${s.id}\` (${KIND_LABEL[s.kind]}, 관련도 ${s.score}) ${s.text.slice(0, 120)}${s.text.length > 120 ? '…' : ''}`), '',
306
+ ].join('\n');
307
+ }
308
+ /** 초안을 파일 묶음으로 만든다. 스킬은 `.claude/skills/<name>/`, 워크플로우는 `workflows/<slug>.md`. 근거는 옆 파일. */
309
+ export function draftFiles(kind, topic, outcome, sources, excludedPrivate) {
310
+ const side = sourcesFile(topic, kind, outcome, sources, excludedPrivate);
311
+ if (kind === 'skill') {
312
+ const name = skillNameFor(outcome.text, topic);
313
+ // 결정론 묶음은 SKILL.md 형식이 아니므로 스킬로 설치되지 않도록 별도 파일 이름을 쓴다.
314
+ if (outcome.mode !== 'haiku')
315
+ return [{ path: `.claude/skills/${name}/DRAFT-BUNDLE.md`, content: `${MARK}\n${outcome.text}` }, { path: `.claude/skills/${name}/SOURCES.md`, content: side }];
316
+ const body = outcome.text.replace(/^(---\n[\s\S]*?\n---\n)/, `$1${MARK}\n`);
317
+ return [{ path: `.claude/skills/${name}/SKILL.md`, content: body.includes(MARK) ? body : `${MARK}\n${body}` }, { path: `.claude/skills/${name}/SOURCES.md`, content: side }];
318
+ }
319
+ const slug = topic.toLowerCase().replace(/[^\p{L}\p{N}]+/gu, '-').replace(/^-+|-+$/g, '').slice(0, 40) || skillNameFor('', topic);
320
+ return [{ path: `workflows/${slug}.md`, content: `${MARK}\n${outcome.text}` }, { path: `workflows/${slug}.sources.md`, content: side }];
321
+ }
322
+ export function readTopic(args) {
323
+ const rest = [];
324
+ for (let i = 0; i < args.length; i++) {
325
+ if (args[i] === '--project' || args[i] === '--out') {
326
+ i++;
327
+ continue;
328
+ }
329
+ if (args[i].startsWith('--'))
330
+ continue;
331
+ rest.push(args[i]);
332
+ }
333
+ const t = rest.join(' ').trim();
334
+ return t || undefined;
335
+ }
@@ -0,0 +1,17 @@
1
+ import type { Profile, Rule } from '../store/types.js';
2
+ import type { Way, WayItem, WayStats } from './types.js';
3
+ export declare function ruleToItem(rule: Rule): WayItem;
4
+ export interface SolutionCounts {
5
+ verified: number;
6
+ unverified: number;
7
+ skipped: number;
8
+ }
9
+ export declare function readSolutions(dir?: string): {
10
+ items: WayItem[];
11
+ counts: SolutionCounts;
12
+ };
13
+ export declare function readHabits(existing: string[], dir?: string): WayItem[];
14
+ export declare function profileHabits(p: Profile | null): WayItem[];
15
+ export declare function computeStats(items: WayItem[], sol: SolutionCounts): WayStats;
16
+ /** 현재 저장소에서 Way 를 만든다. 룰은 활성만. 습관은 항상 계산하지만 컴파일러가 기본 제외한다. */
17
+ export declare function buildWay(now?: Date): Way;
@@ -0,0 +1,172 @@
1
+ /**
2
+ * Way 추출 — 기존 저장소를 Way 항목으로 읽는다 (새 저장소 없음).
3
+ * - 룰(~/.forgen/me/rules) : active 만. 출처는 evidence 의 user_quote 로 확인한다.
4
+ * - 솔루션(~/.forgen/me/solutions) : verified·mature 만 항목. 나머지는 개수만 센다.
5
+ * - 습관 : behavior md 의 `- [분류] 문장` 줄과 프로필 팩. 모델이 쓴 잡음이 많아 기본 내보내기에서 빠진다.
6
+ */
7
+ import * as fs from 'node:fs';
8
+ import * as path from 'node:path';
9
+ import { ME_BEHAVIOR, ME_SOLUTIONS } from '../core/paths.js';
10
+ import { ruleEnforced } from '../engine/rule-detectability.js';
11
+ import { isHabitLog } from '../engine/solution-habit.js';
12
+ import { parseSolutionV3 } from '../engine/solution-format.js';
13
+ import { ruleOrigin } from '../store/rule-origin.js';
14
+ import { loadProfile } from '../store/profile-store.js';
15
+ import { loadAllRules } from '../store/rule-store.js';
16
+ import { conflictingRule } from './conflict.js';
17
+ import { isDuplicate } from './similar.js';
18
+ import { WAY_SCHEMA } from './types.js';
19
+ export function ruleToItem(rule) {
20
+ let provenance;
21
+ let why = '';
22
+ if (rule.source === 'explicit_correction' || rule.source === 'onboarding') {
23
+ const o = ruleOrigin(rule);
24
+ const quote = o?.quoteSource === 'user' ? o.quote : undefined;
25
+ provenance = { kind: 'you-said', ...(quote ? { quote } : {}), ...(o?.date ? { date: o.date } : { date: rule.created_at.slice(0, 10) }) };
26
+ if (quote)
27
+ why = `사용자 발언: "${quote}"`;
28
+ }
29
+ else if (rule.source === 'imported') {
30
+ provenance = { kind: 'imported', from: rule.imported_from ?? 'unknown', date: rule.created_at.slice(0, 10) };
31
+ }
32
+ else {
33
+ provenance = { kind: 'mined', date: rule.created_at.slice(0, 10) };
34
+ }
35
+ return {
36
+ id: rule.rule_id,
37
+ kind: 'rule',
38
+ statement: rule.policy,
39
+ applies_when: rule.trigger,
40
+ why,
41
+ projects: rule.projects ?? [],
42
+ strength: rule.strength,
43
+ provenance,
44
+ enforceable: ruleEnforced(rule),
45
+ status: rule.status === 'active' || rule.status === 'suppressed' || rule.status === 'removed' ? rule.status : undefined,
46
+ category: rule.category,
47
+ render_key: rule.render_key,
48
+ source: rule.source,
49
+ updated_at: rule.updated_at,
50
+ };
51
+ }
52
+ export function readSolutions(dir = ME_SOLUTIONS) {
53
+ const items = [];
54
+ const counts = { verified: 0, unverified: 0, skipped: 0 };
55
+ let files = [];
56
+ try {
57
+ files = fs.readdirSync(dir).filter((f) => f.endsWith('.md')).sort();
58
+ }
59
+ catch {
60
+ return { items, counts };
61
+ }
62
+ for (const f of files) {
63
+ const raw = fs.readFileSync(path.join(dir, f), 'utf-8');
64
+ const parsed = parseSolutionV3(raw);
65
+ const name = f.replace(/\.md$/, '');
66
+ if (!parsed || parsed.frontmatter.status === 'retired' || isHabitLog(name, raw)) {
67
+ counts.skipped++;
68
+ continue;
69
+ }
70
+ const fm = parsed.frontmatter;
71
+ if (fm.status !== 'verified' && fm.status !== 'mature') {
72
+ counts.unverified++;
73
+ continue;
74
+ }
75
+ if (!parsed.content.trim()) {
76
+ counts.skipped++;
77
+ continue;
78
+ }
79
+ counts.verified++;
80
+ items.push({
81
+ id: `solution:${name}`,
82
+ kind: 'solution',
83
+ statement: parsed.content.trim(),
84
+ applies_when: parsed.context.trim(),
85
+ why: '',
86
+ projects: fm.projects ?? [],
87
+ strength: fm.status === 'mature' ? 'strong' : 'default',
88
+ provenance: fm.extractedBy === 'manual' ? { kind: 'you-said', date: fm.created } : { kind: 'mined', date: fm.created },
89
+ enforceable: false,
90
+ category: fm.type,
91
+ source: fm.extractedBy === 'manual' ? 'explicit_correction' : 'behavior_inference',
92
+ updated_at: fm.updated,
93
+ });
94
+ }
95
+ return { items, counts };
96
+ }
97
+ const HABIT_LINE = /^\s*[-*]\s*\[([^\]]{1,20})\]\s+(.{12,300})$/;
98
+ /** behavior md 템플릿이 그대로 남은 줄(예: "패턴 설명 (관찰 근거)")이나 꺾쇠 자리표시. */
99
+ const TEMPLATE_RESIDUE = /^패턴 설명|\(관찰 근거\)\s*$|^<[^>]{2,40}>$|^(?:설명|예시|내용)\s*(?:\(|:)\s*$/;
100
+ export function readHabits(existing, dir = ME_BEHAVIOR) {
101
+ const out = [];
102
+ let files = [];
103
+ try {
104
+ files = fs.readdirSync(dir).filter((f) => f.endsWith('.md')).sort();
105
+ }
106
+ catch {
107
+ return out;
108
+ }
109
+ const seen = [...existing];
110
+ for (const f of files) {
111
+ const raw = fs.readFileSync(path.join(dir, f), 'utf-8');
112
+ const created = raw.match(/^created:\s*"?([\d-]+)"?/m)?.[1];
113
+ let n = 0;
114
+ for (const line of raw.split('\n')) {
115
+ const m = HABIT_LINE.exec(line);
116
+ if (!m)
117
+ continue;
118
+ const text = m[2].replace(/\*\*/g, '').trim();
119
+ if (TEMPLATE_RESIDUE.test(text) || isDuplicate(text, seen))
120
+ continue;
121
+ seen.push(text);
122
+ out.push({
123
+ id: `habit:${f.replace(/\.md$/, '')}:${n++}`,
124
+ kind: 'habit', statement: text, applies_when: m[1], why: '', projects: [], strength: 'soft',
125
+ provenance: { kind: 'mined', date: created }, enforceable: false, category: 'habit',
126
+ });
127
+ }
128
+ }
129
+ return out;
130
+ }
131
+ export function profileHabits(p) {
132
+ if (!p)
133
+ return [];
134
+ const date = p.metadata?.updated_at?.slice(0, 10);
135
+ const packs = [
136
+ ['quality', '품질·안전', p.base_packs.quality_pack],
137
+ ['autonomy', '자율성', p.base_packs.autonomy_pack],
138
+ ['judgment', '판단 방식', p.base_packs.judgment_pack],
139
+ ['communication', '소통', p.base_packs.communication_pack],
140
+ ];
141
+ return packs.map(([k, label, pack]) => ({
142
+ id: `profile:${k}`, kind: 'habit', statement: `${label} 성향: ${pack}`, applies_when: 'profile',
143
+ why: '', projects: [], strength: 'soft', provenance: { kind: 'mined', date }, enforceable: false, category: 'profile',
144
+ }));
145
+ }
146
+ export function computeStats(items, sol) {
147
+ const rules = items.filter((i) => i.kind === 'rule' && i.status === 'active');
148
+ return {
149
+ rules_active: rules.length,
150
+ rules_you_said: rules.filter((i) => i.provenance.kind === 'you-said').length,
151
+ rules_mined: rules.filter((i) => i.provenance.kind === 'mined').length,
152
+ rules_imported: rules.filter((i) => i.provenance.kind === 'imported').length,
153
+ rules_enforceable: rules.filter((i) => i.enforceable).length,
154
+ solutions_verified: sol.verified,
155
+ solutions_unverified: sol.unverified,
156
+ habits: items.filter((i) => i.kind === 'habit').length,
157
+ };
158
+ }
159
+ /** 현재 저장소에서 Way 를 만든다. 룰은 활성만. 습관은 항상 계산하지만 컴파일러가 기본 제외한다. */
160
+ export function buildWay(now = new Date()) {
161
+ const rules = loadAllRules().filter((r) => r.status === 'active' && r.scope === 'me');
162
+ const ruleItems = rules.map(ruleToItem).sort((a, b) => a.id.localeCompare(b.id));
163
+ const sol = readSolutions();
164
+ const habits = [...readHabits(ruleItems.map((r) => r.statement)), ...profileHabits(loadProfile())].map((h) => {
165
+ if (h.category === 'profile')
166
+ return h;
167
+ const c = conflictingRule(h.statement, rules);
168
+ return c ? { ...h, conflicts_with: c.rule_id } : h;
169
+ });
170
+ const items = [...ruleItems, ...sol.items, ...habits];
171
+ return { schema: WAY_SCHEMA, generator: 'forgen-way', generated_at: now.toISOString(), items, stats: computeStats(items, sol.counts) };
172
+ }
@@ -0,0 +1,79 @@
1
+ import type { Rule } from '../store/types.js';
2
+ import type { CompiledFile, WayItem } from './types.js';
3
+ export interface WritePlanEntry {
4
+ path: string;
5
+ abs: string;
6
+ action: 'create' | 'unchanged' | 'overwrite' | 'blocked-exists' | 'blocked-foreign' | 'blocked-escape';
7
+ /** overwrite 일 때 쓰기 전에 옮겨 둘 백업 경로. */
8
+ backup?: string;
9
+ }
10
+ export declare function planWrite(files: CompiledFile[], outDir: string, force: boolean): WritePlanEntry[];
11
+ /** 하나라도 막히면 아무것도 쓰지 않는다. 덮어쓰기 전에는 기존 파일을 백업한다. */
12
+ export declare function writeFiles(files: CompiledFile[], outDir: string, force: boolean): {
13
+ plan: WritePlanEntry[];
14
+ written: number;
15
+ };
16
+ export declare function parseWayJson(text: string): {
17
+ ok: true;
18
+ items: WayItem[];
19
+ } | {
20
+ ok: false;
21
+ errors: string[];
22
+ };
23
+ export interface ImportChange {
24
+ id: string;
25
+ field: 'statement' | 'projects' | 'strength' | 'status' | 'new';
26
+ from?: string;
27
+ to: string;
28
+ }
29
+ export interface ImportPlan {
30
+ changes: ImportChange[];
31
+ ignored: Array<{
32
+ id: string;
33
+ reason: string;
34
+ }>;
35
+ errors: string[];
36
+ warnings: string[];
37
+ newRules: WayItem[];
38
+ }
39
+ export interface ImportOptions {
40
+ allowEnforcedEdit?: boolean;
41
+ }
42
+ export declare function planImport(items: WayItem[], existing: Rule[], opts?: ImportOptions): ImportPlan;
43
+ export declare function applyImport(items: WayItem[], plan: ImportPlan, now?: string): {
44
+ applied: number;
45
+ created: string[];
46
+ };
47
+ export type ExcludeReason = 'duplicate' | 'conflict' | 'secret' | 'truncated' | 'log' | 'duplicate-in-batch';
48
+ export interface MemoryCandidate {
49
+ /** 내용 해시 기반의 안정 id. */
50
+ id: string;
51
+ /** 절대 경로가 아니라 `<프로젝트 슬러그>/<파일명>`. 룰의 imported_from 에도 이것만 남긴다. */
52
+ source: string;
53
+ statement: string;
54
+ applies_when: string;
55
+ why: string;
56
+ /** 추정한 프로젝트 키. null = 전역. 틀리면 사용자가 고친다. */
57
+ project: string | null;
58
+ projectGuess: string;
59
+ /** 기본 제외된 사유. 있으면 가져오지 않는다. */
60
+ excluded?: {
61
+ reason: ExcludeReason;
62
+ detail: string;
63
+ };
64
+ }
65
+ /** 인코딩된 프로젝트 디렉터리 이름(`-home-me-work-repo`)을 실제 경로로 복원한다. 복원 못 하면 null. */
66
+ export declare function decodeProjectDir(name: string): string | null;
67
+ interface ProjectGuess {
68
+ key: string | null;
69
+ note: string;
70
+ slug: string;
71
+ home: boolean;
72
+ }
73
+ export declare function parseMemoryFile(raw: string, source: string, g: ProjectGuess, repoNames?: string[]): MemoryCandidate | null;
74
+ export declare function readMemoryCandidates(dir: string | undefined, rules: Rule[]): {
75
+ candidates: MemoryCandidate[];
76
+ scanned: string[];
77
+ };
78
+ export declare function candidateToItem(c: MemoryCandidate, projectOverride?: string | null): WayItem;
79
+ export {};