@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
package/dist/way/io.js ADDED
@@ -0,0 +1,425 @@
1
+ /**
2
+ * Way 입출력 — 파일 쓰기 보호, json 가져오기, 호스트 메모리 수집.
3
+ */
4
+ import * as fs from 'node:fs';
5
+ import * as os from 'node:os';
6
+ import * as path from 'node:path';
7
+ import { createHash } from 'node:crypto';
8
+ import { CLAUDE_DIR } from '../core/paths.js';
9
+ import { createRule, loadRule, saveRule } from '../store/rule-store.js';
10
+ import { projectKeyFor } from '../store/rule-scope.js';
11
+ import { withStatusChange } from '../store/rule-lifecycle.js';
12
+ import { enforceability } from '../engine/rule-detectability.js';
13
+ import { redactSecrets } from '../hooks/secret-filter.js';
14
+ import { STRENGTH_RANK } from '../renderer/rule-renderer.js';
15
+ import { isWayManaged } from './compile.js';
16
+ import { conflictingRule } from './conflict.js';
17
+ import { isDuplicate } from './similar.js';
18
+ /** 존재하는 가장 깊은 상위까지 realpath 로 풀고 나머지를 붙인다. 끊어진 심링크는 던진다. */
19
+ function realTarget(p) {
20
+ const abs = path.resolve(p);
21
+ let exists = true;
22
+ try {
23
+ fs.lstatSync(abs);
24
+ }
25
+ catch {
26
+ exists = false;
27
+ }
28
+ if (exists)
29
+ return fs.realpathSync(abs); // 끊어진 심링크면 던진다
30
+ const parent = path.dirname(abs);
31
+ if (parent === abs)
32
+ return abs;
33
+ return path.join(realTarget(parent), path.basename(abs));
34
+ }
35
+ /** out 의 실경로 밖으로 나가면 null (상대 경로의 `..`, 심링크 상위 디렉터리, 심링크 파일 모두). */
36
+ function inside(outDir, rel) {
37
+ const abs = path.resolve(outDir, rel);
38
+ const root = path.resolve(outDir);
39
+ if (abs !== root && !abs.startsWith(root + path.sep))
40
+ return null;
41
+ try {
42
+ const realRoot = realTarget(root);
43
+ const real = realTarget(abs);
44
+ if (real !== realRoot && !real.startsWith(realRoot + path.sep))
45
+ return null;
46
+ }
47
+ catch {
48
+ return null;
49
+ }
50
+ return abs;
51
+ }
52
+ const stamp = () => new Date().toISOString().replace(/\D/g, '').slice(0, 14);
53
+ export function planWrite(files, outDir, force) {
54
+ return files.map((f) => {
55
+ const abs = inside(outDir, f.path);
56
+ if (abs === null)
57
+ return { path: f.path, abs: path.resolve(outDir, f.path), action: 'blocked-escape' };
58
+ let existing = null;
59
+ try {
60
+ existing = fs.readFileSync(abs, 'utf-8');
61
+ }
62
+ catch { /* 없음 */ }
63
+ let action;
64
+ if (existing === null)
65
+ action = 'create';
66
+ else if (existing === f.content)
67
+ action = 'unchanged';
68
+ else if (!isWayManaged(existing))
69
+ action = 'blocked-foreign';
70
+ else
71
+ action = force ? 'overwrite' : 'blocked-exists';
72
+ return { path: f.path, abs, action, ...(action === 'overwrite' ? { backup: `${abs}.forgen-bak-${stamp()}` } : {}) };
73
+ });
74
+ }
75
+ /** 하나라도 막히면 아무것도 쓰지 않는다. 덮어쓰기 전에는 기존 파일을 백업한다. */
76
+ export function writeFiles(files, outDir, force) {
77
+ const plan = planWrite(files, outDir, force);
78
+ if (plan.some((p) => p.action.startsWith('blocked')))
79
+ return { plan, written: 0 };
80
+ let written = 0;
81
+ files.forEach((f, i) => {
82
+ if (plan[i].action === 'unchanged')
83
+ return;
84
+ fs.mkdirSync(path.dirname(plan[i].abs), { recursive: true });
85
+ const backup = plan[i].backup;
86
+ if (backup)
87
+ fs.copyFileSync(plan[i].abs, backup);
88
+ fs.writeFileSync(plan[i].abs, f.content, 'utf-8');
89
+ written++;
90
+ });
91
+ return { plan, written };
92
+ }
93
+ // ── json 가져오기 ──
94
+ const STRENGTHS = ['soft', 'default', 'strong', 'hard'];
95
+ const KINDS = ['rule', 'solution', 'habit'];
96
+ const PROV = ['you-said', 'mined', 'imported'];
97
+ const STATUSES = ['active', 'suppressed', 'removed'];
98
+ const TOP_KEYS = new Set(['schema', 'generator', 'generated_at', 'project', 'items', 'stats', 'render']);
99
+ const ITEM_KEYS = new Set(['id', 'kind', 'statement', 'applies_when', 'why', 'projects', 'strength', 'provenance', 'enforceable', 'status', 'category', 'render_key', 'source', 'updated_at', 'conflicts_with']);
100
+ const PROV_KEYS = new Set(['kind', 'quote', 'date', 'from']);
101
+ export function parseWayJson(text) {
102
+ let data;
103
+ try {
104
+ data = JSON.parse(text);
105
+ }
106
+ catch (e) {
107
+ return { ok: false, errors: [`JSON 파싱 실패: ${e.message}`] };
108
+ }
109
+ const errors = [];
110
+ const d = data;
111
+ if (!d || typeof d !== 'object' || Array.isArray(d))
112
+ return { ok: false, errors: ['최상위가 객체가 아니다'] };
113
+ if (d.schema !== 'forgen-way/1')
114
+ errors.push(`schema 는 "forgen-way/1" 이어야 한다 (받은 값: ${JSON.stringify(d.schema)})`);
115
+ for (const k of Object.keys(d))
116
+ if (!TOP_KEYS.has(k))
117
+ errors.push(`알 수 없는 최상위 필드: ${k}`);
118
+ if (!Array.isArray(d.items))
119
+ return { ok: false, errors: [...errors, 'items 배열이 없다'] };
120
+ const items = [];
121
+ const seenIds = new Set();
122
+ d.items.forEach((raw, n) => {
123
+ const it = raw;
124
+ const where = `items[${n}]${typeof it?.id === 'string' ? ` (${it.id})` : ''}`;
125
+ const bad = (m) => errors.push(`${where}: ${m}`);
126
+ if (!it || typeof it !== 'object' || Array.isArray(it))
127
+ return bad('객체가 아니다');
128
+ for (const k of Object.keys(it))
129
+ if (!ITEM_KEYS.has(k))
130
+ bad(`알 수 없는 필드: ${k}`);
131
+ if (typeof it.id !== 'string' || !it.id)
132
+ bad('id 가 없다');
133
+ else if (seenIds.has(it.id))
134
+ bad('같은 파일에 id 가 중복된다');
135
+ else
136
+ seenIds.add(it.id);
137
+ if (!KINDS.includes(it.kind))
138
+ bad(`kind 는 ${KINDS.join('|')}`);
139
+ if (typeof it.statement !== 'string' || !it.statement.trim())
140
+ bad('statement 가 비어 있다');
141
+ if (typeof it.applies_when !== 'string')
142
+ bad('applies_when 은 문자열');
143
+ if (!Array.isArray(it.projects) || it.projects.some((p) => typeof p !== 'string'))
144
+ bad('projects 는 문자열 배열');
145
+ if (!STRENGTHS.includes(it.strength))
146
+ bad(`strength 는 ${STRENGTHS.join('|')}`);
147
+ if (!it.provenance || typeof it.provenance !== 'object' || !PROV.includes(it.provenance.kind))
148
+ bad(`provenance.kind 는 ${PROV.join('|')}`);
149
+ else {
150
+ for (const k of Object.keys(it.provenance))
151
+ if (!PROV_KEYS.has(k))
152
+ bad(`알 수 없는 provenance 필드: ${k}`);
153
+ if (it.provenance.kind === 'imported' && typeof it.provenance.from !== 'string')
154
+ bad('imported 는 from 이 필요하다');
155
+ }
156
+ if (typeof it.enforceable !== 'boolean')
157
+ bad('enforceable 은 불리언');
158
+ if (it.status !== undefined && !STATUSES.includes(it.status))
159
+ bad(`status 는 ${STATUSES.join('|')}`);
160
+ if (!errors.some((e) => e.startsWith(where)))
161
+ items.push({ ...it, why: it.why ?? '' });
162
+ });
163
+ return errors.length ? { ok: false, errors } : { ok: true, items };
164
+ }
165
+ const CATS = ['quality', 'autonomy', 'communication', 'workflow', 'safety'];
166
+ export function planImport(items, existing, opts = {}) {
167
+ const byId = new Map(existing.map((r) => [r.rule_id, r]));
168
+ const plan = { changes: [], ignored: [], errors: [], warnings: [], newRules: [] };
169
+ // 중복 비교는 활성·억제·제거 룰 모두와 한다 (제거한 룰이 다시 들어오지 않게).
170
+ const policies = existing.map((r) => r.policy);
171
+ const guard = (id, msg) => {
172
+ if (opts.allowEnforcedEdit)
173
+ plan.warnings.push(`${id.slice(0, 8)}: ${msg} (--allow-enforced-edit 로 허용됨)`);
174
+ else
175
+ plan.errors.push(`${id.slice(0, 8)}: ${msg}. 의도한 변경이면 --allow-enforced-edit`);
176
+ };
177
+ for (const it of items) {
178
+ if (it.kind !== 'rule') {
179
+ plan.ignored.push({ id: it.id, reason: `${it.kind} 항목은 가져오기 대상이 아니다 (룰만 반영)` });
180
+ continue;
181
+ }
182
+ const r = byId.get(it.id);
183
+ if (!r) {
184
+ if (it.provenance.kind !== 'imported') {
185
+ plan.errors.push(`${it.id}: 저장소에 없는 룰이다. 새 룰은 provenance.kind "imported" 로만 추가할 수 있다`);
186
+ continue;
187
+ }
188
+ if (it.strength === 'hard') {
189
+ plan.errors.push(`${it.id}: 새 룰에 hard 를 줄 수 없다 (hard 는 forgen 에서 직접 지정)`);
190
+ continue;
191
+ }
192
+ if (it.status && it.status !== 'active') {
193
+ plan.errors.push(`${it.id}: 새 룰은 active 로만 추가한다 (받은 status: ${it.status})`);
194
+ continue;
195
+ }
196
+ if (redactSecrets(it.statement).hits.length) {
197
+ plan.errors.push(`${it.id}: 비밀로 보이는 문자열이 있어 가져오지 않는다`);
198
+ continue;
199
+ }
200
+ const dup = isDuplicate(it.statement, policies);
201
+ if (dup) {
202
+ plan.ignored.push({ id: it.id, reason: `기존·같은 파일 룰과 중복: "${dup.slice(0, 40)}"` });
203
+ continue;
204
+ }
205
+ const conf = conflictingRule(it.statement, existing);
206
+ if (conf) {
207
+ plan.ignored.push({ id: it.id, reason: `활성 룰 ${conf.rule_id.slice(0, 8)} 과 상반: "${conf.policy.slice(0, 40)}"` });
208
+ continue;
209
+ }
210
+ policies.push(it.statement);
211
+ plan.newRules.push(it);
212
+ plan.changes.push({ id: it.id, field: 'new', to: it.statement });
213
+ continue;
214
+ }
215
+ if (it.statement.trim() !== r.policy.trim()) {
216
+ plan.changes.push({ id: it.id, field: 'statement', from: r.policy, to: it.statement.trim() });
217
+ if (enforceability(r) === 'detectable' || r.strength === 'hard')
218
+ guard(it.id, `강제되는 룰의 문장을 바꾼다 (탐지기와 문장이 어긋날 수 있다)`);
219
+ }
220
+ const pr = (r.projects ?? []).join(',');
221
+ const pi = it.projects.map((p) => p.toLowerCase()).join(',');
222
+ if (pr !== pi)
223
+ plan.changes.push({ id: it.id, field: 'projects', from: pr || '(전역)', to: pi || '(전역)' });
224
+ if (it.strength !== r.strength) {
225
+ plan.changes.push({ id: it.id, field: 'strength', from: r.strength, to: it.strength });
226
+ if (it.strength === 'hard')
227
+ plan.errors.push(`${it.id.slice(0, 8)}: hard 를 새로 줄 수 없다 (${r.strength} → hard)`);
228
+ else if (STRENGTH_RANK[it.strength] > STRENGTH_RANK[r.strength])
229
+ guard(it.id, `강도를 낮춘다 (${r.strength} → ${it.strength})`);
230
+ }
231
+ if (it.status && it.status !== r.status)
232
+ plan.changes.push({ id: it.id, field: 'status', from: r.status, to: it.status });
233
+ }
234
+ return plan;
235
+ }
236
+ export function applyImport(items, plan, now = new Date().toISOString()) {
237
+ let applied = 0;
238
+ const created = [];
239
+ const touched = new Set(plan.changes.filter((c) => c.field !== 'new').map((c) => c.id));
240
+ for (const id of touched) {
241
+ const it = items.find((x) => x.id === id);
242
+ const rule = loadRule(id);
243
+ if (!it || !rule)
244
+ continue;
245
+ let next = { ...rule, policy: it.statement.trim(), strength: it.strength };
246
+ const projects = it.projects.map((p) => p.toLowerCase()).filter(Boolean);
247
+ if (projects.length)
248
+ next.projects = projects;
249
+ else
250
+ delete next.projects;
251
+ if (it.status && it.status !== rule.status)
252
+ next = withStatusChange(next, it.status, `way import: ${it.status} (json 편집)`, 'way-import', now);
253
+ saveRule(next);
254
+ applied++;
255
+ }
256
+ for (const it of plan.newRules) {
257
+ const from = it.provenance.kind === 'imported' ? it.provenance.from : 'way-import';
258
+ const cat = CATS.includes(it.category ?? '') ? it.category : 'workflow';
259
+ const rule = createRule({
260
+ category: cat, scope: 'me', trigger: it.applies_when || it.statement.slice(0, 40), policy: it.statement.trim(),
261
+ strength: it.strength, source: 'imported', render_key: `imported:${cat}.${shortHash(it.statement)}`,
262
+ projects: it.projects.map((p) => p.toLowerCase()).filter(Boolean),
263
+ });
264
+ rule.imported_from = from;
265
+ saveRule(rule);
266
+ created.push(rule.rule_id);
267
+ applied++;
268
+ }
269
+ return { applied, created };
270
+ }
271
+ const shortHash = (s) => createHash('sha256').update(s).digest('hex').slice(0, 10);
272
+ /** 인코딩된 프로젝트 디렉터리 이름(`-home-me-work-repo`)을 실제 경로로 복원한다. 복원 못 하면 null. */
273
+ export function decodeProjectDir(name) {
274
+ const parts = name.replace(/^-/, '').split('-');
275
+ let cur = path.sep;
276
+ let i = 0;
277
+ while (i < parts.length) {
278
+ let found = false;
279
+ for (let j = parts.length; j > i; j--) {
280
+ const seg = parts.slice(i, j).join('-');
281
+ const cand = path.join(cur, seg);
282
+ if (fs.existsSync(cand)) {
283
+ cur = cand;
284
+ i = j;
285
+ found = true;
286
+ break;
287
+ }
288
+ }
289
+ if (!found)
290
+ return null;
291
+ }
292
+ return cur;
293
+ }
294
+ function isHomeDir(abs) {
295
+ let home = os.homedir();
296
+ try {
297
+ home = fs.realpathSync(home);
298
+ }
299
+ catch { /* 그대로 */ }
300
+ // 메모리가 만들어진 기계의 홈일 수 있으므로(복사본 포함) /home/<user> 형태도 홈으로 본다.
301
+ return path.resolve(abs) === path.resolve(home) || ['/home', '/Users'].includes(path.dirname(abs));
302
+ }
303
+ function guessProject(dirName) {
304
+ const abs = decodeProjectDir(dirName);
305
+ const raw = dirName.replace(/^-+/, '');
306
+ if (!abs)
307
+ return { key: null, note: '경로 복원 실패 → 전역(확인 필요)', slug: raw, home: false };
308
+ if (isHomeDir(abs))
309
+ return { key: null, note: '홈에 저장된 메모리 → 전역(확인 필요)', slug: 'home', home: true };
310
+ const key = projectKeyFor(abs) ?? path.basename(abs).toLowerCase();
311
+ return { key, note: `프로젝트 폴더 ${key}`, slug: key, home: false };
312
+ }
313
+ function section(body, label) {
314
+ const m = new RegExp(`\\*\\*${label}:?\\*\\*:?\\s*([\\s\\S]*?)(?=\\n\\s*\\*\\*[A-Za-z ]+:?\\*\\*|$)`, 'i').exec(body);
315
+ return m ? m[1].replace(/\s+/g, ' ').trim() : '';
316
+ }
317
+ /** 사건 기록(커밋 해시, 푸시·머지 완료 보고, 날짜로 시작하는 경과)은 작업 방식이 아니다. */
318
+ const LOG_LIKE = /(?:커밋|commit)\s*[0-9a-f]{7,40}|[0-9a-f]{7}[·,]\s*[0-9a-f]{7}|(?:푸시|머지|배포|완료)(?:됨|했다|했음)\b|^\d{4}-\d{2}-\d{2}\s+(?:세션|커밋|완료)|\bPR\s*#\d+/i;
319
+ export function parseMemoryFile(raw, source, g, repoNames = []) {
320
+ const m = /^---\n([\s\S]*?)\n---\n?([\s\S]*)$/.exec(raw);
321
+ if (!m)
322
+ return null;
323
+ const fm = m[1];
324
+ const body = m[2].trim();
325
+ let desc = fm.match(/^description:\s*(.+)$/m)?.[1]?.trim().replace(/^["']|["']$/g, '') ?? '';
326
+ desc = desc.replace(/^\d{4}-\d{2}-\d{2}\s*/, '').replace(/^오너\s*[—-]\s*/, '');
327
+ desc = desc.replace(/\\"/g, '"');
328
+ const statement = desc || body.split('\n').find((l) => l.trim())?.trim() || '';
329
+ if (statement.length < 8)
330
+ return null;
331
+ let project = g.key;
332
+ let note = g.note;
333
+ if (g.home) {
334
+ // 홈에 저장된 메모리: 본문에 프로젝트 저장소 이름이 나올 때만 후보를 제안한다.
335
+ const text = `${statement} ${body}`.toLowerCase();
336
+ const hits = [...new Set(repoNames.filter((n) => n.length >= 4 && text.includes(n)))];
337
+ if (hits.length === 1) {
338
+ project = hits[0];
339
+ note = `본문에 저장소 이름 "${hits[0]}" → 후보(확인 필요)`;
340
+ }
341
+ else if (hits.length > 1)
342
+ note = `본문에 저장소 이름 여러 개(${hits.join(', ')}) → 전역(확인 필요)`;
343
+ }
344
+ const c = {
345
+ id: `mem-${shortHash(source + raw)}`, source, statement,
346
+ applies_when: section(body, 'How to apply').slice(0, 200),
347
+ why: section(body, 'Why'),
348
+ project, projectGuess: note,
349
+ };
350
+ if (/…|\.\.\.\s*$/.test(statement))
351
+ c.excluded = { reason: 'truncated', detail: '문장이 잘려 있다' };
352
+ else if (LOG_LIKE.test(statement))
353
+ c.excluded = { reason: 'log', detail: '사건 기록처럼 보인다' };
354
+ else if (redactSecrets(`${statement}\n${c.applies_when}\n${c.why}`).hits.length)
355
+ c.excluded = { reason: 'secret', detail: '비밀로 보이는 문자열' };
356
+ return c;
357
+ }
358
+ export function readMemoryCandidates(dir, rules) {
359
+ const root = dir ? path.resolve(dir) : path.join(CLAUDE_DIR, 'projects');
360
+ const targets = [];
361
+ const add = (d, project) => { if (fs.existsSync(d))
362
+ targets.push({ dir: d, project }); };
363
+ let subs = [];
364
+ try {
365
+ subs = fs.readdirSync(root);
366
+ }
367
+ catch { /* 없음 */ }
368
+ for (const s of subs)
369
+ add(path.join(root, s, 'memory'), s);
370
+ if (!targets.length) {
371
+ add(path.join(root, 'memory'), path.basename(path.dirname(root)));
372
+ add(root, path.basename(root));
373
+ }
374
+ // 홈 메모리의 프로젝트 후보로 쓸 저장소 이름: 다른 프로젝트 메모리 폴더가 가리키는 저장소 + 룰에 이미 쓰인 프로젝트 키
375
+ const repoNames = new Set(rules.flatMap((r) => r.projects ?? []));
376
+ for (const t of targets) {
377
+ const g = guessProject(t.project);
378
+ if (g.key)
379
+ repoNames.add(g.key);
380
+ }
381
+ const candidates = [];
382
+ const scanned = [];
383
+ const seen = rules.map((r) => ({ text: r.policy, label: `${r.status} 룰` }));
384
+ const batch = [];
385
+ for (const t of targets) {
386
+ let files = [];
387
+ try {
388
+ files = fs.readdirSync(t.dir).filter((f) => /^feedback_.*\.md$/.test(f)).sort();
389
+ }
390
+ catch {
391
+ continue;
392
+ }
393
+ const g = guessProject(t.project);
394
+ for (const f of files) {
395
+ const full = path.join(t.dir, f);
396
+ scanned.push(`${g.slug}/${f}`);
397
+ const c = parseMemoryFile(fs.readFileSync(full, 'utf-8'), `${g.slug}/${f}`, g, [...repoNames]);
398
+ if (!c)
399
+ continue;
400
+ if (!c.excluded) {
401
+ const dup = seen.find((o) => isDuplicate(c.statement, [o.text], 0.5));
402
+ if (dup)
403
+ c.excluded = { reason: 'duplicate', detail: `${dup.label}: "${dup.text.slice(0, 40)}"` };
404
+ else if (isDuplicate(c.statement, batch, 0.5))
405
+ c.excluded = { reason: 'duplicate-in-batch', detail: '같은 수집 안의 다른 메모리와 중복' };
406
+ else {
407
+ const conf = conflictingRule(c.statement, rules);
408
+ if (conf)
409
+ c.excluded = { reason: 'conflict', detail: `활성 룰 ${conf.rule_id.slice(0, 8)} 과 상반: "${conf.policy.slice(0, 40)}"` };
410
+ }
411
+ }
412
+ if (!c.excluded)
413
+ batch.push(c.statement);
414
+ candidates.push(c);
415
+ }
416
+ }
417
+ return { candidates, scanned };
418
+ }
419
+ export function candidateToItem(c, projectOverride) {
420
+ const project = projectOverride === undefined ? c.project : projectOverride;
421
+ return {
422
+ id: c.id, kind: 'rule', statement: c.statement, applies_when: c.applies_when, why: c.why,
423
+ projects: project ? [project] : [], strength: 'default', provenance: { kind: 'imported', from: c.source }, enforceable: false, status: 'active', category: 'workflow',
424
+ };
425
+ }
@@ -0,0 +1,2 @@
1
+ export declare function similarity(a: string, b: string): number;
2
+ export declare function isDuplicate(text: string, others: string[], threshold?: number): string | null;
@@ -0,0 +1,30 @@
1
+ /** 문자 bigram Dice 유사도. 한국어·영어 공통, 외부 의존 없음. */
2
+ function grams(s) {
3
+ const t = s.toLowerCase().replace(/[^\p{L}\p{N}]+/gu, '');
4
+ const m = new Map();
5
+ for (let i = 0; i < t.length - 1; i++)
6
+ m.set(t.slice(i, i + 2), (m.get(t.slice(i, i + 2)) ?? 0) + 1);
7
+ return m;
8
+ }
9
+ export function similarity(a, b) {
10
+ const ga = grams(a);
11
+ const gb = grams(b);
12
+ let inter = 0;
13
+ let na = 0;
14
+ let nb = 0;
15
+ for (const v of ga.values())
16
+ na += v;
17
+ for (const v of gb.values())
18
+ nb += v;
19
+ if (!na || !nb)
20
+ return 0;
21
+ for (const [k, v] of ga)
22
+ inter += Math.min(v, gb.get(k) ?? 0);
23
+ return (2 * inter) / (na + nb);
24
+ }
25
+ export function isDuplicate(text, others, threshold = 0.6) {
26
+ for (const o of others)
27
+ if (similarity(text, o) >= threshold)
28
+ return o;
29
+ return null;
30
+ }
@@ -0,0 +1,98 @@
1
+ /**
2
+ * Way — 호스트 중립 "내 방식" 표현 (ADR-020).
3
+ *
4
+ * 새 저장소가 아니다. 기존 저장소(룰·evidence·솔루션·behavior·프로필)를 읽어 만든 뷰다.
5
+ * 호스트 전용 필드(enforce_via, hook 이름 등)는 여기에 없다. 강제 가능 여부만 불리언으로 노출한다.
6
+ */
7
+ export type WayKind = 'rule' | 'solution' | 'habit';
8
+ export type WayStrength = 'soft' | 'default' | 'strong' | 'hard';
9
+ export type Provenance =
10
+ /** 사용자가 한 말. quote 는 발화 원문(있을 때만). */
11
+ {
12
+ kind: 'you-said';
13
+ quote?: string;
14
+ date?: string;
15
+ }
16
+ /** 행동 관찰에서 추론. 사용자가 한 말이 아니다. */
17
+ | {
18
+ kind: 'mined';
19
+ date?: string;
20
+ }
21
+ /** 다른 곳(호스트 메모리 파일 등)에서 가져옴. */
22
+ | {
23
+ kind: 'imported';
24
+ from: string;
25
+ date?: string;
26
+ };
27
+ export interface WayItem {
28
+ id: string;
29
+ kind: WayKind;
30
+ statement: string;
31
+ /** 어떤 상황에서 적용되는가. */
32
+ applies_when: string;
33
+ why: string;
34
+ /** 비어 있으면 전역. */
35
+ projects: string[];
36
+ strength: WayStrength;
37
+ provenance: Provenance;
38
+ /** 결정적 탐지기가 있어 강제할 수 있는 룰인가. false 면 자문. */
39
+ enforceable: boolean;
40
+ /** 룰만: 'active' | 'suppressed' | 'removed'. 가져오기에서 고칠 수 있다. */
41
+ status?: 'active' | 'suppressed' | 'removed';
42
+ category?: string;
43
+ /** 렌더러와 같은 예산 우선순위·중복 제거에 쓰는 값 (저장소의 render_key·source·updated_at). */
44
+ render_key?: string;
45
+ source?: 'explicit_correction' | 'onboarding' | 'behavior_inference' | 'pack_overlay' | 'imported';
46
+ updated_at?: string;
47
+ /** 습관만: 이 활성 룰과 상반된다. */
48
+ conflicts_with?: string;
49
+ }
50
+ export interface WayStats {
51
+ rules_active: number;
52
+ rules_you_said: number;
53
+ rules_mined: number;
54
+ rules_imported: number;
55
+ rules_enforceable: number;
56
+ solutions_verified: number;
57
+ solutions_unverified: number;
58
+ habits: number;
59
+ }
60
+ export interface Way {
61
+ schema: 'forgen-way/1';
62
+ generator: 'forgen-way';
63
+ generated_at: string;
64
+ items: WayItem[];
65
+ stats: WayStats;
66
+ }
67
+ export declare const WAY_SCHEMA = "forgen-way/1";
68
+ export type CompileTarget = 'agents-md' | 'claude-rules' | 'skill' | 'system-prompt' | 'gemini' | 'cursor' | 'workflow' | 'json';
69
+ export declare const COMPILE_TARGETS: CompileTarget[];
70
+ export interface CompiledFile {
71
+ path: string;
72
+ content: string;
73
+ }
74
+ export interface Omitted {
75
+ id: string;
76
+ reason: 'budget' | 'project-scope' | 'not-a-procedure' | 'habit-excluded' | 'not-selected' | 'duplicate' | 'conflict';
77
+ detail?: string;
78
+ }
79
+ export interface Degraded {
80
+ id: string;
81
+ reason: string;
82
+ }
83
+ export interface CompileResult {
84
+ files: CompiledFile[];
85
+ omitted: Omitted[];
86
+ degraded: Degraded[];
87
+ warnings: string[];
88
+ }
89
+ export interface CompileOptions {
90
+ /** 이 프로젝트 키. 없으면 전역 항목만. */
91
+ project?: string;
92
+ /** 본문 글자 수 예산. 넘치면 우선순위로 고르고 나머지는 omitted. */
93
+ budget?: number;
94
+ /** 습관(채굴·프로필)도 포함. 기본 제외. */
95
+ habits?: boolean;
96
+ /** 이 id 만 컴파일 (skill promote 등). */
97
+ only?: string[];
98
+ }
@@ -0,0 +1,2 @@
1
+ export const WAY_SCHEMA = 'forgen-way/1';
2
+ export const COMPILE_TARGETS = ['agents-md', 'claude-rules', 'skill', 'system-prompt', 'gemini', 'cursor', 'workflow', 'json'];
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@wooojin/forgen",
3
- "version": "0.6.8",
3
+ "version": "0.6.10",
4
4
  "preferGlobal": true,
5
5
  "main": "dist/lib.js",
6
6
  "types": "./dist/lib.d.ts",
package/plugin.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "$schema": "https://claude.ai/schemas/claude-plugin.json",
3
3
  "name": "forgen",
4
- "version": "0.6.8",
4
+ "version": "0.6.10",
5
5
  "description": "Claude Code harness — the more you use Claude, the better it gets",
6
6
  "author": {
7
7
  "name": "jang-ujin",