@wooojin/forgen 0.5.8 → 0.6.1

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 (79) hide show
  1. package/.claude-plugin/plugin.json +1 -1
  2. package/CHANGELOG.md +102 -0
  3. package/README.ja.md +12 -0
  4. package/README.ko.md +12 -0
  5. package/README.md +12 -0
  6. package/README.zh.md +12 -0
  7. package/dist/checks/_shared/model-profile.d.ts +1 -1
  8. package/dist/checks/_shared/model-profile.js +9 -5
  9. package/dist/cli.js +32 -3
  10. package/dist/core/auto-compound-runner.js +20 -43
  11. package/dist/core/block-cli.d.ts +1 -0
  12. package/dist/core/block-cli.js +41 -0
  13. package/dist/core/explain-cli.js +29 -1
  14. package/dist/core/inspect-cli.js +9 -8
  15. package/dist/core/rate-limit-forecast.d.ts +113 -0
  16. package/dist/core/rate-limit-forecast.js +236 -0
  17. package/dist/core/state-gc.js +3 -0
  18. package/dist/core/stats-cli.d.ts +15 -0
  19. package/dist/core/stats-cli.js +50 -16
  20. package/dist/core/status-cli.d.ts +18 -1
  21. package/dist/core/status-cli.js +51 -2
  22. package/dist/core/statusline-cli.d.ts +58 -13
  23. package/dist/core/statusline-cli.js +164 -201
  24. package/dist/core/uninstall.js +10 -1
  25. package/dist/core/v1-bootstrap.js +7 -1
  26. package/dist/engine/block-judge-cli.d.ts +2 -0
  27. package/dist/engine/block-judge-cli.js +11 -0
  28. package/dist/engine/block-judge.d.ts +68 -0
  29. package/dist/engine/block-judge.js +248 -0
  30. package/dist/engine/correction-cluster-runner.d.ts +67 -0
  31. package/dist/engine/correction-cluster-runner.js +242 -5
  32. package/dist/engine/correction-clustering.d.ts +15 -0
  33. package/dist/engine/correction-clustering.js +24 -0
  34. package/dist/engine/lifecycle/lifecycle-cli.js +7 -4
  35. package/dist/engine/lifecycle/signals.d.ts +59 -2
  36. package/dist/engine/lifecycle/signals.js +193 -4
  37. package/dist/engine/lifecycle/trigger-t3-bypass.d.ts +5 -3
  38. package/dist/engine/lifecycle/trigger-t3-bypass.js +6 -4
  39. package/dist/engine/lifecycle/types.d.ts +29 -1
  40. package/dist/engine/mined-rule-merge-cli.d.ts +11 -0
  41. package/dist/engine/mined-rule-merge-cli.js +67 -0
  42. package/dist/engine/rule-relevance.d.ts +72 -0
  43. package/dist/engine/rule-relevance.js +183 -0
  44. package/dist/engine/rule-toggle-cli.d.ts +5 -0
  45. package/dist/engine/rule-toggle-cli.js +30 -0
  46. package/dist/fgx.js +1 -1
  47. package/dist/forge/evidence-processor.js +2 -0
  48. package/dist/hooks/post-tool-use.js +9 -14
  49. package/dist/hooks/pre-tool-use.js +71 -8
  50. package/dist/hooks/shared/command-parser.d.ts +11 -0
  51. package/dist/hooks/shared/command-parser.js +120 -0
  52. package/dist/hooks/solution-injector.js +13 -0
  53. package/dist/hooks/stop-guard.d.ts +18 -0
  54. package/dist/hooks/stop-guard.js +55 -10
  55. package/dist/host/install-claude.js +7 -33
  56. package/dist/host/install-codex.d.ts +23 -1
  57. package/dist/host/install-codex.js +128 -49
  58. package/dist/host/install-opencode.d.ts +5 -0
  59. package/dist/host/install-opencode.js +9 -6
  60. package/dist/host/managed-marker.d.ts +22 -0
  61. package/dist/host/managed-marker.js +79 -0
  62. package/dist/host/uninstall-codex.d.ts +2 -0
  63. package/dist/host/uninstall-codex.js +12 -9
  64. package/dist/host/uninstall-opencode.d.ts +36 -0
  65. package/dist/host/uninstall-opencode.js +141 -0
  66. package/dist/mcp/tools.js +7 -1
  67. package/dist/renderer/inspect-renderer.js +23 -6
  68. package/dist/renderer/rule-renderer.js +4 -2
  69. package/dist/store/evidence-store.js +37 -2
  70. package/dist/store/profile-score.d.ts +55 -0
  71. package/dist/store/profile-score.js +100 -0
  72. package/dist/store/profile-store.d.ts +22 -5
  73. package/dist/store/profile-store.js +42 -6
  74. package/dist/store/rule-origin.d.ts +39 -0
  75. package/dist/store/rule-origin.js +84 -0
  76. package/dist/store/types.d.ts +24 -0
  77. package/package.json +1 -1
  78. package/plugin.json +1 -1
  79. package/scripts/postinstall.js +76 -42
@@ -19,7 +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 { clusterCorrectionRules, clusterKey, } from './correction-clustering.js';
22
+ import { clusterCorrectionRules, clusterKey, findMostSimilarRule, isSuppressedCluster, } from './correction-clustering.js';
23
23
  const log = createLogger('correction-cluster');
24
24
  const SUPPRESSION_PATH = path.join(STATE_DIR, 'cluster-suppression.json');
25
25
  /** 동시 세션종료 클러스터링 직렬화용 락 대상 경로(SEV-3 #4). */
