@wooojin/forgen 0.5.9 → 0.6.2

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 (66) hide show
  1. package/.claude-plugin/plugin.json +1 -1
  2. package/CHANGELOG.md +76 -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 +66 -13
  23. package/dist/core/statusline-cli.js +182 -203
  24. package/dist/core/v1-bootstrap.js +7 -1
  25. package/dist/engine/block-judge-cli.d.ts +2 -0
  26. package/dist/engine/block-judge-cli.js +11 -0
  27. package/dist/engine/block-judge.d.ts +68 -0
  28. package/dist/engine/block-judge.js +248 -0
  29. package/dist/engine/correction-cluster-runner.d.ts +67 -0
  30. package/dist/engine/correction-cluster-runner.js +242 -5
  31. package/dist/engine/correction-clustering.d.ts +15 -0
  32. package/dist/engine/correction-clustering.js +24 -0
  33. package/dist/engine/lifecycle/lifecycle-cli.js +7 -4
  34. package/dist/engine/lifecycle/signals.d.ts +59 -2
  35. package/dist/engine/lifecycle/signals.js +193 -4
  36. package/dist/engine/lifecycle/trigger-t3-bypass.d.ts +5 -3
  37. package/dist/engine/lifecycle/trigger-t3-bypass.js +6 -4
  38. package/dist/engine/lifecycle/types.d.ts +29 -1
  39. package/dist/engine/mined-rule-merge-cli.d.ts +11 -0
  40. package/dist/engine/mined-rule-merge-cli.js +67 -0
  41. package/dist/engine/rule-relevance.d.ts +72 -0
  42. package/dist/engine/rule-relevance.js +183 -0
  43. package/dist/engine/rule-toggle-cli.d.ts +5 -0
  44. package/dist/engine/rule-toggle-cli.js +30 -0
  45. package/dist/fgx.js +1 -1
  46. package/dist/forge/evidence-processor.js +2 -0
  47. package/dist/hooks/post-tool-use.js +9 -14
  48. package/dist/hooks/pre-tool-use.js +71 -8
  49. package/dist/hooks/shared/command-parser.d.ts +11 -0
  50. package/dist/hooks/shared/command-parser.js +120 -0
  51. package/dist/hooks/solution-injector.js +13 -0
  52. package/dist/hooks/stop-guard.d.ts +18 -0
  53. package/dist/hooks/stop-guard.js +55 -10
  54. package/dist/mcp/tools.js +7 -1
  55. package/dist/renderer/inspect-renderer.js +23 -6
  56. package/dist/renderer/rule-renderer.js +4 -2
  57. package/dist/store/evidence-store.js +37 -2
  58. package/dist/store/profile-score.d.ts +55 -0
  59. package/dist/store/profile-score.js +100 -0
  60. package/dist/store/profile-store.d.ts +22 -5
  61. package/dist/store/profile-store.js +42 -6
  62. package/dist/store/rule-origin.d.ts +39 -0
  63. package/dist/store/rule-origin.js +84 -0
  64. package/dist/store/types.d.ts +24 -0
  65. package/package.json +1 -1
  66. package/plugin.json +1 -1
