@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.
- package/.claude-plugin/plugin.json +1 -1
- package/CHANGELOG.md +76 -0
- package/README.ja.md +12 -0
- package/README.ko.md +12 -0
- package/README.md +12 -0
- package/README.zh.md +12 -0
- package/dist/checks/_shared/model-profile.d.ts +1 -1
- package/dist/checks/_shared/model-profile.js +9 -5
- package/dist/cli.js +32 -3
- package/dist/core/auto-compound-runner.js +20 -43
- package/dist/core/block-cli.d.ts +1 -0
- package/dist/core/block-cli.js +41 -0
- package/dist/core/explain-cli.js +29 -1
- package/dist/core/inspect-cli.js +9 -8
- package/dist/core/rate-limit-forecast.d.ts +113 -0
- package/dist/core/rate-limit-forecast.js +236 -0
- package/dist/core/state-gc.js +3 -0
- package/dist/core/stats-cli.d.ts +15 -0
- package/dist/core/stats-cli.js +50 -16
- package/dist/core/status-cli.d.ts +18 -1
- package/dist/core/status-cli.js +51 -2
- package/dist/core/statusline-cli.d.ts +66 -13
- package/dist/core/statusline-cli.js +182 -203
- package/dist/core/v1-bootstrap.js +7 -1
- package/dist/engine/block-judge-cli.d.ts +2 -0
- package/dist/engine/block-judge-cli.js +11 -0
- package/dist/engine/block-judge.d.ts +68 -0
- package/dist/engine/block-judge.js +248 -0
- package/dist/engine/correction-cluster-runner.d.ts +67 -0
- package/dist/engine/correction-cluster-runner.js +242 -5
- package/dist/engine/correction-clustering.d.ts +15 -0
- package/dist/engine/correction-clustering.js +24 -0
- package/dist/engine/lifecycle/lifecycle-cli.js +7 -4
- package/dist/engine/lifecycle/signals.d.ts +59 -2
- package/dist/engine/lifecycle/signals.js +193 -4
- package/dist/engine/lifecycle/trigger-t3-bypass.d.ts +5 -3
- package/dist/engine/lifecycle/trigger-t3-bypass.js +6 -4
- package/dist/engine/lifecycle/types.d.ts +29 -1
- package/dist/engine/mined-rule-merge-cli.d.ts +11 -0
- package/dist/engine/mined-rule-merge-cli.js +67 -0
- package/dist/engine/rule-relevance.d.ts +72 -0
- package/dist/engine/rule-relevance.js +183 -0
- package/dist/engine/rule-toggle-cli.d.ts +5 -0
- package/dist/engine/rule-toggle-cli.js +30 -0
- package/dist/fgx.js +1 -1
- package/dist/forge/evidence-processor.js +2 -0
- package/dist/hooks/post-tool-use.js +9 -14
- package/dist/hooks/pre-tool-use.js +71 -8
- package/dist/hooks/shared/command-parser.d.ts +11 -0
- package/dist/hooks/shared/command-parser.js +120 -0
- package/dist/hooks/solution-injector.js +13 -0
- package/dist/hooks/stop-guard.d.ts +18 -0
- package/dist/hooks/stop-guard.js +55 -10
- package/dist/mcp/tools.js +7 -1
- package/dist/renderer/inspect-renderer.js +23 -6
- package/dist/renderer/rule-renderer.js +4 -2
- package/dist/store/evidence-store.js +37 -2
- package/dist/store/profile-score.d.ts +55 -0
- package/dist/store/profile-score.js +100 -0
- package/dist/store/profile-store.d.ts +22 -5
- package/dist/store/profile-store.js +42 -6
- package/dist/store/rule-origin.d.ts +39 -0
- package/dist/store/rule-origin.js +84 -0
- package/dist/store/types.d.ts +24 -0
- package/package.json +1 -1
- 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를
|
|
5
|
-
*
|
|
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
|
-
*
|
|
8
|
-
*
|
|
9
|
-
*
|
|
10
|
-
*
|
|
11
|
-
*
|
|
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,267 +23,239 @@ 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 {
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
const
|
|
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
|
-
|
|
35
|
-
|
|
40
|
+
const SEP = `${DIM} · ${RESET}`;
|
|
41
|
+
/**
|
|
42
|
+
* stdin 페이로드 읽기 — 훅과 같은 이벤트 기반 리더(read-stdin.ts).
|
|
43
|
+
*
|
|
44
|
+
* 2026-10-07 실사용 관측에서 발견: Claude Code(Node)는 statusline 을 `stdio:'pipe'` 로 띄우므로 stdin 이
|
|
45
|
+
* **UNIX socketpair** 다. 이전 구현의 `fs.readFileSync('/dev/stdin')` 은 소켓에서 ENXIO 로 실패해 페이로드가
|
|
46
|
+
* 항상 `{}` 였다 — 0.5.9 부터 statusline 은 세션/모델/컨텍스트/한도를 한 번도 받은 적이 없었고, 셸 파이프로만
|
|
47
|
+
* 검증해 못 잡았다. (Node spawn 재현 테스트: tests/statusline-stdin-socket.test.ts)
|
|
48
|
+
*/
|
|
49
|
+
export async function readStdinJson() {
|
|
36
50
|
if (process.stdin.isTTY)
|
|
37
51
|
return {};
|
|
38
52
|
try {
|
|
39
|
-
const
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
|
|
53
|
+
const { readStdinJSON } = await import('../hooks/shared/read-stdin.js');
|
|
54
|
+
const parsed = await readStdinJSON(1500);
|
|
55
|
+
// 부모(Claude Code)가 stdin 을 닫지 않아도 프로세스가 EOF 를 기다리며 남지 않도록 핸들을 놓는다.
|
|
56
|
+
try {
|
|
57
|
+
process.stdin.destroy();
|
|
58
|
+
}
|
|
59
|
+
catch { /* ignore */ }
|
|
60
|
+
return parsed && typeof parsed === 'object' ? parsed : {};
|
|
43
61
|
}
|
|
44
62
|
catch {
|
|
63
|
+
try {
|
|
64
|
+
process.stdin.destroy();
|
|
65
|
+
}
|
|
66
|
+
catch { /* ignore */ }
|
|
45
67
|
return {};
|
|
46
68
|
}
|
|
47
69
|
}
|
|
48
70
|
function getGitBranch(cwd) {
|
|
49
71
|
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();
|
|
72
|
+
const branch = execSync('git rev-parse --abbrev-ref HEAD', { cwd, stdio: ['ignore', 'pipe', 'ignore'], timeout: 2000 }).toString().trim();
|
|
57
73
|
const isDirty = (() => {
|
|
58
74
|
try {
|
|
59
|
-
|
|
60
|
-
cwd,
|
|
61
|
-
stdio: ['ignore', 'pipe', 'ignore'],
|
|
62
|
-
timeout: 2000,
|
|
63
|
-
}).toString().trim();
|
|
64
|
-
return status.length > 0;
|
|
75
|
+
return execSync('git status --porcelain', { cwd, stdio: ['ignore', 'pipe', 'ignore'], timeout: 2000 }).toString().trim().length > 0;
|
|
65
76
|
}
|
|
66
77
|
catch {
|
|
67
78
|
return false;
|
|
68
79
|
}
|
|
69
80
|
})();
|
|
70
|
-
return
|
|
81
|
+
return `${branch}${isDirty ? '*' : ''}`;
|
|
71
82
|
}
|
|
72
83
|
catch {
|
|
73
84
|
return '';
|
|
74
85
|
}
|
|
75
86
|
}
|
|
76
|
-
|
|
77
|
-
|
|
78
|
-
|
|
79
|
-
|
|
80
|
-
|
|
81
|
-
|
|
82
|
-
|
|
83
|
-
|
|
84
|
-
return {};
|
|
85
|
-
}
|
|
87
|
+
const isNum = (v) => typeof v === 'number' && Number.isFinite(v);
|
|
88
|
+
/** 한도/컨텍스트 공통 색: ≥95 빨강, ≥80 노랑, 그 외 기본. */
|
|
89
|
+
function pctColor(pct) {
|
|
90
|
+
if (pct >= 95)
|
|
91
|
+
return RED;
|
|
92
|
+
if (pct >= 80)
|
|
93
|
+
return YELLOW;
|
|
94
|
+
return '';
|
|
86
95
|
}
|
|
87
|
-
function
|
|
88
|
-
|
|
89
|
-
if (!mcpServers || typeof mcpServers !== 'object')
|
|
90
|
-
return 0;
|
|
91
|
-
return Object.keys(mcpServers).length;
|
|
96
|
+
function colored(text, color) {
|
|
97
|
+
return color ? `${color}${text}${RESET}` : text;
|
|
92
98
|
}
|
|
93
|
-
function
|
|
94
|
-
|
|
95
|
-
|
|
96
|
-
|
|
97
|
-
|
|
98
|
-
|
|
99
|
-
return acc;
|
|
100
|
-
return acc + matchers.length;
|
|
101
|
-
}, 0);
|
|
99
|
+
function fmtWindowSize(size) {
|
|
100
|
+
if (!isNum(size) || size <= 0)
|
|
101
|
+
return '';
|
|
102
|
+
if (size >= 1_000_000)
|
|
103
|
+
return `/${Math.round(size / 1_000_000)}M`;
|
|
104
|
+
return `/${Math.round(size / 1000)}k`;
|
|
102
105
|
}
|
|
103
|
-
|
|
104
|
-
|
|
105
|
-
|
|
106
|
-
|
|
107
|
-
|
|
108
|
-
|
|
109
|
-
|
|
110
|
-
|
|
111
|
-
|
|
112
|
-
|
|
106
|
+
/** 1줄: 사용자 정보. 데이터 없는 세그먼트는 생략. */
|
|
107
|
+
export function buildUserLine(payload, cwd, forecasts, nowMs) {
|
|
108
|
+
const parts = [];
|
|
109
|
+
parts.push(`${BOLD}${CYAN}${payload.model?.display_name ?? 'Claude'}${RESET}`);
|
|
110
|
+
const branch = getGitBranch(cwd);
|
|
111
|
+
const cwdDisplay = cwd.replace(os.homedir(), '~');
|
|
112
|
+
parts.push(`${DIM}${cwdDisplay}${RESET}${branch ? `${GREEN}(${branch})${RESET}` : ''}`);
|
|
113
|
+
const cw = payload.context_window;
|
|
114
|
+
const warn200k = payload.exceeds_200k_tokens ? `${YELLOW}⚠200k${RESET}` : '';
|
|
115
|
+
if (cw && isNum(cw.used_percentage)) {
|
|
116
|
+
const pct = Math.round(cw.used_percentage);
|
|
117
|
+
parts.push(`${colored(`ctx ${pct}%${fmtWindowSize(cw.context_window_size)}`, pctColor(pct))}${warn200k ? ` ${warn200k}` : ''}`);
|
|
113
118
|
}
|
|
114
|
-
|
|
115
|
-
|
|
119
|
+
else if (warn200k) {
|
|
120
|
+
parts.push(warn200k); // used_percentage 가 null(세션 초반)이어도 경고는 유지
|
|
116
121
|
}
|
|
122
|
+
for (const w of ['five_hour', 'seven_day']) {
|
|
123
|
+
const f = forecasts[w];
|
|
124
|
+
if (!f)
|
|
125
|
+
continue;
|
|
126
|
+
const text = fmtForecast(f, nowMs);
|
|
127
|
+
// 리셋 전 소진 예상이면 사용률과 무관하게 최소 노랑.
|
|
128
|
+
const color = f.exhaustsBeforeReset ? (pctColor(f.used) || YELLOW) : pctColor(f.used);
|
|
129
|
+
parts.push(colored(text, color));
|
|
130
|
+
}
|
|
131
|
+
if (payload.cost && isNum(payload.cost.total_cost_usd)) {
|
|
132
|
+
parts.push(`${DIM}$${payload.cost.total_cost_usd.toFixed(2)}${RESET}`);
|
|
133
|
+
}
|
|
134
|
+
return parts.join(SEP);
|
|
117
135
|
}
|
|
118
|
-
|
|
119
|
-
|
|
120
|
-
const gitBranch = getGitBranch(cwd);
|
|
121
|
-
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} `);
|
|
127
|
-
}
|
|
128
|
-
/** Build lifecycle line: "🔥X 🟡X 🥶X 💀X 🌱X" — P3 신설. 0건이면 null */
|
|
129
|
-
function buildLifecycleLine() {
|
|
136
|
+
/** 2줄: forgen 정보. 전부 실측 카운터(computeStats = status 와 같은 기준). 실패 시 생략. */
|
|
137
|
+
export function buildForgenLine(sessionId) {
|
|
130
138
|
try {
|
|
131
|
-
const
|
|
132
|
-
|
|
139
|
+
const rules = (() => { try {
|
|
140
|
+
return loadActiveRules().length;
|
|
141
|
+
}
|
|
142
|
+
catch {
|
|
133
143
|
return null;
|
|
134
|
-
|
|
135
|
-
|
|
136
|
-
|
|
137
|
-
|
|
138
|
-
|
|
144
|
+
} })();
|
|
145
|
+
// ADR-017 D2: 이 세션의 최신 턴 관련 룰 수(solution-injector 가 기록). 파일 부재·손상이면 활성 룰 수로 폴백.
|
|
146
|
+
const turnRelevant = (() => { try {
|
|
147
|
+
return sessionId ? readTurnRules(sessionId)?.rules.length ?? null : null;
|
|
148
|
+
}
|
|
149
|
+
catch {
|
|
139
150
|
return null;
|
|
140
|
-
|
|
141
|
-
|
|
142
|
-
|
|
143
|
-
|
|
144
|
-
|
|
145
|
-
`${DIM}
|
|
146
|
-
|
|
151
|
+
} })();
|
|
152
|
+
const s = computeStats();
|
|
153
|
+
const sessionBlocks = sessionId ? countSessionBlocks(sessionId) : null;
|
|
154
|
+
const parts = [];
|
|
155
|
+
if (turnRelevant !== null)
|
|
156
|
+
parts.push(`${DIM}관련 룰${RESET} ${turnRelevant}`);
|
|
157
|
+
else if (rules !== null)
|
|
158
|
+
parts.push(`${DIM}룰${RESET} ${rules}`);
|
|
159
|
+
if (sessionBlocks !== null)
|
|
160
|
+
parts.push(`${DIM}이 세션 차단${RESET} ${sessionBlocks > 0 ? colored(String(sessionBlocks), YELLOW) : '0'}`);
|
|
161
|
+
parts.push(`${DIM}7d 차단${RESET} ${s.blocks7d}`);
|
|
162
|
+
parts.push(`${DIM}surfaced${RESET} ${s.assistToday.surfaced}`);
|
|
163
|
+
return parts.join(SEP);
|
|
147
164
|
}
|
|
148
165
|
catch {
|
|
149
166
|
return null;
|
|
150
167
|
}
|
|
151
168
|
}
|
|
152
|
-
|
|
153
|
-
* ADR-010 W2-2: 사용량 세그먼트("📊 N/5h · N/wk") 제거 — native /usage 가
|
|
154
|
-
* plan limit 를 정확히 분해한다. 이관 사실을 딱 1회만 공지 (state flag).
|
|
155
|
-
*/
|
|
156
|
-
function buildUsageLine() {
|
|
169
|
+
function countSessionBlocks(sessionId) {
|
|
157
170
|
try {
|
|
158
|
-
const
|
|
159
|
-
if (!fs.existsSync(
|
|
160
|
-
|
|
161
|
-
|
|
162
|
-
|
|
171
|
+
const p = path.join(STATE_DIR, 'enforcement', 'violations.jsonl');
|
|
172
|
+
if (!fs.existsSync(p))
|
|
173
|
+
return 0;
|
|
174
|
+
let n = 0;
|
|
175
|
+
for (const line of fs.readFileSync(p, 'utf-8').split('\n')) {
|
|
176
|
+
if (!line.includes(sessionId))
|
|
177
|
+
continue; // 빠른 선별
|
|
178
|
+
try {
|
|
179
|
+
const e = JSON.parse(line);
|
|
180
|
+
if (e.session_id === sessionId && isRealBlock(e))
|
|
181
|
+
n++;
|
|
182
|
+
}
|
|
183
|
+
catch { /* skip */ }
|
|
163
184
|
}
|
|
164
|
-
return
|
|
185
|
+
return n;
|
|
165
186
|
}
|
|
166
187
|
catch {
|
|
167
|
-
return
|
|
188
|
+
return 0;
|
|
168
189
|
}
|
|
169
190
|
}
|
|
170
|
-
|
|
171
|
-
|
|
172
|
-
|
|
173
|
-
|
|
174
|
-
|
|
175
|
-
|
|
176
|
-
export function buildValueLine() {
|
|
191
|
+
// ── 세션별 2줄(forgen) 캐시 ──
|
|
192
|
+
export function cachePathFor(sessionId) {
|
|
193
|
+
return path.join(STATE_DIR, `statusline-cache-${sessionId ? sanitizeId(sessionId) : 'nosession'}.txt`);
|
|
194
|
+
}
|
|
195
|
+
function readForgenLineCached(sessionId, nowMs) {
|
|
196
|
+
const p = cachePathFor(sessionId);
|
|
177
197
|
try {
|
|
178
|
-
|
|
179
|
-
|
|
180
|
-
|
|
181
|
-
|
|
182
|
-
|
|
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} `);
|
|
198
|
+
const st = fs.statSync(p);
|
|
199
|
+
if (nowMs - st.mtimeMs >= FORGEN_LINE_TTL_MS)
|
|
200
|
+
return null;
|
|
201
|
+
const body = fs.readFileSync(p, 'utf-8').replace(/\n$/, '');
|
|
202
|
+
return body || null;
|
|
194
203
|
}
|
|
195
204
|
catch {
|
|
196
205
|
return null;
|
|
197
206
|
}
|
|
198
207
|
}
|
|
199
|
-
function
|
|
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) {
|
|
208
|
+
function writeForgenLineCache(sessionId, line) {
|
|
231
209
|
try {
|
|
232
210
|
fs.mkdirSync(STATE_DIR, { recursive: true });
|
|
233
|
-
fs.writeFileSync(
|
|
211
|
+
fs.writeFileSync(cachePathFor(sessionId), `${line}\n`);
|
|
234
212
|
}
|
|
235
213
|
catch { /* fail-open */ }
|
|
236
214
|
}
|
|
215
|
+
/**
|
|
216
|
+
* 렌더 — 1줄은 매번, 2줄은 세션별 15초 캐시. 파일 샘플은 기울기 전용이고 **표시는 현재 페이로드에 있는
|
|
217
|
+
* 창만** (critic SEV-1: 옛 샘플을 현재값처럼 보여주지 않는다).
|
|
218
|
+
* @param opts.currentAlreadyAppended handleStatuslineWith 가 이번 샘플을 파일에 이미 append 했으면 true
|
|
219
|
+
* (중복 카운트 방지).
|
|
220
|
+
*/
|
|
221
|
+
export function renderStatusline(payload, nowMs = Date.now(), opts = {}) {
|
|
222
|
+
const cwd = payload.workspace?.current_dir ?? process.cwd();
|
|
223
|
+
const current = samplesFromPayload(payload.rate_limits, nowMs);
|
|
224
|
+
const history = readSamples(undefined, nowMs);
|
|
225
|
+
const all = opts.currentAlreadyAppended ? history : [...history, ...current];
|
|
226
|
+
const forecasts = forecastAll(all, nowMs, current);
|
|
227
|
+
const lines = [buildUserLine(payload, cwd, forecasts, nowMs)];
|
|
228
|
+
let forgenLine = opts.useForgenCache ? readForgenLineCached(payload.session_id, nowMs) : null;
|
|
229
|
+
if (forgenLine === null) {
|
|
230
|
+
forgenLine = buildForgenLine(payload.session_id);
|
|
231
|
+
if (forgenLine && opts.useForgenCache)
|
|
232
|
+
writeForgenLineCache(payload.session_id, forgenLine);
|
|
233
|
+
}
|
|
234
|
+
if (forgenLine)
|
|
235
|
+
lines.push(forgenLine);
|
|
236
|
+
return lines;
|
|
237
|
+
}
|
|
237
238
|
export async function handleStatusline() {
|
|
238
|
-
|
|
239
|
-
|
|
240
|
-
|
|
241
|
-
|
|
242
|
-
//
|
|
243
|
-
// 필드 부재(구버전 CC 등) 시 기록 안 함 = 가드는 'unknown' → block 유지.
|
|
244
|
-
const payload = readStdinJson();
|
|
239
|
+
await handleStatuslineWith(await readStdinJson());
|
|
240
|
+
}
|
|
241
|
+
/** stdin 읽기를 분리한 본체 — 테스트는 페이로드를 직접 넣는다. */
|
|
242
|
+
export async function handleStatuslineWith(payload, nowMs = Date.now()) {
|
|
243
|
+
// (1) 세션별 모델 캐시 — Stop/SubagentStop 가드의 per-model 프로필 조회용. 캐시 판정 앞.
|
|
245
244
|
if (payload.session_id && payload.model?.id) {
|
|
246
245
|
const { cacheSessionModel } = await import('../checks/_shared/model-profile.js');
|
|
247
246
|
const { sanitizeId } = await import('../hooks/shared/sanitize-id.js');
|
|
248
247
|
cacheSessionModel(sanitizeId(payload.session_id), payload.model.id);
|
|
249
248
|
}
|
|
250
|
-
//
|
|
251
|
-
//
|
|
252
|
-
const
|
|
253
|
-
if (
|
|
254
|
-
|
|
255
|
-
|
|
256
|
-
|
|
249
|
+
// (2) D5 샘플 기록 — 매 호출. 압축은 **append 앞**에서(critic r2: append 직후면 mtime 이 항상 신선해
|
|
250
|
+
// 정적 가드가 영원히 막혔다). 크기 ≥256KB·60초 정적일 때만 재작성, 2% 확률.
|
|
251
|
+
const samples = samplesFromPayload(payload.rate_limits, nowMs);
|
|
252
|
+
if (samples.length > 0) {
|
|
253
|
+
if (Math.random() < 0.02)
|
|
254
|
+
compactSamples(undefined, nowMs);
|
|
255
|
+
appendSamples(samples);
|
|
257
256
|
}
|
|
258
|
-
|
|
259
|
-
const
|
|
260
|
-
const
|
|
261
|
-
|
|
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);
|
|
257
|
+
// (3) 렌더 — 1줄 매번, 2줄 15초 캐시
|
|
258
|
+
const lines = renderStatusline(payload, nowMs, { useForgenCache: true, currentAlreadyAppended: samples.length > 0 });
|
|
259
|
+
for (const line of lines)
|
|
260
|
+
console.log(line);
|
|
282
261
|
}
|
|
@@ -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,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;
|