@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
@@ -77,6 +77,23 @@ export function policySimilarity(a, b) {
77
77
  const ba = calculateRelevance(tagsB, tagsA, 1);
78
78
  return (ab.relevance + ba.relevance) / 2;
79
79
  }
80
+ /**
81
+ * R9 — "같은 개념" 판정. 유사도 임계 하나만으로는 뜻이 다른 룰을 묶었다
82
+ * (유사도 0.30 = 임계값인 쌍이 링크됨, "구조 파악 중단 금지" 가 병렬 진행 룰에 흡수돼 뜻이 사라짐).
83
+ * 두 조건을 모두 요구한다:
84
+ * 1. 유사도가 임계를 **초과**(경계값 제외)
85
+ * 2. (제거) 어조 극성 가드는 쓰지 않는다 — 실측에서 진짜 쌍("검증 필수 … 판단 금지", 0.38)과 뜻이 다른 쌍(0.34)을
86
+ * 유사도·극성으로 가를 수 없었다. 대신 병합 자체를 사용자 확인 뒤로 옮기고(runCorrectionClustering confirmed),
87
+ * 클러스터 내부 상반(T5)은 통합에서 제외한다.
88
+ * 3. 상투어 제거 후 공유 태그가 2개 이상 — 태그 1개 우연 일치로는 묶지 않는다
89
+ */
90
+ export function isSameConcept(a, b, tau = CLUSTER_SIMILARITY_TAU) {
91
+ const tagsA = new Set(extractTags(stripPolicyBoilerplate(a)));
92
+ const tagsB = extractTags(stripPolicyBoilerplate(b));
93
+ if (tagsB.filter((t) => tagsA.has(t)).length < 2)
94
+ return false;
95
+ return policySimilarity(a, b) > tau;
96
+ }
80
97
  /**
81
98
  * Laplace 계승법칙 (rule of succession, 1814).
82
99
  * s = 일관 교정 횟수, f = 모순(반박) 횟수. 지속 선호일 사후평균 = (s+1)/(s+f+2).
@@ -130,7 +147,7 @@ export function clusterCorrectionRules(rules, suppressed = new Set()) {
130
147
  };
131
148
  for (let i = 0; i < group.length; i++) {
132
149
  for (let j = i + 1; j < group.length; j++) {
133
- if (policySimilarity(group[i].policy, group[j].policy) >= CLUSTER_SIMILARITY_TAU) {
150
+ if (isSameConcept(group[i].policy, group[j].policy, CLUSTER_SIMILARITY_TAU)) {
134
151
  union(i, j);
135
152
  }
136
153
  }
@@ -226,9 +243,9 @@ export function findMostSimilarRule(policy, candidates, tau = EXPLICIT_LINK_TAU)
226
243
  for (const c of candidates) {
227
244
  if ((c.policy?.length ?? 0) < MIN_POLICY_LEN)
228
245
  continue;
229
- const similarity = policySimilarity(policy, c.policy);
230
- if (similarity < tau)
246
+ if (!isSameConcept(policy, c.policy, tau))
231
247
  continue;
248
+ const similarity = policySimilarity(policy, c.policy);
232
249
  if (!best || similarity > best.similarity)
233
250
  best = { rule: c, similarity };
234
251
  }
@@ -7,7 +7,8 @@
7
7
  import * as path from 'node:path';
8
8
  import { loadAllRules, saveRule, syncRuleCounters } from '../../store/rule-store.js';
9
9
  import { STATE_DIR } from '../../core/paths.js';
10
- import { collectSignals, deriveRuleCounters, readViolationsWindow, ROTATED_KEEP_DAYS, isConfirmedBypass, isSyntheticEntry } from './signals.js';
10
+ import { enforceability } from '../rule-detectability.js';
11
+ import { collectSignals, deriveRuleCounters, passCountsByRule, readViolationsWindow, ROTATED_KEEP_DAYS, isConfirmedBypass, isSyntheticEntry } from './signals.js';
11
12
  import { detect as detectT2 } from './trigger-t2-violation.js';
12
13
  import { detect as detectT3 } from './trigger-t3-bypass.js';
13
14
  import { detect as detectT4 } from './trigger-t4-decay.js';
@@ -40,7 +41,7 @@ export async function handleLifecycleScan(args) {
40
41
  ...detectT5({ rules, ts: now }),
41
42
  ];
42
43
  const demotionCandidates = scanDriftForDemotion({ rules, drift, now });
43
- const promotionCandidates = scanSignalsForPromotion({ rules, signals, ts: now });
44
+ const promotionCandidates = scanSignalsForPromotion({ rules, signals, ts: now, passCounts: passCountsByRule() });
44
45
  console.log(`\n Lifecycle Scan — ${rules.length} rule(s) (${apply ? 'APPLY' : 'dry-run'})\n`);
45
46
  console.log(` Signals: violations.jsonl=${violations.length} (synthetic-session excluded ${syntheticExcluded}) bypass_confirmed=${bypassConfirmed} drift.jsonl=${drift.length}\n`);
46
47
  // 카운터 재계산 — 룰 JSON 의 violation_count/bypass_count 는 훅 경로가 갱신하지 않는 캐시라
@@ -60,7 +61,13 @@ export async function handleLifecycleScan(args) {
60
61
  return n;
61
62
  };
62
63
  if (events.length === 0 && demotionCandidates.length === 0 && promotionCandidates.length === 0) {
63
- console.log(' No lifecycle events. System stable.\n');
64
+ // "System stable" 은 오해 소지가 있었다: 위반을 볼 수 없는 자문 룰이 있으면 '이벤트 없음'은 '문제 없음'이 아니다.
65
+ const advisoryN = rules.filter((r) => r.status === 'active' && enforceability(r) === 'advisory').length;
66
+ console.log(` 이벤트 없음 (이 스캔이 본 신호 기준).`);
67
+ if (advisoryN > 0)
68
+ console.log(` ※ 활성 룰 ${advisoryN}개는 자문(위반 탐지 불가) — '위반 0'이 준수를 뜻하지 않으며 승급 근거로도 쓰지 않습니다.\n`);
69
+ else
70
+ console.log('');
64
71
  if (apply)
65
72
  console.log(` Counters synced: ${applyCounters()} rule(s).\n`);
66
73
  return;
@@ -50,6 +50,8 @@ export declare function promoteMech(from: EnforcementMech): EnforcementMech | nu
50
50
  export interface PromotionCandidate {
51
51
  rule_id: string;
52
52
  injects_rolling_n: number;
53
+ /** D12-C: 실제 평가돼 통과한 기록 수(checks.jsonl) — 위반 0 이 준수라는 유일한 근거. */
54
+ checks_pass_n: number;
53
55
  violations_rolling_n: number;
