@wooojin/forgen 0.6.2 → 0.6.4

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.2",
4
+ "version": "0.6.4",
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,32 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
7
7
 
8
8
  ## [Unreleased]
9
9
 
10
+ ## [0.6.4] — 2026-10-07 — 설치·실행 편의: statusline 자동 등록 · Codex 훅 재승인 제거(고정 shim) · Node 22 함정 안내
11
+
12
+ ### Added
13
+ - **statusline 자동 등록.** `npm i -g` 의 postinstall 이 `~/.claude/settings.json` 의 statusLine 을 이 패키지의 **절대 경로**
14
+ (`"<node>" "<pkg>/dist/cli.js" statusline`)로 등록한다 — PATH 의존 `forgen statusline` 은 nvm 버전마다 다른 바이너리를
15
+ 잡았다(실측: 0.4.8). 다른 명령(claude-hud 등)이 설정돼 있으면 건드리지 않고 안내만, 교체는 `forgen statusline install --force`
16
+ (기존 값은 `statusLine_backup` 에 보관). 켜져 있는 세션도 다음 메시지부터 반영. `forgen doctor` 에 Statusline 체크.
17
+ - **Codex 훅 고정 shim — 업그레이드·nvm 전환마다 `/hooks` 재승인하던 것 제거.** Codex 의 trust 해시는 명령 문자열 단위인데
18
+ 명령에 node·패키지 경로가 박혀 있어 경로가 바뀔 때마다 전부 `modified` 였다. 이제 훅 명령은 `"~/.codex/forgen-hook" "hooks/x.js"`
19
+ 로 고정되고 실제 위임 대상(node·패키지 경로)은 shim 파일 내용에만 있다. postinstall 이 shim 내용만 갱신하므로 hooks.json
20
+ 바이트(= trust)는 그대로. 도입 시 `forgen install codex` 1회 + 마지막 1회 trust 가 필요하고, 그 뒤로는 재승인 불필요.
21
+ POSIX sh shim(`exec`)이라 node 프로세스가 추가로 뜨지 않는다. Windows 는 기존 방식. uninstall 이 shim 도 제거.
22
+
23
+ ### Docs
24
+ - README 4개 언어: **Node 22 이상 필요** — Node 20 에서 `npm i -g @wooojin/forgen` 은 npm 이 `engines` 에 맞는 최신을 골라
25
+ 조용히 0.4.8 을 설치한다(실측). `forgen statusline install` 사용법.
26
+
27
+ ## [0.6.3] — 2026-10-07 — statusline 3줄 + 바 그래프 (오너 피드백)
28
+
29
+ ### Changed
30
+ - **statusline 을 3줄로.** 1줄 `Fable │ ~/proj(main)`, 2줄 `ctx ▓▓▓▓▓▓░░░░ 58%/1M │ 5h ▓▓▓░░░░░░░ 32% (리셋 03:55) │
31
+ 7d ▓▓▓▓▓░░░░░ 48% (리셋 D+1 …) │ $3.20`, 3줄 `forgen │ 관련 룰 4 │ 차단 11 (7d 38) │ surfaced 0`. 숫자 나열은 눈에
32
+ 안 들어온다는 피드백 → 10칸 바(80% 노랑, 95% 빨강), 구분자 `│`, 리셋 전 소진 예상은 빨간 `⚠ HH:MM 소진`. 사용량 데이터가
33
+ 없는 환경(API 키 등)에선 2줄이 생략된다.
34
+ - `exceeds_200k_tokens` 는 창이 200k 보다 크면(1M) 흐린 `200k+` 상태 표시만, 200k 창에서 넘겼을 때만 `⚠200k` 경고.
35
+
10
36
  ## [0.6.2] — 2026-10-07 — statusline 이 실제로는 페이로드를 한 번도 받지 못하고 있었다 (socketpair stdin)
11
37
 
12
38
  ### Fixed
package/README.ja.md CHANGED
@@ -127,6 +127,8 @@ npm install -g @wooojin/forgen
127
127
  forgen
128
128
  ```
129
129
 
130
+ > **Node 22 以上が必要。** Node 20 で `npm i -g @wooojin/forgen` を実行すると、npm が `engines` に合う最新版を選ぶため 0.4.8 が静かにインストールされます。先に `node -v` を確認し、インストール後に `forgen --version` を確認してください。
131
+
130
132
  初回実行を検出すると、4問のオンボーディングが始まります。各質問は具体的なシナリオです:
131
133
 
132
134
  ```
@@ -546,7 +548,8 @@ forgen rule enforce|advise <id> # 自動降格されたルールのブロック
546
548
  forgen status --blocks [N] # 最近の実ブロック + レシート: 一致フラグメント、24h 前後文脈、判定(auto/user)
547
549
  forgen block <id> --ok | --fp # ブロックを判定 (自動 Haiku 判定を上書き) — ルール別 precision に反映
548
550
  forgen status --turn # 今ターンに関連するルールと、各ルールが生まれた修正(日付・種類・あなたの発言)
549
- forgen statusline # 2行: モデル · パス(ブランチ) · ctx % · 5h/7d 上限 + 枯渇予測 · $ / 関連ルール · ブロック · surfaced
551
+ forgen statusline # 3行: モデル · パス(ブランチ) / ctx·5h·7d バー + 枯渇予測 · $ / forgen: 関連ルール · ブロック · surfaced
552
+ forgen statusline install [--force] # ~/.claude/settings.json に statusline を登録(絶対パス, nvm セーフ); --force はカスタム値を置換(バックアップ保持)
550
553
  ```
551
554
 
552
555
  ### 知識管理
package/README.ko.md CHANGED
@@ -87,6 +87,8 @@ npm install -g @wooojin/forgen
87
87
  forgen
88
88
  ```