@@ -163,6 +163,10 @@ async function runCorrectionClusteringLocked() {
163
163
  /**
164
164
  * 통합 취소: 통합 rule 을 removed 처리하고 원본 룰을 active 복원, 조합을 억제목록에 추가.
165
165
  * 억제로 인해 다음 세션종료에 같은 조합이 재통합되지 않는다.
166
+ *
167
+ * ADR-017 D3: 대상이 *explicit 링크 타깃*(채굴 룰이 `clustered_into` 로 가리키는 explicit
168
+ * 룰 — 통합 산물이 아님)이면 explicit 룰은 removed 하지 않고 링크만 푼다(related_to 제거,
169
+ * mined_observations 차감). 채굴끼리 통합한 `auto:…cluster…` 룰은 기존 경로대로 removed.
166
170
  */
167
171
  export function unmergeCluster(mergedRuleId) {
168
172
  const merged = loadRule(mergedRuleId);
@@ -176,13 +180,246 @@ export function unmergeCluster(mergedRuleId) {
176
180
  for (const orig of members) {
177
181
  orig.status = 'active';
178
182
  orig.clustered_into = undefined;
183
+ orig.related_to = undefined;
179
184
  saveRule(orig);
180
185
  }
181
- merged.status = 'removed';
182
- saveRule(merged);
183
- // 이 조합을 억제목록에 추가 → 재통합 방지.
186
+ const linkedMined = members.filter((r) => isMinedRule(r));
187
+ // 링크 타깃 판정: 통합 산물이 아니면서(=explicit 소스) 채굴 멤버만 달려 있는 explicit 룰.
188
+ const isLinkTarget = !isMinedRule(merged) && linkedMined.length === members.length;
189
+ if (isLinkTarget) {
190
+ detachMinedLinks(merged, linkedMined);
191
+ }
192
+ else {
193
+ // 통합 산물이 explicit 클러스터 룰이고 채굴 링크도 달려 있던 혼합 케이스: 채굴 링크는
194
+ // 위에서 이미 복원됐으므로 카운터만 정리하고 통합 룰은 기존대로 removed.
195
+ if (linkedMined.length > 0)
196
+ detachMinedLinks(merged, linkedMined);
197
+ merged.status = 'removed';
198
+ saveRule(merged);
199
+ }
200
+ // 이 조합을 억제목록에 추가 → 재통합/재링크 방지. 링크는 (채굴, explicit) 쌍 단위로 억제해
201
+ // 다른 채굴 룰의 링크나 채굴끼리 통합에는 영향을 주지 않는다(isSuppressedCluster 의
202
+ // 부분집합 판정은 2원소 쌍과 다른 조합 사이에 교차하지 않음).
184
203
  const suppressed = loadSuppression();
185
- suppressed.add(clusterKey(members));
204
+ if (isLinkTarget) {
205
+ for (const m of linkedMined)
206
+ suppressed.add(clusterKey([m, merged]));
207
+ }
208
+ else {
209
+ suppressed.add(clusterKey(members));
210
+ }
186
211
  saveSuppression(suppressed);
187
212
  return { ok: true, restored: members.map((r) => r.rule_id) };
188
213
  }
214
+ function detachMinedLinks(explicitRule, mined) {
215
+ const ids = new Set(mined.map((m) => m.rule_id));
216
+ const related = (explicitRule.related_to ?? []).filter((id) => !ids.has(id));
217
+ explicitRule.related_to = related.length > 0 ? related : undefined;
218
+ const decrement = mined.reduce((n, m) => n + minedObservationCount(m), 0);
219
+ const next = Math.max(0, (explicitRule.mined_observations ?? 0) - decrement);
220
+ explicitRule.mined_observations = next > 0 ? next : undefined;
221
+ saveRule(explicitRule);
222
+ }
223
+ // ─────────────────────────────────────────────────────────────────────────────
224
+ // ADR-017 D3 — 채굴 룰 병합 (채굴끼리만 · explicit 과는 링크만)
225
+ //
226
+ // 불변식(ADR-013, D3 원문):
227
+ // - explicit 룰로의 흡수 금지. 채굴 evidence 는 explicit 의 evidence_refs 에 합산하지 않고
228
+ // strength 도 건드리지 않는다 — `mined_observations` 카운터만 올린다.
229
+ // - 채굴끼리 통합 룰은 strength 'default' 고정, source 'behavior_inference', render_key
230
+ // 'auto:' 네임스페이스 유지, enforce_via [] (advisory-only).
231
+ // - 통합 룰의 created_at 은 가장 오래된 원본(TTL carry-forward, 재채굴로 TTL 연장 금지).
232
+ // - 원본은 superseded + clustered_into 로 보존 → unmergeCluster 로 왕복.
233
+ // ─────────────────────────────────────────────────────────────────────────────
234
+ const AUTO_MINED_PREFIX = 'auto:';
235
+ function isMinedRule(r) {
236
+ return r.source === 'behavior_inference' && r.render_key.startsWith(AUTO_MINED_PREFIX);
237
+ }
238
+ /** 채굴 룰 1개가 대표하는 관측 횟수 — evidence 수(최소 1). */
239
+ function minedObservationCount(r) {
240
+ return Math.max(1, r.evidence_refs?.length ?? 0);
241
+ }
242
+ /**
243
+ * 병합 계획(읽기 전용). 순서: (1) explicit 동개념 링크 → (2) 남은 채굴 룰끼리 클러스터.
244
+ * explicit 매칭은 1:1 최고점(category 무시), 채굴끼리는 기존 clusterCorrectionRules
245
+ * (category 경계 유지 — 전이 연결이 category 를 넘으면 무관한 개념까지 한 덩어리가 된다는
246
+ * 실측에 근거).
247
+ */
248
+ export function planMinedRuleMerge() {
249
+ const all = loadAllRules();
250
+ const activeMe = all.filter((r) => r.scope === 'me' && r.status === 'active');
251
+ const mined = activeMe.filter(isMinedRule);
252
+ const explicit = activeMe.filter((r) => !isMinedRule(r) && r.source !== 'behavior_inference');
253
+ const suppressed = loadSuppression();
254
+ const explicitLinks = [];
255
+ const linkedIds = new Set();
256
+ for (const m of mined) {
257
+ // 이미 통합된 채굴 클러스터 룰은 explicit 에 링크하지 않는다 — 멤버가 딸려 있어
258
+ // 링크 unmerge 가 멤버 복원까지 번진다. 원본 단위로만 링크.
259
+ if (isClusterMergedRule(m))
260
+ continue;
261
+ const eligible = explicit.filter((e) => !isSuppressedCluster([m, e], suppressed));
262
+ const best = findMostSimilarRule(m.policy, eligible);
263
+ if (!best)
264
+ continue;
265
+ explicitLinks.push({
266
+ minedRuleId: m.rule_id,
267
+ minedPolicy: m.policy,
268
+ explicitRuleId: best.rule.rule_id,
269
+ explicitPolicy: best.rule.policy,
270
+ similarity: best.similarity,
271
+ observations: minedObservationCount(m),
272
+ });
273
+ linkedIds.add(m.rule_id);
274
+ }
275
+ const remaining = mined.filter((r) => !linkedIds.has(r.rule_id));
276
+ const clusters = [];
277
+ for (const cluster of clusterCorrectionRules(remaining.map(toClusterable), suppressed)) {
278
+ const memberRules = cluster.members
279
+ .map((m) => remaining.find((r) => r.rule_id === m.rule_id))
280
+ .filter((r) => Boolean(r));
281
+ if (memberRules.length < 2)
282
+ continue;
283
+ const absorber = memberRules.find(isClusterMergedRule);
284
+ const fresh = absorber ? memberRules.filter((r) => r.rule_id !== absorber.rule_id) : memberRules;
285
+ if (fresh.length === 0)
286
+ continue;
287
+ clusters.push({
288
+ category: memberRules[0].category,
289
+ memberIds: fresh.map((r) => r.rule_id),
290
+ memberPolicies: fresh.map((r) => r.policy),
291
+ representativePolicy: cluster.representativePolicy,
292
+ oldestCreatedAt: memberRules
293
+ .map((r) => r.created_at)
294
+ .reduce((a, b) => (Date.parse(b) < Date.parse(a) ? b : a)),
295
+ absorberId: absorber?.rule_id,
296
+ });
297
+ }
298
+ const superseded = clusters.reduce((n, c) => n + c.memberIds.length, 0);
299
+ const newMerged = clusters.filter((c) => !c.absorberId).length;
300
+ return {
301
+ totalMined: mined.length,
302
+ explicitLinks,
303
+ clusters,
304
+ projectedMined: mined.length - explicitLinks.length - superseded + newMerged,
305
+ };
306
+ }
307
+ /**
308
+ * 채굴 룰 병합 실행. apply=false 면 계획만 반환(파일 변경 없음).
309
+ * apply=true 면 클러스터 락 안에서 계획을 *다시* 수립해 적용한다(dry-run 과 apply 사이의
310
+ * 상태 변화로 stale 계획이 적용되는 것을 막는다).
311
+ */
312
+ export async function runMinedRuleMerge(opts) {
313
+ if (!opts.apply)
314
+ return { plan: planMinedRuleMerge(), applied: null };
315
+ fs.mkdirSync(STATE_DIR, { recursive: true });
316
+ return withFileLock(CLUSTER_LOCK_PATH, async () => {
317
+ const plan = planMinedRuleMerge();
318
+ const applied = await applyMinedRuleMergePlan(plan);
319
+ return { plan, applied };
320
+ });
321
+ }
322
+ async function applyMinedRuleMergePlan(plan) {
323
+ const result = { linked: 0, mergedRuleIds: [], supersededIds: [] };
324
+ // (1) explicit 링크 — 채굴 룰은 superseded+clustered_into(explicit), explicit 은 카운터만.
325
+ for (const link of plan.explicitLinks) {
326
+ const mined = loadRule(link.minedRuleId);
327
+ const explicit = loadRule(link.explicitRuleId);
328
+ if (!mined || !explicit || mined.status !== 'active' || explicit.status !== 'active')
329
+ continue;
330
+ linkMinedToExplicit(mined, explicit);
331
+ result.linked++;
332
+ result.supersededIds.push(mined.rule_id);
333
+ }
334
+ // (2) 채굴끼리 통합.
335
+ const { detect: detectT5 } = await import('./lifecycle/trigger-t5-conflict.js');
336
+ for (const cluster of plan.clusters) {
337
+ const fresh = cluster.memberIds
338
+ .map((id) => loadRule(id))
339
+ .filter((r) => Boolean(r) && r?.status === 'active');
340
+ if (fresh.length === 0)
341
+ continue;
342
+ const absorber = cluster.absorberId ? loadRule(cluster.absorberId) : null;
343
+ if (!absorber && fresh.length < 2)
344
+ continue;
345
+ // 상반 교정이 한 클러스터에 있으면 통합하지 않는다(explicit 경로와 동일).
346
+ const conflicts = detectT5({ rules: absorber ? [absorber, ...fresh] : fresh });
347
+ if (conflicts.length > 0) {
348
+ log.debug(`채굴 클러스터 통합 스킵(T5 모순): ${clusterKey(fresh)}`);
349
+ continue;
350
+ }
351
+ const evidenceRefs = Array.from(new Set([...(absorber?.evidence_refs ?? []), ...fresh.flatMap((r) => r.evidence_refs ?? [])]));
352
+ const oldestCreatedAt = [absorber, ...fresh]
353
+ .filter((r) => Boolean(r))
354
+ .map((r) => r.created_at)
355
+ .reduce((a, b) => (Date.parse(b) < Date.parse(a) ? b : a));
356
+ let mergedId;
357
+ if (absorber) {
358
+ absorber.status = 'active';
359
+ absorber.clustered_into = undefined;
360
+ absorber.policy = cluster.representativePolicy;
361
+ absorber.strength = 'default';
362
+ absorber.evidence_refs = evidenceRefs;
363
+ absorber.created_at = oldestCreatedAt;
364
+ absorber.enforce_via = [];
365
+ saveRule(absorber);
366
+ mergedId = absorber.rule_id;
367
+ }
368
+ else {
369
+ const merged = createRule({
370
+ category: fresh[0].category,
371
+ scope: 'me',
372
+ trigger: fresh[0].trigger,
373
+ policy: cluster.representativePolicy,
374
+ strength: 'default',
375
+ source: 'behavior_inference',
376
+ evidence_refs: evidenceRefs,
377
+ render_key: `${AUTO_MINED_PREFIX}${mergedRenderKey({
378
+ members: fresh.map(toClusterable),
379
+ representativePolicy: cluster.representativePolicy,
380
+ confidence: 0,
381
+ strength: 'default',
382
+ evidenceRefs,
383
+ })}`,
384
+ });
385
+ merged.created_at = oldestCreatedAt; // TTL carry-forward — 통합으로 수명 연장 금지
386
+ merged.enforce_via = []; // advisory-only 유지
387
+ saveRule(merged);
388
+ mergedId = merged.rule_id;
389
+ result.mergedRuleIds.push(mergedId);
390
+ }
391
+ for (const orig of fresh) {
392
+ orig.status = 'superseded';
393
+ orig.clustered_into = mergedId;
394
+ saveRule(orig);
395
+ result.supersededIds.push(orig.rule_id);
396
+ }
397
+ log.debug(`채굴 클러스터 통합: +${fresh.length}룰 → ${mergedId}`);
398
+ }
399
+ return result;
400
+ }
401
+ /**
402
+ * 채굴 룰 ↔ explicit 룰 링크(흡수 아님). evidence_refs/strength 는 양쪽 모두 불변.
403
+ * promoteSessionCandidates 의 사전 중복 검사(explicit 매칭)와 병합 실행이 공유한다.
404
+ */
405
+ export function linkMinedToExplicit(mined, explicit) {
406
+ mined.status = 'superseded';
407
+ mined.clustered_into = explicit.rule_id;
408
+ mined.related_to = [explicit.rule_id];
409
+ saveRule(mined);
410
+ recordMinedObservation(explicit, minedObservationCount(mined), mined.rule_id);
411
+ }
412
+ /**
413
+ * explicit 룰에 "채굴 관측 N회" 를 기록한다. evidence_refs 에는 절대 합산하지 않는다 —
414
+ * 합산하면 laplaceConfidence 경로로 환각 교정 1건이 explicit 을 strong 으로 올릴 수 있다
415
+ * (ADR-017 D3 기각 사유). strength 도 건드리지 않는다.
416
+ */
417
+ export function recordMinedObservation(explicit, count, minedRuleId) {
418
+ explicit.mined_observations = (explicit.mined_observations ?? 0) + count;
419
+ if (minedRuleId) {
420
+ const related = new Set(explicit.related_to ?? []);
421
+ related.add(minedRuleId);
422
+ explicit.related_to = [...related];
423
+ }
424
+ saveRule(explicit);
425
+ }
@@ -66,6 +66,21 @@ export declare function strengthForConfidence(confidence: number): RuleStrength;
66
66
  * @param suppressed 억제 조합 키 집합(unmerge 된 조합 재통합 방지) — 정렬된 rule_id join
67
67
  */
68
68
  export declare function clusterCorrectionRules(rules: ClusterableRule[], suppressed?: ReadonlySet<string>): CorrectionCluster[];
69
+ /**
70
+ * ADR-017 D3 — 단일 정책 텍스트에 가장 유사한 룰 1개(유사도 ≥ τ)를 찾는다.
71
+ * 채굴 룰 생성 시 사전 중복 검사와 explicit 링크 판정에 쓰인다.
72
+ *
73
+ * category 를 보지 않는 이유: 채굴 룰의 category 는 axis_hint 에서 파생되어 같은 개념이
74
+ * quality/autonomy/workflow 로 흩어진다(실측: 2026-10-02 채굴 30개). 1:1 최고점 매칭은
75
+ * union-find 와 달리 전이적으로 번지지 않으므로 category 경계를 넘어도 안전하다
76
+ * (반면 clusterCorrectionRules 는 전이 연결 때문에 category 경계를 유지한다).
77
+ */
78
+ export declare function findMostSimilarRule<T extends {
79
+ policy: string;
80
+ }>(policy: string, candidates: readonly T[], tau?: number): {
81
+ rule: T;
82
+ similarity: number;
83
+ } | null;
69
84
  /** 클러스터 멤버 집합의 안정 키(정렬된 rule_id join) — 억제 목록/식별용. */
70
85
  export declare function clusterKey(members: Array<{
71
86
  rule_id: string;
@@ -134,6 +134,30 @@ export function clusterCorrectionRules(rules, suppressed = new Set()) {
134
134
  }
135
135
  return clusters;
136
136
  }
137
+ /**
138
+ * ADR-017 D3 — 단일 정책 텍스트에 가장 유사한 룰 1개(유사도 ≥ τ)를 찾는다.
139
+ * 채굴 룰 생성 시 사전 중복 검사와 explicit 링크 판정에 쓰인다.
140
+ *
141
+ * category 를 보지 않는 이유: 채굴 룰의 category 는 axis_hint 에서 파생되어 같은 개념이
142
+ * quality/autonomy/workflow 로 흩어진다(실측: 2026-10-02 채굴 30개). 1:1 최고점 매칭은
143
+ * union-find 와 달리 전이적으로 번지지 않으므로 category 경계를 넘어도 안전하다
144
+ * (반면 clusterCorrectionRules 는 전이 연결 때문에 category 경계를 유지한다).
145
+ */
146
+ export function findMostSimilarRule(policy, candidates, tau = CLUSTER_SIMILARITY_TAU) {
147
+ if ((policy?.length ?? 0) < MIN_POLICY_LEN)
148
+ return null;
149
+ let best = null;
150
+ for (const c of candidates) {
151
+ if ((c.policy?.length ?? 0) < MIN_POLICY_LEN)
152
+ continue;
153
+ const similarity = policySimilarity(policy, c.policy);
154
+ if (similarity < tau)
155
+ continue;
156
+ if (!best || similarity > best.similarity)
157
+ best = { rule: c, similarity };
158
+ }
159
+ return best;
160
+ }
137
161
  /** 클러스터 멤버 집합의 안정 키(정렬된 rule_id join) — 억제 목록/식별용. */
138
162
  export function clusterKey(members) {
139
163
  return members
@@ -7,7 +7,7 @@
7
7
  import * as path from 'node:path';
8
8
  import { loadAllRules, saveRule } from '../../store/rule-store.js';
9
9
  import { STATE_DIR } from '../../core/paths.js';
10
- import { collectSignals, readJsonlSafe } from './signals.js';
10
+ import { collectSignals, readJsonlSafe, isConfirmedBypass, isSyntheticSession } from './signals.js';
11
11
  import { detect as detectT2 } from './trigger-t2-violation.js';
12
12
  import { detect as detectT3 } from './trigger-t3-bypass.js';
13
13
  import { detect as detectT4 } from './trigger-t4-decay.js';
@@ -24,11 +24,14 @@ export async function handleLifecycleScan(args) {
24
24
  return;
25
25
  }
26
26
  const violations = readJsonlSafe(path.join(STATE_DIR, 'enforcement', 'violations.jsonl'));
27
- const bypass = readJsonlSafe(path.join(STATE_DIR, 'enforcement', 'bypass.jsonl'));
27
+ // ADR-017 D1: bypass.jsonl(자연어 휴리스틱, 전량 오탐)은 더 이상 읽지 않는다. T3 입력은
28
+ // violations 의 kind:'bypass_confirmed'(사용자 명시 우회) 뿐이며 collectSignals 가 거기서 뽑는다.
29
+ const bypassConfirmed = violations.filter(isConfirmedBypass).length;
30
+ const syntheticExcluded = violations.filter((v) => isSyntheticSession(v.session_id)).length;
28
31
  const drift = readDriftEntries();
29
32
  const signals = new Map();
30
33
  for (const r of rules)
31
- signals.set(r.rule_id, collectSignals(r, { violations, bypass, now }));
34
+ signals.set(r.rule_id, collectSignals(r, { violations, now }));
32
35
  const events = [
33
36
  ...detectT2({ rules, signals, ts: now }),
34
37
  ...detectT3({ rules, signals, ts: now }),
@@ -38,7 +41,7 @@ export async function handleLifecycleScan(args) {
38
41
  const demotionCandidates = scanDriftForDemotion({ rules, drift, now });
39
42
  const promotionCandidates = scanSignalsForPromotion({ rules, signals, ts: now });
40
43
  console.log(`\n Lifecycle Scan — ${rules.length} rule(s) (${apply ? 'APPLY' : 'dry-run'})\n`);
41
- console.log(` Signals: violations.jsonl=${violations.length} bypass.jsonl=${bypass.length} drift.jsonl=${drift.length}\n`);
44
+ console.log(` Signals: violations.jsonl=${violations.length} (synthetic-session excluded ${syntheticExcluded}) bypass_confirmed=${bypassConfirmed} drift.jsonl=${drift.length}\n`);
42
45
  if (events.length === 0 && demotionCandidates.length === 0 && promotionCandidates.length === 0) {
43
46
  console.log(' No lifecycle events. System stable.\n');
44
47
  return;
@@ -9,7 +9,13 @@
9
9
  * 모든 IO 는 이 파일에 한정. 트리거들은 pure — collectSignals() 결과를 받아 detect().
10
10
  */
11
11
  import type { Rule } from '../../store/types.js';
12
- import type { RuleSignals, ViolationEntry, BypassEntry } from './types.js';
12
+ /**
13
+ * 영수증·로그용 추가 마스킹 (critic D1 SEV-2): secret-filter 의 공개 키 패턴만으로는 `DB_PASS=…`, mysql -p<값>,
14
+ * sshpass -p, Basic/X-API-Key 헤더, URL userinfo, 무접두 JWT, PEM 본문이 평문으로 남아 Haiku 로 egress 된다.
15
+ * 과잉 마스킹은 영수증 가독성만 깎지만 누락은 유출이므로 넓게 잡는다.
16
+ */
17
+ export declare function redactForReceipt(text: string): string;
18
+ import type { RuleSignals, ViolationEntry, BypassEntry, VerdictEntry, CheckEntry } from './types.js';
13
19
  /**
14
20
  * Best-effort size-based rotation. When `p` exceeds 10MB, renames to
15
21
  * `<p>.<timestamp>` so the next write starts fresh. Missing file or rename
@@ -19,7 +25,58 @@ import type { RuleSignals, ViolationEntry, BypassEntry } from './types.js';
19
25
  */
20
26
  export declare function rotateIfBig(p: string): void;
21
27
  export declare function readJsonlSafe<T>(p: string): T[];
22
- export declare function recordViolation(entry: Omit<ViolationEntry, 'at'>): void;
28
+ /**
29
+ * ADR-017 §2 원칙 2: 훅이 session_id 없이 호출되면 'default'/'unknown' 폴백이 기록된다.
30
+ * 실세션(Claude·Codex 모두 session_id 전달)에서는 나오지 않으며, 실측상 전부 테스트가
31
+ * dist 훅을 spawn 한 흔적이었다(7d 차단 108건 중 78건). 모든 집계에서 제외한다.
32
+ */
33
+ export declare const SYNTHETIC_SESSION_IDS: ReadonlySet<string>;
34
+ export declare function isSyntheticSession(sessionId: unknown): boolean;
35
+ /** 사용자 관점의 "차단": block/deny (+legacy undefined). correction/bypass_confirmed 는 아님. */
36
+ export declare function isBlockKind(kind: unknown): boolean;
37
+ /** 실세션에서 일어난 실제 차단만. stats/explain/lifecycle 이 공유하는 단일 기준. */
38
+ export declare function isRealBlock(e: {
39
+ kind?: unknown;
40
+ session_id?: unknown;
41
+ }): boolean;
42
+ export declare function isConfirmedBypass(e: {
43
+ kind?: unknown;
44
+ session_id?: unknown;
45
+ }): boolean;
46
+ export declare const RECEIPT_TTL_MS: number;
47
+ export declare const MATCHED_MAX = 160;
48
+ export interface RecordViolationOptions {
49
+ /** 영수증 전문(명령/응답/파일 본문). secret-filter 로 마스킹 후 receipts/<id>.txt 에 24h 보관. */
50
+ receipt_text?: string;
51
+ }
52
+ /**
53
+ * 위반/차단 기록. ADR-017 D1: violation_id 를 발급해 반환하고, receipt_text 가 있으면 secret
54
+ * 마스킹 후 전문을 24h TTL 영수증으로 남긴다(로그엔 hash 만). 실패해도 예외 없이 '' 반환.
55
+ */
56
+ export declare function recordViolation(entry: Omit<ViolationEntry, 'at'>, opts?: RecordViolationOptions): string;
57
+ export declare function readReceipt(violationId: string): string | null;
58
+ /** 판정 기록(append-only). 같은 violation_id 에 여러 줄이면 마지막이 유효하되 user > auto. */
59
+ export declare function setVerdict(entry: Omit<VerdictEntry, 'at'>): void;
60
+ export declare function readVerdicts(): VerdictEntry[];
61
+ /** violation_id → 유효 판정 (user 가 있으면 user, 없으면 마지막 auto). */
62
+ export declare function effectiveVerdicts(verdicts?: VerdictEntry[]): Map<string, VerdictEntry>;
63
+ export interface RulePrecision {
64
+ rule_id: string;
65
+ correct: number;
66
+ false_positive: number;
67
+ unjudged: number;
68
+ /** correct/(correct+false_positive); 판정 0건이면 null. */
69
+ precision: number | null;
70
+ }
71
+ /** 룰별 precision (실 차단만, 최근 N일). unsure 는 미판정으로 센다. */
72
+ export declare function precisionByRule(violations: ViolationEntry[], verdicts: VerdictEntry[], days: number, now?: number): Map<string, RulePrecision>;
73
+ /** D2: Stop 평가 결과 기록(통과 포함). violations.jsonl 과 분리. 7일 TTL 은 state-gc 가 담당. */
74
+ export declare const CHECKS_TTL_MS: number;
75
+ export declare function recordCheck(entry: Omit<CheckEntry, 'at'>): void;
76
+ export declare function pruneChecks(now?: number): void;
77
+ export declare function readChecks(): CheckEntry[];
78
+ /** 정규식 매칭 프래그먼트 추출 — 영수증 `matched` 필드용. */
79
+ export declare function matchedFragment(re: RegExp, text: string): string;
23
80
  export declare function recordBypass(entry: Omit<BypassEntry, 'at'>): void;
24
81
  export interface SignalInputs {
25
82
  violations?: ViolationEntry[];
@@ -10,6 +10,25 @@
10
10
  */
11
11
  import * as fs from 'node:fs';
12
12
  import * as path from 'node:path';
13
+ import * as crypto from 'node:crypto';
14
+ import { redactSecrets } from '../../hooks/secret-filter.js'; // ESM main guard 있음 — import 부작용 없음
15
+ /**
16
+ * 영수증·로그용 추가 마스킹 (critic D1 SEV-2): secret-filter 의 공개 키 패턴만으로는 `DB_PASS=…`, mysql -p<값>,
17
+ * sshpass -p, Basic/X-API-Key 헤더, URL userinfo, 무접두 JWT, PEM 본문이 평문으로 남아 Haiku 로 egress 된다.
18
+ * 과잉 마스킹은 영수증 가독성만 깎지만 누락은 유출이므로 넓게 잡는다.
19
+ */
20
+ export function redactForReceipt(text) {
21
+ // PEM 은 secret-filter 보다 먼저 — secret-filter 가 BEGIN 헤더 줄만 치환하면 본문(base64)이 평문으로 남는다.
22
+ let t = text.replace(/-----BEGIN [A-Z ]*PRIVATE KEY-----[\s\S]*?-----END [A-Z ]*PRIVATE KEY-----/g, '[REDACTED:PEM]');
23
+ t = redactSecrets(t).redacted;
24
+ t = t.replace(/\[REDACTED:[^\]]*\][\s\S]*?-----END [A-Z ]*PRIVATE KEY-----/g, '[REDACTED:PEM]');
25
+ t = t.replace(/\b(eyJ[A-Za-z0-9_-]{8,}\.[A-Za-z0-9_-]{8,}\.[A-Za-z0-9_-]{8,})/g, '[REDACTED:JWT]');
26
+ t = t.replace(/(\b[A-Za-z_][A-Za-z0-9_]*(?:pass(?:word|wd)?|pwd|secret|token|api[_-]?key|auth|credential)[A-Za-z0-9_]*\s*[=:]\s*)(["']?)[^\s"'&;]+\2/gi, '$1$2[REDACTED]$2');
27
+ t = t.replace(/((?:mysql|mariadb|mysqldump|sshpass|psql)\b[^\n;|&]*?\s-p)(?!assword)\s*(\S+)/gi, '$1[REDACTED]');
28
+ t = t.replace(/((?:Authorization|X-API-Key|X-Auth-Token|Proxy-Authorization)\s*:\s*)(?:Basic|Bearer|Token)?\s*\S+/gi, '$1[REDACTED]');
29
+ t = t.replace(/(:\/\/[^\s/:@]+:)[^\s/@]+(@)/g, '$1[REDACTED]$2');
30
+ return t;
31
+ }
13
32
  import { STATE_DIR as FORGEN_STATE_DIR } from '../../core/paths.js';
14
33
  const ENFORCEMENT_DIR = path.join(FORGEN_STATE_DIR, 'enforcement');
15
34
  const VIOLATIONS_PATH = path.join(ENFORCEMENT_DIR, 'violations.jsonl');
@@ -57,18 +76,181 @@ export function readJsonlSafe(p) {
57
76
  return [];
58
77
  }
59
78
  }
60
- export function recordViolation(entry) {
79
+ /**
80
+ * ADR-017 §2 원칙 2: 훅이 session_id 없이 호출되면 'default'/'unknown' 폴백이 기록된다.
81
+ * 실세션(Claude·Codex 모두 session_id 전달)에서는 나오지 않으며, 실측상 전부 테스트가
82
+ * dist 훅을 spawn 한 흔적이었다(7d 차단 108건 중 78건). 모든 집계에서 제외한다.
83
+ */
84
+ export const SYNTHETIC_SESSION_IDS = new Set(['default', 'unknown', '']);
85
+ export function isSyntheticSession(sessionId) {
86
+ return typeof sessionId !== 'string' || SYNTHETIC_SESSION_IDS.has(sessionId);
87
+ }
88
+ /** 사용자 관점의 "차단": block/deny (+legacy undefined). correction/bypass_confirmed 는 아님. */
89
+ export function isBlockKind(kind) {
90
+ return kind === 'block' || kind === 'deny' || kind === undefined;
91
+ }
92
+ /** 실세션에서 일어난 실제 차단만. stats/explain/lifecycle 이 공유하는 단일 기준. */
93
+ export function isRealBlock(e) {
94
+ return isBlockKind(e.kind) && !isSyntheticSession(e.session_id);
95
+ }
96
+ export function isConfirmedBypass(e) {
97
+ return e.kind === 'bypass_confirmed' && !isSyntheticSession(e.session_id);
98
+ }
99
+ const RECEIPTS_DIR = path.join(ENFORCEMENT_DIR, 'receipts');
100
+ const VERDICTS_PATH = path.join(ENFORCEMENT_DIR, 'verdicts.jsonl');
101
+ const CHECKS_PATH = path.join(ENFORCEMENT_DIR, 'checks.jsonl');
102
+ export const RECEIPT_TTL_MS = 24 * 3600 * 1000;
103
+ export const MATCHED_MAX = 160;
104
+ function sha16(text) {
105
+ return crypto.createHash('sha256').update(text).digest('hex').slice(0, 16);
106
+ }
107
+ /** receipts/ 의 TTL 지난 파일 정리 — 기록 시마다 best-effort(최대 200개 확인). */
108
+ function pruneReceipts(now) {
109
+ try {
110
+ if (!fs.existsSync(RECEIPTS_DIR))
111
+ return;
112
+ const names = fs.readdirSync(RECEIPTS_DIR).slice(0, 200);
113
+ for (const n of names) {
114
+ const p = path.join(RECEIPTS_DIR, n);
115
+ try {
116
+ if (now - fs.statSync(p).mtimeMs > RECEIPT_TTL_MS)
117
+ fs.unlinkSync(p);
118
+ }
119
+ catch { /* skip */ }
120
+ }
121
+ }
122
+ catch { /* skip */ }
123
+ }
124
+ /**
125
+ * 위반/차단 기록. ADR-017 D1: violation_id 를 발급해 반환하고, receipt_text 가 있으면 secret
126
+ * 마스킹 후 전문을 24h TTL 영수증으로 남긴다(로그엔 hash 만). 실패해도 예외 없이 '' 반환.
127
+ */
128
+ export function recordViolation(entry, opts = {}) {
61
129
  try {
62
130
  fs.mkdirSync(ENFORCEMENT_DIR, { recursive: true });
63
131
  rotateIfBig(VIOLATIONS_PATH);
64
- const full = { at: new Date().toISOString(), ...entry };
132
+ const violation_id = entry.violation_id ?? crypto.randomUUID();
133
+ const full = { at: new Date().toISOString(), violation_id, ...entry };
134
+ // 로그에 남는 프래그먼트/미리보기도 secret 마스킹 — 영수증만 가리고 로그에 키가 남으면 의미 없다.
135
+ if (typeof full.matched === 'string')
136
+ full.matched = redactForReceipt(full.matched);
137
+ if (typeof full.message_preview === 'string')
138
+ full.message_preview = redactForReceipt(full.message_preview);
139
+ if (typeof full.matched === 'string' && full.matched.length > MATCHED_MAX)
140
+ full.matched = `${full.matched.slice(0, MATCHED_MAX - 1)}…`;
141
+ if (opts.receipt_text) {
142
+ full.target_hash = sha16(opts.receipt_text);
143
+ try {
144
+ fs.mkdirSync(RECEIPTS_DIR, { recursive: true, mode: 0o700 });
145
+ fs.writeFileSync(path.join(RECEIPTS_DIR, `${violation_id}.txt`), redactForReceipt(opts.receipt_text), { mode: 0o600 });
146
+ pruneReceipts(Date.now());
147
+ }
148
+ catch { /* 영수증 실패는 기록 자체를 막지 않는다 */ }
149
+ }
65
150
  fs.appendFileSync(VIOLATIONS_PATH, `${JSON.stringify(full)}\n`);
151
+ return violation_id;
66
152
  }
67
153
  catch (e) {
68
154
  // best-effort, 실패 시 debug 로그 (silent swallow 방지)
69
155
  if (process.env.FORGEN_DEBUG_SIGNALS === '1') {
70
156
  console.error(`[forgen:signals] recordViolation failed: ${e.message}`);
71
157
  }
158
+ return '';
159
+ }
160
+ }
161
+ export function readReceipt(violationId) {
162
+ if (!/^[A-Za-z0-9-]+$/.test(violationId))
163
+ return null;
164
+ try {
165
+ return fs.readFileSync(path.join(RECEIPTS_DIR, `${violationId}.txt`), 'utf-8');
166
+ }
167
+ catch {
168
+ return null;
169
+ }
170
+ }
171
+ /** 판정 기록(append-only). 같은 violation_id 에 여러 줄이면 마지막이 유효하되 user > auto. */
172
+ export function setVerdict(entry) {
173
+ try {
174
+ fs.mkdirSync(ENFORCEMENT_DIR, { recursive: true });
175
+ rotateIfBig(VERDICTS_PATH);
176
+ fs.appendFileSync(VERDICTS_PATH, `${JSON.stringify({ at: new Date().toISOString(), ...entry })}\n`);
177
+ }
178
+ catch { /* best-effort */ }
179
+ }
180
+ export function readVerdicts() {
181
+ return readJsonlSafe(VERDICTS_PATH);
182
+ }
183
+ /** violation_id → 유효 판정 (user 가 있으면 user, 없으면 마지막 auto). */
184
+ export function effectiveVerdicts(verdicts = readVerdicts()) {
185
+ const m = new Map();
186
+ for (const v of verdicts) {
187
+ const cur = m.get(v.violation_id);
188
+ if (cur?.by !== 'user' || v.by === 'user')
189
+ m.set(v.violation_id, v);
190
+ }
191
+ return m;
192
+ }
193
+ /** 룰별 precision (실 차단만, 최근 N일). unsure 는 미판정으로 센다. */
194
+ export function precisionByRule(violations, verdicts, days, now = Date.now()) {
195
+ const cutoff = now - days * 24 * 3600 * 1000;
196
+ const eff = effectiveVerdicts(verdicts);
197
+ const out = new Map();
198
+ for (const v of violations) {
199
+ if (!isRealBlock(v))
200
+ continue;
201
+ const t = Date.parse(v.at);
202
+ if (!Number.isFinite(t) || t < cutoff)
203
+ continue;
204
+ const r = out.get(v.rule_id) ?? { rule_id: v.rule_id, correct: 0, false_positive: 0, unjudged: 0, precision: null };
205
+ const verdict = v.violation_id ? eff.get(v.violation_id)?.verdict : undefined;
206
+ if (verdict === 'correct')
207
+ r.correct++;
208
+ else if (verdict === 'false_positive')
209
+ r.false_positive++;
210
+ else
211
+ r.unjudged++;
212
+ out.set(v.rule_id, r);
213
+ }
214
+ for (const r of out.values()) {
215
+ const judged = r.correct + r.false_positive;
216
+ r.precision = judged > 0 ? r.correct / judged : null;
217
+ }
218
+ return out;
219
+ }
220
+ /** D2: Stop 평가 결과 기록(통과 포함). violations.jsonl 과 분리. 7일 TTL 은 state-gc 가 담당. */
221
+ export const CHECKS_TTL_MS = 7 * 24 * 3600 * 1000;
222
+ export function recordCheck(entry) {
223
+ try {
224
+ fs.mkdirSync(ENFORCEMENT_DIR, { recursive: true });
225
+ rotateIfBig(CHECKS_PATH);
226
+ fs.appendFileSync(CHECKS_PATH, `${JSON.stringify({ at: new Date().toISOString(), ...entry })}\n`);
227
+ // 7일 TTL — 통과 기록은 턴마다 쌓이므로 1/50 확률로 압축(rotateIfBig 10MB 에 닿지 않게).
228
+ if (Math.random() < 0.02)
229
+ pruneChecks();
230
+ }
231
+ catch { /* best-effort */ }
232
+ }
233
+ export function pruneChecks(now = Date.now()) {
234
+ try {
235
+ const keep = readJsonlSafe(CHECKS_PATH).filter((c) => now - Date.parse(c.at) < CHECKS_TTL_MS);
236
+ fs.writeFileSync(CHECKS_PATH, keep.map((c) => JSON.stringify(c)).join('\n') + (keep.length ? '\n' : ''));
237
+ }
238
+ catch { /* best-effort */ }
239
+ }
240
+ export function readChecks() {
241
+ return readJsonlSafe(CHECKS_PATH);
242
+ }
243
+ /** 정규식 매칭 프래그먼트 추출 — 영수증 `matched` 필드용. */
244
+ export function matchedFragment(re, text) {
245
+ try {
246
+ const m = re.exec(text);
247
+ if (!m)
248
+ return '';
249
+ const start = Math.max(0, m.index - 30);
250
+ return text.slice(start, m.index + m[0].length + 30).replace(/\s+/g, ' ').trim();
251
+ }
252
+ catch {
253
+ return '';
72
254
  }
73
255
  }
74
256
  export function recordBypass(entry) {
@@ -86,8 +268,15 @@ export function recordBypass(entry) {
86
268
  }
87
269
  export function collectSignals(rule, inputs = {}) {
88
270
  const now = inputs.now ?? Date.now();
89
- const violations = inputs.violations ?? readJsonlSafe(VIOLATIONS_PATH);
90
- const bypass = inputs.bypass ?? readJsonlSafe(BYPASS_PATH);
271
+ const allViolations = inputs.violations ?? readJsonlSafe(VIOLATIONS_PATH);
272
+ // ADR-017 D1/D2: T2 는 실제 차단만 센다 — 이전엔 kind 필터가 없어 메타가드 advise(correction)
273
+ // 와 테스트 유래(default 세션) 기록이 위반으로 집계돼 flag 를 조기 발화시켰다.
274
+ const violations = allViolations.filter(isRealBlock);
275
+ // T3 입력은 bypass.jsonl(자연어 휴리스틱 — 실측 100% 오탐, ADR-017 §1.1)이 아니라
276
+ // 사용자 명시 우회(kind:'bypass_confirmed')다. `inputs.bypass` 는 하위 호환으로 남기되 읽지 않는다.
277
+ const bypass = allViolations
278
+ .filter(isConfirmedBypass)
279
+ .map((v) => ({ at: v.at, rule_id: v.rule_id, session_id: v.session_id, tool: v.source, pattern_preview: v.message_preview ?? '' }));
91
280
  // exact match only — M fix: startsWith 으로 prefix 교차 오염되던 부분 제거.
92
281
  const matchesRule = (ruleId) => ruleId === rule.rule_id;
93
282
  const vCutoff30 = now - VIOLATION_WINDOW_DAYS * 24 * 3600 * 1000;