@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
@@ -0,0 +1,113 @@
1
+ /**
2
+ * Rate-limit forecast — "지금 추세면 언제 다 쓰나" (ADR-017 D5)
3
+ *
4
+ * Claude Code statusline stdin 의 `rate_limits.{five_hour,seven_day}.{used_percentage,resets_at}` 를
5
+ * 호출마다 샘플로 쌓고, 최근 창의 기울기(EMA 평활)로 100% 도달 시각을 추정한다.
6
+ *
7
+ * 정직성 원칙 (ADR-017 §2-5): 근거가 부족하면 예측을 **숨긴다**. 틀린 예측 하나가 맞는 예측
8
+ * 열 개를 무효화한다. 숨김 조건 — 창 내 샘플 < MIN_SAMPLES, 창 내 시간 폭 < 창별 MIN_SPAN,
9
+ * 창 내 총 증가 < MIN_RISE_PCT, 기울기 ≤ 0, used_percentage null/비수치, resets_at 경과.
10
+ *
11
+ * 추정기 (critic SEV-1 반영): 사용률은 API 응답 시점에 **계단**으로 뛰고 호출 간격은 수 초~수십 분으로
12
+ * 불균일하다. 연속 쌍 기울기의 등가중 EMA 는 "정체 n개 + 짧은 dt 의 점프 1개" 에서 수십 배 과대했다
13
+ * (실측 27배). 창 안 **양끝점 기울기** (used_last − used_first)/(t_last − t_first) 로 교체 — dt 가중이
14
+ * 본질이고 점프 순서에 무관하다.
15
+ *
16
+ * 표시 게이트: 현재 페이로드에 그 창이 **수치로 존재할 때만** 출력한다. 파일 샘플은 기울기 전용.
17
+ * (리셋 순간 CC 는 창을 drop 하고 스크립트를 재실행하므로, 파일만 보면 리셋 전 최고치를 보여주게 된다.)
18
+ *
19
+ * 창 리셋 조건 (공식 문서 2026-10-06 확인: 창은 resets_at 을 가지며 지나면 객체가 사라졌다
20
+ * 재등장하고 초기엔 used_percentage 가 null 일 수 있다): resets_at 변화 · 사용률 하락 ·
21
+ * null 샘플 → 이전 샘플 폐기(해당 창만).
22
+ *
23
+ * 순수 함수 + 얇은 IO. 샘플 파일은 한 줄 단일 append, 읽기는 파싱 실패 라인 무시
24
+ * (Claude Code 가 statusline 스크립트를 중간에 취소하면 잘린 줄이 생길 수 있다).
25
+ */
26
+ export type WindowKey = 'five_hour' | 'seven_day';
27
+ export interface RateWindow {
28
+ used_percentage?: number | null;
29
+ resets_at?: number | null;
30
+ }
31
+ export interface RateLimitsPayload {
32
+ five_hour?: RateWindow | null;
33
+ seven_day?: RateWindow | null;
34
+ }
35
+ export interface Sample {
36
+ /** epoch ms */
37
+ t: number;
38
+ used: number;
39
+ /** epoch seconds; 창 식별자 */
40
+ resets_at: number | null;
41
+ }
42
+ export declare const SAMPLES_PATH: string;
43
+ export declare const SAMPLE_TTL_MS: number;
44
+ export declare const MIN_SAMPLES = 3;
45
+ /** 창 안 샘플 시간 폭 최소치 — 짧은 폭의 점프 하나가 추세로 둔갑하지 않게. */
46
+ export declare const MIN_SPAN_MS: Record<WindowKey, number>;
47
+ /** 창 안 총 증가가 이보다 작으면(0.1% 양자화 잡음 수준) 예측 숨김. */
48
+ export declare const MIN_RISE_PCT = 1;
49
+ /** 기울기 추정에 쓰는 창 폭. */
50
+ export declare const LOOKBACK_MS: Record<WindowKey, number>;
51
+ /** compactSamples 가드: 이 크기 미만이거나 최근에 쓰인 파일은 재작성하지 않는다(동시 append 유실 방지). */
52
+ export declare const COMPACT_MIN_BYTES: number;
53
+ export declare const COMPACT_QUIET_MS: number;
54
+ export interface Forecast {
55
+ window: WindowKey;
56
+ used: number;
57
+ resetsAt: number | null;
58
+ /** 100% 도달 예상 시각(epoch ms). 근거 부족·기울기 ≤0 이면 null. */
59
+ exhaustAt: number | null;
60
+ /** exhaustAt 이 resets_at 보다 앞이면 true. */
61
+ exhaustsBeforeReset: boolean;
62
+ /** 리셋 시점 예상 사용률(기울기 외삽, 100 상한). 예측 불가면 null. */
63
+ projectedAtReset: number | null;
64
+ /** %/시간. */
65
+ ratePerHour: number | null;
66
+ sampleCount: number;
67
+ }
68
+ interface SampleLine extends Sample {
69
+ w: WindowKey;
70
+ }
71
+ /** payload → 이번 호출 샘플(창별). null/비수치 사용률은 샘플로 만들지 않는다. */
72
+ export declare function samplesFromPayload(rl: RateLimitsPayload | undefined | null, nowMs: number): SampleLine[];
73
+ export declare function appendSamples(lines: SampleLine[], p?: string): void;
74
+ export declare function readSamples(p?: string, nowMs?: number): SampleLine[];
75
+ /**
76
+ * TTL 넘은 줄 제거. read→truncate 재작성은 다른 세션의 동시 append 를 유실시키므로(critic 실측 33%)
77
+ * **크기 ≥ COMPACT_MIN_BYTES 이고 마지막 수정이 COMPACT_QUIET_MS 이전**일 때만 수행한다.
78
+ * 반환: 실제로 압축했는지.
79
+ */
80
+ export declare function compactSamples(p?: string, nowMs?: number, force?: boolean): boolean;
81
+ /**
82
+ * 같은 창의 샘플 시계열에서 "현재 창"에 속하는 꼬리만 남긴다.
83
+ * 창 경계: resets_at 변화, 사용률 하락. (둘 다 "이전 창의 샘플" 이므로 버린다.)
84
+ */
85
+ export declare function currentWindowTail(samples: Sample[]): Sample[];
86
+ /**
87
+ * 양끝점 기울기(%/ms) — lookback 창 안 첫/마지막 샘플. 시간 가중이 본질이라 점프 순서·간격에 무관.
88
+ * 숨김: 샘플 < MIN_SAMPLES, 시간 폭 < MIN_SPAN_MS[w], 총 증가 < MIN_RISE_PCT.
89
+ */
90
+ export declare function estimateRate(tail: Sample[], nowMs: number, lookbackMs: number, w?: WindowKey): {
91
+ rate: number;
92
+ n: number;
93
+ } | null;
94
+ /**
95
+ * @param current 현재 페이로드의 이 창 샘플. **없으면 null 을 돌려 세그먼트를 생략한다** — 파일의
96
+ * 옛 샘플을 현재값처럼 보여주지 않는다(critic SEV-1). resets_at 이 이미 지났어도 숨긴다.
97
+ */
98
+ export declare function forecastWindow(w: WindowKey, samples: Sample[], nowMs: number, current?: Sample | null): Forecast | null;
99
+ /**
100
+ * 모든 창 예측. `current` 가 주어지면 **그 안에 수치로 존재하는 창만** 출력한다(표시 게이트).
101
+ * 주어지지 않으면(오프라인 분석) 파일 샘플의 마지막을 현재로 간주.
102
+ */
103
+ export declare function forecastAll(all: SampleLine[], nowMs: number, current?: SampleLine[]): Partial<Record<WindowKey, Forecast>>;
104
+ /** HH:MM (로컬). 하루 넘어가면 "D+1 HH:MM". */
105
+ export declare function fmtClock(epochMs: number, nowMs: number): string;
106
+ /**
107
+ * 한 창의 표시 문자열(색 없음 — 호출자가 입힘).
108
+ * "5h 63% → 15:40 소진 (리셋 16:20)" 리셋 전 소진 예상
109
+ * "5h 63% → 리셋 16:20 여유 (예상 81%)" 리셋까지 안 닿음
110
+ * "5h 63% (리셋 16:20)" 예측 근거 부족 — 사용률만
111
+ */
112
+ export declare function fmtForecast(f: Forecast, nowMs: number): string;
113
+ export {};
@@ -0,0 +1,236 @@
1
+ /**
2
+ * Rate-limit forecast — "지금 추세면 언제 다 쓰나" (ADR-017 D5)
3
+ *
4
+ * Claude Code statusline stdin 의 `rate_limits.{five_hour,seven_day}.{used_percentage,resets_at}` 를
5
+ * 호출마다 샘플로 쌓고, 최근 창의 기울기(EMA 평활)로 100% 도달 시각을 추정한다.
6
+ *
7
+ * 정직성 원칙 (ADR-017 §2-5): 근거가 부족하면 예측을 **숨긴다**. 틀린 예측 하나가 맞는 예측
8
+ * 열 개를 무효화한다. 숨김 조건 — 창 내 샘플 < MIN_SAMPLES, 창 내 시간 폭 < 창별 MIN_SPAN,
9
+ * 창 내 총 증가 < MIN_RISE_PCT, 기울기 ≤ 0, used_percentage null/비수치, resets_at 경과.
10
+ *
11
+ * 추정기 (critic SEV-1 반영): 사용률은 API 응답 시점에 **계단**으로 뛰고 호출 간격은 수 초~수십 분으로
12
+ * 불균일하다. 연속 쌍 기울기의 등가중 EMA 는 "정체 n개 + 짧은 dt 의 점프 1개" 에서 수십 배 과대했다
13
+ * (실측 27배). 창 안 **양끝점 기울기** (used_last − used_first)/(t_last − t_first) 로 교체 — dt 가중이
14
+ * 본질이고 점프 순서에 무관하다.
15
+ *
16
+ * 표시 게이트: 현재 페이로드에 그 창이 **수치로 존재할 때만** 출력한다. 파일 샘플은 기울기 전용.
17
+ * (리셋 순간 CC 는 창을 drop 하고 스크립트를 재실행하므로, 파일만 보면 리셋 전 최고치를 보여주게 된다.)
18
+ *
19
+ * 창 리셋 조건 (공식 문서 2026-10-06 확인: 창은 resets_at 을 가지며 지나면 객체가 사라졌다
20
+ * 재등장하고 초기엔 used_percentage 가 null 일 수 있다): resets_at 변화 · 사용률 하락 ·
21
+ * null 샘플 → 이전 샘플 폐기(해당 창만).
22
+ *
23
+ * 순수 함수 + 얇은 IO. 샘플 파일은 한 줄 단일 append, 읽기는 파싱 실패 라인 무시
24
+ * (Claude Code 가 statusline 스크립트를 중간에 취소하면 잘린 줄이 생길 수 있다).
25
+ */
26
+ import * as fs from 'node:fs';
27
+ import * as path from 'node:path';
28
+ import { STATE_DIR } from './paths.js';
29
+ export const SAMPLES_PATH = path.join(STATE_DIR, 'rate-limit-samples.jsonl');
30
+ export const SAMPLE_TTL_MS = 7 * 24 * 3600 * 1000;
31
+ export const MIN_SAMPLES = 3;
32
+ /** 창 안 샘플 시간 폭 최소치 — 짧은 폭의 점프 하나가 추세로 둔갑하지 않게. */
33
+ export const MIN_SPAN_MS = {
34
+ five_hour: 15 * 60 * 1000,
35
+ seven_day: 2 * 3600 * 1000,
36
+ };
37
+ /** 창 안 총 증가가 이보다 작으면(0.1% 양자화 잡음 수준) 예측 숨김. */
38
+ export const MIN_RISE_PCT = 1;
39
+ /** 기울기 추정에 쓰는 창 폭. */
40
+ export const LOOKBACK_MS = {
41
+ five_hour: 30 * 60 * 1000,
42
+ seven_day: 24 * 3600 * 1000,
43
+ };
44
+ /** compactSamples 가드: 이 크기 미만이거나 최근에 쓰인 파일은 재작성하지 않는다(동시 append 유실 방지). */
45
+ export const COMPACT_MIN_BYTES = 256 * 1024;
46
+ export const COMPACT_QUIET_MS = 60 * 1000;
47
+ const isNum = (v) => typeof v === 'number' && Number.isFinite(v);
48
+ /** payload → 이번 호출 샘플(창별). null/비수치 사용률은 샘플로 만들지 않는다. */
49
+ export function samplesFromPayload(rl, nowMs) {
50
+ const out = [];
51
+ if (!rl)
52
+ return out;
53
+ for (const w of ['five_hour', 'seven_day']) {
54
+ const win = rl[w];
55
+ if (!win || !isNum(win.used_percentage))
56
+ continue;
57
+ out.push({ w, t: nowMs, used: win.used_percentage, resets_at: isNum(win.resets_at) ? win.resets_at : null });
58
+ }
59
+ return out;
60
+ }
61
+ export function appendSamples(lines, p = SAMPLES_PATH) {
62
+ if (lines.length === 0)
63
+ return;
64
+ try {
65
+ fs.mkdirSync(path.dirname(p), { recursive: true });
66
+ // 한 줄 단일 write — 취소로 잘려도 다음 줄에 영향 없음.
67
+ fs.appendFileSync(p, `${lines.map((l) => JSON.stringify(l)).join('\n')}\n`);
68
+ }
69
+ catch { /* fail-open */ }
70
+ }
71
+ export function readSamples(p = SAMPLES_PATH, nowMs = Date.now()) {
72
+ try {
73
+ if (!fs.existsSync(p))
74
+ return [];
75
+ const cutoff = nowMs - SAMPLE_TTL_MS;
76
+ const out = [];
77
+ for (const line of fs.readFileSync(p, 'utf-8').split('\n')) {
78
+ if (!line.trim())
79
+ continue;
80
+ try {
81
+ const o = JSON.parse(line);
82
+ if ((o.w !== 'five_hour' && o.w !== 'seven_day') || !isNum(o.t) || !isNum(o.used))
83
+ continue;
84
+ if (o.t < cutoff)
85
+ continue;
86
+ out.push({ w: o.w, t: o.t, used: o.used, resets_at: isNum(o.resets_at) ? o.resets_at : null });
87
+ }
88
+ catch { /* 잘린 줄 무시 */ }
89
+ }
90
+ return out;
91
+ }
92
+ catch {
93
+ return [];
94
+ }
95
+ }
96
+ /**
97
+ * TTL 넘은 줄 제거. read→truncate 재작성은 다른 세션의 동시 append 를 유실시키므로(critic 실측 33%)
98
+ * **크기 ≥ COMPACT_MIN_BYTES 이고 마지막 수정이 COMPACT_QUIET_MS 이전**일 때만 수행한다.
99
+ * 반환: 실제로 압축했는지.
100
+ */
101
+ export function compactSamples(p = SAMPLES_PATH, nowMs = Date.now(), force = false) {
102
+ try {
103
+ if (!fs.existsSync(p))
104
+ return false;
105
+ if (!force) {
106
+ const st = fs.statSync(p);
107
+ if (st.size < COMPACT_MIN_BYTES || nowMs - st.mtimeMs < COMPACT_QUIET_MS)
108
+ return false;
109
+ }
110
+ const keep = readSamples(p, nowMs);
111
+ fs.writeFileSync(p, keep.map((l) => JSON.stringify(l)).join('\n') + (keep.length ? '\n' : ''));
112
+ return true;
113
+ }
114
+ catch {
115
+ return false;
116
+ }
117
+ }
118
+ /**
119
+ * 같은 창의 샘플 시계열에서 "현재 창"에 속하는 꼬리만 남긴다.
120
+ * 창 경계: resets_at 변화, 사용률 하락. (둘 다 "이전 창의 샘플" 이므로 버린다.)
121
+ */
122
+ export function currentWindowTail(samples) {
123
+ const sorted = [...samples].sort((a, b) => a.t - b.t);
124
+ let start = 0;
125
+ for (let i = 1; i < sorted.length; i++) {
126
+ const prev = sorted[i - 1];
127
+ const cur = sorted[i];
128
+ const resetChanged = prev.resets_at !== null && cur.resets_at !== null && prev.resets_at !== cur.resets_at;
129
+ const dropped = cur.used < prev.used - 1e-9;
130
+ if (resetChanged || dropped)
131
+ start = i;
132
+ }
133
+ return sorted.slice(start);
134
+ }
135
+ /**
136
+ * 양끝점 기울기(%/ms) — lookback 창 안 첫/마지막 샘플. 시간 가중이 본질이라 점프 순서·간격에 무관.
137
+ * 숨김: 샘플 < MIN_SAMPLES, 시간 폭 < MIN_SPAN_MS[w], 총 증가 < MIN_RISE_PCT.
138
+ */
139
+ export function estimateRate(tail, nowMs, lookbackMs, w = 'five_hour') {
140
+ const inWin = tail.filter((s) => s.t >= nowMs - lookbackMs).sort((a, b) => a.t - b.t);
141
+ if (inWin.length < MIN_SAMPLES)
142
+ return null;
143
+ const first = inWin[0];
144
+ const last = inWin[inWin.length - 1];
145
+ const span = last.t - first.t;
146
+ if (span < MIN_SPAN_MS[w])
147
+ return null;
148
+ const rise = last.used - first.used;
149
+ if (rise < MIN_RISE_PCT)
150
+ return null;
151
+ return { rate: rise / span, n: inWin.length };
152
+ }
153
+ /**
154
+ * @param current 현재 페이로드의 이 창 샘플. **없으면 null 을 돌려 세그먼트를 생략한다** — 파일의
155
+ * 옛 샘플을 현재값처럼 보여주지 않는다(critic SEV-1). resets_at 이 이미 지났어도 숨긴다.
156
+ */
157
+ export function forecastWindow(w, samples, nowMs, current) {
158
+ if (current === undefined) {
159
+ // 하위 호환(테스트·오프라인 분석): 명시 안 하면 tail 마지막을 현재로 간주.
160
+ const t = currentWindowTail(samples);
161
+ if (t.length === 0)
162
+ return null;
163
+ current = t[t.length - 1];
164
+ }
165
+ if (!current)
166
+ return null;
167
+ if (current.resets_at !== null && current.resets_at * 1000 < nowMs)
168
+ return null;
169
+ const tail = currentWindowTail([...samples.filter((s) => s.t !== current.t), current]);
170
+ const last = current;
171
+ const resetsAt = last.resets_at !== null ? last.resets_at * 1000 : null;
172
+ const base = {
173
+ window: w, used: last.used, resetsAt, exhaustAt: null, exhaustsBeforeReset: false,
174
+ projectedAtReset: null, ratePerHour: null, sampleCount: tail.length,
175
+ };
176
+ const est = estimateRate(tail, nowMs, LOOKBACK_MS[w], w);
177
+ if (!est || est.rate <= 0)
178
+ return base; // 숨김: 근거 부족 또는 소진 방향 아님
179
+ const ratePerMs = est.rate;
180
+ const remaining = Math.max(0, 100 - last.used);
181
+ const exhaustAt = last.t + remaining / ratePerMs;
182
+ const projectedAtReset = resetsAt !== null && resetsAt > last.t
183
+ ? Math.min(100, last.used + ratePerMs * (resetsAt - last.t))
184
+ : null;
185
+ return {
186
+ ...base,
187
+ exhaustAt,
188
+ exhaustsBeforeReset: resetsAt !== null ? exhaustAt < resetsAt : false,
189
+ projectedAtReset,
190
+ ratePerHour: ratePerMs * 3600 * 1000,
191
+ };
192
+ }
193
+ /**
194
+ * 모든 창 예측. `current` 가 주어지면 **그 안에 수치로 존재하는 창만** 출력한다(표시 게이트).
195
+ * 주어지지 않으면(오프라인 분석) 파일 샘플의 마지막을 현재로 간주.
196
+ */
197
+ export function forecastAll(all, nowMs, current) {
198
+ const out = {};
199
+ for (const w of ['five_hour', 'seven_day']) {
200
+ const cur = current ? (current.find((s) => s.w === w) ?? null) : undefined;
201
+ const f = forecastWindow(w, all.filter((s) => s.w === w), nowMs, cur);
202
+ if (f)
203
+ out[w] = f;
204
+ }
205
+ return out;
206
+ }
207
+ /** HH:MM (로컬). 하루 넘어가면 "D+1 HH:MM". */
208
+ export function fmtClock(epochMs, nowMs) {
209
+ const d = new Date(epochMs);
210
+ const hh = String(d.getHours()).padStart(2, '0');
211
+ const mm = String(d.getMinutes()).padStart(2, '0');
212
+ const dayDiff = Math.floor((startOfDay(epochMs) - startOfDay(nowMs)) / (24 * 3600 * 1000));
213
+ return dayDiff > 0 ? `D+${dayDiff} ${hh}:${mm}` : `${hh}:${mm}`;
214
+ }
215
+ function startOfDay(ms) {
216
+ const d = new Date(ms);
217
+ d.setHours(0, 0, 0, 0);
218
+ return d.getTime();
219
+ }
220
+ /**
221
+ * 한 창의 표시 문자열(색 없음 — 호출자가 입힘).
222
+ * "5h 63% → 15:40 소진 (리셋 16:20)" 리셋 전 소진 예상
223
+ * "5h 63% → 리셋 16:20 여유 (예상 81%)" 리셋까지 안 닿음
224
+ * "5h 63% (리셋 16:20)" 예측 근거 부족 — 사용률만
225
+ */
226
+ export function fmtForecast(f, nowMs) {
227
+ const label = f.window === 'five_hour' ? '5h' : '7d';
228
+ const used = `${label} ${Math.round(f.used)}%`;
229
+ const reset = f.resetsAt !== null ? `리셋 ${fmtClock(f.resetsAt, nowMs)}` : '';
230
+ if (f.exhaustAt === null)
231
+ return reset ? `${used} (${reset})` : used;
232
+ if (f.exhaustsBeforeReset)
233
+ return `${used} → ${fmtClock(f.exhaustAt, nowMs)} 소진${reset ? ` (${reset})` : ''}`;
234
+ const proj = f.projectedAtReset !== null ? ` (예상 ${Math.round(f.projectedAtReset)}%)` : '';
235
+ return reset ? `${used} → ${reset} 여유${proj}` : `${used} → ${fmtClock(f.exhaustAt, nowMs)} 소진`;
236
+ }
@@ -21,6 +21,8 @@ import { STATE_DIR, OUTCOMES_DIR } from './paths.js';
21
21
  /** Filename prefixes that identify session-scoped ephemeral files. */
