@wooojin/forgen 0.6.5 → 0.6.7

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 (58) hide show
  1. package/.claude-plugin/plugin.json +1 -1
  2. package/CHANGELOG.md +41 -0
  3. package/README.ja.md +2 -1
  4. package/README.ko.md +2 -1
  5. package/README.md +2 -1
  6. package/README.zh.md +2 -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/classify-enforce-cli.js +40 -0
  21. package/dist/engine/context-signals.d.ts +20 -0
  22. package/dist/engine/context-signals.js +102 -0
  23. package/dist/engine/correction-cluster-runner.d.ts +3 -3
  24. package/dist/engine/correction-cluster-runner.js +48 -12
  25. package/dist/engine/correction-clustering.d.ts +27 -0
  26. package/dist/engine/correction-clustering.js +79 -3
  27. package/dist/engine/enforce-classifier.d.ts +28 -1
  28. package/dist/engine/enforce-classifier.js +90 -19
  29. package/dist/engine/ko-colloquial.d.ts +13 -0
  30. package/dist/engine/ko-colloquial.js +45 -0
  31. package/dist/engine/lifecycle/lifecycle-cli.js +25 -5
  32. package/dist/engine/lifecycle/meta-reclassifier.d.ts +1 -0
  33. package/dist/engine/lifecycle/meta-reclassifier.js +3 -21
  34. package/dist/engine/lifecycle/rotated-logs.d.ts +18 -0
  35. package/dist/engine/lifecycle/rotated-logs.js +67 -0
  36. package/dist/engine/lifecycle/signals.d.ts +27 -1
  37. package/dist/engine/lifecycle/signals.js +55 -32
  38. package/dist/engine/lifecycle/types.d.ts +5 -0
  39. package/dist/engine/match-eval-log.d.ts +2 -0
  40. package/dist/engine/match-eval-log.js +1 -0
  41. package/dist/engine/ranking-pipeline.d.ts +9 -1
  42. package/dist/engine/ranking-pipeline.js +24 -2
  43. package/dist/engine/solution-format.d.ts +2 -0
  44. package/dist/engine/solution-format.js +6 -2
  45. package/dist/engine/solution-matcher.d.ts +5 -1
  46. package/dist/engine/solution-matcher.js +4 -2
  47. package/dist/hooks/post-tool-use.js +3 -1
  48. package/dist/hooks/shared/stop-triggers.d.ts +32 -4
  49. package/dist/hooks/shared/stop-triggers.js +44 -3
  50. package/dist/hooks/solution-injector.js +7 -2
  51. package/dist/hooks/stop-guard.d.ts +2 -2
  52. package/dist/hooks/stop-guard.js +85 -10
  53. package/dist/store/rule-store.d.ts +16 -0
  54. package/dist/store/rule-store.js +34 -2
  55. package/dist/store/types.d.ts +5 -1
  56. package/package.json +1 -1
  57. package/plugin.json +1 -1
  58. package/scripts/postinstall.js +23 -2
