@wooojin/forgen 0.5.9 → 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 (66) hide show
  1. package/.claude-plugin/plugin.json +1 -1
  2. package/CHANGELOG.md +63 -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/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
@@ -1,14 +1,21 @@
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)과 모델 캐시는 캐시와 무관하게 매 호출 수행.
12
19
  */
13
20
  import * as fs from 'node:fs';
14
21
  import * as path from 'node:path';
@@ -16,23 +23,22 @@ import * as os from 'node:os';
16
23
  import { execSync } from 'node:child_process';
17
24
  import { loadActiveRules } from '../store/rule-store.js';
18
25
  import { STATE_DIR } from './paths.js';
19
- import { classifySolutions } from './lifecycle-classifier.js';
20
26
  import { computeStats } from './stats-cli.js';
21
- import { loadRoiDemotions } from '../engine/roi-demotion.js';
22
- // 0.4.6 perf #13 — statusline 출력을 5초 캐싱.
23
- // claude statusLine 은 짧은 간격으로 재호출되는데 매번 git/find/rule-store 를
24
- // 실행하면 ~100ms 누적. CACHE_TTL_MS 동안 동일 출력 재사용.
25
- const STATUSLINE_CACHE_PATH = path.join(STATE_DIR, 'statusline-cache.txt');
26
- const CACHE_TTL_MS = 5_000;
27
+ import { isRealBlock } from '../engine/lifecycle/signals.js';
28
+ import { sanitizeId } from '../hooks/shared/sanitize-id.js';
29
+ import { readTurnRules } from '../engine/rule-relevance.js';
30
+ import { samplesFromPayload, appendSamples, readSamples, compactSamples, forecastAll, fmtForecast, } from './rate-limit-forecast.js';
31
+ const FORGEN_LINE_TTL_MS = 15_000;
27
32
  // ANSI codes
28
33
  const DIM = '\x1b[2m';
29
34
  const CYAN = '\x1b[36m';
30
35
  const GREEN = '\x1b[32m';
31
36
  const YELLOW = '\x1b[33m';
37
+ const RED = '\x1b[31m';
32
38
  const BOLD = '\x1b[1m';
33
39
  const RESET = '\x1b[0m';
