@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
@@ -1,4 +1,4 @@
1
- import type { SolutionFrontmatter, SolutionStatus } from './solution-format.js';
1
+ import type { RetiredReason, SolutionFrontmatter, SolutionStatus } from './solution-format.js';
2
2
  import type { AdaptiveLifecycleThresholds } from './meta-learning/types.js';
3
3
  export interface LifecycleResult {
4
4
  promoted: string[];
@@ -25,9 +25,43 @@ export declare function isStale(fm: SolutionFrontmatter): boolean;
25
25
  * PR2b: solution-writer.mutateSolutionFile로 통합. lock + fresh re-read + atomic write.
26
26
  */
27
27
  export declare function updateSolutionFile(filePath: string, updates: Partial<SolutionFrontmatter>): boolean;
28
+ /**
29
+ * 은퇴 패치. 사유를 남기고, confidence 는 반증(contradicted)일 때만 0 으로 만든다.
30
+ * stale/manual 은 값어치가 없어서가 아니라 시간·사용자 판단 때문이라 confidence 를 보존해야 복귀(reopen)가 의미 있다.
31
+ */
32
+ export declare function retirePatch(fm: SolutionFrontmatter, reason: RetiredReason): Partial<SolutionFrontmatter>;
28
33
  /** Run lifecycle check on all solutions */
29
- export declare function runLifecycleCheck(_sessionId?: string): LifecycleResult;
34
+ export declare function runLifecycleCheck(_sessionId?: string, opts?: {
35
+ dryRun?: boolean;
36
+ }): LifecycleResult;
30
37
  /** Detect contradictions between solutions */
31
38
  export declare function detectContradictions(dirs: string[]): string[];
39
+ /** 영문·한글 낱말 집합의 Jaccard 유사도 (0~1). 같은 이름이라도 내용이 다르면 복귀 대상이 아니다. */
40
+ export declare function contentSimilarity(a: string, b: string): number;
41
+ /** 재추출 내용이 은퇴본과 이만큼 비슷해야 "같은 내용이 다시 나왔다"고 본다. */
42
+ export declare const REOPEN_MIN_SIMILARITY = 0.5;
43
+ /**
44
+ * 은퇴한 솔루션을 후보 상태로 되돌린다 (D6 복귀 경로). me·팩·프로젝트 솔루션 모두 대상.
45
+ * - 은퇴 전 등급을 지킨다: 보존된 confidence 가 verified(0.75)/mature(0.9) 이상이면 그 등급으로 복귀, 아니면 candidate.
46
+ * - 은퇴 사유/시각 제거, updated=오늘(오래됨 판정 리셋).
47
+ * - contradicted 와 사유 미상(구버전 은퇴, 반증이었을 수 있다)은 negative 증거를 0 으로 되돌린다 — 그대로 두면 회로 차단기가 바로 다시 은퇴시킨다.
48
+ */
49
+ export declare function reopenSolution(solutionName: string, cwd?: string): {
50
+ ok: boolean;
51
+ reason?: string;
52
+ previous?: RetiredReason | 'unknown';
53
+ status?: SolutionStatus;
54
+ };
55
+ /** 사용자가 직접 끈다. 사유 manual — confidence 는 보존하고 재추출돼도 자동으로 되살리지 않는다. */
56
+ export declare function deactivateSolution(solutionName: string): boolean;
57
+ export type ReExtractOutcome = 'reopened' | 'different' | 'blocked' | 'none';
58
+ /**
59
+ * 재추출된 솔루션과 같은 이름의 은퇴본이 있을 때의 처리. 이름만으로 복귀시키지 않고 **내용이 비슷할 때만** 복귀한다.
60
+ * - 'reopened' 내용이 비슷하고 stale/사유 미상 → 복귀
61
+ * - 'blocked' 내용이 비슷하지만 manual(사용자가 끔)·contradicted(반증됨) → 되살리지 않음 (새 추출은 버려도 된다)
62
+ * - 'different' 이름만 같고 내용이 다르다 → 복귀하지 않는다. 호출자는 새 추출을 버리면 안 된다
63
+ * - 'none' 은퇴본 없음
64
+ */
65
+ export declare function reopenIfReExtracted(solutionName: string, newContent: string, cwd?: string): ReExtractOutcome;
32
66
  /** Manual verify command: immediately promote to verified */
33
67
  export declare function verifySolution(solutionName: string): boolean;
@@ -2,7 +2,8 @@ import { execFileSync } from 'node:child_process';
2
2
  import * as fs from 'node:fs';
3
3
  import * as path from 'node:path';
4
4
  import { createLogger } from '../core/logger.js';
5
- import { parseFrontmatterOnly } from './solution-format.js';
5
+ import { parseFrontmatterOnly, parseSolutionV3 } from './solution-format.js';
6
+ import { defaultSolutionDirs } from './solution-index.js';
6
7
  import { mutateSolutionFile } from './solution-writer.js';
7
8
  const log = createLogger('compound-lifecycle');
8
9
  import { ME_RULES, ME_SOLUTIONS, META_LEARNING_DIR } from '../core/paths.js';
@@ -165,7 +166,8 @@ export function isStale(fm) {
165
166
  const ninetyDaysMs = staleDays * 24 * 60 * 60 * 1000;
166
167
  if (fm.evidence.injected === 0) {
167
168
  // Never injected — check age
168
- const created = new Date(fm.created).getTime();
169
+ // 복귀(reopen)한 솔루션은 updated 가 갱신되므로 둘 중 늦은 쪽을 기준으로 한다 (아니면 복귀 즉시 다시 stale).
170
+ const created = Math.max(new Date(fm.created).getTime(), new Date(fm.updated).getTime() || 0);
169
171
  const age = Date.now() - created;
170
172
  return age > ninetyDaysMs;
171
173
  }
@@ -187,8 +189,23 @@ export function updateSolutionFile(filePath, updates) {
187
189
  return true;
188
190
  });
189
191
  }
