@wooojin/forgen 0.5.8 → 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 (79) hide show
  1. package/.claude-plugin/plugin.json +1 -1
  2. package/CHANGELOG.md +102 -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/uninstall.js +10 -1
  25. package/dist/core/v1-bootstrap.js +7 -1
  26. package/dist/engine/block-judge-cli.d.ts +2 -0
  27. package/dist/engine/block-judge-cli.js +11 -0
  28. package/dist/engine/block-judge.d.ts +68 -0
  29. package/dist/engine/block-judge.js +248 -0
  30. package/dist/engine/correction-cluster-runner.d.ts +67 -0
  31. package/dist/engine/correction-cluster-runner.js +242 -5
  32. package/dist/engine/correction-clustering.d.ts +15 -0
  33. package/dist/engine/correction-clustering.js +24 -0
  34. package/dist/engine/lifecycle/lifecycle-cli.js +7 -4
  35. package/dist/engine/lifecycle/signals.d.ts +59 -2
  36. package/dist/engine/lifecycle/signals.js +193 -4
  37. package/dist/engine/lifecycle/trigger-t3-bypass.d.ts +5 -3
  38. package/dist/engine/lifecycle/trigger-t3-bypass.js +6 -4
  39. package/dist/engine/lifecycle/types.d.ts +29 -1
  40. package/dist/engine/mined-rule-merge-cli.d.ts +11 -0
  41. package/dist/engine/mined-rule-merge-cli.js +67 -0
  42. package/dist/engine/rule-relevance.d.ts +72 -0
  43. package/dist/engine/rule-relevance.js +183 -0
  44. package/dist/engine/rule-toggle-cli.d.ts +5 -0
  45. package/dist/engine/rule-toggle-cli.js +30 -0
  46. package/dist/fgx.js +1 -1
  47. package/dist/forge/evidence-processor.js +2 -0
  48. package/dist/hooks/post-tool-use.js +9 -14
  49. package/dist/hooks/pre-tool-use.js +71 -8
  50. package/dist/hooks/shared/command-parser.d.ts +11 -0
  51. package/dist/hooks/shared/command-parser.js +120 -0
  52. package/dist/hooks/solution-injector.js +13 -0
  53. package/dist/hooks/stop-guard.d.ts +18 -0
  54. package/dist/hooks/stop-guard.js +55 -10
  55. package/dist/host/install-claude.js +7 -33
  56. package/dist/host/install-codex.d.ts +23 -1
  57. package/dist/host/install-codex.js +128 -49
  58. package/dist/host/install-opencode.d.ts +5 -0
  59. package/dist/host/install-opencode.js +9 -6
  60. package/dist/host/managed-marker.d.ts +22 -0
  61. package/dist/host/managed-marker.js +79 -0
  62. package/dist/host/uninstall-codex.d.ts +2 -0
  63. package/dist/host/uninstall-codex.js +12 -9
  64. package/dist/host/uninstall-opencode.d.ts +36 -0
  65. package/dist/host/uninstall-opencode.js +141 -0
  66. package/dist/mcp/tools.js +7 -1
  67. package/dist/renderer/inspect-renderer.js +23 -6
  68. package/dist/renderer/rule-renderer.js +4 -2
  69. package/dist/store/evidence-store.js +37 -2
  70. package/dist/store/profile-score.d.ts +55 -0
  71. package/dist/store/profile-score.js +100 -0
  72. package/dist/store/profile-store.d.ts +22 -5
  73. package/dist/store/profile-store.js +42 -6
  74. package/dist/store/rule-origin.d.ts +39 -0
  75. package/dist/store/rule-origin.js +84 -0
  76. package/dist/store/types.d.ts +24 -0
  77. package/package.json +1 -1
  78. package/plugin.json +1 -1
  79. package/scripts/postinstall.js +76 -42
@@ -12,8 +12,9 @@
12
12
  * forgen status --rules 활성 룰
13
13
  * forgen status --blocks [N] 최근 차단 N건 (rule·사유·해결)
14
14
  * forgen status --live 실시간 훅 이벤트 스트림
15
+ * forgen status --turn 이번 턴 관련 룰 + 각 룰의 원 교정 (ADR-017 D2)
15
16
  */