34
- function readStdinJson() {
35
- // stdin이 TTY면 파이프 입력 없음 → 빈 payload로 fallback
40
+ const SEP = `${DIM} · ${RESET}`;
41
+ export function readStdinJson() {
36
42
  if (process.stdin.isTTY)
37
43
  return {};
38
44
  try {
@@ -47,236 +53,193 @@ function readStdinJson() {
47
53
  }
48
54
  function getGitBranch(cwd) {
49
55
  try {
50
- const branch = execSync('git rev-parse --abbrev-ref HEAD', {
51
- cwd,
52
- stdio: ['ignore', 'pipe', 'ignore'],
53
- timeout: 2000,
54
- })
55
- .toString()
56
- .trim();
56
+ const branch = execSync('git rev-parse --abbrev-ref HEAD', { cwd, stdio: ['ignore', 'pipe', 'ignore'], timeout: 2000 }).toString().trim();
57
57
  const isDirty = (() => {
58
58
  try {
59
- const status = execSync('git status --porcelain', {
60
- cwd,
61
- stdio: ['ignore', 'pipe', 'ignore'],
62
- timeout: 2000,
63
- }).toString().trim();
64
- return status.length > 0;
59
+ return execSync('git status --porcelain', { cwd, stdio: ['ignore', 'pipe', 'ignore'], timeout: 2000 }).toString().trim().length > 0;
65
60
  }
66
61
  catch {
67
62
  return false;
68
63
  }
69
64
  })();
70
- return `git:(${branch}${isDirty ? '*' : ''})`;
65
+ return `${branch}${isDirty ? '*' : ''}`;
71
66
  }
72
67
  catch {
73
68
  return '';
74
69
  }
75
70
  }
76
- function getSettingsJson(claudeDir) {
77
- const settingsPath = path.join(claudeDir, 'settings.json');
78
- if (!fs.existsSync(settingsPath))
79
- return {};
80
- try {
81
- return JSON.parse(fs.readFileSync(settingsPath, 'utf-8'));
82
- }
83
- catch {
84
- return {};
85
- }
86
- }
87
- function countMcps(settings) {
88
- const mcpServers = settings.mcpServers;
89
- if (!mcpServers || typeof mcpServers !== 'object')
90
- return 0;
91
- return Object.keys(mcpServers).length;
71
+ const isNum = (v) => typeof v === 'number' && Number.isFinite(v);
72
+ /** 한도/컨텍스트 공통 색: ≥95 빨강, ≥80 노랑, 그 외 기본. */
73
+ function pctColor(pct) {
74
+ if (pct >= 95)
75
+ return RED;
76
+ if (pct >= 80)
77
+ return YELLOW;
78
+ return '';
92
79
  }
93
- function countHooks(settings) {
94
- const hooks = settings.hooks;
95
- if (!hooks || typeof hooks !== 'object')
96
- return 0;
97
- return Object.values(hooks).reduce((acc, matchers) => {
98
- if (!Array.isArray(matchers))
99
- return acc;
100
- return acc + matchers.length;
101
- }, 0);
80
+ function colored(text, color) {
81
+ return color ? `${color}${text}${RESET}` : text;
102
82
  }
103
- function countClaudeMd(cwd) {
104
- try {
105
- const result = execSync('find . -maxdepth 2 -name CLAUDE.md', {
106
- cwd,
107
- stdio: ['ignore', 'pipe', 'ignore'],
108
- timeout: 3000,
109
- }).toString().trim();
110
- if (!result)
111
- return 0;
112
- return result.split('\n').filter(Boolean).length;
113
- }
114
- catch {
115
- return 0;
116
- }
83
+ function fmtWindowSize(size) {
84
+ if (!isNum(size) || size <= 0)
85
+ return '';
86
+ if (size >= 1_000_000)
87
+ return `/${Math.round(size / 1_000_000)}M`;
88
+ return `/${Math.round(size / 1000)}k`;
117
89
  }
118
- function buildLine1(payload, cwd) {
119
- const modelName = payload.model?.display_name ?? 'Claude';
120
- const gitBranch = getGitBranch(cwd);
90
+ /** 1줄: 사용자 정보. 데이터 없는 세그먼트는 생략. */
91
+ export function buildUserLine(payload, cwd, forecasts, nowMs) {
92
+ const parts = [];
93
+ parts.push(`${BOLD}${CYAN}${payload.model?.display_name ?? 'Claude'}${RESET}`);
94
+ const branch = getGitBranch(cwd);
121
95
  const cwdDisplay = cwd.replace(os.homedir(), '~');
122
- const parts = [`${BOLD}${CYAN}${modelName}${RESET}`];
123
- parts.push(`${DIM}${cwdDisplay}${RESET}`);
124
- if (gitBranch)
125
- parts.push(`${GREEN}${gitBranch}${RESET}`);
126
- return parts.join(` ${DIM}|${RESET} `);
96
+ parts.push(`${DIM}${cwdDisplay}${RESET}${branch ? `${GREEN}(${branch})${RESET}` : ''}`);
97
+ const cw = payload.context_window;
98
+ const warn200k = payload.exceeds_200k_tokens ? `${YELLOW}⚠200k${RESET}` : '';
99
+ if (cw && isNum(cw.used_percentage)) {
100
+ const pct = Math.round(cw.used_percentage);
101
+ parts.push(`${colored(`ctx ${pct}%${fmtWindowSize(cw.context_window_size)}`, pctColor(pct))}${warn200k ? ` ${warn200k}` : ''}`);
102
+ }
103
+ else if (warn200k) {
104
+ parts.push(warn200k); // used_percentage 가 null(세션 초반)이어도 경고는 유지
105
+ }
106
+ for (const w of ['five_hour', 'seven_day']) {
107
+ const f = forecasts[w];
108
+ if (!f)
109
+ continue;
110
+ const text = fmtForecast(f, nowMs);
111
+ // 리셋 전 소진 예상이면 사용률과 무관하게 최소 노랑.
112
+ const color = f.exhaustsBeforeReset ? (pctColor(f.used) || YELLOW) : pctColor(f.used);
113
+ parts.push(colored(text, color));
114
+ }
115
+ if (payload.cost && isNum(payload.cost.total_cost_usd)) {
116
+ parts.push(`${DIM}$${payload.cost.total_cost_usd.toFixed(2)}${RESET}`);
117
+ }
118
+ return parts.join(SEP);
127
119
  }
128
- /** Build lifecycle line: "🔥X 🟡X 🥶X 💀X 🌱X" — P3 신설. 0건이면 null */
129
- function buildLifecycleLine() {
120
+ /** 2줄: forgen 정보. 전부 실측 카운터(computeStats = status 와 같은 기준). 실패 시 생략. */
121
+ export function buildForgenLine(sessionId) {
130
122
  try {
131
- const classified = classifySolutions();
132
- if (classified.length === 0)
123
+ const rules = (() => { try {
124
+ return loadActiveRules().length;
125
+ }
126
+ catch {
133
127
  return null;
134
- const counts = { hot: 0, warm: 0, cold: 0, dead: 0, new: 0 };
135
- for (const c of classified)
136
- counts[c.lifecycle]++;
137
- const total = counts.hot + counts.warm + counts.cold + counts.dead + counts.new;
138
- if (total === 0)
128
+ } })();
129
+ // ADR-017 D2: 이 세션의 최신 턴 관련 룰 수(solution-injector 가 기록). 파일 부재·손상이면 활성 룰 수로 폴백.
130
+ const turnRelevant = (() => { try {
131
+ return sessionId ? readTurnRules(sessionId)?.rules.length ?? null : null;
132
+ }
133
+ catch {
139
134
  return null;
140
- return [
141
- `${YELLOW}🔥${counts.hot}${RESET}`,
142
- `${YELLOW}🟡${counts.warm}${RESET}`,
143
- `${DIM}🥶${counts.cold}${RESET}`,
144
- `${DIM}💀${counts.dead}${RESET}`,
145
- `${DIM}🌱${counts.new}${RESET}`,
146
- ].join(` `);
135
+ } })();
136
+ const s = computeStats();
137
+ const sessionBlocks = sessionId ? countSessionBlocks(sessionId) : null;
138
+ const parts = [];
139
+ if (turnRelevant !== null)
140
+ parts.push(`${DIM}관련 룰${RESET} ${turnRelevant}`);
141
+ else if (rules !== null)
142
+ parts.push(`${DIM}룰${RESET} ${rules}`);
143
+ if (sessionBlocks !== null)
144
+ parts.push(`${DIM}이 세션 차단${RESET} ${sessionBlocks > 0 ? colored(String(sessionBlocks), YELLOW) : '0'}`);
145
+ parts.push(`${DIM}7d 차단${RESET} ${s.blocks7d}`);
146
+ parts.push(`${DIM}surfaced${RESET} ${s.assistToday.surfaced}`);
147
+ return parts.join(SEP);
147
148
  }
148
149
  catch {
149
150
  return null;
150
151
  }
151
152
  }
152
- /**
153
- * ADR-010 W2-2: 사용량 세그먼트("📊 N/5h · N/wk") 제거 — native /usage 가
154
- * plan limit 를 정확히 분해한다. 이관 사실을 딱 1회만 공지 (state flag).
155
- */
156
- function buildUsageLine() {
153
+ function countSessionBlocks(sessionId) {
157
154
  try {
158
- const noticeFlag = path.join(STATE_DIR, 'usage-notice-shown');
159
- if (!fs.existsSync(noticeFlag)) {
160
- fs.mkdirSync(STATE_DIR, { recursive: true });
161
- fs.writeFileSync(noticeFlag, new Date().toISOString());
162
- return `${DIM}ℹ 사용량 표시는 native /usage 로 이동했습니다 (이 안내는 1회만 표시)${RESET}`;
155
+ const p = path.join(STATE_DIR, 'enforcement', 'violations.jsonl');
156
+ if (!fs.existsSync(p))
157
+ return 0;
158
+ let n = 0;
159
+ for (const line of fs.readFileSync(p, 'utf-8').split('\n')) {
160
+ if (!line.includes(sessionId))
161
+ continue; // 빠른 선별
162
+ try {
163
+ const e = JSON.parse(line);
164
+ if (e.session_id === sessionId && isRealBlock(e))
165
+ n++;
166
+ }
167
+ catch { /* skip */ }
163
168
  }
164
- return null;
169
+ return n;
165
170
  }
166
171
  catch {
167
- return null;
172
+ return 0;
168
173
  }
169
174
  }
170
- /**
171
- * W1-2 (feature-audit 2026-07-21): forgen 가치 카운터 라인 — invisible 가치 가시화.
172
- * native 플랜/토큰 usage(→ /usage, W2에서 물러남)가 아니라 forgen *자체 활동량*을
173
- * 노출한다: recall 주입·surfaced·교정 캡처·ROI 강등·차단. 전부 computeStats()가 이미
174
- * 실측 중인 카운터라 조작 위험 0. computeStats 실패 시 라인 생략(fail-open).
175
- */
176
- export function buildValueLine() {
175
+ // ── 세션별 2줄(forgen) 캐시 ──
176
+ export function cachePathFor(sessionId) {
177
+ return path.join(STATE_DIR, `statusline-cache-${sessionId ? sanitizeId(sessionId) : 'nosession'}.txt`);
178
+ }
179
+ function readForgenLineCached(sessionId, nowMs) {
180
+ const p = cachePathFor(sessionId);
177
181
  try {
178
- let roiDemoted = 0;
179
- try {
180
- roiDemoted = Object.keys(loadRoiDemotions()).length;
181
- }
182
- catch { /* roi store 없음 → 0 */ }
183
- const s = computeStats();
184
- const a = s.assistToday;
185
- const parts = [
186
- `${YELLOW}✦${RESET}`,
187
- `${DIM}recall${RESET} ${a.recallHits}`,
188
- `${DIM}surfaced${RESET} ${a.surfaced}`,
189
- `${DIM}교정${RESET} +${s.corrections7d}${DIM}(7d)${RESET}`,
190
- `${DIM}ROI↓${RESET} ${roiDemoted}`,
191
- `${DIM}차단${RESET} ${s.blocks7d}${DIM}(7d)${RESET}`,
192
- ];
193
- return parts.join(` ${DIM}·${RESET} `);
182
+ const st = fs.statSync(p);
183
+ if (nowMs - st.mtimeMs >= FORGEN_LINE_TTL_MS)
184
+ return null;
185
+ const body = fs.readFileSync(p, 'utf-8').replace(/\n$/, '');
186
+ return body || null;
194
187
  }
195
188
  catch {
196
189
  return null;
197
190
  }
198
191
  }
199
- function buildLine3(claudeDir, cwd) {
200
- const settings = getSettingsJson(claudeDir);
201
- const claudeMdCount = countClaudeMd(cwd);
202
- const rulesCount = (() => {
203
- try {
204
- return loadActiveRules().length;
205
- }
206
- catch {
207
- return 0;
208
- }
209
- })();
210
- const mcpCount = countMcps(settings);
211
- const hookCount = countHooks(settings);
212
- return [
213
- `${YELLOW}${claudeMdCount} CLAUDE.md${RESET}`,
214
- `${YELLOW}${rulesCount} rules${RESET}`,
215
- `${YELLOW}${mcpCount} MCPs${RESET}`,
216
- `${YELLOW}${hookCount} hooks${RESET}`,
217
- ].join(` ${DIM}|${RESET} `);
218
- }
219
- /** 0.4.6 perf #13: cached output if fresh. */
220
- function readCacheIfFresh() {
221
- try {
222
- const stat = fs.statSync(STATUSLINE_CACHE_PATH);
223
- if (Date.now() - stat.mtimeMs < CACHE_TTL_MS) {
224
- return fs.readFileSync(STATUSLINE_CACHE_PATH, 'utf-8');
225
- }
226
- }
227
- catch { /* no cache or stale */ }
228
- return null;
229
- }
230
- function writeCache(content) {
192
+ function writeForgenLineCache(sessionId, line) {
231
193
  try {
232
194
  fs.mkdirSync(STATE_DIR, { recursive: true });
233
- fs.writeFileSync(STATUSLINE_CACHE_PATH, content);
195
+ fs.writeFileSync(cachePathFor(sessionId), `${line}\n`);
234
196
  }
235
197
  catch { /* fail-open */ }
236
198
  }
199
+ /**
200
+ * 렌더 — 1줄은 매번, 2줄은 세션별 15초 캐시. 파일 샘플은 기울기 전용이고 **표시는 현재 페이로드에 있는
201
+ * 창만** (critic SEV-1: 옛 샘플을 현재값처럼 보여주지 않는다).
202
+ * @param opts.currentAlreadyAppended handleStatuslineWith 가 이번 샘플을 파일에 이미 append 했으면 true
203
+ * (중복 카운트 방지).
204
+ */
205
+ export function renderStatusline(payload, nowMs = Date.now(), opts = {}) {
206
+ const cwd = payload.workspace?.current_dir ?? process.cwd();
207
+ const current = samplesFromPayload(payload.rate_limits, nowMs);
208
+ const history = readSamples(undefined, nowMs);
209
+ const all = opts.currentAlreadyAppended ? history : [...history, ...current];
210
+ const forecasts = forecastAll(all, nowMs, current);
211
+ const lines = [buildUserLine(payload, cwd, forecasts, nowMs)];
212
+ let forgenLine = opts.useForgenCache ? readForgenLineCached(payload.session_id, nowMs) : null;
213
+ if (forgenLine === null) {
214
+ forgenLine = buildForgenLine(payload.session_id);
215
+ if (forgenLine && opts.useForgenCache)
216
+ writeForgenLineCache(payload.session_id, forgenLine);
217
+ }
218
+ if (forgenLine)
219
+ lines.push(forgenLine);
220
+ return lines;
221
+ }
237
222
  export async function handleStatusline() {
238
- // W4-3 (ADR-010): hook stdin 엔 모델 필드가 없으므로 statusline 이 세션별
239
- // 모델을 캐시 → Stop/SubagentStop 가드가 per-model 프로필 조회에 사용.
240
- // 리뷰 SEV-2: 이 기록은 반드시 5초 표시-캐시 early-return **앞**에 있어야
241
- // 한다 — /model 로 세션 중 모델을 바꾸면 cache-hit 렌더가 payload 를 아예
242
- // 안 읽어 stale 모델(잘못된 가드 모드)이 유지되는 창이 생긴다.
243
- // 필드 부재(구버전 CC 등) 시 기록 안 함 = 가드는 'unknown' → block 유지.
244
- const payload = readStdinJson();
223
+ await handleStatuslineWith(readStdinJson());
224
+ }
225
+ /** stdin 읽기를 분리한 본체 — 테스트는 페이로드를 직접 넣는다. */
226
+ export async function handleStatuslineWith(payload, nowMs = Date.now()) {
227
+ // (1) 세션별 모델 캐시 — Stop/SubagentStop 가드의 per-model 프로필 조회용. 캐시 판정 앞.
245
228
  if (payload.session_id && payload.model?.id) {
246
229
  const { cacheSessionModel } = await import('../checks/_shared/model-profile.js');
247
230
  const { sanitizeId } = await import('../hooks/shared/sanitize-id.js');
248
231
  cacheSessionModel(sanitizeId(payload.session_id), payload.model.id);
249
232
  }
250
- // 캐시 hit 시 표시만 캐시에서 (5초 윈도우 내 동일 출력 가정).
251
- // 라인 단위 cache → console.log 라인별 (테스트 호환).
252
- const cached = readCacheIfFresh();
253
- if (cached !== null) {
254
- for (const line of cached.split('\n').filter(Boolean))
255
- console.log(line);
256
- return;
257
- }
258
- const cwd = payload.workspace?.current_dir ?? process.cwd();
259
- const claudeDir = path.join(os.homedir(), '.claude');
260
- const line1 = buildLine1(payload, cwd);
261
- const line3 = buildLine3(claudeDir, cwd);
262
- const usageLine = buildUsageLine();
263
- const valueLine = buildValueLine(); // W1-2: forgen 가치 카운터
264
- const lifecycleLine = buildLifecycleLine();
265
- console.log(line1);
266
- console.log(line3);
267
- if (usageLine)
268
- console.log(usageLine);
269
- if (valueLine)
270
- console.log(valueLine);
271
- if (lifecycleLine)
272
- console.log(lifecycleLine);
273
- // W2-2: 1회 공지(usageLine)는 캐시에 넣지 않는다 — 캐시 재생 시
274
- // "1회만" 약속이 5초 창 동안 반복 위반되는 실측 버그 방지.
275
- const cacheLines = [line1, line3];
276
- if (valueLine)
277
- cacheLines.push(valueLine);
278
- if (lifecycleLine)
279
- cacheLines.push(lifecycleLine);
280
- const cacheBody = `${cacheLines.join('\n')}\n`;
281
- writeCache(cacheBody);
233
+ // (2) D5 샘플 기록 — 매 호출. 압축은 **append 앞**에서(critic r2: append 직후면 mtime 이 항상 신선해
234
+ // 정적 가드가 영원히 막혔다). 크기 ≥256KB·60초 정적일 때만 재작성, 2% 확률.
235
+ const samples = samplesFromPayload(payload.rate_limits, nowMs);
236
+ if (samples.length > 0) {
237
+ if (Math.random() < 0.02)
238
+ compactSamples(undefined, nowMs);
239
+ appendSamples(samples);
240
+ }
241
+ // (3) 렌더 — 1줄 매번, 2줄 15초 캐시
242
+ const lines = renderStatusline(payload, nowMs, { useForgenCache: true, currentAlreadyAppended: samples.length > 0 });
243
+ for (const line of lines)
244
+ console.log(line);
282
245
  }
@@ -18,7 +18,7 @@ import * as crypto from 'node:crypto';
18
18
  import { FORGEN_HOME, ME_DIR, ME_RULES, ME_BEHAVIOR, V1_RECOMMENDATIONS_DIR, V1_SESSIONS_DIR, STATE_DIR, V1_RAW_LOGS_DIR, ME_SOLUTIONS, SESSIONS_DIR } from './paths.js';
19
19
  import { checkLegacyProfile, runLegacyCutover } from './legacy-detector.js';
20
20
  import { detectRuntimeCapability } from './runtime-detector.js';
21
- import { backupCorruptProfile, loadProfile, profileExists } from '../store/profile-store.js';
21
+ import { backupCorruptProfile, loadProfile, profileExists, recomputeIfNeverReclassified } from '../store/profile-store.js';
22
22
  import { loadActiveRules, cleanupStaleSessionRules, markRulesInjected } from '../store/rule-store.js';
23
23
  import { composeSession } from '../preset/preset-manager.js';
24
24
  import { renderRules, DEFAULT_CONTEXT } from '../renderer/rule-renderer.js';
@@ -62,6 +62,12 @@ export function bootstrapV1Session() {
62
62
  mismatch: null,
63
63
  };
64
64
  }
65
+ // ADR-017 §6-8: score 산출 로직이 없던 버전의 프로필(last_reclassification_at=null)은
66
+ // 세션 시작 시 1회 재계산. 이미 계산된 프로필은 no-op. fail-open.
67
+ try {
68
+ recomputeIfNeverReclassified();
69
+ }
70
+ catch { /* fail-open */ }
65
71
  const profile = loadProfile();
66
72
  if (!profile) {
67
73
  // v0.4.8 — corrupt/invalid profile auto-repair.
@@ -0,0 +1,2 @@
1
+ #!/usr/bin/env node
2
+ export {};
@@ -0,0 +1,11 @@
1
+ #!/usr/bin/env node
2
+ /**
3
+ * block-judge-cli — detached 자동 판정 프로세스 진입점 (ADR-017 D1).
4
+ * 사용: node dist/engine/block-judge-cli.js <violation_id>
5
+ * 훅이 spawn 하며 결과는 verdicts.jsonl 에만 남긴다. 어떤 경우에도 exit 0.
6
+ */
7
+ import { judgeViolation } from './block-judge.js';
8
+ const id = process.argv[2];
9
+ if (!id)
10
+ process.exit(0);
11
+ judgeViolation(id).then(() => process.exit(0)).catch(() => process.exit(0));
@@ -0,0 +1,68 @@
1
+ /**
2
+ * Block judge — 차단 영수증 자동 판정 (ADR-017 D1, 오너 결정 "안 누를 것 같다 → 자동으로")
3
+ *
4
+ * 차단 직후 background 로 Haiku 에게 영수증(룰 policy + 출처 교정 + 매칭 프래그먼트 + 전후 문맥)을
5
+ * 보여 주고 `{verdict: correct|false_positive|unsure, reason}` 을 받아 verdicts.jsonl 에 by:'auto' 로
6
+ * 기록한다. 사용자 판정(`forgen block <id> --ok|--fp`)은 자동 판정을 덮어쓴다.
7
+ *
8
+ * 안전장치:
9
+ * - auto-compound 와 같은 consent(ADR-012, compound-consent) — 동의 없으면 아무것도 보내지 않는다.
10
+ * - 같은 execHost 경로 + FORGEN_NESTED_RUN 재귀 가드.
11
+ * - 비용 상한: 세션당 10건, 일 30건 (verdicts.jsonl 의 by:'auto' 기준).
12
+ * - 심판 실패·타임아웃·파싱 실패 → 'unsure'(미판정) 로 남긴다. 거짓 확신 금지.
13
+ * - precision 강등(enforce_mode:'advise')은 **하드 룰(strength 'hard')·builtin 에 적용하지 않는다**.
14
+ * 그 외 룰은 7d 판정 ≥ 5 이고 precision < 0.5 이면 advise 로 강등하고 알린다.
15
+ */
16
+ import type { ViolationEntry, Verdict } from './lifecycle/types.js';
17
+ export declare const JUDGE_MODEL = "haiku";
18
+ export declare const JUDGE_CAP_PER_SESSION = 10;
19
+ export declare const JUDGE_CAP_PER_DAY = 30;
20
+ export declare const DEMOTE_MIN_JUDGED = 5;
21
+ export declare const DEMOTE_PRECISION_BELOW = 0.5;
22
+ export declare const INFLIGHT_STALE_MS: number;
23
+ export declare function markInflight(violationId: string): void;
24
+ export declare function clearInflight(violationId: string): void;
25
+ export interface JudgeInput {
26
+ violation: ViolationEntry;
27
+ rulePolicy: string;
28
+ originLine: string;
29
+ receipt: string;
30
+ }
31
+ export interface JudgeOutput {
32
+ verdict: Verdict;
33
+ reason: string;
34
+ }
35
+ /** 영수증을 심판 프롬프트로. 전문은 2,000자로 자르고 매칭 프래그먼트 주변을 우선 보여준다. */
36
+ export declare function buildJudgePrompt(input: JudgeInput): string;
37
+ /** 매칭 프래그먼트 주변 ±3줄(ADR D1), 총 maxLen 자 상한. 매칭을 못 찾으면 앞부분만. */
38
+ export declare function excerptAround(text: string, matched: string, maxLen: number): string;
39
+ /** 모델 출력 파싱 — JSON 한 줄을 찾는다. 실패하면 unsure. */
40
+ export declare function parseJudgeOutput(raw: string): JudgeOutput;
41
+ /** 비용 상한 확인 — by:'auto' 판정 수 기준. */
42
+ export declare function withinJudgeCaps(sessionId: string, now?: number, verdicts?: import("./lifecycle/types.js").VerdictEntry[], violations?: ViolationEntry[], inflight?: string[]): boolean;
43
+ export declare function findViolation(violationId: string): ViolationEntry | null;
44
+ /**
45
+ * 한 건 판정 (동기, 호출자는 detached 프로세스). consent·캡 확인 → 프롬프트 → execHost(haiku) → 기록.
46
+ * 반환: 기록된 verdict 또는 null(스킵).
47
+ */
48
+ export declare function judgeViolation(violationId: string, deps?: {
49
+ exec?: (prompt: string) => Promise<string>;
50
+ consent?: () => boolean;
51
+ now?: number;
52
+ }): Promise<Verdict | null>;
53
+ /**
54
+ * precision 강등: 7d 판정 ≥ DEMOTE_MIN_JUDGED 이고 precision < DEMOTE_PRECISION_BELOW 이면 enforce_mode='advise'.
55
+ * 하드 룰·builtin 제외(ADR-017 D1). 이미 advise 면 no-op. 복귀는 사용자 명시(`forgen rule enforce <id>`).
56
+ */
57
+ export declare function maybeDemote(ruleId: string, now?: number): boolean;
58
+ /** 가장 최근 강등 기록(표시용). 없으면 null. */
59
+ export declare function lastDemotion(ruleId: string): {
60
+ at: string;
61
+ precision: number;
62
+ judged: number;
63
+ } | null;
64
+ /**
65
+ * 훅에서 호출: detached 로 심판 프로세스를 띄운다. 훅 지연 0. 조건 미충족이면 즉시 return.
66
+ * (consent 는 자식에서도 재확인하지만 여기서 먼저 걸러 불필요한 spawn 을 막는다.)
67
+ */
68
+ export declare function spawnBlockJudge(violationId: string, sessionId: string): boolean;