89
89
 
90
+ > **Node 22 이상 필요.** Node 20에서 `npm i -g @wooojin/forgen`을 하면 npm이 `engines`에 맞는 최신 버전을 고르기 때문에 조용히 0.4.8이 설치됩니다. 먼저 `node -v`를 확인하고, 설치 후 `forgen --version`으로 확인하세요.
91
+
90
92
  첫 실행을 감지하면 4문항 온보딩이 시작됩니다. 각 질문은 구체적인 시나리오입니다:
91
93
 
92
94
  ```
@@ -531,7 +533,8 @@ forgen rule enforce|advise <id> # 자동 강등된 규칙의 차단 복귀 / 기
531
533
  forgen status --blocks [N] # 최근 실제 차단 + 영수증: 매칭 프래그먼트, 24h 전후 문맥, 판정(auto/user)
532
534
  forgen block <id> --ok | --fp # 차단 판정 (자동 Haiku 판정을 덮어씀) — 규칙별 precision 에 반영
533
535
  forgen status --turn # 이번 턴 관련 규칙과 각 규칙이 생긴 교정(날짜·종류·당신의 말)
534
- forgen statusline # 2줄: 모델 · 경로(브랜치) · ctx % · 5h/7d 한도 + 소진 예측 · $ / 관련 규칙 · 차단 · surfaced
536
+ forgen statusline # 3줄: 모델 · 경로(브랜치) / ctx·5h·7d 바 + 소진 예측 · $ / forgen: 관련 규칙 · 차단 · surfaced
537
+ forgen statusline install [--force] # ~/.claude/settings.json 에 statusline 등록(절대 경로, nvm 안전); --force 는 커스텀 값을 교체(백업 보관)
535
538
  ```
536
539
 
537
540
  ### 지식 관리
package/README.md CHANGED
@@ -180,6 +180,8 @@ npm install -g @wooojin/forgen
180
180
  forgen
181
181
  ```
182
182
 
183
+ > **Node 22+ required.** On Node 20, `npm i -g @wooojin/forgen` silently installs the last Node-20-compatible version (0.4.8) because npm picks the newest release whose `engines` matches. Check `node -v` first, or pin: `npm i -g @wooojin/forgen@latest` and verify `forgen --version`.
184
+
183
185
  Forgen detects this is your first run and launches a 4-question onboarding. Each question is a concrete scenario:
184
186
 
185
187
  ```
@@ -728,7 +730,8 @@ forgen rule enforce|advise <id> # Restore blocking for an auto-demoted rule / re
728
730
  forgen status --blocks [N] # Recent real blocks with receipt: matched fragment, 24h context, verdict (auto/user)
729
731
  forgen block <id> --ok | --fp # Judge a block (overrides the automatic Haiku verdict); feeds per-rule precision
730
732
  forgen status --turn # Rules relevant to the current turn, each with the correction (date/kind/your words) it came from
731
- forgen statusline # 2 lines: model · path(branch) · ctx % · 5h/7d limits + exhaustion forecast · $ / related rules · blocks · surfaced
733
+ forgen statusline # 3 lines: model · path(branch) / ctx·5h·7d bars + exhaustion forecast · $ / forgen: related rules · blocks · surfaced
734
+ forgen statusline install [--force] # Register the statusline in ~/.claude/settings.json (absolute path, nvm-safe); --force replaces a custom one (backup kept)
732
735
  ```
733
736
 
734
737
  ### Knowledge management
package/README.zh.md CHANGED
@@ -127,6 +127,8 @@ npm install -g @wooojin/forgen
127
127
  forgen
128
128
  ```
129
129
 
130
+ > **需要 Node 22+。** 在 Node 20 上执行 `npm i -g @wooojin/forgen` 时,npm 会选择与 `engines` 匹配的最新版本,从而静默安装 0.4.8。请先检查 `node -v`,安装后用 `forgen --version` 确认。
131
+
130
132
  forgen 检测到这是首次运行,启动4题引导问卷。每个问题都是一个具体场景:
131
133
 
132
134
  ```
@@ -515,7 +517,8 @@ forgen rule enforce|advise <id> # 恢复自动降级规则的拦截 / 仅记录
515
517
  forgen status --blocks [N] # 最近真实拦截 + 回执: 匹配片段、24h 上下文、判定(auto/user)
516
518
  forgen block <id> --ok | --fp # 判定一次拦截 (覆盖自动 Haiku 判定) — 计入规则级 precision
517
519
  forgen status --turn # 本轮相关规则,以及每条规则来源的纠正(日期·类型·你的原话)
518
- forgen statusline # 2 行: 模型 · 路径(分支) · ctx % · 5h/7d 配额 + 耗尽预测 · $ / 相关规则 · 拦截 · surfaced
520
+ forgen statusline # 3 行: 模型 · 路径(分支) / ctx·5h·7d 条形 + 耗尽预测 · $ / forgen: 相关规则 · 拦截 · surfaced
521
+ forgen statusline install [--force] # 在 ~/.claude/settings.json 注册 statusline(绝对路径, nvm 安全); --force 替换自定义值(保留备份)
519
522
  ```
520
523
 
521
524
  ### 知识管理