22
22
  const SESSION_SCOPED_PREFIXES = [
23
23
  'active-agents-',
24
+ 'statusline-cache', // ADR-017 D4: 세션별 statusline 캐시 (+ 구 전역 statusline-cache.txt 도 정리)
25
+ 'turn-rules-', // ADR-017 D2: 세션별 턴 관련 룰
24
26
  'checkpoint-',
25
27
  'injection-cache-',
26
28
  'modified-files-',
@@ -103,6 +105,7 @@ const ROTATABLE_LOGS = [
103
105
  'prompt-history.jsonl',
104
106
  'usage-telemetry.jsonl',
105
107
  'rate-limit-misses.jsonl',
108
+ 'rate-limit-samples.jsonl', // ADR-017 D5: 10MB 백스톱 (7d TTL 압축과 양립)
106
109
  ];
107
110
  const DEFAULT_MAX_LOG_BYTES = 10 * 1024 * 1024; // 10MB
108
111
  export function rotateAppendOnlyLogs(opts = {}) {
@@ -4,13 +4,20 @@ export interface StatsSnapshot {
4
4
  correctionsTotal: number;
5
5
  corrections7d: number;
6
6
  blocks7d: number;
7
+ /** ADR-017 §2 원칙 1: 집계에서 제외된 합성 세션(default/unknown) 기록 수 — 누락을 가시화. */
8
+ syntheticExcluded7d: number;
7
9
  acks7d: number;
8
10
  bypass7d: number;
9
11
  drift7d: number;
10
12
  retired7d: number;
11
13
  lastExtraction: string;
12
14
  assistToday: {
15
+ /** 후보가 1개 이상 나온 실세션(hook) recall. */
13
16
  recallHits: number;
17
+ /** 오늘 hook 경로 recall 시도 전체(후보 0건 포함). */
18
+ recallAttempts: number;
19
+ /** 오늘 mcp(compound-search) 경로 호출 수 — 테스트 격리(2026-10-06) 이후엔 실 호출. 별도 표기. */
20
+ recallMcp: number;
14
21
  surfaced: number;
15
22
  referenced: number;
16
23
  extractedToday: number;
@@ -34,6 +41,14 @@ export interface StatsSnapshot {
34
41
  name: string;
35
42
  count: number;
36
43
  }>;
44
+ /** ADR-017 D1: 룰별 precision(7d) — 판정 출처 무관 유효 판정 기준. */
45
+ precision7d: Array<{
46
+ rule_id: string;
47
+ correct: number;
48
+ false_positive: number;
49
+ unjudged: number;
50
+ precision: number | null;
51
+ }>;
37
52
  /** v0.5.0: 이번주 vs 지난주 변화량 */
38
53
  weeklyTrend: {
39
54
  blocksThisWeek: number;
@@ -10,12 +10,15 @@ import * as path from 'node:path';
10
10
  import { loadAllRules } from '../store/rule-store.js';
11
11
  import { loadAllEvidence } from '../store/evidence-store.js';
12
12
  import { STATE_DIR, ME_DIR } from './paths.js';
13
+ import { isRealBlock, isConfirmedBypass, isSyntheticSession, precisionByRule, readVerdicts } from '../engine/lifecycle/signals.js';
13
14
  import { computeFixFeatRatio, formatFixRatio } from './git-stats.js';
14
15
  // v0.4.1 격리 fix: 이전에는 os.homedir() 직접 사용해서 FORGEN_HOME env 로
15
16
  // 홈 격리해도 이 파일의 경로는 여전히 실 홈 가리켰음. paths.ts 상수 import.
16
17
  const ENFORCEMENT_DIR = path.join(STATE_DIR, 'enforcement');
17
18
  const LIFECYCLE_DIR = path.join(STATE_DIR, 'lifecycle');
18
19
  const SOLUTIONS_DIR = path.join(ME_DIR, 'solutions');
20
+ const C_DIM = '\x1b[2m';
21
+ const C_RESET = '\x1b[0m';
19
22
  const MS_PER_DAY = 24 * 60 * 60 * 1000;
20
23
  function readJsonl(p) {
21
24
  if (!fs.existsSync(p))
@@ -100,12 +103,25 @@ function computeAssistToday() {
100
103
  const startOfDay = new Date();
101
104
  startOfDay.setHours(0, 0, 0, 0);
102
105
  const cutoffMs = startOfDay.getTime();
103
- // recall hits: match-eval-log 의 오늘 entries
106
+ // ADR-017 §1.5a: 이전엔 match-eval-log 의 오늘 entry 수 전체를 "Recall hits" 로 셌다 —
107
+ // 후보 0건·mcp 쿼리·vitest 픽스처(7d 773건 중 351건)까지 포함돼 "25회 recall 에 0 surfaced"
108
+ // 라는 틀린 그림을 만들었다. hit = source:hook 이고 후보 ≥1. attempts = hook 전체.
104
109
  const matchLog = readJsonl(path.join(STATE_DIR, 'match-eval-log.jsonl'));
105
110
  let recallHits = 0;
111
+ let recallAttempts = 0;
112
+ let recallMcp = 0;
106
113
  for (const e of matchLog) {
107
114
  const ts = typeof e.ts === 'string' ? Date.parse(e.ts) : NaN;
108
- if (Number.isFinite(ts) && ts >= cutoffMs)
115
+ if (!Number.isFinite(ts) || ts < cutoffMs)
116
+ continue;
117
+ if (e.source === 'mcp') {
118
+ recallMcp++;
119
+ continue;
120
+ }
121
+ if (e.source !== 'hook')
122
+ continue;
123
+ recallAttempts++;
124
+ if (Array.isArray(e.candidates) && e.candidates.length > 0)
109
125
  recallHits++;
110
126
  }
111
127
  // surfaced + referenced — 같은 스트림 1회 loop 로.
@@ -135,7 +151,7 @@ function computeAssistToday() {
135
151
  }
136
152
  }
137
153
  catch { /* fail-open */ }
138
- return { recallHits, surfaced, referenced, extractedToday };
154
+ return { recallHits, recallAttempts, recallMcp, surfaced, referenced, extractedToday };
139
155
  }
140
156
  /** v0.4.1: forge-profile 에서 고도화 지표 추출. 파일 없거나 깨지면 undefined. */
141
157
  function computePhilosophy() {
@@ -177,20 +193,24 @@ export function computeStats() {
177
193
  // content 의 quote 본문까지 raw 매칭해서 bypass 로 오기록. 실 관찰: L1-no-rm-rf
178
194
  // -unconfirmed bypass 20건 중 Write/Edit 15건. stats 표시는 **실 실행 맥락** 인
179
195
  // Bash/Agent/기타만 집계 — 앞으로의 시계열 일관성 + 과거 noise 제거.
180
- const bypassRaw = readJsonl(path.join(ENFORCEMENT_DIR, 'bypass.jsonl'));
181
- const bypass = bypassRaw.filter((e) => e.tool !== 'Write' && e.tool !== 'Edit');
196
+ // ADR-017 D1: bypass.jsonl(자연어 휴리스틱)은 더 이상 읽지 않는다 — 실측 전량 오탐, 실 우회 0건.
197
+ // "Bypass" 는 FORGEN_USER_CONFIRMED=1 명시 우회(kind:'bypass_confirmed')만 센다.
198
+ const bypass = violations.filter(isConfirmedBypass);
182
199
  const drift = readJsonl(path.join(ENFORCEMENT_DIR, 'drift.jsonl'));
183
200
  const acks = readJsonl(path.join(ENFORCEMENT_DIR, 'acknowledgments.jsonl'));
184
201
  // R9-PA2: violations 는 'block' (stop-guard/post-tool) + 'deny' (pre-tool Mech-A)
185
- // + 'correction' (user bypass audit) 혼재. 사용자 관점에서 "Block" 은 앞의 2종이며
202
+ // + 'correction' (메타가드 advise) + 'bypass_confirmed' (사용자 명시 우회) 혼재. 사용자 관점에서 "Block" 은 앞의 2종이며
186
203
  // correction 은 제외해야 ack ratio 가 의미를 갖는다. legacy-undefined 엔트리도 포함.
187
- const realBlocks = violations.filter((e) => e.kind === 'block' || e.kind === 'deny' || e.kind === undefined);
204
+ // ADR-017 §2 원칙 2: session_id 'default'/'unknown'(훅이 session 없이 호출 — 실측 전부 테스트
205
+ // 유래) 도 제외. 기준은 signals.isRealBlock 하나로 통일(explain/lifecycle 과 동일).
206
+ const realBlocks = violations.filter(isRealBlock);
188
207
  return {
189
208
  activeRules,
190
209
  suppressedRules,
191
210
  correctionsTotal,
192
211
  corrections7d,
193
212
  blocks7d: countWithin(realBlocks, 7),
213
+ syntheticExcluded7d: countWithin(violations.filter((e) => isSyntheticSession(e.session_id)), 7),
194
214
  acks7d: countWithin(acks, 7),
195
215
  bypass7d: countWithin(bypass, 7),
196
216
  drift7d: countWithin(drift, 7),
@@ -200,6 +220,7 @@ export function computeStats() {
200
220
  philosophy: computePhilosophy(),
201
221
  solutionHealth: computeSolutionHealth(),
202
222
  topRules7d: computeTopRules7d(realBlocks),
223
+ precision7d: [...precisionByRule(violations, readVerdicts(), 7).values()].sort((a, b) => (b.correct + b.false_positive + b.unjudged) - (a.correct + a.false_positive + a.unjudged)).slice(0, 8),
203
224
  weeklyTrend: computeWeeklyTrend(realBlocks),
204
225
  };
205
226
  }
@@ -265,10 +286,13 @@ function computeTopRules7d(violations) {
265
286
  const ts = typeof v.at === 'string' ? Date.parse(v.at) : NaN;
266
287
  if (!Number.isFinite(ts) || ts < cutoff)
267
288
  continue;
268
- const rule = typeof v.rule === 'string' ? v.rule
269
- : typeof v.guard === 'string' ? v.guard
270
- : typeof v.source === 'string' ? v.source
271
- : 'unknown';
289
+ // ADR-017 D1 (critic 관찰): 이전엔 rule_id 를 보지 않아 'pre-tool-guard' 같은 source 로 집계돼
290
+ // 룰별 precision 과 조인되지 않았다. rule_id 우선.
291
+ const rule = typeof v.rule_id === 'string' ? v.rule_id
292
+ : typeof v.rule === 'string' ? v.rule
293
+ : typeof v.guard === 'string' ? v.guard
294
+ : typeof v.source === 'string' ? v.source
295
+ : 'unknown';
272
296
  counts.set(rule, (counts.get(rule) ?? 0) + 1);
273
297
  }
274
298
  return [...counts.entries()]
@@ -335,13 +359,15 @@ export function renderStats(s) {
335
359
  : '';
336
360
  lines.push(` Blocks ${padNum(s.blocks7d)} — times Claude was asked to retract ${ackRateLabel}`);
337
361
  lines.push(` Acknowledgments ${padNum(s.acks7d)} — block → retract → pass loops`);
338
- lines.push(` Bypass ${padNum(s.bypass7d)} — user overrides`);
362
+ lines.push(` Bypass (confirmed) ${padNum(s.bypass7d)} — FORGEN_USER_CONFIRMED=1 overrides (audited)`);
363
+ if (s.syntheticExcluded7d > 0)
364
+ lines.push(` Excluded ${padNum(s.syntheticExcluded7d)} — session-less records (tests/probes), not counted above`);
339
365
  lines.push(` Drift events ${padNum(s.drift7d)} — stuck-loop force-approves`);
340
366
  lines.push(` Retired rules ${padNum(s.retired7d)} — superseded or timed out`);
341
367
  lines.push('');
342
368
  // H3: Assist 축 — enforcement 옆에 나란히 가시화.
343
369
  lines.push(' Today (assist)');
344
- lines.push(` Recall hits ${padNum(s.assistToday.recallHits)} — compound 매칭 시도 수`);
370
+ lines.push(` Recall hits ${padNum(s.assistToday.recallHits)} — 후보가 나온 recall (hook 시도 ${s.assistToday.recallAttempts} · mcp ${s.assistToday.recallMcp})`);
345
371
  lines.push(` Surfaced ${padNum(s.assistToday.surfaced)} — 실제 주입된 솔루션 수`);
346
372
  const ratio = s.assistToday.surfaced > 0
347
373
  ? ` (${Math.round(100 * s.assistToday.referenced / s.assistToday.surfaced)}% referenced)`
@@ -383,12 +409,20 @@ export function renderStats(s) {
383
409
  lines.push(` Utilization (7d) ${Math.round(sh.utilization7d * 100)}% — matched at least once`);
384
410
  lines.push('');
385
411
  }
386
- // v0.5.0: Top rules (7d)
412
+ // v0.5.0: Top rules (7d) + ADR-017 D1 precision
387
413
  if (s.topRules7d.length > 0) {
388
- lines.push(' Top rules (7d)');
414
+ lines.push(' Top rules (7d) precision (judged / unjudged)');
415
+ const adviseRules = new Set(loadAllRules().filter((r) => r.enforce_mode === 'advise').map((r) => r.rule_id));
416
+ const pmap = new Map(s.precision7d.map((p) => [p.rule_id, p]));
389
417
  for (const r of s.topRules7d) {
390
- lines.push(` ${padNum(r.count)}x ${r.name}`);
418
+ const p = pmap.get(r.name);
419
+ const prec = !p ? '' : p.precision === null ? ` — (0 / ${p.unjudged})` : ` ${Math.round(p.precision * 100)}% (${p.correct + p.false_positive} / ${p.unjudged})`;
420
+ const advise = adviseRules.has(r.name) ? ' [advise]' : '';
421
+ lines.push(` ${padNum(r.count)}x ${r.name.padEnd(28).slice(0, 28)}${prec}${advise}`);
391
422
  }
423
+ const unjudged = s.precision7d.reduce((n, p) => n + p.unjudged, 0);
424
+ if (unjudged > 0)
425
+ lines.push(` ${C_DIM}unjudged ${unjudged} — 자동 판정(Haiku) 은 compound consent 가 켜져 있을 때만 돕니다: forgen compound consent on${C_RESET}`);
392
426
  lines.push('');
393
427
  }
394
428
  // v0.5.0: Weekly trend
@@ -12,9 +12,26 @@
12
12
  * forgen status --rules 활성 룰
13
13
  * forgen status --blocks [N] 최근 차단 N건 (rule·사유·해결)
14
14
  * forgen status --live 실시간 훅 이벤트 스트림
15
+ * forgen status --turn 이번 턴 관련 룰 + 각 룰의 원 교정 (ADR-017 D2)
15
16
  */
16
- declare const VIEWS: readonly ['--compound', '--profile', '--rules', '--blocks', '--live', '--overview'];
17
+ import type { Rule } from '../store/types.js';
18
+ import type { TurnRulesFile } from '../engine/rule-relevance.js';
19
+ declare const VIEWS: readonly ['--compound', '--profile', '--rules', '--blocks', '--live', '--overview', '--turn'];
17
20
  type View = (typeof VIEWS)[number];
18
21
  export declare function resolveView(args: string[]): View | null;
19
22
  export declare function handleStatus(args: string[]): Promise<void>;
23
+ type OriginLookup = (rule: Rule) => {
24
+ date: string;
25
+ kind?: string;
26
+ quote: string;
27
+ quoteSource: 'user' | 'summary' | 'none';
28
+ } | null;
29
+ /**
30
+ * 한 줄: `[category/strength] policy (score) — 출처: 2026-09-30 당신의 말 (avoid-this): "…"`.
31
+ * 출처 문구는 rule-origin.originLine 과 같은 규칙(사용자 원문 > 모델 요약 > 날짜·kind 만)이되 접두사 없이.
32
+ * 채굴 룰(behavior_inference)은 사용자가 한 말이 아니므로 "채굴 룰" 로만 표기한다.
33
+ */
34
+ export declare function formatTurnRuleLine(rule: Rule, score: number, origin: OriginLookup): string;
35
+ /** 순수 렌더 — 테스트용. file 이 null 이거나 관련 룰이 0이면 한 줄("이번 턴 관련 룰 없음"). */
36
+ export declare function renderTurnRules(file: TurnRulesFile | null, allRules: readonly Rule[], origin: OriginLookup): string[];
20
37
  export {};