@@ -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 {};
@@ -12,8 +12,9 @@
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
- const VIEWS = ['--compound', '--profile', '--rules', '--blocks', '--live', '--overview'];
17
+ const VIEWS = ['--compound', '--profile', '--rules', '--blocks', '--live', '--overview', '--turn'];
17
18
  const ALIASES = {
18
19
  '-c': '--compound',
19
20
  '-p': '--profile',
@@ -21,6 +22,7 @@ const ALIASES = {
21
22
  '-b': '--blocks',
22
23
  '-l': '--live',
23
24
  '-o': '--overview',
25
+ '-t': '--turn',
24
26
  };
25
27
  export function resolveView(args) {
26
28
  for (const a of args) {
@@ -84,13 +86,24 @@ export async function handleStatus(args) {
84
86
  await handleDashboard();
85
87
  return;
86
88
  }
89
+ case '--turn': {
90
+ // ADR-017 D2: 현재 세션(FORGEN_SESSION_ID, 없으면 가장 최근 turn-rules 파일)의 관련 룰 + 원 교정.
91
+ const { readTurnRules, resolveTurnRulesSession } = await import('../engine/rule-relevance.js');
92
+ const { loadAllRules } = await import('../store/rule-store.js');
93
+ const { ruleOrigin } = await import('../store/rule-origin.js');
94
+ const session = resolveTurnRulesSession(process.env.FORGEN_SESSION_ID);
95
+ const file = session ? readTurnRules(session) : null;
96
+ for (const line of renderTurnRules(file, loadAllRules(), ruleOrigin))
97
+ console.log(line);
98
+ return;
99
+ }
87
100
  default: {
88
101
  // 요약: health 헤더 + one-screen stats (둘 다 computeStats() 기반).
89
102
  const { computeHealth, renderHealthLine } = await import('./health-cli.js');
90
103
  const { computeStats, renderStats } = await import('./stats-cli.js');
91
104
  console.log(renderHealthLine(computeHealth()));
92
105
  console.log(renderStats(computeStats()));
93
- console.log(` ${dim('views:')} forgen status --compound | --profile | --rules | --blocks [N] | --live`);
106
+ console.log(` ${dim('views:')} forgen status --compound | --profile | --rules | --blocks [N] | --live | --turn`);
94
107
  return;
95
108
  }
96
109
  }
@@ -98,3 +111,39 @@ export async function handleStatus(args) {
98
111
  function dim(s) {
99
112
  return `\x1b[2m${s}\x1b[0m`;
100
113
  }
114
+ /**
115
+ * 한 줄: `[category/strength] policy (score) — 출처: 2026-09-30 당신의 말 (avoid-this): "…"`.
116
+ * 출처 문구는 rule-origin.originLine 과 같은 규칙(사용자 원문 > 모델 요약 > 날짜·kind 만)이되 접두사 없이.
117
+ * 채굴 룰(behavior_inference)은 사용자가 한 말이 아니므로 "채굴 룰" 로만 표기한다.
118
+ */
119
+ export function formatTurnRuleLine(rule, score, origin) {
120
+ const head = `[${rule.category}/${rule.strength}] ${rule.policy} (${score.toFixed(1)})`;
121
+ const o = origin(rule);
122
+ if (!o)
123
+ return rule.source === 'behavior_inference' ? `${head} — 채굴 룰` : head;
124
+ const kind = o.kind ? ` (${o.kind})` : '';
125
+ if (o.quoteSource === 'user')
126
+ return `${head} — 출처: ${o.date} 당신의 말${kind}: "${o.quote}"`;
127
+ if (o.quoteSource === 'summary')
128
+ return `${head} — 출처: ${o.date} 교정 기록${kind}: "${o.quote}"`;
129
+ return `${head} — 출처: ${o.date} 교정 기록${kind}`;
130
+ }
131
+ /** 순수 렌더 — 테스트용. file 이 null 이거나 관련 룰이 0이면 한 줄("이번 턴 관련 룰 없음"). */
132
+ export function renderTurnRules(file, allRules, origin) {
133
+ if (!file || file.rules.length === 0)
134
+ return ['이번 턴 관련 룰 없음'];
135
+ const byId = new Map(allRules.map((r) => [r.rule_id, r]));
136
+ const when = file.at ? ` · ${file.at.slice(0, 16).replace('T', ' ')}` : '';
137
+ const lines = [`이번 턴 관련 룰 ${file.rules.length} ${dim(`(세션 ${file.session_id.slice(0, 8)}${when} · 프롬프트 ${file.prompt_hash || '?'})`)}`];
138
+ for (const r of file.rules) {
139
+ const rule = byId.get(r.rule_id);
140
+ if (!rule) {
141
+ lines.push(` ${r.rule_id} (${r.score.toFixed(1)}) — 룰 파일 없음(삭제됨)`);
142
+ continue;
143
+ }
144
+ lines.push(` ${formatTurnRuleLine(rule, r.score, origin)}`);
145
+ if (r.matchedTerms.length > 0)
146
+ lines.push(` ${dim(`매칭: ${r.matchedTerms.join(', ')}`)}`);
147
+ }
148
+ return lines;
149
+ }
@@ -1,20 +1,73 @@
1
1
  /**
2
- * forgen statusline — Claude Code statusLine 명령
2
+ * forgen statusline — Claude Code statusLine 명령 (ADR-017 D4/D5 재설계, 2026-10-06)
3
3
  *
4
- * Claude Code는 statusLine.command를 주기적으로 호출하고 stdin에 JSON을 전달함.
5
- * 이 명령은 compact multi-line 형식으로 HUD 정보를 출력함.
4
+ * Claude Code 는 assistant 메시지마다(300ms 디바운스) statusLine.command 를 호출하고 stdin 에 JSON 을
5
+ * 준다 (공식: code.claude.com/docs/en/statusline — context_window / rate_limits / cost / model / workspace).
6
6
  *
7
- * Line 1: 모델 | cwd | git branch
8
- * Line 2: (TODO: context/usage — stdin spec 미확인으로 생략)
9
- * Line 3: CLAUDE.md count | rules count | MCPs count | hooks count
10
- * Line 4: (TODO: tool counts — 추적 인프라 없음)
11
- * Line 5: (TODO: active task — 추적 인프라 없음)
7
+ * 2줄 고정:
8
+ * 1줄 (사용자): 모델 · 경로(브랜치) · ctx 42%/1M · 5h 63% → 15:40 소진 (리셋 16:20) · 7d 21% → 리셋 … 여유 · $1.23
9
+ * 2줄 (forgen): 관련 룰 3 · 이 세션 차단 1 · 7d 차단 33 · surfaced 0 (turn-rules 파일 없으면 '룰 N' = 활성 수)
10
+ *
11
+ * 원칙 (ADR-017 §2): 출처 없는 숫자는 표시하지 않는다. 데이터가 없으면 세그먼트를 생략한다(자리 채우기 금지).
12
+ * 이전 3~4줄의 운영자 지표(recall/ROI/이모지 분포)는 `forgen status` 에 있고, CLAUDE.md·MCP·hook 카운트는
13
+ * **삭제**했다(MCP 카운트는 settings.json 만 읽어 0 으로 틀렸고, 어느 뷰에도 없다 — critic 정정). 사용량
14
+ * 세그먼트는 ADR-010 §2b 로 철수했으나 본 ADR 이 그 결정을 부분 supersede 한다(CC 가 stdin 으로 직접 제공).
15
+ *
16
+ * 캐시(critic SEV-2 반영): 1줄(사용자)은 매 호출 렌더(0.1s 이하). 2줄(forgen, computeStats 전체 스캔
17
+ * ~150ms)은 **세션별 별도 캐시 15초 TTL** — ctx% 가 메시지마다 바뀌어도 2줄 비용은 15초에 1회.
18
+ * 샘플 기록(D5)과 모델 캐시는 캐시와 무관하게 매 호출 수행.
19
+ */
20
+ import { type RateLimitsPayload, type Forecast } from './rate-limit-forecast.js';
21
+ /** 공식 statusline stdin 스키마의 부분집합 (2026-10 확인). 전부 optional — 구버전/다른 플랜은 비어 있을 수 있다. */
22
+ export interface StdinPayload {
23
+ session_id?: string;
24
+ model?: {
25
+ id?: string;
26
+ display_name?: string;
27
+ };
28
+ workspace?: {
29
+ current_dir?: string;
30
+ project_dir?: string;
31
+ };
32
+ context_window?: {
33
+ total_input_tokens?: number;
34
+ total_output_tokens?: number;
35
+ context_window_size?: number;
36
+ used_percentage?: number | null;
37
+ remaining_percentage?: number | null;
38
+ };
39
+ rate_limits?: RateLimitsPayload | null;
40
+ cost?: {
41
+ total_cost_usd?: number;
42
+ total_duration_ms?: number;
43
+ };
44
+ exceeds_200k_tokens?: boolean;
45
+ [key: string]: unknown;
46
+ }
47
+ /**
48
+ * stdin 페이로드 읽기 — 훅과 같은 이벤트 기반 리더(read-stdin.ts).
49
+ *
50
+ * 2026-10-07 실사용 관측에서 발견: Claude Code(Node)는 statusline 을 `stdio:'pipe'` 로 띄우므로 stdin 이
51
+ * **UNIX socketpair** 다. 이전 구현의 `fs.readFileSync('/dev/stdin')` 은 소켓에서 ENXIO 로 실패해 페이로드가
52
+ * 항상 `{}` 였다 — 0.5.9 부터 statusline 은 세션/모델/컨텍스트/한도를 한 번도 받은 적이 없었고, 셸 파이프로만
53
+ * 검증해 못 잡았다. (Node spawn 재현 테스트: tests/statusline-stdin-socket.test.ts)
12
54
  */
55
+ export declare function readStdinJson(): Promise<StdinPayload>;
56
+ /** 1줄: 사용자 정보. 데이터 없는 세그먼트는 생략. */
57
+ export declare function buildUserLine(payload: StdinPayload, cwd: string, forecasts: Partial<Record<'five_hour' | 'seven_day', Forecast>>, nowMs: number): string;
58
+ /** 2줄: forgen 정보. 전부 실측 카운터(computeStats = status 와 같은 기준). 실패 시 생략. */
59
+ export declare function buildForgenLine(sessionId: string | undefined): string | null;
60
+ export declare function cachePathFor(sessionId: string | undefined): string;
13
61
  /**
14
- * W1-2 (feature-audit 2026-07-21): forgen 가치 카운터 라인 — invisible 가치 가시화.
15
- * native 플랜/토큰 usage(→ /usage, W2에서 물러남)가 아니라 forgen *자체 활동량*을
16
- * 노출한다: recall 주입·surfaced·교정 캡처·ROI 강등·차단. 전부 computeStats()가 이미
17
- * 실측 중인 카운터라 조작 위험 0. computeStats 실패 시 라인 생략(fail-open).
62
+ * 렌더 — 1줄은 매번, 2줄은 세션별 15초 캐시. 파일 샘플은 기울기 전용이고 **표시는 현재 페이로드에 있는
63
+ * 창만** (critic SEV-1: 옛 샘플을 현재값처럼 보여주지 않는다).
64
+ * @param opts.currentAlreadyAppended handleStatuslineWith 가 이번 샘플을 파일에 이미 append 했으면 true
65
+ * (중복 카운트 방지).
18
66
  */
19
- export declare function buildValueLine(): string | null;
67
+ export declare function renderStatusline(payload: StdinPayload, nowMs?: number, opts?: {
68
+ useForgenCache?: boolean;
69
+ currentAlreadyAppended?: boolean;
70
+ }): string[];
20
71
  export declare function handleStatusline(): Promise<void>;
72
+ /** stdin 읽기를 분리한 본체 — 테스트는 페이로드를 직접 넣는다. */
73
+ export declare function handleStatuslineWith(payload: StdinPayload, nowMs?: number): Promise<void>;