16
- const VIEWS = ['--compound', '--profile', '--rules', '--blocks', '--live', '--overview'];
17
+ const VIEWS = ['--compound', '--profile', '--rules', '--blocks', '--live', '--overview', '--turn'];
17
18
  const ALIASES = {
18
19
  '-c': '--compound',
19
20
  '-p': '--profile',
@@ -21,6 +22,7 @@ const ALIASES = {
21
22
  '-b': '--blocks',
22
23
  '-l': '--live',
23
24
  '-o': '--overview',
25
+ '-t': '--turn',
24
26
  };
25
27
  export function resolveView(args) {
26
28
  for (const a of args) {
@@ -84,13 +86,24 @@ export async function handleStatus(args) {
84
86
  await handleDashboard();
85
87
  return;
86
88
  }
89
+ case '--turn': {
90
+ // ADR-017 D2: 현재 세션(FORGEN_SESSION_ID, 없으면 가장 최근 turn-rules 파일)의 관련 룰 + 원 교정.
91
+ const { readTurnRules, resolveTurnRulesSession } = await import('../engine/rule-relevance.js');
92
+ const { loadAllRules } = await import('../store/rule-store.js');
93
+ const { ruleOrigin } = await import('../store/rule-origin.js');
94
+ const session = resolveTurnRulesSession(process.env.FORGEN_SESSION_ID);
95
+ const file = session ? readTurnRules(session) : null;
96
+ for (const line of renderTurnRules(file, loadAllRules(), ruleOrigin))
97
+ console.log(line);
98
+ return;
99
+ }
87
100
  default: {
88
101
  // 요약: health 헤더 + one-screen stats (둘 다 computeStats() 기반).
89
102
  const { computeHealth, renderHealthLine } = await import('./health-cli.js');
90
103
  const { computeStats, renderStats } = await import('./stats-cli.js');
91
104
  console.log(renderHealthLine(computeHealth()));
92
105
  console.log(renderStats(computeStats()));
93
- console.log(` ${dim('views:')} forgen status --compound | --profile | --rules | --blocks [N] | --live`);
106
+ console.log(` ${dim('views:')} forgen status --compound | --profile | --rules | --blocks [N] | --live | --turn`);
94
107
  return;
95
108
  }
96
109
  }
@@ -98,3 +111,39 @@ export async function handleStatus(args) {
98
111
  function dim(s) {
99
112
  return `\x1b[2m${s}\x1b[0m`;
100
113
  }
114
+ /**
115
+ * 한 줄: `[category/strength] policy (score) — 출처: 2026-09-30 당신의 말 (avoid-this): "…"`.
116
+ * 출처 문구는 rule-origin.originLine 과 같은 규칙(사용자 원문 > 모델 요약 > 날짜·kind 만)이되 접두사 없이.
117
+ * 채굴 룰(behavior_inference)은 사용자가 한 말이 아니므로 "채굴 룰" 로만 표기한다.
118
+ */
119
+ export function formatTurnRuleLine(rule, score, origin) {
120
+ const head = `[${rule.category}/${rule.strength}] ${rule.policy} (${score.toFixed(1)})`;
121
+ const o = origin(rule);
122
+ if (!o)
123
+ return rule.source === 'behavior_inference' ? `${head} — 채굴 룰` : head;
124
+ const kind = o.kind ? ` (${o.kind})` : '';
125
+ if (o.quoteSource === 'user')
126
+ return `${head} — 출처: ${o.date} 당신의 말${kind}: "${o.quote}"`;
127
+ if (o.quoteSource === 'summary')
128
+ return `${head} — 출처: ${o.date} 교정 기록${kind}: "${o.quote}"`;
129
+ return `${head} — 출처: ${o.date} 교정 기록${kind}`;
130
+ }
131
+ /** 순수 렌더 — 테스트용. file 이 null 이거나 관련 룰이 0이면 한 줄("이번 턴 관련 룰 없음"). */
132
+ export function renderTurnRules(file, allRules, origin) {
133
+ if (!file || file.rules.length === 0)
134
+ return ['이번 턴 관련 룰 없음'];
135
+ const byId = new Map(allRules.map((r) => [r.rule_id, r]));
136
+ const when = file.at ? ` · ${file.at.slice(0, 16).replace('T', ' ')}` : '';
137
+ const lines = [`이번 턴 관련 룰 ${file.rules.length} ${dim(`(세션 ${file.session_id.slice(0, 8)}${when} · 프롬프트 ${file.prompt_hash || '?'})`)}`];
138
+ for (const r of file.rules) {
139
+ const rule = byId.get(r.rule_id);
140
+ if (!rule) {
141
+ lines.push(` ${r.rule_id} (${r.score.toFixed(1)}) — 룰 파일 없음(삭제됨)`);
142
+ continue;
143
+ }
144
+ lines.push(` ${formatTurnRuleLine(rule, r.score, origin)}`);
145
+ if (r.matchedTerms.length > 0)
146
+ lines.push(` ${dim(`매칭: ${r.matchedTerms.join(', ')}`)}`);
147
+ }
148
+ return lines;
149
+ }
@@ -1,20 +1,65 @@
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
  */
20
+ import { type RateLimitsPayload, type Forecast } from './rate-limit-forecast.js';
21
+ /** 공식 statusline stdin 스키마의 부분집합 (2026-10 확인). 전부 optional — 구버전/다른 플랜은 비어 있을 수 있다. */
22
+ export interface StdinPayload {
23
+ session_id?: string;
24
+ model?: {
25
+ id?: string;
26
+ display_name?: string;
27
+ };
28
+ workspace?: {
29
+ current_dir?: string;
30
+ project_dir?: string;
31
+ };
32
+ context_window?: {
33
+ total_input_tokens?: number;
34
+ total_output_tokens?: number;
35
+ context_window_size?: number;
36
+ used_percentage?: number | null;
37
+ remaining_percentage?: number | null;
38
+ };
39
+ rate_limits?: RateLimitsPayload | null;
40
+ cost?: {
41
+ total_cost_usd?: number;
42
+ total_duration_ms?: number;
43
+ };
44
+ exceeds_200k_tokens?: boolean;
45
+ [key: string]: unknown;
46
+ }
47
+ export declare function readStdinJson(): StdinPayload;
48
+ /** 1줄: 사용자 정보. 데이터 없는 세그먼트는 생략. */
49
+ export declare function buildUserLine(payload: StdinPayload, cwd: string, forecasts: Partial<Record<'five_hour' | 'seven_day', Forecast>>, nowMs: number): string;
50
+ /** 2줄: forgen 정보. 전부 실측 카운터(computeStats = status 와 같은 기준). 실패 시 생략. */
51
+ export declare function buildForgenLine(sessionId: string | undefined): string | null;
52
+ export declare function cachePathFor(sessionId: string | undefined): string;
13
53
  /**
14
- * W1-2 (feature-audit 2026-07-21): forgen 가치 카운터 라인 — invisible 가치 가시화.
15
- * native 플랜/토큰 usage(→ /usage, W2에서 물러남)가 아니라 forgen *자체 활동량*을
16
- * 노출한다: recall 주입·surfaced·교정 캡처·ROI 강등·차단. 전부 computeStats()가 이미
17
- * 실측 중인 카운터라 조작 위험 0. computeStats 실패 시 라인 생략(fail-open).
54
+ * 렌더 — 1줄은 매번, 2줄은 세션별 15초 캐시. 파일 샘플은 기울기 전용이고 **표시는 현재 페이로드에 있는
55
+ * 창만** (critic SEV-1: 옛 샘플을 현재값처럼 보여주지 않는다).
56
+ * @param opts.currentAlreadyAppended handleStatuslineWith 가 이번 샘플을 파일에 이미 append 했으면 true
57
+ * (중복 카운트 방지).
18
58
  */
19
- export declare function buildValueLine(): string | null;
59
+ export declare function renderStatusline(payload: StdinPayload, nowMs?: number, opts?: {
60
+ useForgenCache?: boolean;
61
+ currentAlreadyAppended?: boolean;
62
+ }): string[];
20
63
  export declare function handleStatusline(): Promise<void>;
64
+ /** stdin 읽기를 분리한 본체 — 테스트는 페이로드를 직접 넣는다. */
65
+ export declare function handleStatuslineWith(payload: StdinPayload, nowMs?: number): Promise<void>;
@@ -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
  }
@@ -364,7 +364,8 @@ export async function handleUninstall(cwd, options) {
364
364
  console.log(' 4. Remove forgen block from CLAUDE.md');
365
365
  console.log(' 5. Remove slash commands (~/.claude/commands/forgen/) and the forgen-managed verify skill (~/.claude/skills/verify/)');
366
366
  console.log(' 6. Remove plugin artifacts (cache, installed_plugins.json, plugin directory), dev-guide skills, and the forgen-compound MCP entry in ~/.claude.json');
367
- console.log(' 7. Codex (if $CODEX_HOME or ~/.codex exists): forgen hooks in hooks.json, the MCP/notify blocks in config.toml, forgen skills, ch-*.toml agents, and the AGENTS.md block — hooks and files from other tools are kept');
367
+ console.log(' 7. Codex (if $CODEX_HOME or ~/.codex exists): forgen hooks in hooks.json, the MCP/notify blocks in config.toml, forgen skills, ch-*.toml agents, and the AGENTS.md blocks (every project recorded at install time) — hooks and files from other tools are kept');
368
+ console.log(' OpenCode (if its config dir exists): the forgen plugin, the forgen-compound MCP entry, AGENTS.md blocks');
368
369
  if (options.purge) {
369
370
  console.log(' 8. --purge: Delete ~/.forgen/ entirely (rules, me/, state/, solutions/, behavior/)');
370
371
  console.log(' WARNING: this erases all accumulated corrections, rules, drift, and lifecycle history.');
@@ -409,6 +410,14 @@ export async function handleUninstall(cwd, options) {
409
410
  catch (e) {
410
411
  console.error(' ✗ Codex cleanup failed:', e instanceof Error ? e.message : String(e));
411
412
  }
413
+ try {
414
+ const { planOpencodeUninstall, renderOpencodeUninstall } = await import('../host/uninstall-opencode.js');
415
+ for (const line of renderOpencodeUninstall(planOpencodeUninstall({ pkgRoot })))
416
+ console.log(line);
417
+ }
418
+ catch (e) {
419
+ console.error(' ✗ OpenCode cleanup failed:', e instanceof Error ? e.message : String(e));
420
+ }
412
421
  cleanPluginArtifacts();
413
422
  if (options.purge) {
414
423
  try {