54
56
  current_mechs: EnforcementMech[];
55
57
  reason: string;
@@ -57,10 +59,17 @@ export interface PromotionCandidate {
57
59
  /**
58
60
  * rolling N 개 inject 중 violation 0 → Mech 승급 후보.
59
61
  * inject 추적 인프라가 완비되기 전에는 `rolling_min_injects` (기본 20) 미만이면 skip.
62
+ *
63
+ * D12-C: "위반 0" 은 탐지기가 있고 실제로 평가돼 통과한 기록이 있을 때만 준수의 근거다.
64
+ * - 탐지 불가(자문) 룰은 위반을 볼 수 없으므로 승급 대상이 아니다.
65
+ * - 탐지 가능 룰도 `passCounts`(checks.jsonl 의 통과 수)가 `min_pass_checks` 이상이어야 한다.
60
66
  */
61
67
  export declare function scanSignalsForPromotion(options: {
62
68
  rules: Rule[];
63
69
  rolling_min_injects?: number;
70
+ /** 룰별 평가 통과 수. 생략하면 증거 없음(0)으로 본다 → 승급 후보 없음. */
71
+ passCounts?: Map<string, number>;
72
+ min_pass_checks?: number;
64
73
  cooldownDays?: number;
65
74
  ts?: number;
66
75
  signals: Map<string, import('./types.js').RuleSignals>;
@@ -15,6 +15,7 @@
15
15
  * 이 경로는 별도 evidence source (solution-outcomes) 필요.
16
16
  * - 30 일 쿨다운.
17
17
  */
18
+ import { enforceability } from '../rule-detectability.js';
18
19
  import * as fs from 'node:fs';
19
20
  import * as path from 'node:path';
20
21
  import { initLifecycle } from '../../store/rule-lifecycle.js';
@@ -107,8 +108,13 @@ export function promoteMech(from) {
107
108
  /**
108
109
  * rolling N 개 inject 중 violation 0 → Mech 승급 후보.
109
110
  * inject 추적 인프라가 완비되기 전에는 `rolling_min_injects` (기본 20) 미만이면 skip.
111
+ *
112
+ * D12-C: "위반 0" 은 탐지기가 있고 실제로 평가돼 통과한 기록이 있을 때만 준수의 근거다.
113
+ * - 탐지 불가(자문) 룰은 위반을 볼 수 없으므로 승급 대상이 아니다.
114
+ * - 탐지 가능 룰도 `passCounts`(checks.jsonl 의 통과 수)가 `min_pass_checks` 이상이어야 한다.
110
115
  */
111
116
  export function scanSignalsForPromotion(options) {
117
+ const minPass = options.min_pass_checks ?? 10;
112
118
  const minInjects = options.rolling_min_injects ?? 20;
113
119
  const out = [];
114
120
  // R8-A1: promote 도 cooldown 적용. architect 예측대로 promote → demote → promote ping-pong 차단.
@@ -129,6 +135,11 @@ export function scanSignalsForPromotion(options) {
129
135
  continue;
130
136
  if (s.violations_rolling_n > 0)
131
137
  continue;
138
+ if (enforceability(rule) !== 'detectable')
139
+ continue; // 자문 룰: 위반을 볼 수 없으니 "위반 0" 은 증거가 아니다
140
+ const passN = options.passCounts?.get(rule.rule_id) ?? 0;
141
+ if (passN < minPass)
142
+ continue; // 평가돼 통과한 기록이 없으면 준수 근거 없음
132
143
  const mechs = (rule.enforce_via ?? []).map((spec) => spec.mech);
133
144
  const hasPromotable = mechs.some((m) => m === 'B' || m === 'C');
134
145
  if (!hasPromotable)
@@ -136,9 +147,10 @@ export function scanSignalsForPromotion(options) {
136
147
  out.push({
137
148
  rule_id: rule.rule_id,
138
149
  injects_rolling_n: s.injects_rolling_n,
150
+ checks_pass_n: passN,
139
151
  violations_rolling_n: s.violations_rolling_n,
140
152
  current_mechs: [...new Set(mechs)],
141
- reason: `rolling ${s.injects_rolling_n} injects, 0 violations — promotion candidate`,
153
+ reason: `${passN} evaluated passes, 0 violations (detectable rule) — promotion candidate`,
142
154
  });
143
155
  }
144
156
  return out;
@@ -176,8 +188,8 @@ export function applyPromotion(rule, candidate, now = Date.now()) {
176
188
  to_mech: spec.mech,
177
189
  reason: 'consistent_adherence',
178
190
  trigger_stats: {
179
- window_n: candidate.injects_rolling_n,
180
- adherence_rate: 1.0,
191
+ window_n: candidate.checks_pass_n,
192
+ adherence_rate: candidate.checks_pass_n / Math.max(1, candidate.checks_pass_n + candidate.violations_rolling_n),
181
193
  },
182
194
  })).filter((p) => p.from_mech !== p.to_mech);
183
195
  const updatedRule = {
@@ -23,6 +23,7 @@
23
23
  import * as fs from 'node:fs';
24
24
  import * as path from 'node:path';
25
25
  import { STATE_DIR } from '../../core/paths.js';
26
+ import { withStatusChange } from '../../store/rule-lifecycle.js';
26
27
  /**
27
28
  * R5-B1: rule 이 inactive 상태로 전이될 때 block-count 디렉터리의 잔여 파일 정리.
28
29
  * phantom stuck-loop (retired 된 rule 이 다시 GC 전까지 counter 에 반영되는 문제) 차단.
@@ -106,9 +107,9 @@ export function applyEvent(rule, event, now = Date.now()) {
106
107
  if (INACTIVE_STATUSES.has(nextStatusValue) && !INACTIVE_STATUSES.has(rule.status)) {
107
108
  sweepBlockCountsForRule(rule.rule_id);
108
109
  }
110
+ const refs = event.evidence?.refs?.length ? ` ${event.evidence.refs.join(',')}` : '';
109
111
  return {
110
- ...rule,
111
- status: nextStatusValue,
112
+ ...withStatusChange(rule, nextStatusValue, `${event.kind}${refs}`, 'lifecycle', new Date(now).toISOString()),
112
113
  lifecycle: updatedLifecycle,
113
114
  updated_at: new Date(now).toISOString(),
114
115
  };
@@ -34,7 +34,11 @@ export declare function rotateIfBig(p: string): void;
34
34
  */
35
35
  export declare const SYNTHETIC_SESSION_IDS: ReadonlySet<string>;
36
36
  export declare function isSyntheticSession(sessionId: unknown): boolean;
37
- /** FORGEN_SYNTHETIC=1 (eval/probe 러너가 설정) 이면 기록에 synthetic:true 를 붙인다. */
37
+ /**
38
+ * FORGEN_SYNTHETIC=1 (eval/probe 러너가 설정) 이면 기록에 synthetic:true 를 붙인다.
39
+ * FORGEN_NESTED_RUN=1 (추출·block-judge 등 forgen 이 띄운 중첩 실행)도 사용자 세션이 아니므로 같은 취급 —
40
+ * 중첩 실행 안에서 난 위반이 실사용자의 차단/우회 집계(precision 강등·T3·stats)를 오염시키지 않게 한다.
41
+ */
38
42
  export declare function syntheticStamp(): {
39
43
  synthetic?: true;
40
44
  };
@@ -84,6 +88,18 @@ export interface RulePrecision {
84
88
  /** correct/(correct+false_positive); 판정 0건이면 null. */
85
89
  precision: number | null;
86
90
  }
91
+ /**
92
+ * D12-C: 주제 게이트 도입 이전의 Stop 판정은 "무관한 룰이 무관한 완료 보고를 막은" 오탐이 섞여 있어 그 룰의 정밀도 근거가 아니다.
93
+ * `forgen rule restore-demoted --apply` 가 이 시각을 기록하고, precisionByRule 은 이 시각 이전의 stop-guard(store 룰) 차단을 세지 않는다.
94
+ */
95
+ export declare function readJudgeEpoch(): number;
96
+ export declare function writeJudgeEpoch(now?: number): void;
97
+ /**
98
+ * 룰별 정밀도 기준 시각. `rule restore-demoted --apply` 가 **복구한 룰에만** 기록한다 — 전역 epoch 는 다른 모든 룰의
99
+ * 정밀도 기록까지 지우므로 쓰지 않는다. 이 시각 이전의 그 룰 차단은 정밀도에 세지 않는다(복구 즉시 재강등 방지).
100
+ */
101
+ export declare function readRuleEpochs(): Record<string, number>;
102
+ export declare function writeRuleEpoch(ruleId: string, now?: number): void;
87
103
  /** 룰별 precision (실 차단만, 최근 N일). unsure 는 미판정으로 센다. */
88
104
  export declare function precisionByRule(violations: ViolationEntry[], verdicts: VerdictEntry[], days: number, now?: number): Map<string, RulePrecision>;
89
105
  /** D2: Stop 평가 결과 기록(통과 포함). violations.jsonl 과 분리. 7일 TTL 은 state-gc 가 담당. */
@@ -91,6 +107,8 @@ export declare const CHECKS_TTL_MS: number;
91
107
  export declare function recordCheck(entry: Omit<CheckEntry, 'at'>): void;
92
108
  export declare function pruneChecks(now?: number): void;
93
109
  export declare function readChecks(): CheckEntry[];
110
+ /** 룰별 "평가돼 통과한" 횟수 (checks.jsonl, 합성 제외). 준수 판정의 유일한 근거. */
111
+ export declare function passCountsByRule(checks?: CheckEntry[]): Map<string, number>;
94
112
  /** 정규식 매칭 프래그먼트 추출 — 영수증 `matched` 필드용. */
95
113
  export declare function matchedFragment(re: RegExp, text: string): string;
96
114
  export declare function recordBypass(entry: Omit<BypassEntry, 'at'>): void;
@@ -71,9 +71,13 @@ const UUID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/
71
71
  export function isSyntheticSession(sessionId) {
72
72
  return typeof sessionId !== 'string' || SYNTHETIC_SESSION_IDS.has(sessionId) || !UUID_RE.test(sessionId);
73
73
  }
74
- /** FORGEN_SYNTHETIC=1 (eval/probe 러너가 설정) 이면 기록에 synthetic:true 를 붙인다. */
74
+ /**
75
+ * FORGEN_SYNTHETIC=1 (eval/probe 러너가 설정) 이면 기록에 synthetic:true 를 붙인다.
76
+ * FORGEN_NESTED_RUN=1 (추출·block-judge 등 forgen 이 띄운 중첩 실행)도 사용자 세션이 아니므로 같은 취급 —
77
+ * 중첩 실행 안에서 난 위반이 실사용자의 차단/우회 집계(precision 강등·T3·stats)를 오염시키지 않게 한다.
78
+ */
75
79
  export function syntheticStamp() {
76
- return process.env.FORGEN_SYNTHETIC === '1' ? { synthetic: true } : {};
80
+ return process.env.FORGEN_SYNTHETIC === '1' || process.env.FORGEN_NESTED_RUN === '1' ? { synthetic: true } : {};
77
81
  }
78
82
  /** 엔트리 단위 합성 판정: 명시적 synthetic 플래그 또는 합성 세션 id. */
79
83
  export function isSyntheticEntry(e) {
@@ -189,17 +193,64 @@ export function effectiveVerdicts(verdicts = readVerdicts()) {
189
193
  }
190
194
  return m;
191
195
  }
196
+ const JUDGE_EPOCH_PATH = path.join(ENFORCEMENT_DIR, 'judge-epoch.json');
197
+ /**
198
+ * D12-C: 주제 게이트 도입 이전의 Stop 판정은 "무관한 룰이 무관한 완료 보고를 막은" 오탐이 섞여 있어 그 룰의 정밀도 근거가 아니다.
199
+ * `forgen rule restore-demoted --apply` 가 이 시각을 기록하고, precisionByRule 은 이 시각 이전의 stop-guard(store 룰) 차단을 세지 않는다.
200
+ */
201
+ export function readJudgeEpoch() {
202
+ try {
203
+ return Date.parse(JSON.parse(fs.readFileSync(JUDGE_EPOCH_PATH, 'utf-8')).at) || 0;
204
+ }
205
+ catch {
206
+ return 0;
207
+ }
208
+ }
209
+ export function writeJudgeEpoch(now = Date.now()) {
210
+ fs.mkdirSync(ENFORCEMENT_DIR, { recursive: true });
211
+ fs.writeFileSync(JUDGE_EPOCH_PATH, `${JSON.stringify({ at: new Date(now).toISOString(), reason: 'topic-gate: earlier stop-guard verdicts are not precision evidence' })}\n`);
212
+ }
213
+ const RULE_EPOCHS_PATH = path.join(ENFORCEMENT_DIR, 'rule-epochs.json');
214
+ /**
215
+ * 룰별 정밀도 기준 시각. `rule restore-demoted --apply` 가 **복구한 룰에만** 기록한다 — 전역 epoch 는 다른 모든 룰의
216
+ * 정밀도 기록까지 지우므로 쓰지 않는다. 이 시각 이전의 그 룰 차단은 정밀도에 세지 않는다(복구 즉시 재강등 방지).
217
+ */
218
+ export function readRuleEpochs() {
219
+ try {
220
+ const raw = JSON.parse(fs.readFileSync(RULE_EPOCHS_PATH, 'utf-8'));
221
+ return Object.fromEntries(Object.entries(raw).map(([k, v]) => [k, Date.parse(v) || 0]));
222
+ }
223
+ catch {
224
+ return {};
225
+ }
226
+ }
227
+ export function writeRuleEpoch(ruleId, now = Date.now()) {
228
+ fs.mkdirSync(ENFORCEMENT_DIR, { recursive: true });
229
+ let cur = {};
230
+ try {
231
+ cur = JSON.parse(fs.readFileSync(RULE_EPOCHS_PATH, 'utf-8'));
232
+ }
233
+ catch { /* none */ }
234
+ cur[ruleId] = new Date(now).toISOString();
235
+ fs.writeFileSync(RULE_EPOCHS_PATH, `${JSON.stringify(cur, null, 1)}\n`);
236
+ }
192
237
  /** 룰별 precision (실 차단만, 최근 N일). unsure 는 미판정으로 센다. */
193
238
  export function precisionByRule(violations, verdicts, days, now = Date.now()) {
194
239
  const cutoff = now - days * 24 * 3600 * 1000;
195
240
  const eff = effectiveVerdicts(verdicts);
196
241
  const out = new Map();
242
+ const epoch = readJudgeEpoch();
243
+ const ruleEpochs = readRuleEpochs();
197
244
  for (const v of violations) {
198
245
  if (!isRealBlock(v))
199
246
  continue;
200
247
  const t = Date.parse(v.at);
201
248
  if (!Number.isFinite(t) || t < cutoff)
202
249
  continue;
250
+ if (epoch && t < epoch && v.source === 'stop-guard' && !v.rule_id.startsWith('builtin:'))
251
+ continue;
252
+ if (t < (ruleEpochs[v.rule_id] ?? 0))
253
+ continue;
203
254
  const r = out.get(v.rule_id) ?? { rule_id: v.rule_id, correct: 0, false_positive: 0, unjudged: 0, precision: null };
204
255
  const verdict = v.violation_id ? eff.get(v.violation_id)?.verdict : undefined;
205
256
  if (verdict === 'correct')
@@ -239,6 +290,14 @@ export function pruneChecks(now = Date.now()) {
239
290
  export function readChecks() {
240
291
  return readJsonlWindow(CHECKS_PATH, CHECKS_TTL_MS / (24 * 3600 * 1000)).filter((c) => !isSyntheticEntry(c));
241
292
  }
293
+ /** 룰별 "평가돼 통과한" 횟수 (checks.jsonl, 합성 제외). 준수 판정의 유일한 근거. */
294
+ export function passCountsByRule(checks = readChecks()) {
295
+ const m = new Map();
296
+ for (const c of checks)
297
+ if (c.result === 'pass')
298
+ m.set(c.rule_id, (m.get(c.rule_id) ?? 0) + 1);
299
+ return m;
300
+ }
242
301
  /** 정규식 매칭 프래그먼트 추출 — 영수증 `matched` 필드용. */
243
302
  export function matchedFragment(re, text) {
244
303
  try {
@@ -3,7 +3,7 @@
3
3
  *
4
4
  * 입력: Evidence(type='explicit_correction') + rules[].
5
5
  * 로직:
6
- * 1. evidence.axis_refs 에 rule.category 매칭 OR evidence.summary 에 rule.render_key 토큰 포함 → rule 매칭
6
+ * 1. candidate_rule_refs 또는 raw_payload.target_rule_id 가 rule 을 지목 → rule 매칭. 그 외 전이 없음.
7
7
  * 2. correction kind 에 따라 suggested_action 결정:
8
8
  * - 'avoid-this' (이 rule 을 따르지 말아라) → retire
9
9
  * - 'fix-now' (이 rule 을 수정해야 한다) → flag (사용자 후속 편집 대기)
@@ -3,7 +3,7 @@
3
3
  *
4
4
  * 입력: Evidence(type='explicit_correction') + rules[].
5
5
  * 로직:
6
- * 1. evidence.axis_refs 에 rule.category 매칭 OR evidence.summary 에 rule.render_key 토큰 포함 → rule 매칭
6
+ * 1. candidate_rule_refs 또는 raw_payload.target_rule_id 가 rule 을 지목 → rule 매칭. 그 외 전이 없음.
7
7
  * 2. correction kind 에 따라 suggested_action 결정:
8
8
  * - 'avoid-this' (이 rule 을 따르지 말아라) → retire
9
9
  * - 'fix-now' (이 rule 을 수정해야 한다) → flag (사용자 후속 편집 대기)
@@ -11,36 +11,17 @@
11
11
  *
12
12
  * 출력: LifecycleEvent[]. 순수 — IO 없음.
13
13
  */
14
- const CATEGORY_AXIS_MAP = {
15
- quality: ['quality_safety', 'quality'],
16
- autonomy: ['autonomy'],
17
- communication: ['communication_style', 'communication'],
18
- workflow: ['workflow', 'judgment_philosophy'],
19
- safety: ['quality_safety', 'safety'],
20
- };
14
+ /**
15
+ * 교정이 이 룰을 **rule_id 로 명시 지목**했는가.
16
+ *
17
+ * 추측 매칭은 하지 않는다. 축 + 토큰 겹침은 실데이터 전이 9건 중 8건이 오탐이었고(드리블 교정의
18
+ * "사용자" 토큰으로 한국어 답변 룰이 retire), target 슬러그 일치는 같은 교정을 반복하면 그 교정으로
19
+ * 만든 룰을 스스로 폐기한다. 지목은 correction-record 의 rule_id 인자로만 한다.
20
+ */
21
21
  function matchesRule(evidence, rule) {
22
- // 가장 강한 신호: 사용자가 명시적으로 rule_id 지목.
23
22
  if (evidence.candidate_rule_refs.includes(rule.rule_id))
24
23
  return true;
25
- // 그 외: axis 일치만으로는 과매칭 (예: "typescript-any" correction 이 "early-return"
26
- // rule 까지 끌어오는 FP). axis AND 키워드 둘 다 요구.
27
- const axes = CATEGORY_AXIS_MAP[rule.category] ?? [];
28
- const axisMatch = axes.some((a) => evidence.axis_refs.includes(a));
29
- if (!axisMatch)
30
- return false;
31
- const keyTokens = rule.render_key
32
- .split(/[._-]/)
33
- .filter((t) => t.length >= 3);
34
- if (keyTokens.length === 0)
35
- return false;
36
- const summaryLower = evidence.summary.toLowerCase();
37
- const targetToken = (evidence.raw_payload?.target ?? '')
38
- .toString()
39
- .toLowerCase();
40
- return keyTokens.some((t) => {
41
- const tokLower = t.toLowerCase();
42
- return summaryLower.includes(tokLower) || (targetToken?.includes(tokLower));
43
- });
24
+ return evidence.raw_payload?.target_rule_id === rule.rule_id;
44
25
  }
45
26
  export function detect(input) {
46
27
  const { evidence, rules } = input;
@@ -8,6 +8,14 @@
8
8
  */
9
9
  import type { Rule } from '../../store/types.js';
10
10
  import type { LifecycleEvent } from './types.js';
11
+ /**
12
+ * R10: 이전 정규식 `\b(없|금지|마라…)\b` 는 한글에서 영원히 매칭되지 않았다 — JS 의 \b 는 ASCII 단어 경계라
13
+ * 한글 글자 사이/옆에는 경계가 없다. 한글 부정 표지는 경계 없이, 영문만 \b 를 쓴다.
14
+ * 한글: 금지, 마라/말라, 말 것, 하지 말, 하지 않, 않는다/않는, 안 된다/안된다, 불가, 못 한다/못한다.
15
+ */
16
+ export declare const NEGATION_RE: RegExp;
17
+ /** 정책 문장이 부정(금지/하지 마) 어조인가. 클러스터링의 극성 가드도 같은 판정을 쓴다. */
18
+ export declare function hasNegation(policy: string): boolean;
11
19
  export interface T5Input {
12
20
  rules: Rule[];
13
21
  min_shared_tokens?: number;
@@ -6,13 +6,66 @@
6
6
  *
7
7
  * auto-merge 안 함. conflict_refs 플래그만 설정 → 사용자 수동 해소.
8
8
  */
9
- const NEGATION_RE = /\b(없|금지|마라|말라|하지\s*않|don'?t|never|not\s+|no\s+|avoid)\b/i;
9
+ /**
10
+ * R10: 이전 정규식 `\b(없|금지|마라…)\b` 는 한글에서 영원히 매칭되지 않았다 — JS 의 \b 는 ASCII 단어 경계라
11
+ * 한글 글자 사이/옆에는 경계가 없다. 한글 부정 표지는 경계 없이, 영문만 \b 를 쓴다.
12
+ * 한글: 금지, 마라/말라, 말 것, 하지 말, 하지 않, 않는다/않는, 안 된다/안된다, 불가, 못 한다/못한다.
13
+ */
14
+ // 한글은 경계가 없어 부분 문자열 오탐이 생긴다: 마라톤/마라탕, 불가피/불가분, 단독 '않는'(지 않는 만 부정 표지).
15
+ export const NEGATION_RE = /(금지|마라(?!톤|탕|샹)|말라|말\s*것|말것|하지\s*말|지\s*않(?:는|도록)|하지\s*않|안\s*된다|안\s*됨|불가(?!피|분|침|결|사의|항력)|못\s*한다|하면\s*안)|\b(don'?t|do\s+not|never|not|avoid|must\s+not|forbidden|prohibited)\b/i;
16
+ /** 한글 어미·조사를 벗겨 어간만 남긴다: 실행하라/실행하지/실행해라 → 실행. 영문은 소문자 그대로. */
17
+ const HANGUL_SUFFIX_RE = /(하십시오|하세요|합니다|한다|하라|하지|하는|하게|하며|하고|하기|해라|해서|해야|할|함|하여|으로|에서|에게|까지|부터|처럼|보다|은|는|이|가|을|를|에|의|로|와|과|도|만)$/;
18
+ function stem(w) {
19
+ if (!/[가-힣]/.test(w))
20
+ return w;
21
+ let cur = w;
22
+ for (let i = 0; i < 2; i++) {
23
+ const next = cur.replace(HANGUL_SUFFIX_RE, '');
24
+ if (next.length < 2 || next === cur)
25
+ break;
26
+ cur = next;
27
+ }
28
+ return cur;
29
+ }
30
+ /** 모든 룰에 흔한 상투어는 공유 토큰 근거에서 제외 — 상반 판정이 우연한 겹침으로 나지 않게. */
31
+ const STOP_STEMS = new Set(['사용자', '작업', '진행', '필요', '반드시', '항상', '그리고', '때문', '경우', '대한', '위해', '있는', '없는', '것']);
32
+ /** 정책 문장이 부정(금지/하지 마) 어조인가. 클러스터링의 극성 가드도 같은 판정을 쓴다. */
33
+ export function hasNegation(policy) {
34
+ return NEGATION_RE.test(policy);
35
+ }
10
36
  function tokens(policy) {
11
37
  return new Set(policy
12
38
  .toLowerCase()
13
39
  .replace(/[.,;:!?()[\]{}"'`~]/g, ' ')
14
40
  .split(/\s+/)
15
- .filter((w) => w.length >= 3));
41
+ .map(stem)
42
+ // 한글 어간은 2음절부터 의미 단위(실행, 배포), 영문/숫자는 3자 이상
43
+ .filter((w) => (/[가-힣]/.test(w) ? w.length >= 2 : w.length >= 3) && !STOP_STEMS.has(w) && !NEGATION_RE.test(w)));
44
+ }
45
+ /**
46
+ * 부정 표지 근처(앞뒤 2어절)의 어간 = "무엇을 하지 말라는가". 한글은 동사가 앞에(실행하지 마라),
47
+ * 영문은 뒤에(don't deploy) 오므로 양쪽을 본다.
48
+ * 상반 판정은 이 집합이 반대편 룰 본문에 **긍정 어조로** 등장할 때만 한다 — 어간 2개 겹침만으로는
49
+ * "검증 필수 … 판단 금지" 같은 같은 원칙의 두 표현을 모순으로 오탐한다(한글 부정 탐지를 고친 뒤 실측).
50
+ */
51
+ function negatedActions(policy) {
52
+ // 아포스트로피는 유지한다("don't" 가 "don t" 로 쪼개지면 부정 표지를 잃는다).
53
+ const text = policy.toLowerCase().replace(/[.,;:!?()[\]{}"`~]/g, ' ').replace(/\s+/g, ' ').trim();
54
+ const words = text.split(' ').filter(Boolean);
55
+ const out = new Set();
56
+ const re = new RegExp(NEGATION_RE.source, 'gi');
57
+ for (const m of text.matchAll(re)) {
58
+ const wi = text.slice(0, m.index ?? 0).split(' ').length - 1;
59
+ const wEnd = wi + m[0].split(' ').length - 1;
60
+ for (let k = Math.max(0, wi - 2); k <= Math.min(words.length - 1, wEnd + 2); k++) {
61
+ const st = stem(words[k].replace(/'/g, ''));
62
+ if (NEGATION_RE.test(words[k]))
63
+ continue;
64
+ if ((/[가-힣]/.test(st) ? st.length >= 2 : st.length >= 3) && !STOP_STEMS.has(st) && !['말', '것'].includes(st))
65
+ out.add(st);
66
+ }
67
+ }
68
+ return out;
16
69
  }
17
70
  function sharedTokens(a, b, min) {
18
71
  let count = 0;
@@ -48,6 +101,11 @@ export function detect(input) {
48
101
  continue; // 같은 어조 — 충돌 아님
49
102
  if (!sharedTokens(aTokens, bTokens, minShared))
50
103
  continue;
104
+ // 부정된 동작이 반대편 룰의 (긍정) 본문에 실제로 나와야 상반이다.
105
+ const negated = negatedActions(aNeg ? a.policy : b.policy);
106
+ const otherTokens = aNeg ? bTokens : aTokens;
107
+ if (![...negated].some((t) => otherTokens.has(t)))
108
+ continue;
51
109
  const key = [a.rule_id, b.rule_id].sort().join('|');
52
110
  if (reported.has(key))
53
111
  continue;
@@ -39,7 +39,17 @@ export interface RoiThresholds {
39
39
  rateMax: number;
40
40
  }
41
41
  export declare const DEFAULT_ROI_THRESHOLDS: RoiThresholds;
42
+ /**
43
+ * ROI 격리 상태 파일. home 을 주면 `<home>/.forgen/state` (테스트·이관용), 안 주면 FORGEN_HOME 을 따른다.
44
+ * 예전에는 os.homedir() 고정이라 FORGEN_HOME 격리 환경에서도 실제 홈의 파일을 읽고 썼다 (D6).
45
+ */
42
46
  export declare function roiDemotionsPath(home?: string): string;
47
+ /**
48
+ * ROI 강등·격리 사용 여부. **기본 꺼짐** (D6): 판정 입력인 acted_on 이 신뢰할 수 없어(prompt-keyword 오탐 16건,
49
+ * 격리되면 주입이 안 돼 acted_on 이 영영 안 쌓이는 단방향 사멸) 격리가 사실상 영구 추방이었다.
50
+ * acted_on 이 신뢰할 만해지면 config.json 의 `roiDemotion.enabled: true` 로 켠다.
51
+ */
52
+ export declare function isRoiDemotionEnabled(): boolean;
43
53
  export declare function loadRoiDemotions(home?: string): RoiDemotions;
44
54
  export declare function saveRoiDemotions(demotions: RoiDemotions, home?: string): void;
45
55
  /**
@@ -76,4 +86,5 @@ export declare function applyRoiDemotions<T extends RoiAdjustable>(matches: T[],
76
86
  export declare function updateRoiDemotions(home?: string): {
77
87
  demoted: number;
78
88
  quarantined: number;
89
+ released?: number;
79
90
  } | null;
@@ -17,14 +17,35 @@
17
17
  * acted_on 신규 발생 → 즉시 해제
18
18
  */
19
19
  import * as fs from 'node:fs';
20
- import * as os from 'node:os';
21
20
  import * as path from 'node:path';
22
21
  import { queryHitRate } from '../core/observability-store.js';
22
+ import { FORGEN_HOME, STATE_DIR } from '../core/paths.js';
23
23
  export const DEFAULT_ROI_THRESHOLDS = { surfacedMin: 3, rateMax: 0.1 };
24
- export function roiDemotionsPath(home = os.homedir()) {
25
- return path.join(home, '.forgen', 'state', 'roi-demotions.json');
24
+ /**
25
+ * ROI 격리 상태 파일. home 을 주면 `<home>/.forgen/state` (테스트·이관용), 안 주면 FORGEN_HOME 을 따른다.
26
+ * 예전에는 os.homedir() 고정이라 FORGEN_HOME 격리 환경에서도 실제 홈의 파일을 읽고 썼다 (D6).
27
+ */
28
+ export function roiDemotionsPath(home) {
29
+ return home === undefined ? path.join(STATE_DIR, 'roi-demotions.json') : path.join(home, '.forgen', 'state', 'roi-demotions.json');
26
30
  }
27
- export function loadRoiDemotions(home = os.homedir()) {
31
+ /**
32
+ * ROI 강등·격리 사용 여부. **기본 꺼짐** (D6): 판정 입력인 acted_on 이 신뢰할 수 없어(prompt-keyword 오탐 16건,
33
+ * 격리되면 주입이 안 돼 acted_on 이 영영 안 쌓이는 단방향 사멸) 격리가 사실상 영구 추방이었다.
34
+ * acted_on 이 신뢰할 만해지면 config.json 의 `roiDemotion.enabled: true` 로 켠다.
35
+ */
36
+ export function isRoiDemotionEnabled() {
37
+ try {
38
+ const cfg = JSON.parse(fs.readFileSync(path.join(FORGEN_HOME, 'config.json'), 'utf-8'));
39
+ return cfg.roiDemotion?.enabled === true;
40
+ }
41
+ catch {
42
+ return false;
43
+ }
44
+ }
45
+ export function loadRoiDemotions(home) {
46
+ // 꺼져 있으면 기존 격리도 적용하지 않는다 (해제 경로 포함). 파일은 updateRoiDemotions 가 정리한다.
47
+ if (home === undefined && !isRoiDemotionEnabled())
48
+ return {};
28
49
  try {
29
50
  const parsed = JSON.parse(fs.readFileSync(roiDemotionsPath(home), 'utf-8'));
30
51
  return typeof parsed === 'object' && parsed !== null ? parsed : {};
@@ -33,7 +54,7 @@ export function loadRoiDemotions(home = os.homedir()) {
33
54
  return {};
34
55
  }
35
56
  }
36
- export function saveRoiDemotions(demotions, home = os.homedir()) {
57
+ export function saveRoiDemotions(demotions, home) {
37
58
  try {
38
59
  const p = roiDemotionsPath(home);
39
60
  fs.mkdirSync(path.dirname(p), { recursive: true });
@@ -78,9 +99,13 @@ export function evaluateRoiDemotions(rows, prev, thresholds = DEFAULT_ROI_THRESH
78
99
  const elapsed = existing
79
100
  ? new Date(nowIso).getTime() - new Date(existing.lastEvaluatedAt).getTime()
80
101
  : Number.POSITIVE_INFINITY;
81
- const advanceWindow = elapsed >= 24 * 60 * 60 * 1000;
102
+ // 새 증거(노출이 늘었는가) 없이 시간만 흘렀을 때는 올리지 않는다 — 노출이 3에 멈춘 솔루션이
103
+ // 하루마다 +1 되어 windowCount 8~10 으로 부풀던 버그 (D6, 실측).
104
+ const advanceWindow = elapsed >= 24 * 60 * 60 * 1000 && (!existing || surfaced > existing.surfaced);
82
105
  next[row.solutionId] = existing && !advanceWindow
83
- ? existing // 24h 미만 — 그대로 유지 (카운트/스냅샷 불변)
106
+ // 윈도는 올리지 않는다(새 증거 없음). 다만 acted 가 윈도 밖으로 빠져 줄었으면 스냅샷은 현재값으로 맞춘다 —
107
+ // 안 맞추면 저장된 actedOn 이 현재보다 커서 "acted 증가" 해제 조건이 영영 안 걸린다.
108
+ ? (acted < existing.actedOn ? { ...existing, actedOn: acted, surfaced } : existing)
84
109
  : {
85
110
  solutionId: row.solutionId,
86
111
  reason: 'low-roi',
@@ -138,8 +163,25 @@ export function applyRoiDemotions(matches, demotions) {
138
163
  * observability 이벤트 → 판정 → 저장. fail-open.
139
164
  * @returns 강등/격리 수 (로그용) 또는 null (판정 불가)
140
165
  */
141
- export function updateRoiDemotions(home = os.homedir()) {
166
+ export function updateRoiDemotions(home) {
142
167
  try {
168
+ if (home === undefined && !isRoiDemotionEnabled()) {
169
+ // 꺼진 상태: 새 판정을 하지 않고, 남아 있는 격리·강등은 백업을 남기고 해제한다.
170
+ const p = roiDemotionsPath();
171
+ let prevRaw = {};
172
+ try {
173
+ prevRaw = JSON.parse(fs.readFileSync(p, 'utf-8'));
174
+ }
175
+ catch {
176
+ return { demoted: 0, quarantined: 0 };
177
+ }
178
+ const n = Object.keys(prevRaw).length;
179
+ if (n === 0)
180
+ return { demoted: 0, quarantined: 0 };
181
+ fs.writeFileSync(p.replace(/\.json$/, '.released.json'), `${JSON.stringify(prevRaw, null, 2)}\n`);
182
+ saveRoiDemotions({});
183
+ return { demoted: 0, quarantined: 0, released: n };
184
+ }
143
185
  // observability-store 는 sqlite 미지원/DB 부재 시 내부 fail-open ([] 반환)
144
186
  const rows = queryHitRate();
145
187
  if (rows.length === 0)
@@ -0,0 +1,39 @@
1
+ /**
2
+ * 룰 탐지 가능성 (D12-C) — "이 룰이 위반을 실제로 알아낼 수 있는가".
3
+ *
4
+ * 문제(R5): 활성 룰 18개 중 8개는 `drift_key` 만 있어 아무것도 하지 않았고, "구현 먼저 금지" 같은 평문 지시는
5
+ * 코드가 위반을 판정할 수 없는데도 "위반 0" 을 근거로 B→A 승급됐다. `adherence_rate: 1` 은 준수의 증거가 아니라
6
+ * 탐지 불능의 결과였다. 위반 0 이 준수를 뜻하려면 (1) 탐지기가 있고 (2) 실제로 평가돼 통과한 기록이 있어야 한다.
7
+ *
8
+ * - detectable : 결정적 탐지기가 있다 — tool_arg_regex(패턴), artifact_check, tool_evidence, language_ratio,
9
+ * evidence_path 가 있는 self_check_prompt(증거 파일로 판정).
10
+ * - advisory : 그 외(자문). self_check_prompt 는 트리거되면 모델에게 되묻기만 할 뿐 위반 여부를 판정하지 못한다.
11
+ * drift_key 만 있는 spec, enforce_via 없음도 여기.
12
+ */
13
+ import type { Rule, EnforceSpec } from '../store/types.js';
14
+ export type Enforceability = 'detectable' | 'advisory';
15
+ /**
16
+ * 옛 분류기는 본문에 없는 증거 파일(e2e-result.json 등)을 게이트로 붙였다. 그런 게이트는 어떤 사용자에게든
17
+ * 모든 완료 보고를 막으므로 평가하지 않는다. 룰 파일을 고치는 마이그레이션 없이 모든 설치에 적용된다.
18
+ */
19
+ export declare function artifactGateIsStale(rule: Pick<Rule, 'policy' | 'trigger'>, spec: EnforceSpec): boolean;
20
+ export declare function enforceability(rule: Pick<Rule, 'enforce_via'>): Enforceability;
21
+ /**
22
+ * 의미 룰 차단 정책 (2026-11-05 오너 결정): 키워드로 발동하는 self_check 는 실데이터 정밀도가 약 0.10 이라
23
+ * 기본은 주입과 기록만 한다. 차단은 (1) 사용자가 `forgen rule enforce` 로 켠 룰(enforce_mode 'block'),
24
+ * (2) 결정적 탐지기가 있는 spec, (3) hard 룰(ADR-002: advise 로 내릴 수 없음)에만 적용한다.
25
+ * 명시 enforce_mode 가 항상 우선한다.
26
+ */
27
+ export declare function effectiveEnforceMode(rule: Pick<Rule, 'enforce_mode' | 'strength'>, spec: EnforceSpec): 'block' | 'advise';
28
+ /** 이 룰의 Stop spec 이 위반 시 실제로 차단하는가. Stop spec 이 없으면 false. */
29
+ export declare function stopBlocks(rule: Pick<Rule, 'enforce_mode' | 'strength' | 'enforce_via' | 'policy' | 'trigger'>): boolean;
30
+ /** 표시용: 위반 시 실제로 막는 룰인가. Stop 은 차단 정책을, 나머지 hook 은 결정적 탐지기와 advise 여부를 본다. */
31
+ export declare function ruleEnforced(rule: Pick<Rule, 'enforce_mode' | 'strength' | 'enforce_via' | 'policy' | 'trigger'>): boolean;
32
+ /** 표시용 한 단어. */
33
+ export declare function enforceabilityLabel(rule: Pick<Rule, 'enforce_via'>): '탐지' | '자문';
34
+ /**
35
+ * 주제 게이트는 "의미를 코드가 못 읽는" self_check 에만 적용한다 — 결정적 탐지기(언어 비율·도구 증거 등)는 그대로.
36
+ * communication 룰(답변 언어·형식·길이)은 모든 응답에 적용되는 문체 규칙이라 주제로 거르면 안 된다:
37
+ * "영어로 답하지 말 것" 은 영어 응답(= 위반)에서 룰 용어가 하나도 안 나온다.
38
+ */
39
+ export declare function topicGateApplies(kind: string, category?: string): boolean;