package/dist/cli.js CHANGED
@@ -120,8 +120,13 @@ const commands = [
120
120
  },
121
121
  {
122
122
  name: 'statusline',
123
- description: 'Compact HUD for Claude Code statusLine (reads stdin JSON)',
124
- handler: async (_args) => {
123
+ description: 'Compact HUD for Claude Code statusLine (reads stdin JSON). `statusline install [--force]` registers it in settings.json',
124
+ handler: async (args) => {
125
+ if (args[0] === 'install') {
126
+ const { handleStatuslineInstall } = await import('./core/statusline-install.js');
127
+ await handleStatuslineInstall(args.slice(1));
128
+ return;
129
+ }
125
130
  const { handleStatusline } = await import('./core/statusline-cli.js');
126
131
  await handleStatusline();
127
132
  },
@@ -25,6 +25,14 @@ function check(label, condition, hint) {
25
25
  failedChecks.push({ section: currentSection, label, hint });
26
26
  }
27
27
  }
28
+ function readSettingsForDoctor() {
29
+ try {
30
+ return JSON.parse(fs.readFileSync(path.join(os.homedir(), '.claude', 'settings.json'), 'utf-8'));
31
+ }
32
+ catch {
33
+ return {};
34
+ }
35
+ }
28
36
  function exists(p) {
29
37
  return fs.existsSync(p);
30
38
  }
@@ -254,6 +262,15 @@ export async function runDoctor(opts = {}) {
254
262
  }
255
263
  }
256
264
  console.log();
265
+ section('Statusline');
266
+ try {
267
+ const sl = readSettingsForDoctor().statusLine?.command;
268
+ const owned = !sl || /^forgen(\s|$)/.test(sl.trim()) || /[\\/]dist[\\/]cli\.js"?\s+statusline(\s|$)/.test(sl);
269
+ check('statusLine → forgen', owned, `another command is set (${(sl ?? '').slice(0, 50)}…). Switch: forgen statusline install --force`);
270
+ if (owned)
271
+ check('statusLine uses absolute path (nvm-safe)', !!sl && !/^forgen(\s|$)/.test(sl.trim()), 'PATH-dependent `forgen statusline` picks whatever nvm version is active. Fix: forgen statusline install');
272
+ }
273
+ catch { /* fail-open */ }
257
274
  section('Directories');
258
275
  check('~/.forgen/', exists(FORGEN_HOME));
259
276
  check('~/.forgen/me/', exists(ME_DIR));
@@ -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;
@@ -53,8 +56,17 @@ export interface StdinPayload {
53
56
  * 검증해 못 잡았다. (Node spawn 재현 테스트: tests/statusline-stdin-socket.test.ts)
54
57
  */
55
58
  export declare function readStdinJson(): Promise<StdinPayload>;
56
- /** 1줄: 사용자 정보. 데이터 없는 세그먼트는 생략. */
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줄 시절 호환 — 헤더+사용량을 한 줄로. 테스트·외부 호출용. */
57
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;
58
70
  /** 2줄: forgen 정보. 전부 실측 카운터(computeStats = status 와 같은 기준). 실패 시 생략. */
59
71
  export declare function buildForgenLine(sessionId: string | undefined): string | null;
60
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,7 +38,16 @@ 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
+ 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
+ }
41
51
  /**
42
52
  * stdin 페이로드 읽기 — 훅과 같은 이벤트 기반 리더(read-stdin.ts).
43
53
  *
@@ -103,18 +113,26 @@ function fmtWindowSize(size) {
103
113
  return `/${Math.round(size / 1_000_000)}M`;
104
114
  return `/${Math.round(size / 1000)}k`;
105
115
  }
106
- /** 1줄: 사용자 정보. 데이터 없는 세그먼트는 생략. */
107
- export function buildUserLine(payload, cwd, forecasts, nowMs) {
108
- const parts = [];
109
- parts.push(`${BOLD}${CYAN}${payload.model?.display_name ?? 'Claude'}${RESET}`);
116
+ /** 1줄: 모델 │ 경로(브랜치). */
117
+ export function buildHeaderLine(payload, cwd) {
110
118
  const branch = getGitBranch(cwd);
111
119
  const cwdDisplay = cwd.replace(os.homedir(), '~');
112
- 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 = [];
113
128
  const cw = payload.context_window;
114
- 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}`) : '';
115
133
  if (cw && isNum(cw.used_percentage)) {
116
134
  const pct = Math.round(cw.used_percentage);
117
- 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}` : ''}`);
118
136
  }
119
137
  else if (warn200k) {
120
138
  parts.push(warn200k); // used_percentage 가 null(세션 초반)이어도 경고는 유지
@@ -123,15 +141,34 @@ export function buildUserLine(payload, cwd, forecasts, nowMs) {
123
141
  const f = forecasts[w];
124
142
  if (!f)
125
143
  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));
144
+ parts.push(fmtLimitSegment(f, nowMs));
130
145
  }
131
146
  if (payload.cost && isNum(payload.cost.total_cost_usd)) {
132
147
  parts.push(`${DIM}$${payload.cost.total_cost_usd.toFixed(2)}${RESET}`);
133
148
  }
134
- 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}` : ''}`;
135
172
  }
136
173
  /** 2줄: forgen 정보. 전부 실측 카운터(computeStats = status 와 같은 기준). 실패 시 생략. */
137
174
  export function buildForgenLine(sessionId) {
@@ -151,14 +188,15 @@ export function buildForgenLine(sessionId) {
151
188
  } })();
152
189
  const s = computeStats();
153
190
  const sessionBlocks = sessionId ? countSessionBlocks(sessionId) : null;
154
- const parts = [];
191
+ const parts = [`${BOLD}${CYAN}forgen${RESET}`];
155
192
  if (turnRelevant !== null)
156
193
  parts.push(`${DIM}관련 룰${RESET} ${turnRelevant}`);
157
194
  else if (rules !== null)
158
195
  parts.push(`${DIM}룰${RESET} ${rules}`);
159
196
  if (sessionBlocks !== null)
160
- parts.push(`${DIM}이 세션 차단${RESET} ${sessionBlocks > 0 ? colored(String(sessionBlocks), YELLOW) : '0'}`);
161
- 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}`);
162
200
  parts.push(`${DIM}surfaced${RESET} ${s.assistToday.surfaced}`);
