@wooojin/forgen 0.6.4 → 0.6.6

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 (51) hide show
  1. package/.claude-plugin/plugin.json +1 -1
  2. package/CHANGELOG.md +35 -0
  3. package/README.ja.md +1 -1
  4. package/README.ko.md +1 -1
  5. package/README.md +1 -1
  6. package/README.zh.md +1 -1
  7. package/dist/cli.js +2 -2
  8. package/dist/core/block-cli.js +2 -4
  9. package/dist/core/dashboard.js +1 -1
  10. package/dist/core/explain-cli.js +3 -28
  11. package/dist/core/rate-limit-forecast.js +7 -1
  12. package/dist/core/state-gc.d.ts +14 -0
  13. package/dist/core/state-gc.js +47 -4
  14. package/dist/core/stats-cli.js +5 -5
  15. package/dist/core/statusline-cli.d.ts +24 -2
  16. package/dist/core/statusline-cli.js +125 -23
  17. package/dist/core/statusline-install.d.ts +8 -1
  18. package/dist/core/statusline-install.js +34 -3
  19. package/dist/engine/block-judge.js +4 -5
  20. package/dist/engine/context-signals.d.ts +20 -0
  21. package/dist/engine/context-signals.js +102 -0
  22. package/dist/engine/correction-cluster-runner.d.ts +3 -3
  23. package/dist/engine/correction-cluster-runner.js +48 -12
  24. package/dist/engine/correction-clustering.d.ts +27 -0
  25. package/dist/engine/correction-clustering.js +79 -3
  26. package/dist/engine/ko-colloquial.d.ts +13 -0
  27. package/dist/engine/ko-colloquial.js +45 -0
  28. package/dist/engine/lifecycle/lifecycle-cli.js +25 -5
  29. package/dist/engine/lifecycle/meta-reclassifier.d.ts +1 -0
  30. package/dist/engine/lifecycle/meta-reclassifier.js +3 -21
  31. package/dist/engine/lifecycle/rotated-logs.d.ts +18 -0
  32. package/dist/engine/lifecycle/rotated-logs.js +67 -0
  33. package/dist/engine/lifecycle/signals.d.ts +27 -1
  34. package/dist/engine/lifecycle/signals.js +55 -32
  35. package/dist/engine/lifecycle/types.d.ts +5 -0
  36. package/dist/engine/match-eval-log.d.ts +2 -0
  37. package/dist/engine/match-eval-log.js +1 -0
  38. package/dist/engine/ranking-pipeline.d.ts +9 -1
  39. package/dist/engine/ranking-pipeline.js +24 -2
  40. package/dist/engine/solution-format.d.ts +2 -0
  41. package/dist/engine/solution-format.js +6 -2
  42. package/dist/engine/solution-matcher.d.ts +5 -1
  43. package/dist/engine/solution-matcher.js +4 -2
  44. package/dist/hooks/solution-injector.js +7 -2
  45. package/dist/host/codex-hook-shim.d.ts +11 -0
  46. package/dist/host/codex-hook-shim.js +47 -0
  47. package/dist/store/rule-store.d.ts +10 -0
  48. package/dist/store/rule-store.js +26 -2
  49. package/package.json +1 -1
  50. package/plugin.json +1 -1
  51. package/scripts/postinstall.js +12 -7
@@ -35,6 +35,7 @@ import { appendImplicitFeedback } from '../store/implicit-feedback-store.js';
35
35
  import { emitSolutionEvent, querySurfacedWithin } from '../core/observability-store.js';
36
36
  import { parseSolutionV3 } from '../engine/solution-format.js';
37
37
  import { ME_SOLUTIONS } from '../core/paths.js';
38
+ import { buildContextTokens } from '../engine/context-signals.js';
38
39
  const MAX_SOLUTIONS_PER_SESSION = 10;
