@wooojin/forgen 0.6.1 → 0.6.3

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.
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "$schema": "https://claude.ai/schemas/claude-plugin.json",
3
3
  "name": "forgen",
4
- "version": "0.6.1",
4
+ "version": "0.6.3",
5
5
  "description": "Claude Code harness — the more you use Claude, the better it gets",
6
6
  "author": {
7
7
  "name": "jang-ujin",
package/CHANGELOG.md CHANGED
@@ -7,6 +7,28 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
7
7
 
8
8
  ## [Unreleased]
9
9
 
10
+ ## [0.6.3] — 2026-10-07 — statusline 3줄 + 바 그래프 (오너 피드백)
11
+
12
+ ### Changed
13
+ - **statusline 을 3줄로.** 1줄 `Fable │ ~/proj(main)`, 2줄 `ctx ▓▓▓▓▓▓░░░░ 58%/1M │ 5h ▓▓▓░░░░░░░ 32% (리셋 03:55) │
14
+ 7d ▓▓▓▓▓░░░░░ 48% (리셋 D+1 …) │ $3.20`, 3줄 `forgen │ 관련 룰 4 │ 차단 11 (7d 38) │ surfaced 0`. 숫자 나열은 눈에
15
+ 안 들어온다는 피드백 → 10칸 바(80% 노랑, 95% 빨강), 구분자 `│`, 리셋 전 소진 예상은 빨간 `⚠ HH:MM 소진`. 사용량 데이터가
16
+ 없는 환경(API 키 등)에선 2줄이 생략된다.
17
+ - `exceeds_200k_tokens` 는 창이 200k 보다 크면(1M) 흐린 `200k+` 상태 표시만, 200k 창에서 넘겼을 때만 `⚠200k` 경고.
18
+
19
+ ## [0.6.2] — 2026-10-07 — statusline 이 실제로는 페이로드를 한 번도 받지 못하고 있었다 (socketpair stdin)
20
+
21
+ ### Fixed
22
+ - **`forgen statusline` 이 Claude Code 가 주는 stdin JSON 을 0.5.9 부터 단 한 번도 읽지 못했다.** Claude Code(Node)는
23
+ statusline 을 `stdio:'pipe'` 로 띄우고 Linux 에서 그 stdin 은 UNIX **socketpair** 인데, 구현이 `fs.readFileSync('/dev/stdin')`
24
+ 으로 읽어 소켓에서 ENXIO 로 실패 → 페이로드가 항상 `{}` → 모델명 'Claude', 세션 없음(`statusline-cache-nosession`),
25
+ 컨텍스트·한도·소진 예측·관련 룰·세션 모델 캐시 전부 공백. 셸 파이프(`echo … | forgen statusline`)로만 검증해 v0.6.0/0.6.1
26
+ 까지 못 잡았고, 배포 후 15시간 실사용 관측(한도 샘플 1건·세션 캐시 nosession 만 갱신)으로 드러났다. 훅과 같은 이벤트
27
+ 기반 리더(`read-stdin.ts`, idle/timeout)로 교체. Node `spawn` 으로 socketpair 경로를 그대로 재현하는 회귀 테스트 추가
28
+ (지연 도착·EOF 없음·빈 페이로드 포함).
29
+ - 부수: 세션별 모델 캐시(`current-model-<session>.json`)가 이제야 실제로 기록되므로, 측정된 모델(Opus 4.8 등)에서
30
+ 완료 가드가 advise 모드로 동작하는 ADR-010 W4-3 경로도 이번에 처음 live 가 된다.
31
+
10
32
  ## [0.6.1] — 2026-10-06 — 핫픽스: 임시 경로 예외가 CI(루트 디렉터리 부재)에서 전부 false 이던 것 · self-gate 테스트 픽스처
11
33
 
12
34
  ### Fixed
@@ -4,9 +4,10 @@
4
4
  * Claude Code 는 assistant 메시지마다(300ms 디바운스) statusLine.command 를 호출하고 stdin 에 JSON 을
5
5
  * 준다 (공식: code.claude.com/docs/en/statusline — context_window / rate_limits / cost / model / workspace).
6
6
  *
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' = 활성 수)
7
+ * 3줄 (오너 요청 2026-10-07):
8
+ * 1줄: Fable │ ~/proj(main)
9
+ * 2줄: ctx ▓▓▓▓░░░░░░ 42%/1M │ 5h ▓▓▓▓▓▓░░░░ 63% ⚠ 15:40 소진 (리셋 16:20) │ 7d ▓▓░░░░░░░░ 21% │ $1.23 (데이터 없으면 생략)
10
+ * 3줄: forgen │ 관련 룰 3 │ 차단 1 (7d 33) │ surfaced 0 (turn-rules 파일 없으면 '룰 N' = 활성 수)
10
11
  *
11
12
  * 원칙 (ADR-017 §2): 출처 없는 숫자는 표시하지 않는다. 데이터가 없으면 세그먼트를 생략한다(자리 채우기 금지).
12
13
  * 이전 3~4줄의 운영자 지표(recall/ROI/이모지 분포)는 `forgen status` 에 있고, CLAUDE.md·MCP·hook 카운트는
@@ -18,6 +19,8 @@
18
19
  * 샘플 기록(D5)과 모델 캐시는 캐시와 무관하게 매 호출 수행.
19
20
  */
20
21
  import { type RateLimitsPayload, type Forecast } from './rate-limit-forecast.js';
22
+ /** 0~100 → ▓▓▓░░░░░░░ (10칸). 색은 pctColor(80 노랑/95 빨강, 그 외 초록). 오너 요청(2026-10-07): 숫자만으론 눈에 안 들어온다. */
23
+ export declare function bar(pct: number, cells?: number): string;
21
24
  /** 공식 statusline stdin 스키마의 부분집합 (2026-10 확인). 전부 optional — 구버전/다른 플랜은 비어 있을 수 있다. */
22
25
  export interface StdinPayload {
23
26
  session_id?: string;
@@ -44,9 +47,26 @@ export interface StdinPayload {
44
47
  exceeds_200k_tokens?: boolean;
45
48
  [key: string]: unknown;
46
49
  }
47
- export declare function readStdinJson(): StdinPayload;
48
- /** 1줄: 사용자 정보. 데이터 없는 세그먼트는 생략. */
50
+ /**
51
+ * stdin 페이로드 읽기 — 훅과 같은 이벤트 기반 리더(read-stdin.ts).
52
+ *
53
+ * 2026-10-07 실사용 관측에서 발견: Claude Code(Node)는 statusline 을 `stdio:'pipe'` 로 띄우므로 stdin 이
54
+ * **UNIX socketpair** 다. 이전 구현의 `fs.readFileSync('/dev/stdin')` 은 소켓에서 ENXIO 로 실패해 페이로드가
55
+ * 항상 `{}` 였다 — 0.5.9 부터 statusline 은 세션/모델/컨텍스트/한도를 한 번도 받은 적이 없었고, 셸 파이프로만
56
+ * 검증해 못 잡았다. (Node spawn 재현 테스트: tests/statusline-stdin-socket.test.ts)
57
+ */
58
+ export declare function readStdinJson(): Promise<StdinPayload>;
59
+ /** 1줄: 모델 │ 경로(브랜치). */
60
+ export declare function buildHeaderLine(payload: StdinPayload, cwd: string): string;
61
+ /** 2줄: ctx · 5h · 7d · $ (바 그래프). 데이터 없는 세그먼트는 생략, 전부 없으면 null. */
62
+ export declare function buildUsageLine(payload: StdinPayload, forecasts: Partial<Record<'five_hour' | 'seven_day', Forecast>>, nowMs: number): string | null;
63
+ /** @deprecated 2줄 시절 호환 — 헤더+사용량을 한 줄로. 테스트·외부 호출용. */
49
64
  export declare function buildUserLine(payload: StdinPayload, cwd: string, forecasts: Partial<Record<'five_hour' | 'seven_day', Forecast>>, nowMs: number): string;
65
+ /**
66
+ * 한도 세그먼트: `5h ▓▓▓░░░░░░░ 29% (리셋 04:00)` / 소진 예상 `5h ▓▓▓▓▓▓▓░░░ 72% ⚠ 03:40 소진 (리셋 04:00)`
67
+ * / 여유 `… → 리셋 04:00 여유 (예상 81%)`. 예측 근거 부족이면 사용률+리셋만.
68
+ */
69
+ export declare function fmtLimitSegment(f: Forecast, nowMs: number): string;
50
70
  /** 2줄: forgen 정보. 전부 실측 카운터(computeStats = status 와 같은 기준). 실패 시 생략. */
51
71
  export declare function buildForgenLine(sessionId: string | undefined): string | null;
52
72
  export declare function cachePathFor(sessionId: string | undefined): string;
@@ -4,9 +4,10 @@
4
4
  * Claude Code 는 assistant 메시지마다(300ms 디바운스) statusLine.command 를 호출하고 stdin 에 JSON 을
5
5
  * 준다 (공식: code.claude.com/docs/en/statusline — context_window / rate_limits / cost / model / workspace).
6
6
  *
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' = 활성 수)
7
+ * 3줄 (오너 요청 2026-10-07):
8
+ * 1줄: Fable │ ~/proj(main)
9
+ * 2줄: ctx ▓▓▓▓░░░░░░ 42%/1M │ 5h ▓▓▓▓▓▓░░░░ 63% ⚠ 15:40 소진 (리셋 16:20) │ 7d ▓▓░░░░░░░░ 21% │ $1.23 (데이터 없으면 생략)
10
+ * 3줄: forgen │ 관련 룰 3 │ 차단 1 (7d 33) │ surfaced 0 (turn-rules 파일 없으면 '룰 N' = 활성 수)
10
11
  *
11
12
  * 원칙 (ADR-017 §2): 출처 없는 숫자는 표시하지 않는다. 데이터가 없으면 세그먼트를 생략한다(자리 채우기 금지).
12
13
  * 이전 3~4줄의 운영자 지표(recall/ROI/이모지 분포)는 `forgen status` 에 있고, CLAUDE.md·MCP·hook 카운트는
@@ -27,7 +28,7 @@ import { computeStats } from './stats-cli.js';
27
28
  import { isRealBlock } from '../engine/lifecycle/signals.js';
28
29
  import { sanitizeId } from '../hooks/shared/sanitize-id.js';
29
30
  import { readTurnRules } from '../engine/rule-relevance.js';
30
- import { samplesFromPayload, appendSamples, readSamples, compactSamples, forecastAll, fmtForecast, } from './rate-limit-forecast.js';
31
+ import { samplesFromPayload, appendSamples, readSamples, compactSamples, forecastAll, fmtClock, } from './rate-limit-forecast.js';
31
32
  const FORGEN_LINE_TTL_MS = 15_000;
32
33
  // ANSI codes
33
34
  const DIM = '\x1b[2m';
@@ -37,17 +38,42 @@ const YELLOW = '\x1b[33m';
37
38
  const RED = '\x1b[31m';
38
39
  const BOLD = '\x1b[1m';
39
40
  const RESET = '\x1b[0m';
40
- const SEP = `${DIM} · ${RESET}`;
41
- export function readStdinJson() {
41
+ const SEP = `${DIM} │ ${RESET}`;
42
+ const BAR_CELLS = 10;
43
+ /** 0~100 → ▓▓▓░░░░░░░ (10칸). 색은 pctColor(80 노랑/95 빨강, 그 외 초록). 오너 요청(2026-10-07): 숫자만으론 눈에 안 들어온다. */
44
+ export function bar(pct, cells = BAR_CELLS) {
45
+ const p = Math.max(0, Math.min(100, pct));
46
+ const filled = Math.round((p / 100) * cells);
47
+ const body = `${'▓'.repeat(filled)}${'░'.repeat(cells - filled)}`;
48
+ const color = pctColor(p) || GREEN;
49
+ return `${color}${body}${RESET}`;
50
+ }
51
+ /**
52
+ * stdin 페이로드 읽기 — 훅과 같은 이벤트 기반 리더(read-stdin.ts).
53
+ *
54
+ * 2026-10-07 실사용 관측에서 발견: Claude Code(Node)는 statusline 을 `stdio:'pipe'` 로 띄우므로 stdin 이
55
+ * **UNIX socketpair** 다. 이전 구현의 `fs.readFileSync('/dev/stdin')` 은 소켓에서 ENXIO 로 실패해 페이로드가
56
+ * 항상 `{}` 였다 — 0.5.9 부터 statusline 은 세션/모델/컨텍스트/한도를 한 번도 받은 적이 없었고, 셸 파이프로만
57
+ * 검증해 못 잡았다. (Node spawn 재현 테스트: tests/statusline-stdin-socket.test.ts)
58
+ */
59
+ export async function readStdinJson() {
42
60
  if (process.stdin.isTTY)
43
61
  return {};
44
62
  try {
45
- const raw = fs.readFileSync('/dev/stdin', 'utf-8').trim();
46
- if (!raw)
47
- return {};
48
- return JSON.parse(raw);
63
+ const { readStdinJSON } = await import('../hooks/shared/read-stdin.js');
64
+ const parsed = await readStdinJSON(1500);
65
+ // 부모(Claude Code)가 stdin 을 닫지 않아도 프로세스가 EOF 를 기다리며 남지 않도록 핸들을 놓는다.
66
+ try {
67
+ process.stdin.destroy();
68
+ }
69
+ catch { /* ignore */ }
70
+ return parsed && typeof parsed === 'object' ? parsed : {};
49
71
  }
50
72
  catch {
73
+ try {
74
+ process.stdin.destroy();
75
+ }
76
+ catch { /* ignore */ }
51
77
  return {};
52
78
  }
53
79
  }
@@ -87,18 +113,26 @@ function fmtWindowSize(size) {
87
113
  return `/${Math.round(size / 1_000_000)}M`;
88
114
  return `/${Math.round(size / 1000)}k`;
89
115
  }
90
- /** 1줄: 사용자 정보. 데이터 없는 세그먼트는 생략. */
91
- export function buildUserLine(payload, cwd, forecasts, nowMs) {
92
- const parts = [];
93
- parts.push(`${BOLD}${CYAN}${payload.model?.display_name ?? 'Claude'}${RESET}`);
116
+ /** 1줄: 모델 │ 경로(브랜치). */
117
+ export function buildHeaderLine(payload, cwd) {
94
118
  const branch = getGitBranch(cwd);
95
119
  const cwdDisplay = cwd.replace(os.homedir(), '~');
96
- parts.push(`${DIM}${cwdDisplay}${RESET}${branch ? `${GREEN}(${branch})${RESET}` : ''}`);
120
+ return [
121
+ `${BOLD}${CYAN}${payload.model?.display_name ?? 'Claude'}${RESET}`,
122
+ `${DIM}${cwdDisplay}${RESET}${branch ? `${GREEN}(${branch})${RESET}` : ''}`,
123
+ ].join(SEP);
124
+ }
125
+ /** 2줄: ctx · 5h · 7d · $ (바 그래프). 데이터 없는 세그먼트는 생략, 전부 없으면 null. */
126
+ export function buildUsageLine(payload, forecasts, nowMs) {
127
+ const parts = [];
97
128
  const cw = payload.context_window;
98
- const warn200k = payload.exceeds_200k_tokens ? `${YELLOW}⚠200k${RESET}` : '';
129
+ // exceeds_200k_tokens 는 창 크기와 무관한 고정 임계(공식 문서). 1M 창에선 위험이 아니라 상태이므로 흐리게 '200k+',
130
+ // 창이 200k 이하일 때만(= 창을 꽉 채운 것) ⚠ 경고. (오너 질문 2026-10-07)
131
+ const bigWindow = isNum(cw?.context_window_size) && (cw?.context_window_size ?? 0) > 200_000;
132
+ const warn200k = payload.exceeds_200k_tokens ? (bigWindow ? `${DIM}200k+${RESET}` : `${YELLOW}⚠200k${RESET}`) : '';
99
133
  if (cw && isNum(cw.used_percentage)) {
100
134
  const pct = Math.round(cw.used_percentage);
101
- parts.push(`${colored(`ctx ${pct}%${fmtWindowSize(cw.context_window_size)}`, pctColor(pct))}${warn200k ? ` ${warn200k}` : ''}`);
135
+ parts.push(`${BOLD}ctx${RESET} ${bar(pct)} ${colored(`${pct}%`, pctColor(pct))}${DIM}${fmtWindowSize(cw.context_window_size)}${RESET}${warn200k ? ` ${warn200k}` : ''}`);
102
136
  }
103
137
  else if (warn200k) {
104
138
  parts.push(warn200k); // used_percentage 가 null(세션 초반)이어도 경고는 유지
@@ -107,15 +141,34 @@ export function buildUserLine(payload, cwd, forecasts, nowMs) {
107
141
  const f = forecasts[w];
108
142
  if (!f)
109
143
  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));
144
+ parts.push(fmtLimitSegment(f, nowMs));
114
145
  }
115
146
  if (payload.cost && isNum(payload.cost.total_cost_usd)) {
116
147
  parts.push(`${DIM}$${payload.cost.total_cost_usd.toFixed(2)}${RESET}`);
117
148
  }
118
- return parts.join(SEP);
149
+ return parts.length ? parts.join(SEP) : null;
150
+ }
151
+ /** @deprecated 2줄 시절 호환 — 헤더+사용량을 한 줄로. 테스트·외부 호출용. */
152
+ export function buildUserLine(payload, cwd, forecasts, nowMs) {
153
+ const usage = buildUsageLine(payload, forecasts, nowMs);
154
+ return usage ? `${buildHeaderLine(payload, cwd)}${SEP}${usage}` : buildHeaderLine(payload, cwd);
155
+ }
156
+ /**
157
+ * 한도 세그먼트: `5h ▓▓▓░░░░░░░ 29% (리셋 04:00)` / 소진 예상 `5h ▓▓▓▓▓▓▓░░░ 72% ⚠ 03:40 소진 (리셋 04:00)`
158
+ * / 여유 `… → 리셋 04:00 여유 (예상 81%)`. 예측 근거 부족이면 사용률+리셋만.
159
+ */
160
+ export function fmtLimitSegment(f, nowMs) {
161
+ const label = f.window === 'five_hour' ? '5h' : '7d';
162
+ const pct = Math.round(f.used);
163
+ const reset = f.resetsAt !== null ? `리셋 ${fmtClock(f.resetsAt, nowMs)}` : '';
164
+ let tail = reset ? `${DIM}(${reset})${RESET}` : '';
165
+ if (f.exhaustAt !== null) {
166
+ if (f.exhaustsBeforeReset)
167
+ tail = `${RED}⚠ ${fmtClock(f.exhaustAt, nowMs)} 소진${RESET}${reset ? ` ${DIM}(${reset})${RESET}` : ''}`;
168
+ else if (reset)
169
+ tail = `${DIM}→ ${reset} 여유${f.projectedAtReset !== null ? ` (예상 ${Math.round(f.projectedAtReset)}%)` : ''}${RESET}`;
170
+ }
171
+ return `${BOLD}${label}${RESET} ${bar(pct)} ${colored(`${pct}%`, pctColor(pct))}${tail ? ` ${tail}` : ''}`;
119
172
  }
120
173
  /** 2줄: forgen 정보. 전부 실측 카운터(computeStats = status 와 같은 기준). 실패 시 생략. */
121
174
  export function buildForgenLine(sessionId) {
@@ -135,14 +188,15 @@ export function buildForgenLine(sessionId) {
135
188
  } })();
136
189
  const s = computeStats();
137
190
  const sessionBlocks = sessionId ? countSessionBlocks(sessionId) : null;
138
- const parts = [];
191
+ const parts = [`${BOLD}${CYAN}forgen${RESET}`];
139
192
  if (turnRelevant !== null)
140
193
  parts.push(`${DIM}관련 룰${RESET} ${turnRelevant}`);
141
194
  else if (rules !== null)
142
195
  parts.push(`${DIM}룰${RESET} ${rules}`);
143
196
  if (sessionBlocks !== null)
144
- parts.push(`${DIM}이 세션 차단${RESET} ${sessionBlocks > 0 ? colored(String(sessionBlocks), YELLOW) : '0'}`);
145
- parts.push(`${DIM}7d 차단${RESET} ${s.blocks7d}`);
197
+ parts.push(`${DIM}차단${RESET} ${sessionBlocks > 0 ? colored(String(sessionBlocks), YELLOW) : '0'} ${DIM}(7d ${s.blocks7d})${RESET}`);
198
+ else
199
+ parts.push(`${DIM}7d 차단${RESET} ${s.blocks7d}`);
146
200
  parts.push(`${DIM}surfaced${RESET} ${s.assistToday.surfaced}`);
147
201
  return parts.join(SEP);
148
202
  }
@@ -208,7 +262,11 @@ export function renderStatusline(payload, nowMs = Date.now(), opts = {}) {
208
262
  const history = readSamples(undefined, nowMs);
209
263
  const all = opts.currentAlreadyAppended ? history : [...history, ...current];
210
264
  const forecasts = forecastAll(all, nowMs, current);
211
- const lines = [buildUserLine(payload, cwd, forecasts, nowMs)];
265
+ // 오너 요청(2026-10-07): 3줄 — 모델·경로 / 사용량 바 / forgen.
266
+ const lines = [buildHeaderLine(payload, cwd)];
267
+ const usage = buildUsageLine(payload, forecasts, nowMs);
268
+ if (usage)
269
+ lines.push(usage);
212
270
  let forgenLine = opts.useForgenCache ? readForgenLineCached(payload.session_id, nowMs) : null;
213
271
  if (forgenLine === null) {
214
272
  forgenLine = buildForgenLine(payload.session_id);
@@ -220,7 +278,7 @@ export function renderStatusline(payload, nowMs = Date.now(), opts = {}) {
220
278
  return lines;
221
279
  }
222
280
  export async function handleStatusline() {
223
- await handleStatuslineWith(readStdinJson());
281
+ await handleStatuslineWith(await readStdinJson());
224
282
  }
225
283
  /** stdin 읽기를 분리한 본체 — 테스트는 페이로드를 직접 넣는다. */
226
284
  export async function handleStatuslineWith(payload, nowMs = Date.now()) {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@wooojin/forgen",
3
- "version": "0.6.1",
3
+ "version": "0.6.3",
4
4
  "preferGlobal": true,
5
5
  "main": "dist/lib.js",
6
6
  "types": "./dist/lib.d.ts",
package/plugin.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "$schema": "https://claude.ai/schemas/claude-plugin.json",
3
3
  "name": "forgen",
4
- "version": "0.6.1",
4
+ "version": "0.6.3",
5
5
  "description": "Claude Code harness — the more you use Claude, the better it gets",
6
6
  "author": {
7
7
  "name": "jang-ujin",