192
+ /**
193
+ * 은퇴 패치. 사유를 남기고, confidence 는 반증(contradicted)일 때만 0 으로 만든다.
194
+ * stale/manual 은 값어치가 없어서가 아니라 시간·사용자 판단 때문이라 confidence 를 보존해야 복귀(reopen)가 의미 있다.
195
+ */
196
+ export function retirePatch(fm, reason) {
197
+ return {
198
+ status: 'retired',
199
+ retiredReason: reason,
200
+ retiredAt: new Date().toISOString().split('T')[0],
201
+ ...(reason === 'contradicted' ? { confidence: 0 } : { confidence: fm.confidence }),
202
+ };
203
+ }
190
204
  /** Run lifecycle check on all solutions */
191
- export function runLifecycleCheck(_sessionId = 'system') {
205
+ export function runLifecycleCheck(_sessionId = 'system', opts = {}) {
206
+ const dryRun = opts.dryRun === true;
207
+ // dry-run 이면 파일을 쓰지 않고 "바뀔 항목"만 결과에 담는다 (CLI 미리보기).
208
+ const apply = (file, patch) => (dryRun ? true : updateSolutionFile(file, patch));
192
209
  const result = { promoted: [], demoted: [], retired: [], contradictions: [] };
193
210
  // Meta-learning: load adaptive thresholds if available
194
211
  const adaptiveThresholds = loadAdaptiveThresholds();
@@ -212,7 +229,7 @@ export function runLifecycleCheck(_sessionId = 'system') {
212
229
  continue;
213
230
  // 1. Check stale
214
231
  if (isStale(fm)) {
215
- if (updateSolutionFile(filePath, { status: 'retired', confidence: 0 })) {
232
+ if (apply(filePath, retirePatch(fm, 'stale'))) {
216
233
  result.retired.push(fm.name);
217
234
  }
218
235
  continue;
@@ -220,10 +237,9 @@ export function runLifecycleCheck(_sessionId = 'system') {
220
237
  // 2. Check confidence-status consistency
221
238
  const demoteTo = checkConfidenceDemotion(fm);
222
239
  if (demoteTo) {
223
- if (updateSolutionFile(filePath, {
224
- status: demoteTo,
225
- confidence: statusConfidence(demoteTo),
226
- })) {
240
+ if (apply(filePath, demoteTo === 'retired'
241
+ ? retirePatch(fm, 'contradicted') // experiment 의 confidence 가 하한 아래 = 반증 누적의 결과
242
+ : { status: demoteTo, confidence: statusConfidence(demoteTo) })) {
227
243
  result.demoted.push(`${fm.name}: ${fm.status} → ${demoteTo}`);
228
244
  }
229
245
  continue;
@@ -231,7 +247,7 @@ export function runLifecycleCheck(_sessionId = 'system') {
231
247
  // 3. Circuit breaker BEFORE promotion — negative evidence takes priority
232
248
  const cbThreshold = CIRCUIT_BREAKER_THRESHOLDS[fm.status];
233
249
  if (cbThreshold !== undefined && fm.evidence.negative >= cbThreshold) {
234
- if (updateSolutionFile(filePath, { status: 'retired', confidence: 0 })) {
250
+ if (apply(filePath, retirePatch(fm, 'contradicted'))) {
235
251
  result.retired.push(`${fm.name} (circuit-breaker:${fm.status})`);
236
252
  }
237
253
  continue;
@@ -245,7 +261,7 @@ export function runLifecycleCheck(_sessionId = 'system') {
245
261
  if (ageMs >= minAgeMs) {
246
262
  const next = nextStatus(fm.status);
247
263
  if (next) {
248
- if (updateSolutionFile(filePath, { status: next, confidence: statusConfidence(next) })) {
264
+ if (apply(filePath, { status: next, confidence: statusConfidence(next) })) {
249
265
  result.promoted.push(`${fm.name}: ${fm.status} → ${next}`);
250
266
  }
251
267
  }
@@ -257,7 +273,7 @@ export function runLifecycleCheck(_sessionId = 'system') {
257
273
  const effectiveCwd = process.env.FORGEN_CWD ?? process.env.COMPOUND_CWD ?? process.cwd();
258
274
  if (checkIdentifierStaleness(fm, effectiveCwd)) {
259
275
  const newConf = Math.max(0, fm.confidence - 0.2);
260
- if (updateSolutionFile(filePath, { confidence: newConf })) {
276
+ if (apply(filePath, { confidence: newConf })) {
261
277
  result.demoted.push(`${fm.name}: identifier-stale (confidence → ${newConf})`);
262
278
  }
263
279
  }
@@ -314,6 +330,110 @@ export function detectContradictions(dirs) {
314
330
  }
315
331
  return contradictions;
316
332
  }
333
+ /** 영문·한글 낱말 집합의 Jaccard 유사도 (0~1). 같은 이름이라도 내용이 다르면 복귀 대상이 아니다. */
334
+ export function contentSimilarity(a, b) {
335
+ const tokens = (t) => new Set((t.toLowerCase().match(/[a-z0-9가-힣]{2,}/g) ?? []));
336
+ const A = tokens(a);
337
+ const B = tokens(b);
338
+ if (A.size === 0 || B.size === 0)
339
+ return 0;
340
+ let inter = 0;
341
+ for (const t of A)
342
+ if (B.has(t))
343
+ inter++;
344
+ return inter / (A.size + B.size - inter);
345
+ }
346
+ /** 재추출 내용이 은퇴본과 이만큼 비슷해야 "같은 내용이 다시 나왔다"고 본다. */
347
+ export const REOPEN_MIN_SIMILARITY = 0.5;
348
+ /** me + 설치된 팩 + cwd 프로젝트 솔루션 디렉터리에서 이름으로 파일을 찾는다 (심볼릭 링크 제외). */
349
+ function findSolutionFile(solutionName, cwd) {
350
+ for (const { dir } of defaultSolutionDirs(cwd)) {
351
+ if (!fs.existsSync(dir))
352
+ continue;
353
+ for (const file of fs.readdirSync(dir).filter((f) => f.endsWith('.md'))) {
354
+ const filePath = path.join(dir, file);
355
+ try {
356
+ if (fs.lstatSync(filePath).isSymbolicLink())
357
+ continue;
358
+ }
359
+ catch {
360
+ continue;
361
+ }
362
+ const raw = fs.readFileSync(filePath, 'utf-8');
363
+ const fm = parseFrontmatterOnly(raw);
364
+ if (fm && fm.name === solutionName)
365
+ return { filePath, fm, raw };
366
+ }
367
+ }
368
+ return null;
369
+ }
370
+ /**
371
+ * 은퇴한 솔루션을 후보 상태로 되돌린다 (D6 복귀 경로). me·팩·프로젝트 솔루션 모두 대상.
372
+ * - 은퇴 전 등급을 지킨다: 보존된 confidence 가 verified(0.75)/mature(0.9) 이상이면 그 등급으로 복귀, 아니면 candidate.
373
+ * - 은퇴 사유/시각 제거, updated=오늘(오래됨 판정 리셋).
374
+ * - contradicted 와 사유 미상(구버전 은퇴, 반증이었을 수 있다)은 negative 증거를 0 으로 되돌린다 — 그대로 두면 회로 차단기가 바로 다시 은퇴시킨다.
375
+ */
376
+ export function reopenSolution(solutionName, cwd) {
377
+ const found = findSolutionFile(solutionName, cwd);
378
+ if (!found)
379
+ return { ok: false, reason: 'not-found' };
380
+ const { filePath, fm } = found;
381
+ if (fm.status !== 'retired')
382
+ return { ok: false, reason: 'not-retired' };
383
+ const previous = fm.retiredReason ?? 'unknown';
384
+ let restored = 'candidate';
385
+ const ok = mutateSolutionFile(filePath, (sol) => {
386
+ const f = sol.frontmatter;
387
+ restored = f.confidence >= statusConfidence('mature') ? 'mature' : f.confidence >= statusConfidence('verified') ? 'verified' : 'candidate';
388
+ f.status = restored;
389
+ f.confidence = f.confidence > 0 ? f.confidence : statusConfidence('candidate');
390
+ delete f.retiredReason;
391
+ delete f.retiredAt;
392
+ if (previous === 'contradicted' || previous === 'unknown')
393
+ f.evidence.negative = 0;
394
+ return true;
395
+ });
396
+ return ok ? { ok: true, previous, status: restored } : { ok: false, reason: 'write-failed' };
397
+ }
398
+ /** 사용자가 직접 끈다. 사유 manual — confidence 는 보존하고 재추출돼도 자동으로 되살리지 않는다. */
399
+ export function deactivateSolution(solutionName) {
400
+ if (!fs.existsSync(ME_SOLUTIONS))
401
+ return false;
402
+ for (const file of fs.readdirSync(ME_SOLUTIONS).filter((f) => f.endsWith('.md'))) {
403
+ const filePath = path.join(ME_SOLUTIONS, file);
404
+ try {
405
+ if (fs.lstatSync(filePath).isSymbolicLink())
406
+ continue;
407
+ }
408
+ catch {
409
+ continue;
410
+ }
411
+ const fm = parseFrontmatterOnly(fs.readFileSync(filePath, 'utf-8'));
412
+ if (!fm || fm.name !== solutionName || fm.status === 'retired')
413
+ continue;
414
+ return updateSolutionFile(filePath, retirePatch(fm, 'manual'));
415
+ }
416
+ return false;
417
+ }
418
+ /**
419
+ * 재추출된 솔루션과 같은 이름의 은퇴본이 있을 때의 처리. 이름만으로 복귀시키지 않고 **내용이 비슷할 때만** 복귀한다.
420
+ * - 'reopened' 내용이 비슷하고 stale/사유 미상 → 복귀
421
+ * - 'blocked' 내용이 비슷하지만 manual(사용자가 끔)·contradicted(반증됨) → 되살리지 않음 (새 추출은 버려도 된다)
422
+ * - 'different' 이름만 같고 내용이 다르다 → 복귀하지 않는다. 호출자는 새 추출을 버리면 안 된다
423
+ * - 'none' 은퇴본 없음
424
+ */
425
+ export function reopenIfReExtracted(solutionName, newContent, cwd) {
426
+ const found = findSolutionFile(solutionName, cwd);
427
+ if (!found || found.fm.status !== 'retired')
428
+ return 'none';
429
+ const oldBody = parseSolutionV3(found.raw)?.content ?? found.raw;
430
+ const newBody = parseSolutionV3(newContent)?.content ?? newContent;
431
+ if (contentSimilarity(oldBody, newBody) < REOPEN_MIN_SIMILARITY)
432
+ return 'different';
433
+ if (found.fm.retiredReason === 'manual' || found.fm.retiredReason === 'contradicted')
434
+ return 'blocked';
435
+ return reopenSolution(solutionName, cwd).ok ? 'reopened' : 'none';
436
+ }
317
437
  /** Manual verify command: immediately promote to verified */
318
438
  export function verifySolution(solutionName) {
319
439
  const dirs = [ME_SOLUTIONS, ME_RULES];
@@ -9,6 +9,10 @@ export interface CompoundInsight {
9
9
  /** 분류 근거 */
10
10
  reason: string;
11
11
  source: 'session' | 'manual';
12
+ /** 적용 조건·출처 (솔루션 `## Context` 칸). 없으면 빈 칸. */
13
+ context?: string;
14
+ /** 적용 프로젝트 키들 (없으면 전역). */
15
+ projects?: string[];
12
16
  }
13
17
  /** 키워드 기반으로 인사이트를 개인/팀으로 자동 분류 */
14
18
  export declare function classifyInsight(title: string, content: string): {
@@ -2,7 +2,7 @@ import * as fs from 'node:fs';
2
2
  import * as path from 'node:path';
3
3
  import { ME_SOLUTIONS, ME_RULES } from '../core/paths.js';
4
4
  import { resolveScope } from '../core/scope-resolver.js';
5
- import { serializeSolutionV3, extractTags, DEFAULT_EVIDENCE, slugify } from './solution-format.js';
5
+ import { serializeSolutionV3, extractSolutionTags, DEFAULT_EVIDENCE, slugify } from './solution-format.js';
6
6
  /** 키워드 기반으로 인사이트를 개인/팀으로 자동 분류 */
7
7
  export function classifyInsight(title, content) {
8
8
  const teamKeywords = [
@@ -44,15 +44,36 @@ export async function runCompoundLoop(cwd, insights) {
44
44
  continue;
45
45
  }
46
46
  // 중복 체크
47
+ let target = destPath;
47
48
  if (fs.existsSync(destPath)) {
48
- skipped.push(`${insight.title}: already exists`);
49
- continue;
49
+ // 은퇴한 같은 이름의 솔루션: 내용이 비슷할 때만 복귀시킨다 (D6). 내용이 다르면 새 추출을 버리지 않고 다른 이름으로 저장한다.
50
+ let differentFromRetired = false;
51
+ if (insight.type === 'solution' || insight.type === 'pattern') {
52
+ const { reopenIfReExtracted } = await import('./compound-lifecycle.js');
53
+ const outcome = reopenIfReExtracted(path.basename(destPath, '.md'), insight.content, cwd);
54
+ if (outcome === 'reopened') {
55
+ saved.push(`${insight.scope}/${insight.type}: ${insight.title} (reopened from retired)`);
56
+ continue;
57
+ }
58
+ if (outcome === 'different') {
59
+ differentFromRetired = true;
60
+ const base = destPath.replace(/\.md$/, '');
61
+ let n = 2;
62
+ while (fs.existsSync(`${base}-${n}.md`))
63
+ n++;
64
+ target = `${base}-${n}.md`;
65
+ }
66
+ }
67
+ if (!differentFromRetired) {
68
+ skipped.push(`${insight.title}: already exists`);
69
+ continue;
70
+ }
50
71
  }
51
72
  // 디렉토리 생성
52
- fs.mkdirSync(path.dirname(destPath), { recursive: true });
73
+ fs.mkdirSync(path.dirname(target), { recursive: true });
53
74
  // 파일 저장
54
- const fileContent = formatInsight(insight);
55
- fs.writeFileSync(destPath, fileContent);
75
+ const fileContent = formatInsight(insight, path.basename(target, '.md'));
76
+ fs.writeFileSync(target, fileContent);
56
77
  saved.push(`${insight.scope}/${insight.type}: ${insight.title}`);
57
78
  }
58
79
  catch (err) {
@@ -98,25 +119,26 @@ function inferIdentifiers(title, content) {
98
119
  .filter(id => id.length >= 4 && id.length <= 50);
99
120
  return all.slice(0, 10); // max 10 identifiers
100
121
  }
101
- function formatInsight(insight) {
122
+ function formatInsight(insight, name) {
102
123
  const today = new Date().toISOString().split('T')[0];
103
124
  const solution = {
104
125
  frontmatter: {
105
- name: slugify(insight.title),
126
+ name: name ?? slugify(insight.title),
106
127
  version: 1,
107
128
  status: 'candidate',
108
129
  confidence: 0.5,
109
130
  type: mapInsightType(insight.type),
110
131
  scope: insight.scope,
111
- tags: extractTags(`${insight.title} ${insight.content}`),
132
+ tags: extractSolutionTags(`${insight.title} ${insight.content}`),
112
133
  identifiers: inferIdentifiers(insight.title, insight.content),
113
134
  evidence: { ...DEFAULT_EVIDENCE },
114
135
  created: today,
115
136
  updated: today,
116
137
  supersedes: null,
117
138
  extractedBy: insight.source === 'manual' ? 'manual' : 'auto',
139
+ ...(insight.projects?.length ? { projects: insight.projects } : {}),
118
140
  },
119
- context: '',
141
+ context: insight.context ?? '',
120
142
  content: insight.content,
121
143
  };
122
144
  return serializeSolutionV3(solution);
@@ -187,7 +209,8 @@ export async function handleCompound(args) {
187
209
  Rollback unused auto-extracted solutions since date
188
210
 
189
211
  Lifecycle:
190
- forgen compound --lifecycle Run promotion/demotion/circuit-breaker check
212
+ forgen compound --lifecycle [--apply]
213
+ Preview promotion/demotion/circuit-breaker changes (--apply to write)
191
214
  forgen compound --verify <name> Manually promote solution to verified
192
215
 
193
216
  Export/Import (whole store, tar.gz):
@@ -272,8 +295,10 @@ export async function handleCompound(args) {
272
295
  // --- lifecycle command ---
273
296
  if (args.includes('--lifecycle') || args.includes('lifecycle')) {
274
297
  const { runLifecycleCheck } = await import('./compound-lifecycle.js');
275
- const result = runLifecycleCheck();
276
- console.log('\n Compound Lifecycle Check\n');
298
+ // 상태를 바꾸는 명령이라 기본은 미리보기. --apply 를 줘야 실제로 승급·강등·폐기한다.
299
+ const apply = args.includes('--apply');
300
+ const result = runLifecycleCheck('system', { dryRun: !apply });
301
+ console.log(`\n Compound Lifecycle Check${apply ? '' : ' (미리보기 — 아무것도 바꾸지 않았습니다)'}\n`);
277
302
  if (result.promoted.length) {
278
303
  console.log(' Promoted:');
279
304
  for (const p of result.promoted)
@@ -297,6 +322,9 @@ export async function handleCompound(args) {
297
322
  if (!result.promoted.length && !result.demoted.length && !result.retired.length && !result.contradictions.length) {
298
323
  console.log(' No lifecycle changes needed.\n');
299
324
  }
325
+ else if (!apply) {
326
+ console.log('\n 적용하려면: forgen compound --lifecycle --apply');
327
+ }
300
328
  console.log();
301
329
  return;
302
330
  }
@@ -353,10 +381,46 @@ export async function handleCompound(args) {
353
381
  removeSolution(name);
354
382
  return;
355
383
  }
384
+ // --- reopen / retired (D6: 은퇴 복귀 경로) ---
385
+ if (args[0] === 'reopen') {
386
+ const name = args[1];
387
+ if (!name || name.startsWith('--')) {
388
+ console.log(' Usage: forgen compound reopen <solution-name>\n');
389
+ return;
390
+ }
391
+ const { reopenSolution } = await import('./compound-lifecycle.js');
392
+ const r = reopenSolution(name, process.cwd());
393
+ if (r.ok)
394
+ console.log(`\n ✓ Reopened: ${name} (이전 은퇴 사유: ${r.previous}) → ${r.status ?? 'candidate'}\n`);
395
+ else
396
+ console.log(`\n Reopen 실패: ${name} (${r.reason})\n`);
397
+ return;
398
+ }
399
+ if (args[0] === 'deactivate') {
400
+ const name = args[1];
401
+ if (!name || name.startsWith('--')) {
402
+ console.log(' Usage: forgen compound deactivate <solution-name> (사용자가 끔 — retiredReason=manual, 자동 복귀 없음)\n');
403
+ return;
404
+ }
405
+ const { deactivateSolution } = await import('./compound-lifecycle.js');
406
+ console.log(deactivateSolution(name) ? `\n ✓ Deactivated: ${name} (manual). 되돌리기: forgen compound reopen ${name}\n` : `\n Deactivate 실패: ${name} (없거나 이미 은퇴)\n`);
407
+ return;
408
+ }
409
+ if (args[0] === 'retired') {
410
+ const { listRetired } = await import('./compound-cli.js');
411
+ listRetired();
412
+ return;
413
+ }
356
414
  // --- retag command ---
357
415
  if (args.includes('retag') || args.includes('--retag')) {
358
416
  const { retagSolutions } = await import('./compound-cli.js');
359
- retagSolutions();
417
+ retagSolutions(args.includes('--apply')); // 상태를 바꾸므로 기본은 미리보기
418
+ return;
419
+ }
420
+ // --- habits command (습관 로그를 솔루션에서 behavior 로 분리) ---
421
+ if (args[0] === 'habits' || args.includes('--habits')) {
422
+ const { migrateHabitLogs } = await import('./compound-cli.js');
423
+ migrateHabitLogs(args.includes('--apply'));
360
424
  return;
361
425
  }
362
426
  // --- rollback command ---
@@ -436,14 +500,15 @@ export async function handleCompound(args) {
436
500
  // 인자가 없거나 알 수 없는 플래그만 있으면 수동 추가/interactive가 아닌 것으로 간주
437
501
  const knownFlags = [
438
502
  '--solution', '--rule', '--convention', '--pattern', '--to', '--pause-auto', '--resume-auto',
439
- '--lifecycle', '--verify', '--save', '--interactive',
440
- 'list', 'inspect', 'remove', 'rollback', 'retag', 'lifecycle',
503
+ '--lifecycle', '--apply', '--verify', '--save', '--interactive', '--project',
504
+ 'list', 'inspect', 'remove', 'rollback', 'retag', 'lifecycle', 'habits', '--habits', 'reopen', 'retired', 'deactivate',
441
505
  '--list', '--inspect', '--remove', '--rollback', '--retag', '--since', 'interactive',
442
506
  'export', 'import', '--output', '--out', '--dry-run',
443
507
  ];
444
508
  const hasTypeFlag = knownFlags.some(f => args.includes(f));
445
509
  if (!hasTypeFlag) {
446
- console.log(' Unknown compound arguments. Run `forgen compound --help` for usage.\n');
510
+ console.error(` Unknown compound arguments: ${args.join(' ')}\n Run \`forgen compound --help\` for usage.\n`);
511
+ process.exitCode = 1;
447
512
  return;
448
513
  }
449
514
  await handleManualAdd(args, cwd, scope);
@@ -468,7 +533,15 @@ async function handleManualAdd(args, cwd, scope) {
468
533
  // --solution/--rule 다음 인자들이 제목과 내용 (-- 접두사 인자 필터)
469
534
  const typeFlag = `--${type}`;
470
535
  const flagIdx = args.indexOf(typeFlag);
471
- const positionalArgs = args.slice(flagIdx + 1).filter(a => !a.startsWith('--'));
536
+ // --context <text>: 값이 위치 인자로 새지 않도록 플래그와 함께 제거.
537
+ const ctxIdx = args.indexOf('--context');
538
+ const context = ctxIdx !== -1 ? args[ctxIdx + 1] : undefined;
539
+ const prjIdx = args.indexOf('--project');
540
+ const projectOpt = prjIdx !== -1 && args[prjIdx + 1] && !args[prjIdx + 1].startsWith('--') ? args[prjIdx + 1].toLowerCase() : undefined;
541
+ const argsNoPrj = prjIdx !== -1 ? [...args.slice(0, prjIdx), ...args.slice(prjIdx + 2)] : args;
542
+ const ctxIdx2 = argsNoPrj.indexOf('--context');
543
+ const argsNoCtx = ctxIdx2 !== -1 ? [...argsNoPrj.slice(0, ctxIdx2), ...argsNoPrj.slice(ctxIdx2 + 2)] : argsNoPrj;
544
+ const positionalArgs = argsNoCtx.slice(argsNoCtx.indexOf(typeFlag) + 1).filter(a => !a.startsWith('--'));
472
545
  const title = positionalArgs[0];
473
546
  const content = positionalArgs.slice(1).join(' ');
474
547
  if (!title) {
@@ -486,6 +559,8 @@ async function handleManualAdd(args, cwd, scope) {
486
559
  classification,
487
560
  reason,
488
561
  source: 'manual',
562
+ ...(context && !context.startsWith('--') ? { context: context.slice(0, 600) } : {}),
563
+ ...(projectOpt ? { projects: [projectOpt] } : {}),
489
564
  };
490
565
  const result = await runCompoundLoop(cwd, [insight]);
491
566
  for (const s of result.saved) {
@@ -26,7 +26,17 @@ export interface ClusterMergeResult {
26
26
  * 세션종료 클러스터링 실행. 통합 발생 시 각 통합 요약 배열 반환(빈 배열이면 no-op).
27
27
  * 자동 실행이므로 조용하지 않게 — 호출측이 결과를 stderr/알림으로 노출한다.
28
28
  */
29
- export declare function runCorrectionClustering(): Promise<ClusterMergeResult[]>;
29
+ export declare function runCorrectionClustering(opts?: {
30
+ confirmed?: boolean; /** 지정하면 이 제안 ID(미리보기에 표시된 것)만 적용한다. */
31
+ only?: string[];
32
+ }): Promise<ClusterMergeResult[]>;
33
+ /** 확인 대기 중인 explicit 병합 제안 (`forgen rule merge-explicit` 가 보여주고 --apply 로 적용). */
34
+ export declare const MERGE_PROPOSALS_PATH: string;
35
+ /**
36
+ * 병합 제안 ID — 멤버 룰의 현재 내용(id·policy·strength)과 대표 정책이 바뀌면 달라진다.
37
+ * `merge-explicit --apply <id>` 가 "미리보기에서 본 바로 그 제안"만 적용하도록 고정하는 용도.
38
+ */
39
+ export declare function mergeProposalId(members: Rule[], representativePolicy: string, strength: string): string;
30
40
  export interface UnmergeResult {
31
41
  ok: boolean;
32
42
  restored: string[];
@@ -19,6 +19,7 @@ import { STATE_DIR } from '../core/paths.js';
19
19
  import { atomicWriteJSON, safeReadJSON } from '../hooks/shared/atomic-write.js';
20
20
  import { withFileLock } from '../hooks/shared/file-lock.js';
21
21
  import { createRule, loadAllRules, loadRule, saveRule } from '../store/rule-store.js';
22
+ import { withStatusChange } from '../store/rule-lifecycle.js';
22
23
  import { clusterCorrectionRules, clusterKey, findMostSimilarRule, isSuppressedCluster, mergeAcrossCategories, } from './correction-clustering.js';
23
24
  const log = createLogger('correction-cluster');
24
25
  const SUPPRESSION_PATH = path.join(STATE_DIR, 'cluster-suppression.json');
@@ -75,14 +76,24 @@ function isClusterMergedRule(r) {
75
76
  * 세션종료 클러스터링 실행. 통합 발생 시 각 통합 요약 배열 반환(빈 배열이면 no-op).
76
77
  * 자동 실행이므로 조용하지 않게 — 호출측이 결과를 stderr/알림으로 노출한다.
77
78
  */
78
- export async function runCorrectionClustering() {
79
+ export async function runCorrectionClustering(opts = {}) {
79
80
  // 리뷰 SEV-3 #4: auto-compound 는 세션별 detached 실행이라 두 세션 동시 종료 시
80
81
  // 병렬 진입 가능 → 같은 후보로 각자 통합룰 생성/last-write-wins 불일치. 파일락으로
81
82
  // 클러스터링 임계구역을 직렬화한다. fail-open(락 실패는 예외 → 호출측 catch).
82
83
  fs.mkdirSync(STATE_DIR, { recursive: true }); // 락 파일 생성 전 상태 디렉터리 보장
83
- return withFileLock(CLUSTER_LOCK_PATH, () => runCorrectionClusteringLocked());
84
+ return withFileLock(CLUSTER_LOCK_PATH, () => runCorrectionClusteringLocked(opts.confirmed === true, opts.only ? new Set(opts.only) : undefined));
84
85
  }
85
- async function runCorrectionClusteringLocked() {
86
+ /** 확인 대기 중인 explicit 병합 제안 (`forgen rule merge-explicit` 가 보여주고 --apply 로 적용). */
87
+ export const MERGE_PROPOSALS_PATH = path.join(STATE_DIR, 'merge-proposals.json');
88
+ /**
89
+ * 병합 제안 ID — 멤버 룰의 현재 내용(id·policy·strength)과 대표 정책이 바뀌면 달라진다.
90
+ * `merge-explicit --apply <id>` 가 "미리보기에서 본 바로 그 제안"만 적용하도록 고정하는 용도.
91
+ */
92
+ export function mergeProposalId(members, representativePolicy, strength) {
93
+ const body = members.map((r) => `${r.rule_id}\u0000${r.policy}\u0000${r.strength}\u0000${r.status}`).sort().join('\u0001');
94
+ return crypto.createHash('sha1').update(`${body}\u0002${representativePolicy}\u0002${strength}`).digest('hex').slice(0, 8);
95
+ }
96
+ async function runCorrectionClusteringLocked(confirmed, only) {
86
97
  const all = loadAllRules();
87
98
  const candidates = all.filter((r) => r.scope === 'me' &&
88
99
  r.status === 'active' &&
@@ -97,6 +108,7 @@ async function runCorrectionClusteringLocked() {
97
108
  // T5 내부 모순 확인용 detector (동적 import — 순환 의존 회피).
98
109
  const { detect: detectT5 } = await import('./lifecycle/trigger-t5-conflict.js');
99
110
  const results = [];
111
+ const proposals = [];
100
112
  for (const cluster of clusters) {
101
113
  const memberRules = cluster.members
102
114
  .map((m) => candidates.find((c) => c.rule_id === m.rule_id))
@@ -109,6 +121,15 @@ async function runCorrectionClusteringLocked() {
109
121
  log.debug(`클러스터 통합 스킵(T5 모순): ${clusterKey(cluster.members)}`);
110
122
  continue;
111
123
  }
124
+ // R9: explicit(사용자가 직접 한 교정) 룰은 사용자 확인 없이 다른 룰에 흡수·대체하지 않는다.
125
+ // 자동 경로(세션 종료)는 제안만 기록하고, `forgen rule merge-explicit --apply` 가 확인 후 적용한다.
126
+ const proposalId = mergeProposalId(memberRules, cluster.representativePolicy, cluster.strength);
127
+ if (!confirmed) {
128
+ proposals.push({ id: proposalId, members: memberRules.map((r) => r.rule_id), representative_policy: cluster.representativePolicy, strength: cluster.strength });
129
+ continue;
130
+ }
131
+ if (only && !only.has(proposalId))
132
+ continue; // 미리보기에서 고른 제안만 적용
112
133
  const category = memberRules[0].category;
113
134
  // 리뷰 SEV-3 #2: 클러스터에 이미 통합룰이 있으면 새 M2 를 만들지 않고 *기존 통합룰에
114
135
  // 흡수*한다(supersession 체인 방지). evidence/강도/policy 를 갱신하고 신규 멤버만
@@ -144,9 +165,7 @@ async function runCorrectionClusteringLocked() {
144
165
  }
145
166
  // 흡수된 원본은 삭제하지 않고 superseded + clustered_into 링크(unmerge 복원 가능).
146
167
  for (const orig of absorbed) {
147
- orig.status = 'superseded';
148
- orig.clustered_into = mergedId;
149
- saveRule(orig);
168
+ saveRule({ ...withStatusChange(orig, 'superseded', `clustered-into ${mergedId}`, 'cluster'), clustered_into: mergedId });
150
169
  }
151
170
  results.push({
152
171
  mergedRuleId: mergedId,
@@ -158,6 +177,13 @@ async function runCorrectionClusteringLocked() {
158
177
  });
159
178
  log.debug(`클러스터 통합: +${absorbed.length}룰 → ${mergedId} (${cluster.strength})`);
160
179
  }
180
+ if (!confirmed) {
181
+ try {
182
+ fs.mkdirSync(STATE_DIR, { recursive: true });
183
+ fs.writeFileSync(MERGE_PROPOSALS_PATH, `${JSON.stringify({ at: new Date().toISOString(), proposals }, null, 1)}\n`);
184
+ }
185
+ catch { /* best-effort */ }
186
+ }
161
187
  return results;
162
188
  }
163
189
  /**
@@ -194,8 +220,7 @@ export function unmergeCluster(mergedRuleId) {
194
220
  // 위에서 이미 복원됐으므로 카운터만 정리하고 통합 룰은 기존대로 removed.
195
221
  if (linkedMined.length > 0)
196
222
  detachMinedLinks(merged, linkedMined);
197
- merged.status = 'removed';
198
- saveRule(merged);
223
+ saveRule(withStatusChange(merged, 'removed', 'unmerged', 'cluster'));
199
224
  }
200
225
  // 이 조합을 억제목록에 추가 → 재통합/재링크 방지. 링크는 (채굴, explicit) 쌍 단위로 억제해
201
226
  // 다른 채굴 룰의 링크나 채굴끼리 통합에는 영향을 주지 않는다(isSuppressedCluster 의
@@ -425,9 +450,7 @@ async function applyMinedRuleMergePlan(plan) {
425
450
  result.mergedRuleIds.push(mergedId);
426
451
  }
427
452
  for (const orig of fresh) {
428
- orig.status = 'superseded';
429
- orig.clustered_into = mergedId;
430
- saveRule(orig);
453
+ saveRule({ ...withStatusChange(orig, 'superseded', `clustered-into ${mergedId}`, 'cluster'), clustered_into: mergedId });
431
454
  result.supersededIds.push(orig.rule_id);
432
455
  }
433
456
  log.debug(`채굴 클러스터 통합: +${fresh.length}룰 → ${mergedId}`);
@@ -439,10 +462,11 @@ async function applyMinedRuleMergePlan(plan) {
439
462
  * promoteSessionCandidates 의 사전 중복 검사(explicit 매칭)와 병합 실행이 공유한다.
440
463
  */
441
464
  export function linkMinedToExplicit(mined, explicit) {
442
- mined.status = 'superseded';
443
- mined.clustered_into = explicit.rule_id;
444
- mined.related_to = [explicit.rule_id];
445
- saveRule(mined);
465
+ saveRule({
466
+ ...withStatusChange(mined, 'superseded', `linked-to ${explicit.rule_id}`, 'cluster'),
467
+ clustered_into: explicit.rule_id,
468
+ related_to: [explicit.rule_id],
469
+ });
446
470
  recordMinedObservation(explicit, minedObservationCount(mined), mined.rule_id);
447
471
  }
448
472
  /**
@@ -60,6 +60,17 @@ export declare function stripPolicyBoilerplate(text: string): string;
60
60
  * 양방향 평균으로 대칭화한다. confidence 인자는 1(순수 태그 매치만 보고 싶음).
61
61
  */
62
62
  export declare function policySimilarity(a: string, b: string): number;
63
+ /**
64
+ * R9 — "같은 개념" 판정. 유사도 임계 하나만으로는 뜻이 다른 룰을 묶었다
65
+ * (유사도 0.30 = 임계값인 쌍이 링크됨, "구조 파악 중단 금지" 가 병렬 진행 룰에 흡수돼 뜻이 사라짐).
66
+ * 두 조건을 모두 요구한다:
67
+ * 1. 유사도가 임계를 **초과**(경계값 제외)
68
+ * 2. (제거) 어조 극성 가드는 쓰지 않는다 — 실측에서 진짜 쌍("검증 필수 … 판단 금지", 0.38)과 뜻이 다른 쌍(0.34)을
69
+ * 유사도·극성으로 가를 수 없었다. 대신 병합 자체를 사용자 확인 뒤로 옮기고(runCorrectionClustering confirmed),
70
+ * 클러스터 내부 상반(T5)은 통합에서 제외한다.
71
+ * 3. 상투어 제거 후 공유 태그가 2개 이상 — 태그 1개 우연 일치로는 묶지 않는다
72
+ */
73
+ export declare function isSameConcept(a: string, b: string, tau?: number): boolean;
63
74
  /**
64
75
  * Laplace 계승법칙 (rule of succession, 1814).
65
76
  * s = 일관 교정 횟수, f = 모순(반박) 횟수. 지속 선호일 사후평균 = (s+1)/(s+f+2).