39
40
  /**
40
41
  * Minimum relevance thresholds by fitness state (2026-04-21 gate sweep).
@@ -471,7 +472,8 @@ async function main() {
471
472
  // allMatched는 backfill 용도로 보존: 이미 injected된 entry라도 같은 솔루션이
472
473
  // 다시 매칭되면 그 정보로 cache의 missing tags를 채울 수 있다.
473
474
  // matches는 새 주입 후보 (이미 injected는 제외).
474
- const allMatched = matchSolutions(input.prompt, scope, cwd);
475
+ const contextTokens = buildContextTokens(cwd, input.session_id);
476
+ const allMatched = matchSolutions(input.prompt, scope, cwd, contextTokens);
475
477
  // Observability P1: matched emit — top-5 후보 각각 기록
476
478
  try {
477
479
  for (const candidate of allMatched.slice(0, 5)) {
@@ -571,10 +573,13 @@ async function main() {
571
573
  for (const sol of matches) {
572
574
  if (injected.has(sol.name))
573
575
  continue;
574
- if (sol.relevance < minRelevanceFor(sol.name))
576
+ // 맥락 가산은 순위에만 — relevance 하한 게이트는 가산 전 값으로 비교한다(맥락만으로 게이트 통과 금지).
577
+ if (sol.relevance - (sol.contextBonus ?? 0) < minRelevanceFor(sol.name))
575
578
  continue;
576
579
  const idMatches = sol.matchedIdentifiers?.length ?? 0;
577
580
  const tagMatches = Math.max(0, sol.matchedTags.length - idMatches);
581
+ // 맥락 토큰(cwd/최근 편집 파일)은 relevance 가산에만 쓰고 이 게이트의 태그 수에는 넣지 않는다.
582
+ // 실측(S16): 범용 프롬프트 토큰 1개 + 맥락 3개를 0.5 가중으로 합산하면 무관한 솔루션이 통과했다.
578
583
  if (idMatches < 1 && tagMatches < 2)
579
584
  continue;
580
585
  if (sol.status === 'experiment') {
@@ -29,3 +29,14 @@ export declare function writeCodexHookShim(pkgRoot: string, nodePath: string, sh
29
29
  * 형태가 다르면(사용자 수정 등) 원문 그대로 반환.
30
30
  */
31
31
  export declare function toShimCommand(command: string, shimPath: string): string;
32
+ export interface ShimMigrationResult {
33
+ status: 'migrated' | 'none' | 'no-hooks-file' | 'shim-foreign' | 'error';
34
+ rewritten: number;
35
+ }
36
+ /**
37
+ * npm postinstall 용 자동 마이그레이션 (2026-10-07, 오너 피드백 "forgen install codex 도 자동으로").
38
+ * hooks.json 의 **이전 형식 forgen 훅 명령만** 제자리에서 shim 형식으로 바꾸고 shim 을 쓴다.
39
+ * 그룹/훅 순서(= Codex trust 키 `<event>:<groupIdx>:<hookIdx>`)·사용자 훅·config.toml 은 건드리지 않는다.
40
+ * Codex 의 trust 승인 자체는 자동화하지 않는다(보안 정책 우회가 되므로) — 전환 후 마지막 1회만 필요.
41
+ */
42
+ export declare function migrateCodexHooksToShim(codexHome: string, pkgRoot: string, nodePath: string): ShimMigrationResult;
@@ -77,3 +77,50 @@ export function toShimCommand(command, shimPath) {
77
77
  const rel = full.slice(root.length + 1);
78
78
  return `"${shimPath}" "${rel}"${rest}`;
79
79
  }