163
201
  return parts.join(SEP);
164
202
  }
@@ -224,7 +262,11 @@ export function renderStatusline(payload, nowMs = Date.now(), opts = {}) {
224
262
  const history = readSamples(undefined, nowMs);
225
263
  const all = opts.currentAlreadyAppended ? history : [...history, ...current];
226
264
  const forecasts = forecastAll(all, nowMs, current);
227
- 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);
228
270
  let forgenLine = opts.useForgenCache ? readForgenLineCached(payload.session_id, nowMs) : null;
229
271
  if (forgenLine === null) {
230
272
  forgenLine = buildForgenLine(payload.session_id);
@@ -0,0 +1,27 @@
1
+ /**
2
+ * forgen statusline install [--force] — ~/.claude/settings.json 의 statusLine 을 forgen 으로 (ADR-017 후속, 2026-10-07)
3
+ *
4
+ * 왜 따로 있나: 오너 실측 — 다른 머신에서 statusLine 이 claude-hud 로 잡혀 있어 forgen statusline 이 한 번도 실행되지 않았고,
5
+ * `forgen install claude` 는 사용자 커스텀 statusLine 을 건드리지 않게 돼 있어 손으로 settings.json 을 고쳐야 했다.
6
+ * 또 `forgen statusline` 처럼 PATH 에 의존하면 nvm 버전마다 다른 바이너리(0.4.8)가 잡힌다 → **절대 경로**로 등록한다.
7
+ *
8
+ * 정책:
9
+ * - statusLine 이 없거나 forgen 소유(`forgen …` / `…/dist/cli.js statusline`)면 → 현재 패키지의 절대 경로로 갱신.
10
+ * - 커스텀(claude-hud 등)이면 → 기본은 건드리지 않고 안내만. `--force` 면 `statusLine_backup` 에 보관 후 교체.
11
+ * - 켜져 있는 세션도 settings.json 의 statusLine.command 변경은 즉시 반영된다(Claude Code 가 감시).
12
+ */
13
+ export interface StatusLineInstallResult {
14
+ status: 'installed' | 'updated' | 'unchanged' | 'skipped_custom' | 'error';
15
+ command: string;
16
+ previous?: string;
17
+ backedUp?: boolean;
18
+ message: string;
19
+ }
20
+ /** 이 패키지의 cli.js 절대 경로로 만든 statusline 명령 — PATH/nvm 무관. */
21
+ export declare function forgenStatuslineCommand(): string;
22
+ export declare function isForgenStatusline(command: unknown): boolean;
23
+ export declare function installStatusline(opts?: {
24
+ force?: boolean;
25
+ settingsPath?: string;
26
+ }): StatusLineInstallResult;
27
+ export declare function handleStatuslineInstall(args: string[]): Promise<void>;
@@ -0,0 +1,77 @@
1
+ /**
2
+ * forgen statusline install [--force] — ~/.claude/settings.json 의 statusLine 을 forgen 으로 (ADR-017 후속, 2026-10-07)
3
+ *
4
+ * 왜 따로 있나: 오너 실측 — 다른 머신에서 statusLine 이 claude-hud 로 잡혀 있어 forgen statusline 이 한 번도 실행되지 않았고,
5
+ * `forgen install claude` 는 사용자 커스텀 statusLine 을 건드리지 않게 돼 있어 손으로 settings.json 을 고쳐야 했다.
6
+ * 또 `forgen statusline` 처럼 PATH 에 의존하면 nvm 버전마다 다른 바이너리(0.4.8)가 잡힌다 → **절대 경로**로 등록한다.
7
+ *
8
+ * 정책:
9
+ * - statusLine 이 없거나 forgen 소유(`forgen …` / `…/dist/cli.js statusline`)면 → 현재 패키지의 절대 경로로 갱신.
10
+ * - 커스텀(claude-hud 등)이면 → 기본은 건드리지 않고 안내만. `--force` 면 `statusLine_backup` 에 보관 후 교체.
11
+ * - 켜져 있는 세션도 settings.json 의 statusLine.command 변경은 즉시 반영된다(Claude Code 가 감시).
12
+ */
13
+ import * as fs from 'node:fs';
14
+ import * as path from 'node:path';
15
+ import { fileURLToPath } from 'node:url';
16
+ import { CLAUDE_DIR } from './paths.js';
17
+ /** 이 패키지의 cli.js 절대 경로로 만든 statusline 명령 — PATH/nvm 무관. */
18
+ export function forgenStatuslineCommand() {
19
+ const cli = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..', 'cli.js');
20
+ return `"${process.execPath}" "${cli}" statusline`;
21
+ }
22
+ export function isForgenStatusline(command) {
23
+ if (typeof command !== 'string' || !command.trim())
24
+ return true; // 없음 = forgen 이 가져가도 됨
25
+ return /^forgen(\s|$)/.test(command.trim()) || /[\\/]dist[\\/]cli\.js"?\s+statusline(\s|$)/.test(command);
26
+ }
27
+ export function installStatusline(opts = {}) {
28
+ const settingsPath = opts.settingsPath ?? path.join(CLAUDE_DIR, 'settings.json');
29
+ const command = forgenStatuslineCommand();
30
+ let settings = {};
31
+ try {
32
+ if (fs.existsSync(settingsPath))
33
+ settings = JSON.parse(fs.readFileSync(settingsPath, 'utf-8'));
34
+ }
35
+ catch (e) {
36
+ return { status: 'error', command, message: `settings.json 파싱 실패 — 건드리지 않음: ${e.message}` };
37
+ }
38
+ const existing = settings.statusLine;
39
+ const previous = existing?.command;
40
+ if (previous === command)
41
+ return { status: 'unchanged', command, previous, message: '이미 forgen statusline(절대 경로)입니다.' };
42
+ if (!isForgenStatusline(previous) && !opts.force) {
43
+ return {
44
+ status: 'skipped_custom', command, previous,
45
+ message: `statusLine 이 다른 명령으로 설정돼 있어 건드리지 않았습니다: ${String(previous).slice(0, 80)}\n forgen 으로 바꾸려면: forgen statusline install --force (기존 값은 settings.json 의 statusLine_backup 에 보관)`,
46
+ };
47
+ }
48
+ let backedUp = false;
49
+ if (!isForgenStatusline(previous) && opts.force) {
50
+ settings.statusLine_backup = previous;
51
+ backedUp = true;
52
+ }
53
+ settings.statusLine = { type: 'command', command };
54
+ try {
55
+ fs.mkdirSync(path.dirname(settingsPath), { recursive: true });
56
+ if (fs.existsSync(settingsPath))
57
+ fs.copyFileSync(settingsPath, `${settingsPath}.bak`);
58
+ const tmp = `${settingsPath}.tmp-${process.pid}`;
59
+ fs.writeFileSync(tmp, `${JSON.stringify(settings, null, 2)}\n`);
60
+ fs.renameSync(tmp, settingsPath);
61
+ }
62
+ catch (e) {
63
+ return { status: 'error', command, previous, message: `settings.json 쓰기 실패: ${e.message}` };
64
+ }
65
+ return {
66
+ status: previous ? 'updated' : 'installed', command, previous, backedUp,
67
+ message: `statusLine → ${command}${backedUp ? ' (기존 값 statusLine_backup 에 보관)' : ''}\n 켜져 있는 세션도 다음 메시지부터 반영됩니다.`,
68
+ };
69
+ }
70
+ export async function handleStatuslineInstall(args) {
71
+ const force = args.includes('--force');
72
+ const r = installStatusline({ force });
73
+ const icon = r.status === 'error' ? '✗' : r.status === 'skipped_custom' ? 'ℹ' : '✓';
74
+ console.log(`${icon} [forgen] ${r.message}`);
75
+ if (r.status === 'error')
76
+ process.exitCode = 1;
77
+ }
@@ -0,0 +1,31 @@
1
+ /**
2
+ * Codex 훅 고정 shim (2026-10-07, 오너 피드백 "매번 trust all 해야 에러가 안 난다").
3
+ *
4
+ * Codex 의 훅 trust 해시는 핸들러 명령 **문자열** 단위다(ADR-016). 이전엔 명령에
5
+ * `node "<nvm>/v22.x/lib/node_modules/@wooojin/forgen/dist/host/codex-adapter.js" "<…>/dist/hooks/x.js"`
6
+ * 처럼 node·패키지 경로가 박혀 있어서 nvm 버전 전환·재설치 위치 변경마다 모든 훅이 `modified` →
7
+ * Codex 가 skip → `/hooks` 에서 다시 trust 해야 했다.
8
+ *
9
+ * 해결: 명령은 버전 무관한 고정 경로 `<CODEX_HOME>/forgen-hook "hooks/x.js" args` 로 쓰고, 실제 위임 대상
10
+ * (node 바이너리·패키지 경로)은 **shim 파일 내용**에 둔다. 설치·업그레이드는 shim 내용만 다시 쓰므로
11
+ * hooks.json 바이트가 그대로 → trust 해시 유지. (shim 도입 직후 1회만 재승인 필요.)
12
+ *
13
+ * POSIX sh 스크립트라 node 프로세스가 추가로 뜨지 않는다(exec). Windows 는 기존 방식 유지.
14
+ */
15
+ export declare const SHIM_MARKER = "# forgen-managed codex-hook shim";
16
+ /** shim 은 codexHome 아래 — 실환경 `~/.codex/forgen-hook`(고정), 격리 테스트는 임시 codexHome 으로 자동 격리. */
17
+ export declare function codexHookShimPath(codexHome: string): string;
18
+ /** 소유 판정용 — 명령이 forgen shim 을 가리키는가. */
19
+ export declare const SHIM_COMMAND_RE: RegExp;
20
+ export declare function shimSupported(platform?: NodeJS.Platform): boolean;
21
+ export declare function renderShim(pkgRoot: string, nodePath: string): string;
22
+ /**
23
+ * shim 을 (재)작성. 내용이 같으면 쓰지 않는다. 사용자가 마커를 지운 파일은 덮어쓰지 않는다.
24
+ * 반환: 'written' | 'unchanged' | 'foreign'(사용자 파일) | 'error'.
25
+ */
26
+ export declare function writeCodexHookShim(pkgRoot: string, nodePath: string, shimPath: string): 'written' | 'unchanged' | 'foreign' | 'error';
27
+ /**
28
+ * `node "<root>/host/codex-adapter.js" "<root>/<rel>" args` → `"<shim>" "<rel>" args`.
29
+ * 형태가 다르면(사용자 수정 등) 원문 그대로 반환.
30
+ */
31
+ export declare function toShimCommand(command: string, shimPath: string): string;
@@ -0,0 +1,79 @@
1
+ /**
2
+ * Codex 훅 고정 shim (2026-10-07, 오너 피드백 "매번 trust all 해야 에러가 안 난다").
3
+ *
4
+ * Codex 의 훅 trust 해시는 핸들러 명령 **문자열** 단위다(ADR-016). 이전엔 명령에
5
+ * `node "<nvm>/v22.x/lib/node_modules/@wooojin/forgen/dist/host/codex-adapter.js" "<…>/dist/hooks/x.js"`
6
+ * 처럼 node·패키지 경로가 박혀 있어서 nvm 버전 전환·재설치 위치 변경마다 모든 훅이 `modified` →
7
+ * Codex 가 skip → `/hooks` 에서 다시 trust 해야 했다.
8
+ *
9
+ * 해결: 명령은 버전 무관한 고정 경로 `<CODEX_HOME>/forgen-hook "hooks/x.js" args` 로 쓰고, 실제 위임 대상
10
+ * (node 바이너리·패키지 경로)은 **shim 파일 내용**에 둔다. 설치·업그레이드는 shim 내용만 다시 쓰므로
11
+ * hooks.json 바이트가 그대로 → trust 해시 유지. (shim 도입 직후 1회만 재승인 필요.)
12
+ *
13
+ * POSIX sh 스크립트라 node 프로세스가 추가로 뜨지 않는다(exec). Windows 는 기존 방식 유지.
14
+ */
15
+ import * as fs from 'node:fs';
16
+ import * as path from 'node:path';
17
+ export const SHIM_MARKER = '# forgen-managed codex-hook shim';
18
+ /** shim 은 codexHome 아래 — 실환경 `~/.codex/forgen-hook`(고정), 격리 테스트는 임시 codexHome 으로 자동 격리. */
19
+ export function codexHookShimPath(codexHome) {
20
+ return path.join(codexHome, 'forgen-hook');
21
+ }
22
+ /** 소유 판정용 — 명령이 forgen shim 을 가리키는가. */
23
+ export const SHIM_COMMAND_RE = /[\\/]forgen-hook"?(?![\w-])/;
24
+ export function shimSupported(platform = process.platform) {
25
+ return platform !== 'win32';
26
+ }
27
+ const shq = (s) => `'${s.replace(/'/g, `'\\''`)}'`;
28
+ export function renderShim(pkgRoot, nodePath) {
29
+ return [
30
+ '#!/bin/sh',
31
+ SHIM_MARKER,
32
+ '# 설치·업그레이드마다 재작성된다. Codex hooks.json 은 이 파일 경로만 가리키므로 node/패키지 경로가',
33
+ '# 바뀌어도 훅 명령 문자열(= trust 해시)이 그대로 유지된다.',
34
+ `FORGEN_PKG=${shq(pkgRoot)}`,
35
+ `FORGEN_NODE=${shq(nodePath)}`,
36
+ '[ -x "$FORGEN_NODE" ] || FORGEN_NODE=node',
37
+ 'rel="$1"; shift',
38
+ 'exec "$FORGEN_NODE" "$FORGEN_PKG/dist/host/codex-adapter.js" "$FORGEN_PKG/dist/$rel" "$@"',
39
+ '',
40
+ ].join('\n');
41
+ }
42
+ /**
43
+ * shim 을 (재)작성. 내용이 같으면 쓰지 않는다. 사용자가 마커를 지운 파일은 덮어쓰지 않는다.
44
+ * 반환: 'written' | 'unchanged' | 'foreign'(사용자 파일) | 'error'.
45
+ */
46
+ export function writeCodexHookShim(pkgRoot, nodePath, shimPath) {
47
+ try {
48
+ const content = renderShim(pkgRoot, nodePath);
49
+ if (fs.existsSync(shimPath)) {
50
+ const cur = fs.readFileSync(shimPath, 'utf-8');
51
+ if (cur === content)
52
+ return 'unchanged';
53
+ if (!cur.includes(SHIM_MARKER))
54
+ return 'foreign';
55
+ }
56
+ fs.mkdirSync(path.dirname(shimPath), { recursive: true });
57
+ const tmp = `${shimPath}.tmp-${process.pid}`;
58
+ fs.writeFileSync(tmp, content, { mode: 0o755 });
59
+ fs.renameSync(tmp, shimPath);
60
+ return 'written';
61
+ }
62
+ catch {
63
+ return 'error';
64
+ }
65
+ }
66
+ /**
67
+ * `node "<root>/host/codex-adapter.js" "<root>/<rel>" args` → `"<shim>" "<rel>" args`.
68
+ * 형태가 다르면(사용자 수정 등) 원문 그대로 반환.
69
+ */
70
+ export function toShimCommand(command, shimPath) {
71
+ const m = command.match(/^node "(.+?)[\\/]host[\\/]codex-adapter\.js" "(.+?)"(.*)$/s);
72
+ if (!m)
73
+ return command;
74
+ const [, root, full, rest] = m;
75
+ if (!full.startsWith(`${root}/`) && !full.startsWith(`${root}\\`))
76
+ return command;
77
+ const rel = full.slice(root.length + 1);
78
+ return `"${shimPath}" "${rel}"${rest}`;
79
+ }
@@ -22,6 +22,10 @@ export interface CodexInstallOptions {
22
22
  registerMcp?: boolean;
23
23
  /** hooks-generator releaseMode (default true: 환경 독립). */
24
24
  releaseMode?: boolean;
25
+ /** 고정 shim 사용(기본: POSIX 에서 true). false 면 이전 방식(node+절대경로). */
26
+ useShim?: boolean;
27
+ /** shim 경로 override — 격리 테스트용. */
28
+ shimPath?: string;
25
29
  /** AGENTS.md 위치 override (default: pkgRoot 기준 자동 resolve). 격리 테스트용. */
26
30
  agentsMdPath?: string;
27
31
  /** ADR-016 D1: config.toml 에 forgen notify 폴백 등록 여부 (default true). */
@@ -16,6 +16,7 @@ import * as fs from 'node:fs';
16
16
  import * as os from 'node:os';
17
17
  import * as path from 'node:path';
18
18
  import { generateHooksJson } from '../hooks/hooks-generator.js';
19
+ import { SHIM_COMMAND_RE, codexHookShimPath, shimSupported, toShimCommand, writeCodexHookShim } from './codex-hook-shim.js';
19
20
  import { HOOK_REGISTRY } from '../hooks/hook-registry.js';
20
21
  import { hasManagedSkillMarker, installSkillFile, isManagedAgentToml, removeOwnedDevGuideSkills } from './managed-marker.js';
21
22
  const MCP_MARKER_BEGIN = '# >>> forgen-managed-mcp';
@@ -48,6 +49,8 @@ export function isForgenHookCommand(command, pkgRoot) {
48
49
  return true;
49
50
  if (FORGEN_ADAPTER_RE.test(command))
50
51
  return true;
52
+ if (SHIM_COMMAND_RE.test(command))
53
+ return true; // 고정 shim 경유 (2026-10-07)
51
54
  const script = command.match(FORGEN_HOOK_SCRIPT_RE)?.[1];
52
55
  return script !== undefined && FORGEN_HOOK_SCRIPT_NAMES.has(script);
53
56
  }
@@ -459,6 +462,19 @@ export function planCodexInstall(opts) {
459
462
  releaseMode,
460
463
  });
461
464
  const generatedHooks = generated.hooks;
465
+ // 1b) 고정 shim (오너 피드백: nvm 전환·재설치마다 /hooks 재승인). 명령을 버전 무관한 shim 경로로 바꿔
466
+ // hooks.json 바이트(= trust 해시)를 고정한다. 실제 위임 대상은 shim 파일 내용(아래 5에서 기록).
467
+ const useShim = opts.useShim ?? shimSupported();
468
+ const shimPath = opts.shimPath ?? codexHookShimPath(codexHome);
469
+ if (useShim) {
470
+ for (const groups of Object.values(generatedHooks)) {
471
+ for (const g of groups) {
472
+ for (const h of g.hooks ?? [])
473
+ if (typeof h.command === 'string')
474
+ h.command = toShimCommand(h.command, shimPath);
475
+ }
476
+ }
477
+ }
462
478
  // 2) 기존 hooks.json 읽기 — forgen 그룹은 *제자리에서* 교체, 사용자 그룹은 위치 그대로 보존.
463
479
  // (0.5.3 critic/실머신: 이전엔 사용자 그룹을 앞으로 모으고 forgen 을 뒤에 붙여 그룹 인덱스가
464
480
  // 바뀌었고, Codex 의 trust 키 `<event>:<groupIdx>:<hookIdx>` 가 어긋나 20/21 → 12/21 로
@@ -536,6 +552,8 @@ export function planCodexInstall(opts) {
536
552
  const configTomlToWrite = configToml !== currentToml ? configToml : null;
537
553
  // 5) 실제 쓰기 (dryRun 이면 skip) — hooks.json + config.toml
538
554
  if (!opts.dryRun) {
555
+ if (useShim)
556
+ writeCodexHookShim(opts.pkgRoot, process.execPath, shimPath);
539
557
  fs.mkdirSync(codexHome, { recursive: true });
540
558
  fs.writeFileSync(hooksPath, `${JSON.stringify(finalHooksFile, null, 2)}\n`, 'utf-8');
541
559
  if (configTomlToWrite !== null) {
@@ -183,6 +183,15 @@ export function planCodexUninstall(opts) {
183
183
  else
184
184
  fs.writeFileSync(hooksPath, `${JSON.stringify(stripped.next, null, 2)}\n`, 'utf-8');
185
185
  });
186
+ // 1b) 고정 shim(<codexHome>/forgen-hook) — forgen 마커가 있는 파일만 제거.
187
+ step('forgen-hook shim', () => {
188
+ const shim = path.join(codexHome, 'forgen-hook');
189
+ try {
190
+ if (fs.existsSync(shim) && fs.readFileSync(shim, 'utf-8').includes('forgen-managed codex-hook shim') && !dryRun)
191
+ fs.unlinkSync(shim);
192
+ }
193
+ catch { /* best-effort */ }
194
+ });
186
195
  // 2) config.toml — MCP / notify 블록
187
196
  step('config.toml', () => {
188
197
  const configTomlPath = path.join(codexHome, 'config.toml');
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@wooojin/forgen",
3
- "version": "0.6.2",
3
+ "version": "0.6.4",
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.2",
4
+ "version": "0.6.4",
5
5
  "description": "Claude Code harness — the more you use Claude, the better it gets",
6
6
  "author": {
7
7
  "name": "jang-ujin",
@@ -260,6 +260,23 @@ function registerPlugin() {
260
260
  }
261
261
 
262
262
  /** settings 객체에 enabledPlugins를 적용합니다 (settings.json 쓰기는 main에서 일괄 수행). */
263
+ /**
264
+ * statusLine 자동 등록 (2026-10-07, 오너 피드백 "설치 후 forgen install 을 또 해야 하는 게 불편").
265
+ * - 없거나 forgen 소유(`forgen …` / `…/dist/cli.js statusline`) → 이 패키지의 **절대 경로**로 등록
266
+ * (PATH 의존 `forgen statusline` 은 nvm 버전마다 다른 바이너리가 잡힌다 — 실측 0.4.8).
267
+ * - 커스텀(claude-hud 등) → 건드리지 않고 안내만. 교체는 `forgen statusline install --force`.
268
+ * 반환: 'installed' | 'updated' | 'unchanged' | 'custom'
269
+ */
270
+ function applyStatusLineAuto(settings) {
271
+ const cmd = `"${process.execPath}" "${join(PKG_ROOT, 'dist', 'cli.js')}" statusline`;
272
+ const existing = settings.statusLine && settings.statusLine.command;
273
+ const owned = !existing || /^forgen(\s|$)/.test(String(existing).trim()) || /[\\/]dist[\\/]cli\.js"?\s+statusline(\s|$)/.test(String(existing));
274
+ if (!owned) return 'custom';
275
+ if (existing === cmd) return 'unchanged';
276
+ settings.statusLine = { type: 'command', command: cmd };
277
+ return existing ? 'updated' : 'installed';
278
+ }
279
+
263
280
  function applyPluginSettings(settings) {
264
281
  const pluginKey = 'forgen@forgen-local';
265
282
  const enabled = settings.enabledPlugins ?? {};
@@ -997,6 +1014,27 @@ async function main() {
997
1014
  }
998
1015
  }
999
1016
 
1017
+ // ── 2.4. Codex 훅 shim 갱신 — 이미 쓰고 있으면 새 node/패키지 경로로 내용만 재작성(hooks.json 불변 → trust 유지) ──
1018
+ try {
1019
+ const shimMod = await import(join(PKG_ROOT, 'dist', 'host', 'codex-hook-shim.js'));
1020
+ const shimFile = shimMod.codexHookShimPath(process.env.CODEX_HOME || join(HOME, '.codex'));
1021
+ if (existsSync(shimFile)) {
1022
+ const r = shimMod.writeCodexHookShim(PKG_ROOT, process.execPath, shimFile);
1023
+ if (r === 'written') console.log('[forgen] Codex hook shim updated → no /hooks re-trust needed.');
1024
+ } else {
1025
+ // 이전 형식(node + 절대경로) forgen 훅이 등록돼 있으면 1회 마이그레이션 안내 — 이후로는 재승인 불필요.
1026
+ const hooksFile = join(process.env.CODEX_HOME || join(HOME, '.codex'), 'hooks.json');
1027
+ if (existsSync(hooksFile) && /[\\/]dist[\\/]host[\\/]codex-adapter\.js/.test(readFileSync(hooksFile, 'utf-8'))) {
1028
+ console.log('[forgen] Codex: run `forgen install codex` once to switch hooks to a stable shim —');
1029
+ console.log('[forgen] after one last /hooks trust, upgrades and nvm switches no longer need re-trust.');
1030
+ }
1031
+ }
1032
+ } catch { /* dist 없음(dev) 또는 실패 — 다음 forgen install codex 가 처리 */ }
1033
+
1034
+ // ── 2.5. statusLine 자동 등록 (settings 단일 쓰기에 포함) ──
1035
+ let statusLineResult = 'unchanged';
1036
+ try { statusLineResult = applyStatusLineAuto(settings); } catch (err) { console.error(`[forgen] statusLine setup skipped: ${err?.message ?? err}`); }
1037
+
1000
1038
  // ── 3. hooks.json 동적 생성 ──
1001
1039
  //
1002
1040
  // A4 guard (2026-04-09): skip regeneration when running inside the
@@ -1141,6 +1179,12 @@ async function main() {
1141
1179
  if (parts.length > 0) {
1142
1180
  console.log(`[forgen] Installed: ${parts.join(', ')} → ${HOME}`);
1143
1181
  }
1182
+ if (statusLineResult === 'installed' || statusLineResult === 'updated') {
1183
+ console.log('[forgen] statusLine registered (absolute path) — running sessions pick it up on the next message.');
1184
+ } else if (statusLineResult === 'custom') {
1185
+ console.log('[forgen] statusLine is set to another command (e.g. claude-hud) — left untouched.');
1186
+ console.log('[forgen] To switch to forgen (backup kept in statusLine_backup): forgen statusline install --force');
1187
+ }
1144
1188
 
1145
1189
  // First-run banner (신규 사용자 안내) — feat/codex-support P1-6
1146
1190
  if (!isExistingForgenUser) {