@@ -90,7 +90,7 @@ export function rulesFromStore(rules) {
90
90
  continue;
91
91
  if (!spec.verifier)
92
92
  continue;
93
- if (spec.verifier.kind !== 'self_check_prompt' && spec.verifier.kind !== 'artifact_check')
93
+ if (spec.verifier.kind !== 'self_check_prompt' && spec.verifier.kind !== 'artifact_check' && spec.verifier.kind !== 'tool_evidence' && spec.verifier.kind !== 'language_ratio')
94
94
  continue;
95
95
  out.push({
96
96
  id: rule.rule_id,
@@ -189,15 +189,90 @@ function messageTriggersRule(message, rule) {
189
189
  return false;
190
190
  if (!safeRegexTest(includeRes.regex, m))
191
191
  return false;
192
- if (t.context_exclude_regex) {
193
- const excludeRes = compileSafeRegex(t.context_exclude_regex, 'i');
194
- if (excludeRes.regex && safeRegexTest(excludeRes.regex, m))
195
- return false;
192
+ if (!t.context_exclude_regex)
193
+ return true;
194
+ const excludeRes = compileSafeRegex(t.context_exclude_regex, 'i');
195
+ if (!excludeRes.regex)
196
+ return true;
197
+ // 2026-10-07: 제외 조건은 **매칭이 일어난 문장**에만 적용한다. 이전엔 메시지 전체를 봐서 "끝났습니다. 실패는
198
+ // 없습니다" 처럼 다른 문장의 '없습니다' 때문에 정상 완료 보고의 67% 를 놓쳤다(30일 실측).
199
+ // 길이 0 매칭(lookahead 결합 트리거)은 문장을 특정할 수 없어 기존처럼 메시지 전체로 판단.
200
+ const sentences = matchedSentences(m, includeRes.regex);
201
+ if (sentences === null)
202
+ return !safeRegexTest(excludeRes.regex, m);
203
+ return sentences.some((s) => !safeRegexTest(excludeRes.regex, s));
204
+ }
205
+ /** 문장 경계 — 줄바꿈, 반각 마침표류(. ! ?) 뒤 공백, 전각 마침표류(。!?) 뒤. 마침표는 앞 문장에 속한다. */
206
+ // 전각 부호(。!?)는 일·중 표기에서 공백 없이 이어 쓰므로 공백 없이도 경계(critic 재검증 SEV-3).
207
+ const SENTENCE_BOUNDARY = /\r?\n|(?<=[.!?])[ \t]+|(?<=[。!?])[ \t]*/g;
208
+ /** 텍스트 상한 — safeRegexTest 와 같은 절단(긴 최종 보고에서 Stop 훅 timeout 방지). */
209
+ const SENTENCE_SCAN_MAX = 65536;
210
+ /**
211
+ * include 매칭마다 **매칭의 마지막 글자가 속한 문장**을 돌려준다. 길이 0 매칭만 있으면 null.
212
+ * (critic SEV-1: 이전 구현은 매칭 자체의 끝 '다. ' 를 경계로 오인해 빈 문장/다음 문장을 판정했다.)
213
+ */
214
+ function matchedSentences(raw, re) {
215
+ const text = raw.length > SENTENCE_SCAN_MAX ? raw.slice(0, SENTENCE_SCAN_MAX) : raw;
216
+ const bounds = [];
217
+ let from = 0;
218
+ for (const b of text.matchAll(SENTENCE_BOUNDARY)) {
219
+ const at = b.index ?? 0;
220
+ bounds.push([from, at]);
221
+ from = at + b[0].length;
222
+ }
223
+ bounds.push([from, text.length]);
224
+ const sentenceAt = (pos) => {
225
+ for (const [a, z] of bounds)
226
+ if (pos >= a && pos < z)
227
+ return text.slice(a, z);
228
+ return '';
229
+ };
230
+ const g = new RegExp(re.source, re.flags.includes('g') ? re.flags : `${re.flags}g`);
231
+ const out = [];
232
+ let sawNonEmpty = false;
233
+ let guard = 0;
234
+ for (let mm = g.exec(text); mm && guard < 50; mm = g.exec(text), guard++) {
235
+ if (mm[0].length === 0) {
236
+ g.lastIndex++;
237
+ continue;
238
+ }
239
+ sawNonEmpty = true;
240
+ out.push(sentenceAt(mm.index + mm[0].length - 1));
196
241
  }
197
- return true;
242
+ return sawNonEmpty ? out : null;
198
243
  }
199
- function evaluateVerifier(rule) {
244
+ function evaluateVerifier(rule, recentTools = [], message = '') {
200
245
  const v = rule.verifier;
246
+ // 2026-10-07: 언어 룰 — 코드·URL·경로를 뺀 본문 글자 중 한글 비율. 기준 미달이면 위반.
247
+ if (v.kind === 'language_ratio') {
248
+ const body = message.replace(/```[\s\S]*?```/g, ' ').replace(/`[^`]*`/g, ' ').replace(/https?:\/\/\S+/g, ' ').replace(/[~./\\][\w./\\-]+/g, ' ');
249
+ const letters = body.match(/[A-Za-z가-힣]/g) ?? [];
250
+ if (letters.length < 20)
251
+ return { violated: false, reason: '' };
252
+ const hangul = letters.filter((c) => /[가-힣]/.test(c)).length;
253
+ const ratio = hangul / letters.length;
254
+ const min = Number(v.params.min_ratio ?? 0.5);
255
+ return ratio >= min ? { violated: false, reason: '' } : { violated: true, reason: String(v.params.question ?? '한국어로 다시 답하라.') };
256
+ }
257
+ // 2026-10-07: 자기 신고("위반 없음") 대신 실행 기록으로 판정 — 최근 도구 호출에 지정 도구가 있으면 통과.
258
+ // (critic 룰: 30일 실측에서 차단 후 실제 critic 실행 29%, 말로만 통과 29%.)
259
+ if (v.kind === 'tool_evidence') {
260
+ const want = String(v.params.tools ?? 'Agent,Task,Workflow').split(',').map((s) => s.trim()).filter(Boolean);
261
+ const window = Number(v.params.window ?? 60);
262
+ // 도구 기록이 아예 없으면(기록하지 않는 호스트·세션 id 불명) 판정 불가 → 통과(fail-open). 증거 부재와 기록 부재를 구분.
263
+ if (recentTools.length === 0)
264
+ return { violated: false, reason: '' };
265
+ // 청크 경계 증거(커밋 해시·커밋·배포 등)가 메시지에 없으면 이 룰의 대상(청크 완료)이 아니다 — 정규식 lookahead 대신 선형 검사.
266
+ if (typeof v.params.only_if === 'string') {
267
+ const only = compileSafeRegex(v.params.only_if, 'i');
268
+ if (only.regex && !safeRegexTest(only.regex, message))
269
+ return { violated: false, reason: '' };
270
+ }
271
+ const tail = recentTools.slice(-window);
272
+ if (tail.some((t) => want.includes(t)))
273
+ return { violated: false, reason: '' };
274
+ return { violated: true, reason: String(v.params.question ?? rule.block_message ?? `최근 작업에 ${want.join('/')} 실행 기록이 없음`) };
275
+ }
201
276
  if (v.kind === 'self_check_prompt') {
202
277
  const q = String(v.params.question ?? rule.block_message ?? '자가점검 필요');
203
278
  // self_check_prompt 는 증거가 없으면(artifact path 미지정/미존재) 위반 간주.
@@ -278,7 +353,7 @@ function artifactFresh(relOrAbs, maxAgeS) {
278
353
  }
279
354
  }
280
355
  /** Pure core — 단위 테스트용. stdin/IO 없음. */
281
- export function evaluateStop(lastAssistantMessage, rules) {
356
+ export function evaluateStop(lastAssistantMessage, rules, recentTools = []) {
282
357
  // ADR-017 D2: 실제 평가돼 통과한 룰(passed)과, D1 advise 강등으로 차단 대신 기록만 하는 룰(advised)을 함께 반환.
283
358
  const passed = [];
284
359
  const advised = [];
@@ -287,7 +362,7 @@ export function evaluateStop(lastAssistantMessage, rules) {
287
362
  continue;
288
363
  if (!messageTriggersRule(lastAssistantMessage, rule))
289
364
  continue;
290
- const result = evaluateVerifier(rule);
365
+ const result = evaluateVerifier(rule, recentTools, lastAssistantMessage);
291
366
  if (result.violated) {
292
367
  if (rule.enforce_mode === 'advise') {
293
368
  advised.push({ rule, reason: result.reason });
@@ -550,8 +625,8 @@ export async function main() {
550
625
  console.log(approveWithOptionalExtractionNotice());
551
626
  return;
552
627
  }
553
- const result = evaluateStop(lastMessage, rules);
554
628
  const sessionId = input?.session_id ?? 'unknown';
629
+ const result = evaluateStop(lastMessage, rules, loadRecentToolNames(sessionId));
555
630
  // ADR-017 D2: 실제 평가된 룰의 통과를 checks.jsonl 에 기록(violations 와 분리). D1: advise 강등 룰의
556
631
  // 위반은 kind:'correction' 으로 기록만 하고 차단하지 않는다.
557
632
  for (const id of result.passed)
@@ -32,6 +32,12 @@ export declare function appendRule(rule: Rule): Promise<{
32
32
  }>;
33
33
  export declare function loadRule(ruleId: string): Rule | null;
34
34
  export declare function loadAllRules(): Rule[];
35
+ /**
36
+ * 현재 프로젝트 cwd 의 `.forgen/rules/` 경로. FORGEN_CWD/COMPOUND_CWD 우선.
37
+ * 테스트 / CI 에서 프로젝트 스코프 로딩을 비활성화하려면 FORGEN_DISABLE_PROJECT_RULES=1.
38
+ */
39
+ /** 이 룰을 덮어쓰는 프로젝트 룰 파일(<cwd>/.forgen/rules/<id>.json)이 있으면 그 경로. 없으면 null. */
40
+ export declare function projectRuleOverridePath(ruleId: string): string | null;
35
41
  export declare function loadActiveRules(): Rule[];
36
42
  /**
37
43
  * render_key(+source, +scope)로 기존 rule을 찾는다 — status 무관(active/suppressed/removed/
@@ -57,6 +63,16 @@ export declare function findRuleByRenderKey(renderKey: string, source?: RuleSour
57
63
  * Meta promotion (B→A) 의 rolling window 집계가 이 카운터를 소비한다.
58
64
  */
59
65
  export declare function markRulesInjected(ruleIds: string[], nowIso?: string): void;
66
+ /**
67
+ * lifecycle-scan --apply 가 signals(위반 로그)에서 재계산한 카운터를 저장한다.
68
+ * markRulesInjected 와 같이 updated_at 을 건드리지 않는다 — 카운터 동기화가 T4 decay 의
69
+ * "마지막 갱신" 신호를 리셋하면 안 된다. 값이 같으면 쓰지 않고 false 반환.
70
+ */
71
+ export declare function syncRuleCounters(ruleId: string, counters: {
72
+ violation_count: number;
73
+ bypass_count: number;
74
+ last_violation_at?: string;
75
+ }): boolean;
60
76
  export declare function updateRuleStatus(ruleId: string, status: RuleStatus): boolean;
61
77
  /**
62
78
  * 현재 세션 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
  }
@@ -151,6 +155,14 @@ function isCompatibleSchema(rule, filename) {
151
155
  * 현재 프로젝트 cwd 의 `.forgen/rules/` 경로. FORGEN_CWD/COMPOUND_CWD 우선.
152
156
  * 테스트 / CI 에서 프로젝트 스코프 로딩을 비활성화하려면 FORGEN_DISABLE_PROJECT_RULES=1.
153
157
  */
158
+ /** 이 룰을 덮어쓰는 프로젝트 룰 파일(<cwd>/.forgen/rules/<id>.json)이 있으면 그 경로. 없으면 null. */
159
+ export function projectRuleOverridePath(ruleId) {
160
+ const dir = resolveProjectRulesDir();
161
+ if (!dir)
162
+ return null;
163
+ const p = path.join(dir, `${ruleId}.json`);
164
+ return fs.existsSync(p) ? p : null;
165
+ }
154
166
  function resolveProjectRulesDir() {
155
167
  if (process.env.FORGEN_DISABLE_PROJECT_RULES === '1')
156
168
  return null;
@@ -211,6 +223,26 @@ export function markRulesInjected(ruleIds, nowIso = new Date().toISOString()) {
211
223
  atomicWriteJSON(rulePath(rule.rule_id), updated, { pretty: true });
212
224
  }
213
225
  }
226
+ /**
227
+ * lifecycle-scan --apply 가 signals(위반 로그)에서 재계산한 카운터를 저장한다.
228
+ * markRulesInjected 와 같이 updated_at 을 건드리지 않는다 — 카운터 동기화가 T4 decay 의
229
+ * "마지막 갱신" 신호를 리셋하면 안 된다. 값이 같으면 쓰지 않고 false 반환.
230
+ */
231
+ export function syncRuleCounters(ruleId, counters) {
232
+ const rule = loadRule(ruleId);
233
+ if (!rule)
234
+ return false;
235
+ const lifecycle = initLifecycle(rule);
236
+ const lastViolation = counters.last_violation_at ?? lifecycle.last_violation_at;
237
+ if (lifecycle.violation_count === counters.violation_count && lifecycle.bypass_count === counters.bypass_count && lifecycle.last_violation_at === lastViolation)
238
+ return false;
239
+ const updated = {
240
+ ...rule,
241
+ lifecycle: { ...lifecycle, violation_count: counters.violation_count, bypass_count: counters.bypass_count, last_violation_at: lastViolation },
242
+ };
243
+ atomicWriteJSON(rulePath(rule.rule_id), updated, { pretty: true });
244
+ return true;
245
+ }
214
246
  export function updateRuleStatus(ruleId, status) {
215
247
  const rule = loadRule(ruleId);
216
248
  if (!rule)
@@ -17,7 +17,11 @@ export type RuleSource = 'onboarding' | 'explicit_correction' | 'behavior_infere
17
17
  export type RuleStatus = 'active' | 'suppressed' | 'removed' | 'superseded';
18
18
  export type EnforcementMech = 'A' | 'B' | 'C';
19
19
  export type HookPoint = 'PreToolUse' | 'PostToolUse' | 'Stop' | 'UserPromptSubmit';
20
- export type VerifierKind = 'file_exists' | 'pattern_match' | 'tool_arg_regex' | 'artifact_check' | 'self_check_prompt';
20
+ export type VerifierKind = 'file_exists' | 'pattern_match' | 'tool_arg_regex' | 'artifact_check' | 'self_check_prompt'
21
+ /** 2026-10-07: 최근 도구 호출 기록에 지정 도구(params.tools)가 있으면 통과 — 자기 신고 대신 실행 증거. */
22
+ | 'tool_evidence'
23
+ /** 2026-10-07: 응답의 문자 비율(params.script='hangul', min_ratio)로 언어 룰을 기계 판정. */
24
+ | 'language_ratio';
21
25
  export interface VerifierSpec {
22
26
  kind: VerifierKind;
23
27
  /** 각 kind 별로 의미가 다름 — 예: self_check_prompt 는 `question`, artifact_check 는 `path`+`max_age_s`. */
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@wooojin/forgen",
3
- "version": "0.6.5",
3
+ "version": "0.6.7",
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.5",
4
+ "version": "0.6.7",
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
 
@@ -1032,6 +1035,23 @@ async function main() {
1032
1035
  }
1033
1036
  } catch { /* dist 없음(dev) 또는 실패 — 다음 forgen install codex 가 처리 */ }
1034
1037
 
1038
+ // ── 2.4b. Stop 룰 발동 조건 재조정 1회 마이그레이션 (2026-10-07, v0.6.7) ──
1039
+ // 룰별 발동 조건·critic 실행 증거 판정은 룰 파일에 구워져 있어 업그레이드만으론 반영되지 않는다.
1040
+ // 사용자 룰만 대상(프로젝트 룰은 git 소스라 건드리지 않음). 마커로 1회만.
1041
+ try {
1042
+ const forgenHome = process.env.FORGEN_HOME || join(HOME, '.forgen');
1043
+ const marker = join(forgenHome, 'state', 'stop-retune-v1.done');
1044
+ if (existsSync(join(forgenHome, 'me', 'rules')) && !existsSync(marker)) {
1045
+ process.env.FORGEN_HOME = forgenHome;
1046
+ process.env.FORGEN_DISABLE_PROJECT_RULES = '1';
1047
+ const mod = await import(join(PKG_ROOT, 'dist', 'engine', 'enforce-classifier.js'));
1048
+ const n = await mod.applyStopRetuneToUserRules();
1049
+ mkdirSync(join(forgenHome, 'state'), { recursive: true });
1050
+ writeFileSync(marker, `${new Date().toISOString()} changed=${n}\n`);
1051
+ if (n > 0) console.log(`[forgen] Stop rules retuned: ${n} rule(s) now fire on their own claim (forgen rule classify --stop-only to review).`);
1052
+ }
1053
+ } catch (err) { console.error(`[forgen] Stop rule retune skipped: ${err?.message ?? err}`); }
1054
+
1035
1055
  // ── 2.5. statusLine 자동 등록 (settings 단일 쓰기에 포함) ──
1036
1056
  let statusLineResult = 'unchanged';
1037
1057
  try { statusLineResult = applyStatusLineAuto(settings); } catch (err) { console.error(`[forgen] statusLine setup skipped: ${err?.message ?? err}`); }
@@ -1185,6 +1205,7 @@ async function main() {
1185
1205
  } else if (statusLineResult === 'custom') {
1186
1206
  console.log('[forgen] statusLine is set to another command (e.g. claude-hud) — left untouched.');
1187
1207
  console.log('[forgen] To switch to forgen (backup kept in statusLine_backup): forgen statusline install --force');
1208
+ console.log('[forgen] To keep it AND show forgen\'s line after it (chain, original kept in statusLine_backup): forgen statusline install --chain');
1188
1209
  }
1189
1210
 
1190
1211
  // First-run banner (신규 사용자 안내) — feat/codex-support P1-6