80
+ /** 이전 형식 forgen 훅 명령(`node "<…>/dist/host/codex-adapter.js" "<…>/dist/hooks/…"`)인가. */
81
+ const LEGACY_FORGEN_CMD_RE = /^node "[^"]*[\\/]dist[\\/]host[\\/]codex-adapter\.js" "[^"]*[\\/]dist[\\/]hooks[\\/][a-z][a-z0-9-]*\.js"/;
82
+ /**
83
+ * npm postinstall 용 자동 마이그레이션 (2026-10-07, 오너 피드백 "forgen install codex 도 자동으로").
84
+ * hooks.json 의 **이전 형식 forgen 훅 명령만** 제자리에서 shim 형식으로 바꾸고 shim 을 쓴다.
85
+ * 그룹/훅 순서(= Codex trust 키 `<event>:<groupIdx>:<hookIdx>`)·사용자 훅·config.toml 은 건드리지 않는다.
86
+ * Codex 의 trust 승인 자체는 자동화하지 않는다(보안 정책 우회가 되므로) — 전환 후 마지막 1회만 필요.
87
+ */
88
+ export function migrateCodexHooksToShim(codexHome, pkgRoot, nodePath) {
89
+ const hooksPath = path.join(codexHome, 'hooks.json');
90
+ try {
91
+ if (!fs.existsSync(hooksPath))
92
+ return { status: 'no-hooks-file', rewritten: 0 };
93
+ const raw = fs.readFileSync(hooksPath, 'utf-8');
94
+ const file = JSON.parse(raw);
95
+ const shimPath = codexHookShimPath(codexHome);
96
+ let rewritten = 0;
97
+ for (const groups of Object.values(file.hooks ?? {})) {
98
+ for (const g of groups ?? []) {
99
+ for (const h of g.hooks ?? []) {
100
+ if (typeof h.command !== 'string' || !LEGACY_FORGEN_CMD_RE.test(h.command))
101
+ continue;
102
+ const next = toShimCommand(h.command, shimPath);
103
+ if (next !== h.command) {
104
+ h.command = next;
105
+ rewritten += 1;
106
+ }
107
+ }
108
+ }
109
+ }
110
+ if (rewritten === 0)
111
+ return { status: 'none', rewritten: 0 };
112
+ const w = writeCodexHookShim(pkgRoot, nodePath, shimPath);
113
+ if (w === 'foreign')
114
+ return { status: 'shim-foreign', rewritten: 0 };
115
+ if (w === 'error')
116
+ return { status: 'error', rewritten: 0 };
117
+ fs.copyFileSync(hooksPath, `${hooksPath}.bak-pre-shim`);
118
+ const tmp = `${hooksPath}.tmp-${process.pid}`;
119
+ fs.writeFileSync(tmp, `${JSON.stringify(file, null, 2)}\n`, 'utf-8');
120
+ fs.renameSync(tmp, hooksPath);
121
+ return { status: 'migrated', rewritten };
122
+ }
123
+ catch {
124
+ return { status: 'error', rewritten: 0 };
125
+ }
126
+ }
@@ -57,6 +57,16 @@ export declare function findRuleByRenderKey(renderKey: string, source?: RuleSour
57
57
  * Meta promotion (B→A) 의 rolling window 집계가 이 카운터를 소비한다.
58
58
  */
59
59
  export declare function markRulesInjected(ruleIds: string[], nowIso?: string): void;
60
+ /**
61
+ * lifecycle-scan --apply 가 signals(위반 로그)에서 재계산한 카운터를 저장한다.
62
+ * markRulesInjected 와 같이 updated_at 을 건드리지 않는다 — 카운터 동기화가 T4 decay 의
63
+ * "마지막 갱신" 신호를 리셋하면 안 된다. 값이 같으면 쓰지 않고 false 반환.
64
+ */
65
+ export declare function syncRuleCounters(ruleId: string, counters: {
66
+ violation_count: number;
67
+ bypass_count: number;
68
+ last_violation_at?: string;
69
+ }): boolean;
60
70
  export declare function updateRuleStatus(ruleId: string, status: RuleStatus): boolean;
61
71
  /**
62
72
  * 현재 세션 ID와 다른 scope:'session' 규칙을 비활성화.
@@ -125,8 +125,12 @@ export function loadAllRules() {
125
125
  if (!rule || !isCompatibleSchema(rule, file))
126
126
  continue;
127
127
  const existingIdx = rules.findIndex((r) => r.rule_id === rule.rule_id);
128
- if (existingIdx >= 0)
129
- rules[existingIdx] = rule; // project override
128
+ if (existingIdx >= 0) {
129
+ // project override 는 정책 본문만 — lifecycle(주입/위반 카운터·phase)은 사용자 로컬 상태라 me 쪽을 유지한다.
130
+ // 안 그러면 repo 에 commit 된 룰의 lifecycle(0)이 saveRule 로 me 파일을 덮어써 inject_count 가 리셋된다.
131
+ const meLifecycle = rules[existingIdx].lifecycle;
132
+ rules[existingIdx] = meLifecycle ? { ...rule, lifecycle: meLifecycle } : rule;
133
+ }
130
134
  else
131
135
  rules.push(rule);
132
136
  }
@@ -211,6 +215,26 @@ export function markRulesInjected(ruleIds, nowIso = new Date().toISOString()) {
211
215
  atomicWriteJSON(rulePath(rule.rule_id), updated, { pretty: true });
212
216
  }
213
217
  }
218
+ /**
219
+ * lifecycle-scan --apply 가 signals(위반 로그)에서 재계산한 카운터를 저장한다.
220
+ * markRulesInjected 와 같이 updated_at 을 건드리지 않는다 — 카운터 동기화가 T4 decay 의
221
+ * "마지막 갱신" 신호를 리셋하면 안 된다. 값이 같으면 쓰지 않고 false 반환.
222
+ */
223
+ export function syncRuleCounters(ruleId, counters) {
224
+ const rule = loadRule(ruleId);
225
+ if (!rule)
226
+ return false;
227
+ const lifecycle = initLifecycle(rule);
228
+ const lastViolation = counters.last_violation_at ?? lifecycle.last_violation_at;
229
+ if (lifecycle.violation_count === counters.violation_count && lifecycle.bypass_count === counters.bypass_count && lifecycle.last_violation_at === lastViolation)
230
+ return false;
231
+ const updated = {
232
+ ...rule,
233
+ lifecycle: { ...lifecycle, violation_count: counters.violation_count, bypass_count: counters.bypass_count, last_violation_at: lastViolation },
234
+ };
235
+ atomicWriteJSON(rulePath(rule.rule_id), updated, { pretty: true });
236
+ return true;
237
+ }
214
238
  export function updateRuleStatus(ruleId, status) {
215
239
  const rule = loadRule(ruleId);
216
240
  if (!rule)
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@wooojin/forgen",
3
- "version": "0.6.4",
3
+ "version": "0.6.6",
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.4",
4
+ "version": "0.6.6",
5
5
  "description": "Claude Code harness — the more you use Claude, the better it gets",
6
6
  "author": {
7
7
  "name": "jang-ujin",
@@ -272,8 +272,11 @@ function applyStatusLineAuto(settings) {
272
272
  const existing = settings.statusLine && settings.statusLine.command;
273
273
  const owned = !existing || /^forgen(\s|$)/.test(String(existing).trim()) || /[\\/]dist[\\/]cli\.js"?\s+statusline(\s|$)/.test(String(existing));
274
274
  if (!owned) return 'custom';
275
- if (existing === cmd) return 'unchanged';
276
- settings.statusLine = { type: 'command', command: cmd };
275
+ // 체인(`… statusline --after '<원본>'`)이면 forgen 경로만 갱신하고 --after 이후는 보존한다.
276
+ const chainAt = existing ? String(existing).search(/\sstatusline\s+--after\s/) : -1;
277
+ const next = chainAt >= 0 ? `${cmd}${String(existing).slice(chainAt + ' statusline'.length)}` : cmd;
278
+ if (existing === next) return 'unchanged';
279
+ settings.statusLine = { type: 'command', command: next };
277
280
  return existing ? 'updated' : 'installed';
278
281
  }
279
282
 
@@ -1022,11 +1025,12 @@ async function main() {
1022
1025
  const r = shimMod.writeCodexHookShim(PKG_ROOT, process.execPath, shimFile);
1023
1026
  if (r === 'written') console.log('[forgen] Codex hook shim updated → no /hooks re-trust needed.');
1024
1027
  } 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.');
1028
+ // 이전 형식(node + 절대경로) forgen 훅 → shim 형식으로 자동 전환 (forgen 훅 명령만, 순서·사용자 훅 보존).
1029
+ const codexHome = process.env.CODEX_HOME || join(HOME, '.codex');
1030
+ const r = shimMod.migrateCodexHooksToShim(codexHome, PKG_ROOT, process.execPath);
1031
+ if (r.status === 'migrated') {
1032
+ console.log(`[forgen] Codex: ${r.rewritten} forgen hooks switched to a stable shim (backup: hooks.json.bak-pre-shim).`);
1033
+ console.log('[forgen] Approve once in Codex (/hooks → trust all). Future upgrades and nvm switches keep the trust.');
1030
1034
  }
1031
1035
  }
1032
1036
  } catch { /* dist 없음(dev) 또는 실패 — 다음 forgen install codex 가 처리 */ }
@@ -1184,6 +1188,7 @@ async function main() {
1184
1188
  } else if (statusLineResult === 'custom') {
1185
1189
  console.log('[forgen] statusLine is set to another command (e.g. claude-hud) — left untouched.');
1186
1190
  console.log('[forgen] To switch to forgen (backup kept in statusLine_backup): forgen statusline install --force');
1191
+ console.log('[forgen] To keep it AND show forgen\'s line after it (chain, original kept in statusLine_backup): forgen statusline install --chain');
1187
1192
  }
1188
1193
 
1189
1194
  // First-run banner (신규 사용자 안내) — feat/codex-support P1-6