@wooojin/forgen 0.5.9 → 0.6.2

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 (66) hide show
  1. package/.claude-plugin/plugin.json +1 -1
  2. package/CHANGELOG.md +76 -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 +66 -13
  23. package/dist/core/statusline-cli.js +182 -203
  24. package/dist/core/v1-bootstrap.js +7 -1
  25. package/dist/engine/block-judge-cli.d.ts +2 -0
  26. package/dist/engine/block-judge-cli.js +11 -0
  27. package/dist/engine/block-judge.d.ts +68 -0
  28. package/dist/engine/block-judge.js +248 -0
  29. package/dist/engine/correction-cluster-runner.d.ts +67 -0
  30. package/dist/engine/correction-cluster-runner.js +242 -5
  31. package/dist/engine/correction-clustering.d.ts +15 -0
  32. package/dist/engine/correction-clustering.js +24 -0
  33. package/dist/engine/lifecycle/lifecycle-cli.js +7 -4
  34. package/dist/engine/lifecycle/signals.d.ts +59 -2
  35. package/dist/engine/lifecycle/signals.js +193 -4
  36. package/dist/engine/lifecycle/trigger-t3-bypass.d.ts +5 -3
  37. package/dist/engine/lifecycle/trigger-t3-bypass.js +6 -4
  38. package/dist/engine/lifecycle/types.d.ts +29 -1
  39. package/dist/engine/mined-rule-merge-cli.d.ts +11 -0
  40. package/dist/engine/mined-rule-merge-cli.js +67 -0
  41. package/dist/engine/rule-relevance.d.ts +72 -0
  42. package/dist/engine/rule-relevance.js +183 -0
  43. package/dist/engine/rule-toggle-cli.d.ts +5 -0
  44. package/dist/engine/rule-toggle-cli.js +30 -0
  45. package/dist/fgx.js +1 -1
  46. package/dist/forge/evidence-processor.js +2 -0
  47. package/dist/hooks/post-tool-use.js +9 -14
  48. package/dist/hooks/pre-tool-use.js +71 -8
  49. package/dist/hooks/shared/command-parser.d.ts +11 -0
  50. package/dist/hooks/shared/command-parser.js +120 -0
  51. package/dist/hooks/solution-injector.js +13 -0
  52. package/dist/hooks/stop-guard.d.ts +18 -0
  53. package/dist/hooks/stop-guard.js +55 -10
  54. package/dist/mcp/tools.js +7 -1
  55. package/dist/renderer/inspect-renderer.js +23 -6
  56. package/dist/renderer/rule-renderer.js +4 -2
  57. package/dist/store/evidence-store.js +37 -2
  58. package/dist/store/profile-score.d.ts +55 -0
  59. package/dist/store/profile-score.js +100 -0
  60. package/dist/store/profile-store.d.ts +22 -5
  61. package/dist/store/profile-store.js +42 -6
  62. package/dist/store/rule-origin.d.ts +39 -0
  63. package/dist/store/rule-origin.js +84 -0
  64. package/dist/store/types.d.ts +24 -0
  65. package/package.json +1 -1
  66. package/plugin.json +1 -1
@@ -0,0 +1,183 @@
1
+ /**
2
+ * Rule relevance — "이번 턴에 어떤 룰이 관련 있는가" (ADR-017 D2, 턴 단위 룰 관련도)
3
+ *
4
+ * UserPromptSubmit 에서 프롬프트를 활성 룰의 `trigger`/`policy` 용어와 매칭해
5
+ * `state/turn-rules-<session>.json` 에 기록한다. statusline 이 이 파일을 읽어 "관련 룰 N" 을 보여주고
6
+ * `forgen status --turn` 이 각 룰의 원 교정(날짜·종류·사용자 발화)을 함께 보여준다.
7
+ *
8
+ * 정직성 원칙:
9
+ * - "관련" 이지 "적용" 이 아니다. 모델이 룰을 따랐는지는 여기서 알 수 없다(ADR-017 §5 — 인용 태그는 보류).
10
+ * - 프롬프트 원문은 저장하지 않는다. sha256 앞 16자만 남긴다(어느 프롬프트의 결과인지 대조용).
11
+ * - 프롬프트 주입에는 아무것도 보태지 않는다 — 토큰 비용 0.
12
+ *
13
+ * 매칭 (solution-matcher 와 같은 term 매칭 재사용):
14
+ * - 룰 용어: `extractTags`(solution-format) 를 trigger + policy 의 8단어 창마다 돌려 합친다. extractTags 는
15
+ * 빈도순 8개 cap 이 있어 긴 policy 를 통째로 넣으면 핵심 명사가 잘린다 — 8단어 창이면 cap 이 안 걸린다.
16
+ * - 프롬프트 매칭: `classifyMatch`(term-matcher) 를 **전체 룰 용어 합집합에 대해 한 번** 호출한다 —
17
+ * 프롬프트 NFC 정규화·한글 stem Set 계산이 룰 수와 무관하게 1회. 영문은 단어 경계, 한글은 조사 제거 후 비교.
18
+ * - 공통어 제외: term-matcher NEGATIVE_TERM_BLOCKLIST(코드/파일/테스트 …) + scoring-algorithms COMMON_TAGS
19
+ * (수정/추가/함수 …) + 룰 문장에 흔한 메타어(RULE_COMMON_TERMS: 사용자/작업/먼저/금지 …).
20
+ *
21
+ * 임계 (보수적 — 거짓 양성이 신뢰를 깎는다):
22
+ * 용어마다 가중치: 식별자급 1.0, 일반 0.5. 합 ≥ 1.0 이면 관련.
23
+ * 즉 **일반 용어 2개 이상, 또는 식별자급 용어 1개**.
24
+ * 식별자급 = 영문/숫자 6자 이상(`statusline`, `codex-cli`) 또는 한글 3음절 이상(`한국어`, `에이전트`, `리서치`).
25
+ * 한글은 음절당 정보량이 라틴 문자의 약 2배라 3음절을 영문 6자에 대응시켰다 — 2음절어(설계·검증·병렬)는
26
+ * 단독으로는 잡지 않는다. ("한국어로 답해" 가 '사용자 응답 언어' 룰을 잡아야 한다는 ADR-017 §검증 기준.)
27
+ *
28
+ * 비용: 룰 100개 × 프롬프트 1개 5ms 이내(테스트로 고정). 프롬프트는 앞 32KB 만 본다.
29
+ */
30
+ import * as crypto from 'node:crypto';
31
+ import * as fs from 'node:fs';
32
+ import * as path from 'node:path';
33
+ import { STATE_DIR } from '../core/paths.js';
34
+ import { atomicWriteJSON, safeReadJSON } from '../hooks/shared/atomic-write.js';
35
+ import { sanitizeId } from '../hooks/shared/sanitize-id.js';
36
+ import { COMMON_TAGS } from './scoring-algorithms.js';
37
+ import { extractTags } from './solution-format.js';
38
+ import { classifyMatch, filterMatchableTerms } from './term-matcher.js';
39
+ export const RELEVANCE_THRESHOLD = 1.0;
40
+ const SPECIFIC_WEIGHT = 1.0;
41
+ const GENERIC_WEIGHT = 0.5;
42
+ const SPECIFIC_LATIN_MIN = 6;
43
+ const SPECIFIC_HANGUL_MIN = 3;
44
+ /** 프롬프트 매칭 상한 — 붙여넣기 대용량 프롬프트가 훅 지연을 만들지 않게. */
45
+ const PROMPT_MAX_CHARS = 32_000;
46
+ export const PROMPT_HASH_LENGTH = 16;
47
+ /**
48
+ * 룰 문장에 흔히 등장하지만 "이 턴과 관련" 의 근거가 못 되는 메타어.
49
+ * NEGATIVE_TERM_BLOCKLIST(코드/파일/테스트/에러) · COMMON_TAGS(수정/추가/함수) 와 합쳐 제외한다.
50
+ */
51
+ export const RULE_COMMON_TERMS = new Set([
52
+ // 한국어 — 룰 policy 의 상투어
53
+ '사용자', '오너', '작업', '기능', '요청', '방식', '방법', '단계', '진행', '시작', '완료', '상황', '전체', '필요',
54
+ '이전', '앞으로', '반드시', '명시', '지시', '먼저', '금지', '가능', '결과', '내용', '정리', '확인', '처리',
55
+ '규칙', '정책', '기준', '순서', '상태', '경우', '대상', '포함', '제외', '실제', '실행', '유지', '우선',
56
+ '새로운', '기존', '현재', '이후', '이렇게', '그렇게', '하지', '말것', '않는다', '한다', '해야', '해라', '하라',
57
+ // 영어 — 프로젝트/도구 이름 등 어느 프롬프트에나 나오는 것
58
+ 'forgen', 'claude', 'user', 'users', 'rule', 'rules', 'work', 'task', 'tasks', 'session', 'sessions',
59
+ 'project', 'make', 'need', 'needs', 'always', 'never', 'must', 'please', 'help', 'want',
60
+ ]);
61
+ /** 영문/숫자 6자 이상 또는 한글 3음절 이상 — 단독으로도 관련 근거가 되는 용어. */
62
+ export function isSpecificTerm(term) {
63
+ if (/[가-힣]/.test(term))
64
+ return term.length >= SPECIFIC_HANGUL_MIN;
65
+ return term.length >= SPECIFIC_LATIN_MIN;
66
+ }
67
+ function isCommonTerm(term) {
68
+ const t = term.toLowerCase();
69
+ return RULE_COMMON_TERMS.has(t) || COMMON_TAGS.has(t);
70
+ }
71
+ /**
72
+ * extractTags 는 호출당 최대 8개(빈도순)만 돌려준다. 단어 8개짜리 창으로 잘라 호출하면 창마다 후보가 8개
73
+ * 이하라 cap 이 절대 걸리지 않는다 — 실 룰 45개 중 43개가 문장 단위 호출에서는 용어를 잃었다(실측).
74
+ */
75
+ const TERM_WINDOW_WORDS = 8;
76
+ /**
77
+ * 룰 한 개의 매칭 용어. trigger + policy 를 8단어 창으로 extractTags 해 합친다(손실 없음).
78
+ * 반환은 중복 제거·필터(길이/블록리스트/공통어) 완료 상태.
79
+ */
80
+ export function ruleTerms(rule) {
81
+ const words = `${rule.trigger ?? ''} ${rule.policy ?? ''}`.split(/\s+/).filter(Boolean);
82
+ const seen = new Set();
83
+ for (let i = 0; i < words.length; i += TERM_WINDOW_WORDS) {
84
+ for (const tag of extractTags(words.slice(i, i + TERM_WINDOW_WORDS).join(' ')))
85
+ seen.add(tag);
86
+ }
87
+ return filterMatchableTerms([...seen]).filter((t) => !isCommonTerm(t));
88
+ }
89
+ function scoreTerms(terms) {
90
+ let s = 0;
91
+ for (const t of terms)
92
+ s += isSpecificTerm(t) ? SPECIFIC_WEIGHT : GENERIC_WEIGHT;
93
+ return Math.round(s * 100) / 100;
94
+ }
95
+ /**
96
+ * 프롬프트와 관련된 룰. 순수 함수 — IO 없음. 임계 이상만, score 내림차순(동점은 rule_id 순).
97
+ */
98
+ export function relevantRules(prompt, rules) {
99
+ if (!prompt || rules.length === 0)
100
+ return [];
101
+ const text = prompt.length > PROMPT_MAX_CHARS ? prompt.slice(0, PROMPT_MAX_CHARS) : prompt;
102
+ const termsByRule = [];
103
+ const union = new Set();
104
+ for (const rule of rules) {
105
+ const terms = ruleTerms(rule);
106
+ if (terms.length === 0)
107
+ continue;
108
+ termsByRule.push({ rule_id: rule.rule_id, terms });
109
+ for (const t of terms)
110
+ union.add(t);
111
+ }
112
+ if (union.size === 0)
113
+ return [];
114
+ // 프롬프트 정규화·한글 stem 은 이 한 번의 호출 안에서만 계산된다.
115
+ const matched = new Set(classifyMatch(text, [], [...union]).matchedTags);
116
+ if (matched.size === 0)
117
+ return [];
118
+ const out = [];
119
+ for (const { rule_id, terms } of termsByRule) {
120
+ const hits = terms.filter((t) => matched.has(t));
121
+ if (hits.length === 0)
122
+ continue;
123
+ const score = scoreTerms(hits);
124
+ if (score < RELEVANCE_THRESHOLD)
125
+ continue;
126
+ out.push({ rule_id, score, matchedTerms: hits });
127
+ }
128
+ return out.sort((a, b) => b.score - a.score || a.rule_id.localeCompare(b.rule_id));
129
+ }
130
+ // ── turn-rules 파일 IO (훅이 쓰고 statusline / status --turn 이 읽는다) ──
131
+ export function promptHash(prompt) {
132
+ return crypto.createHash('sha256').update(prompt).digest('hex').slice(0, PROMPT_HASH_LENGTH);
133
+ }
134
+ export function turnRulesPath(sessionId) {
135
+ return path.join(STATE_DIR, `turn-rules-${sanitizeId(sessionId)}.json`);
136
+ }
137
+ /** 덮어쓰기(세션당 최신 턴 하나). 디렉터리 0700 · 파일 0600 — 다른 세션 캐시와 같은 정책. */
138
+ export function writeTurnRules(sessionId, prompt, rules) {
139
+ const data = {
140
+ at: new Date().toISOString(),
141
+ session_id: sessionId,
142
+ prompt_hash: promptHash(prompt),
143
+ rules,
144
+ };
145
+ atomicWriteJSON(turnRulesPath(sessionId), data, { mode: 0o600, dirMode: 0o700 });
146
+ return data;
147
+ }
148
+ /** 부재·손상이면 null (fail-open). */
149
+ export function readTurnRules(sessionId) {
150
+ const data = safeReadJSON(turnRulesPath(sessionId), null);
151
+ if (!data || typeof data !== 'object' || !Array.isArray(data.rules))
152
+ return null;
153
+ const rules = data.rules.filter((r) => !!r && typeof r === 'object' && typeof r.rule_id === 'string' && typeof r.score === 'number').map((r) => ({ rule_id: r.rule_id, score: r.score, matchedTerms: Array.isArray(r.matchedTerms) ? r.matchedTerms.filter((t) => typeof t === 'string') : [] }));
154
+ return {
155
+ at: typeof data.at === 'string' ? data.at : '',
156
+ session_id: typeof data.session_id === 'string' ? data.session_id : sessionId,
157
+ prompt_hash: typeof data.prompt_hash === 'string' ? data.prompt_hash : '',
158
+ rules,
159
+ };
160
+ }
161
+ /**
162
+ * `forgen status --turn` 의 세션 결정: 지정 세션의 파일이 있으면 그것, 없으면 가장 최근 turn-rules 파일.
163
+ * 반환은 원래 session_id 가 아니라 파일명에서 복원한 sanitized id — 읽기에는 충분하다.
164
+ */
165
+ export function resolveTurnRulesSession(preferred) {
166
+ try {
167
+ if (preferred && fs.existsSync(turnRulesPath(preferred)))
168
+ return preferred;
169
+ let best = null;
170
+ for (const name of fs.readdirSync(STATE_DIR)) {
171
+ const m = /^turn-rules-(.+)\.json$/.exec(name);
172
+ if (!m)
173
+ continue;
174
+ const mtime = fs.statSync(path.join(STATE_DIR, name)).mtimeMs;
175
+ if (!best || mtime > best.mtime)
176
+ best = { id: m[1], mtime };
177
+ }
178
+ return best?.id ?? null;
179
+ }
180
+ catch {
181
+ return null;
182
+ }
183
+ }
@@ -10,4 +10,9 @@
10
10
  * - hard strength rule 은 cli 로도 suppress 불가 (ADR-002 불변 원칙).
11
11
  */
12
12
  export declare function handleSuppressRule(args: string[]): Promise<void>;
13
+ /**
14
+ * ADR-017 D1: enforce_mode 전환. `advise` = 차단 대신 기록만(precision 자동 강등과 같은 상태),
15
+ * `enforce` = 차단 복귀(자동 강등 해제 — 사용자 명시). 하드 룰은 advise 로 내릴 수 없다.
16
+ */
17
+ export declare function handleEnforceMode(args: string[], mode: 'block' | 'advise'): Promise<void>;
13
18
  export declare function handleActivateRule(args: string[]): Promise<void>;
@@ -45,6 +45,36 @@ export async function handleSuppressRule(args) {
45
45
  console.log(` Policy: ${rule.policy.slice(0, 80)}`);
46
46
  console.log(` Re-activate with: forgen activate-rule ${rule.rule_id}`);
47
47
  }
48
+ /**
49
+ * ADR-017 D1: enforce_mode 전환. `advise` = 차단 대신 기록만(precision 자동 강등과 같은 상태),
50
+ * `enforce` = 차단 복귀(자동 강등 해제 — 사용자 명시). 하드 룰은 advise 로 내릴 수 없다.
51
+ */
52
+ export async function handleEnforceMode(args, mode) {
53
+ const { loadAllRules, saveRule } = await import('../store/rule-store.js');
54
+ const prefix = args[0];
55
+ if (!prefix) {
56
+ console.log(`usage: forgen rule ${mode === 'advise' ? 'advise' : 'enforce'} <id-or-prefix>`);
57
+ return;
58
+ }
59
+ const matches = loadAllRules().filter((r) => r.rule_id.startsWith(prefix) && r.status === 'active');
60
+ if (matches.length === 0) {
61
+ console.log(`no active rule matching ${prefix}`);
62
+ return;
63
+ }
64
+ if (matches.length > 1) {
65
+ console.log(`ambiguous prefix ${prefix} → ${matches.map((r) => r.rule_id.slice(0, 8)).join(', ')}`);
66
+ return;
67
+ }
68
+ const rule = matches[0];
69
+ if (mode === 'advise' && rule.strength === 'hard') {
70
+ console.log(`✗ [forgen] hard rule ${rule.rule_id.slice(0, 8)} cannot be set to advise`);
71
+ return;
72
+ }
73
+ const prev = rule.enforce_mode ?? 'block';
74
+ rule.enforce_mode = mode;
75
+ saveRule(rule);
76
+ console.log(`✓ [forgen] ${rule.rule_id.slice(0, 8)} enforce_mode: ${prev} → ${mode}${mode === 'block' ? ' (차단 복귀 — 자동 강등 해제)' : ' (기록만, 차단 안 함)'}`);
77
+ }
48
78
  export async function handleActivateRule(args) {
49
79
  const partial = args[0];
50
80
  if (!partial) {
package/dist/fgx.js CHANGED
@@ -16,7 +16,7 @@ const args = process.argv.slice(2);
16
16
  const FORGEN_SUBCOMMANDS = new Set([
17
17
  // Wave 1 통합(feature-audit 2026-07-21): status(←stats/health/dashboard/me/
18
18
  // recall/explain/last-block/watch), dev(←probe-workflow/parity/migrate/regress-map).
19
- 'forge', 'compound', 'skill', 'status', 'learn', 'statusline',
19
+ 'forge', 'compound', 'skill', 'block', 'status', 'learn', 'statusline', 'rules',
20
20
  'config', 'mcp', 'init', 'install', 'maintenance', 'dev',
21
21
  'notepad', 'inspect', 'doctor', 'uninstall', 'rule',
22
22
  'classify-enforce', 'rule-meta-scan', 'lifecycle-scan',
@@ -29,6 +29,8 @@ export function processCorrection(req) {
29
29
  axis_hint: req.axis_hint,
30
30
  // avoid-this는 현재 설정과 반대 방향의 교정 → mismatch 감지용
31
31
  direction: req.kind === 'avoid-this' ? 'opposite' : 'same',
32
+ // ADR-017 D0: 사용자 발화 원문(있을 때만). rule-origin 이 "당신의 말" 인용에 사용.
33
+ ...(req.user_quote ? { user_quote: req.user_quote } : {}),
32
34
  },
33
35
  });
34
36
  appendEvidence(evidence); // T1 lifecycle trigger fires here for explicit_correction
@@ -281,10 +281,9 @@ async function main() {
281
281
  })() || toolResponse;
282
282
  if (target) {
283
283
  try {
284
- const [{ loadActiveRules }, { recordViolation, recordBypass }, { scanForBypass }, { compileSafeRegex, safeRegexTest }, { preprocessForMatch },] = await Promise.all([
284
+ const [{ loadActiveRules }, { recordViolation, matchedFragment }, { compileSafeRegex, safeRegexTest }, { preprocessForMatch },] = await Promise.all([
285
285
  import('../store/rule-store.js'),
286
286
  import('../engine/lifecycle/signals.js'),
287
- import('../engine/lifecycle/bypass-detector.js'),
288
287
  import('./shared/safe-regex.js'),
289
288
  import('./shared/command-parser.js'),
290
289
  ]);
@@ -317,21 +316,17 @@ async function main() {
317
316
  source: 'post-tool-guard',
318
317
  kind: 'block',
319
318
  message_preview: target.slice(0, 120),
320
- });
319
+ matched: matchedFragment(re.regex, mechTarget),
320
+ target_kind: toolName === 'Bash' ? 'command' : 'file',
321
+ }, { receipt_text: target });
321
322
  messages.push(`<compound-rule-violation>\n[Forgen] Rule ${rule.rule_id.slice(0, 8)} pattern matched in ${toolName} output.\n${spec.block_message ?? rule.policy.slice(0, 120)}\n</compound-rule-violation>`);
322
323
  }
323
324
  }
324
- // T3 bypass detection — scanForBypass 는 rule.policy 자연어에서 패턴 추출이라
325
- // match_target 개념 없음. Write/Edit 는 파일 본문이라 bypass-detector 의
326
- // 자연어 휴리스틱이 false-positive 과다 (L1-no-rm-rf-unconfirmed bypass 20건
327
- // 중 Write/Edit 15건이 실측). 이 경로만 masked. Bash 는 실제 실행된 명령이라
328
- // raw 유지. Mech-A pattern_match 는 위에서 rule-per-rule 로 이미 처리.
329
- const isFileContentTool = toolName === 'Write' || toolName === 'Edit';
330
- const bypassTarget = isFileContentTool ? preprocessForMatch(target, 'masked') : target;
331
- const candidates = scanForBypass({ rules, tool_name: toolName, tool_output: bypassTarget, session_id: sessionId });
332
- for (const c of candidates) {
333
- recordBypass({ rule_id: c.rule_id, session_id: c.session_id, tool: c.tool, pattern_preview: c.pattern_preview });
334
- }
325
+ // ADR-017 D1 (2026-10-06): 자연어 휴리스틱 bypass 기록(scanForBypass → bypass.jsonl)을
326
+ // 중단. 실측 1,114건 전부 룰 policy 의 단어("먼저","Team","Fable")가 도구 출력에
327
+ // 등장한 오탐이었고 실 사용자 우회는 0건. T3 는 이제 FORGEN_USER_CONFIRMED 감사
328
+ // 기록(kind:'bypass_confirmed')만 입력으로 쓴다. bypass-detector 모듈과 기존
329
+ // bypass.jsonl 은 삭제하지 않는다(역사 보존) — 읽지 않을 뿐.
335
330
  }
336
331
  catch (e) {
337
332
  log.debug('enforce_via/bypass post-tool dispatch 실패', e);
@@ -352,6 +352,8 @@ async function main() {
352
352
  const toolName = data.tool_name ?? data.toolName ?? '';
353
353
  const toolInput = data.tool_input ?? data.toolInput ?? {};
354
354
  const sessionId = data.session_id ?? 'default';
355
+ // ADR-017 §6-2: 상대 경로 rm 대상 해석용 (Claude Code 훅 stdin 의 cwd).
356
+ const hookCwd = typeof data.cwd === 'string' ? String(data.cwd) : undefined;
355
357
  // ADR-008 / codex-integration.md — Codex `approval_policy=auto` 에서
356
358
  // PermissionRequest 가 dispatch 안 되는 갭 보완. 모든 tool call 을
357
359
  // permissions-<id>.jsonl 에 supplement 로 append (source='pre-tool-use').
@@ -360,8 +362,10 @@ async function main() {
360
362
  // ADR-001 Mech-A PreToolUse dispatcher — 사용자가 정의한 rule 이 빌트인 위험-명령 감지보다 먼저.
361
363
  // 이렇게 해야 rule.block_message (맥락 있는 안내) 가 제네릭 "Dangerous command blocked" 대신 노출됨.
362
364
  // fail-open: 예외는 hook 차단 안 함.
365
+ // ADR-017 D1: advise 강등 룰의 안내 메시지 — 차단 판정이 모두 끝난 뒤 승인 응답에 합쳐 출력한다.
366
+ const advisories = [];
363
367
  try {
364
- const [{ loadActiveRules }, { recordViolation }, { compileSafeRegex, safeRegexTest }, { preprocessForMatch },] = await Promise.all([
368
+ const [{ loadActiveRules }, { recordViolation, matchedFragment }, { compileSafeRegex, safeRegexTest }, { preprocessForMatch, isTempOnlyRm, isSuspiciousRm },] = await Promise.all([
365
369
  import('../store/rule-store.js'),
366
370
  import('../engine/lifecycle/signals.js'),
367
371
  import('./shared/safe-regex.js'),
@@ -394,23 +398,64 @@ async function main() {
394
398
  const target = preprocessForMatch(command, matchTarget);
395
399
  if (!safeRegexTest(re.regex, target))
396
400
  continue;
401
+ // ADR-017 §6-2 (오너 결정): rm -rf 류 룰이 Claude 의 임시 작업 폴더(/tmp/claude-*/… 등) 삭제에
402
+ // 걸린 경우는 막지 않는다 — 같은 명령 안의 변수 대입까지 한 단계 해석해 대상이 전부 임시 경로일 때만.
403
+ // critic D1 SEV-1: 예외는 **매칭된 토큰 자체가 rm** 일 때만 (pattern.includes('rm') 은 terraform 룰까지 껐다).
404
+ const matchTok = re.regex.exec(target)?.[0] ?? '';
405
+ if (/^\s*rm\b/.test(matchTok) && !isSuspiciousRm(command) && isTempOnlyRm(command, hookCwd)) {
406
+ log.debug(`rule ${rule.rule_id}: temp-only rm — exempt`);
407
+ continue;
408
+ }
397
409
  const requiresFlag = v.params?.requires_flag;
398
410
  const confirmed = process.env.FORGEN_USER_CONFIRMED === '1';
411
+ const matchedFrag = matchedFragment(re.regex, target);
412
+ // ADR-017 D1: precision 강등된 룰(enforce_mode 'advise')은 차단 대신 기록만.
413
+ if (requiresFlag && !confirmed && rule.enforce_mode === 'advise') {
414
+ recordViolation({ rule_id: rule.rule_id, session_id: sessionId, source: 'pre-tool-guard', kind: 'correction', message_preview: command.slice(0, 120), matched: matchedFrag, target_kind: 'command' });
415
+ // ship-review MAJOR: 여기서 return 하면 같은 명령의 나머지 룰(하드 포함)과 빌트인 위험 검사를 건너뛴다 → 모아서 마지막에 경고.
416
+ let why = '';
417
+ try {
418
+ const { lastDemotion } = await import('../engine/block-judge.js');
419
+ const d = lastDemotion(rule.rule_id);
420
+ if (d)
421
+ why = ` (${d.at.slice(0, 10)} 7d 판정 ${d.judged}건 중 오탐률 ${Math.round((1 - d.precision) * 100)}% → 안내 모드)`;
422
+ }
423
+ catch { /* fail-open */ }
424
+ advisories.push(`[Forgen] (advise) ${spec.block_message ?? rule.policy.slice(0, 120)}${why} — 차단 대신 안내만 합니다. 복귀: forgen rule enforce ${rule.rule_id.slice(0, 8)}`);
425
+ continue;
426
+ }
399
427
  if (requiresFlag && !confirmed) {
400
- recordViolation({ rule_id: rule.rule_id, session_id: sessionId, source: 'pre-tool-guard', kind: 'deny', message_preview: command.slice(0, 120) });
428
+ const violationId = recordViolation({ rule_id: rule.rule_id, session_id: sessionId, source: 'pre-tool-guard', kind: 'deny', message_preview: command.slice(0, 120), matched: matchedFrag, target_kind: 'command' }, { receipt_text: command });
429
+ try {
430
+ const { spawnBlockJudge } = await import('../engine/block-judge.js');
431
+ spawnBlockJudge(violationId, sessionId);
432
+ }
433
+ catch { /* fail-open */ }
401
434
  const baseMsg = spec.block_message ?? `[${rule.rule_id}] policy violation: ${rule.policy.slice(0, 120)}`;
435
+ // ADR-017 D0: 룰의 출처 교정 인용.
436
+ const origin = await (async () => {
437
+ try {
438
+ const { originLine } = await import('../store/rule-origin.js');
439
+ return originLine(rule);
440
+ }
441
+ catch {
442
+ return '';
443
+ }
444
+ })();
402
445
  // G8: override 힌트 — FORGEN_USER_CONFIRMED=1 으로 사용자 명시 승인 가능, 감사 로그 기록됨.
403
- const msgWithHint = `${baseMsg}\n\n(override: set FORGEN_USER_CONFIRMED=1 (bypass will be audited in violations.jsonl))`;
446
+ const msgWithHint = `${baseMsg}${origin ? `\n${origin}` : ''}\n\n(override: set FORGEN_USER_CONFIRMED=1 (bypass will be audited in violations.jsonl). 오탐이면: forgen block ${violationId.slice(0, 8)} --fp)`;
404
447
  console.log(denyOrObserve('pre-tool-use', msgWithHint));
405
448
  return;
406
449
  }
407
450
  if (requiresFlag && confirmed) {
408
451
  // H3: 우회 감사 — FORGEN_USER_CONFIRMED 으로 Mech-A 를 우회할 때마다 violation 로그에
409
- // kind='correction' 으로 기록. T3 bypass 누적 대신 별도 채널로 운영자가 monitoring 가능.
452
+ // (ADR-017: kind='bypass_confirmed' — T3 의 유일한 입력. 아래 주석의 'correction' 은 구 의미.)
410
453
  recordViolation({
411
454
  rule_id: rule.rule_id, session_id: sessionId,
412
455
  source: 'pre-tool-guard',
413
- kind: 'correction', // 'correction' = 사용자 명시 우회, rule 위반이지만 의도된 것
456
+ // ADR-017 D1: 사용자 명시 우회 전용 kind. (이전 'correction' 은 메타가드 advise 와 섞여
457
+ // "사용자 우회 87건"으로 둔갑했다.) T3 의 유일한 입력.
458
+ kind: 'bypass_confirmed',
414
459
  message_preview: `[FORGEN_USER_CONFIRMED=1 bypass] ${command.slice(0, 120)}`,
415
460
  });
416
461
  }
@@ -421,18 +466,32 @@ async function main() {
421
466
  log.debug('enforce_via[PreToolUse] dispatch 실패', e);
422
467
  }
423
468
  // Bash 도구: 위험 명령어 감지 (빌트인 safety net)
469
+ // critic D1: `rm -rf /tmp/../home`, `/tmp/{a,../..}`, `/tmp/*` 는 빌트인 /tmp lookahead 를 우회한다 → 먼저 차단.
470
+ try {
471
+ const cmd0 = typeof toolInput.command === 'string' ? String(toolInput.command) : '';
472
+ if (toolName === 'Bash' && cmd0) {
473
+ const { isSuspiciousRm, preprocessForMatch } = await import('./shared/command-parser.js');
474
+ // heredoc 본문·따옴표 안 문자열(문서/테스트 소스에 적힌 예시)은 실행되는 명령이 아니다 → masked 로 검사.
475
+ if (isSuspiciousRm(preprocessForMatch(cmd0, 'masked'))) {
476
+ console.log(denyOrObserve('pre-tool-use', `[Forgen] Dangerous command blocked: recursive rm with path traversal/glob under a temp path\nCommand: ${cmd0.slice(0, 200)}`));
477
+ return;
478
+ }
479
+ }
480
+ }
481
+ catch { /* fail-open */ }
424
482
  const check = checkDangerousCommand(toolName, toolInput);
425
483
  if (check.action === 'block') {
426
484
  console.log(denyOrObserve('pre-tool-use', `[Forgen] Dangerous command blocked: ${check.description}\nCommand: ${check.command}`));
427
485
  return;
428
486
  }
487
+ const withAdvisories = (body) => (advisories.length ? `${advisories.map((x) => `<compound-tool-warning>\n${x}\n</compound-tool-warning>`).join('\n')}${body ? `\n${body}` : ''}` : body);
429
488
  if (check.action === 'warn') {
430
- console.log(approveWithWarning(`<compound-tool-warning>\n[Forgen] ⚠ Dangerous command detected: ${check.description}\nProceed with caution.\n</compound-tool-warning>`));
489
+ console.log(approveWithWarning(withAdvisories(`<compound-tool-warning>\n[Forgen] ⚠ Dangerous command detected: ${check.description}\nProceed with caution.\n</compound-tool-warning>`)));
431
490
  return;
432
491
  }
433
492
  // Output size guard: warn when Grep is used without head_limit
434
493
  if (toolName === 'Grep' && !toolInput?.head_limit) {
435
- console.log(approveWithWarning(`<compound-tool-warning>\n[Forgen] Grep without head_limit may produce large output. Set head_limit or pipe through | head -n to limit output size.\n</compound-tool-warning>`));
494
+ console.log(approveWithWarning(withAdvisories(`<compound-tool-warning>\n[Forgen] Grep without head_limit may produce large output. Set head_limit or pipe through | head -n to limit output size.\n</compound-tool-warning>`)));
436
495
  return;
437
496
  }
438
497
  // Compound v3: Code Reflection check (non-blocking)
@@ -450,10 +509,14 @@ async function main() {
450
509
  if (shouldShowReminderIO()) {
451
510
  const reminders = getActiveReminders();
452
511
  if (reminders.length > 0) {
453
- console.log(approveWithWarning(`<compound-reminder>\n${reminders.join('\n')}\n</compound-reminder>`));
512
+ console.log(approveWithWarning(withAdvisories(`<compound-reminder>\n${reminders.join('\n')}\n</compound-reminder>`)));
454
513
  return;
455
514
  }
456
515
  }
516
+ if (advisories.length) {
517
+ console.log(approveWithWarning(withAdvisories('')));
518
+ return;
519
+ }
457
520
  console.log(approve());
458
521
  }
459
522
  finally {
@@ -42,3 +42,14 @@ export declare function maskQuotedContent(cmd: string): string;
42
42
  */
43
43
  export type MatchTarget = 'raw' | 'masked' | 'command_tokens';
44
44
  export declare function preprocessForMatch(cmd: string, target: MatchTarget | undefined): string;
45
+ /**
46
+ * ADR-017 §6-2 (오너 결정): "확인 없는 rm -rf 금지" 하드 룰은 Claude 가 **자기 임시 작업 폴더**를 지우는 경우까지
47
+ * 막았다(7d 실 차단 14건 중 13건). 같은 명령 안의 **rm 이전** 대입(`S=/tmp/claude-x; rm -rf $S`)을 한 단계 치환하고,
48
+ * 상대 경로는 stdin cwd(또는 같은 명령의 직전 `cd`)로 해석해, rm -rf 대상이 **전부** Claude 임시 루트 아래이면 true.
49
+ *
50
+ * critic D1 SEV-1 반영 — 하나라도 다음이면 false: `..`/brace/glob/백틱/`$()` 포함, 미해석 변수, 비임시 루트, 루트
51
+ * 디렉터리 자체, 실존 경로의 realpath 가 임시 루트 밖(symlink 탈출). 빈 대상·rm 없음도 false.
52
+ */
53
+ export declare function isTempOnlyRm(cmd: string, cwd?: string): boolean;
54
+ /** `..`·glob·brace 가 섞인 재귀 삭제 — 빌트인 /tmp 예외를 우회하려는 모양. 호출자가 차단에 쓴다. */
55
+ export declare function isSuspiciousRm(cmd: string): boolean;
@@ -1,3 +1,4 @@
1
+ import * as fs from 'node:fs';
1
2
  /**
2
3
  * Command-token parser — quote-aware shell command preprocessing.
3
4
  *
@@ -48,3 +49,122 @@ export function preprocessForMatch(cmd, target) {
48
49
  return cmd;
49
50
  return maskQuotedContent(cmd);
50
51
  }
52
+ /**
53
+ * 임시 경로 접두 — 삭제해도 사용자 파일이 아닌 곳. ADR-017 §6-2 의 대상은 **Claude 의 자기 작업 폴더**이므로
54
+ * `/tmp/claude-*` (Claude Code scratchpad) 와 `$TMPDIR/claude-*` 로 좁힌다 (critic D1: `/tmp/*` 전체는 너무 넓다).
55
+ */
56
+ function tempRoots() {
57
+ const roots = ['/tmp/claude-', '/private/tmp/claude-', '/var/tmp/claude-', '/var/folders/'];
58
+ const t = process.env.TMPDIR?.replace(/\/+$/, '');
59
+ if (t && t !== '/tmp')
60
+ roots.push(`${t}/claude-`);
61
+ return roots;
62
+ }
63
+ /** 경로 조작·확장 메타문자 — 하나라도 있으면 "임시 전용" 판정을 포기한다(보수적). */
64
+ const UNSAFE_TARGET_RE = /(^|\/)\.\.(\/|$)|[{}*?[\]`~]|\$\(/;
65
+ /**
66
+ * ADR-017 §6-2 (오너 결정): "확인 없는 rm -rf 금지" 하드 룰은 Claude 가 **자기 임시 작업 폴더**를 지우는 경우까지
67
+ * 막았다(7d 실 차단 14건 중 13건). 같은 명령 안의 **rm 이전** 대입(`S=/tmp/claude-x; rm -rf $S`)을 한 단계 치환하고,
68
+ * 상대 경로는 stdin cwd(또는 같은 명령의 직전 `cd`)로 해석해, rm -rf 대상이 **전부** Claude 임시 루트 아래이면 true.
69
+ *
70
+ * critic D1 SEV-1 반영 — 하나라도 다음이면 false: `..`/brace/glob/백틱/`$()` 포함, 미해석 변수, 비임시 루트, 루트
71
+ * 디렉터리 자체, 실존 경로의 realpath 가 임시 루트 밖(symlink 탈출). 빈 대상·rm 없음도 false.
72
+ */
73
+ export function isTempOnlyRm(cmd, cwd) {
74
+ if (!cmd)
75
+ return false;
76
+ const roots = tempRoots();
77
+ const assignRe = /(?:^|[;&|\n]\s*|\s)([A-Za-z_][A-Za-z0-9_]*)=(?:"([^"]*)"|'([^']*)'|([^\s;&|]+))/g;
78
+ const cdRe = /(?:^|[;&|\n])\s*cd\s+(?:"([^"]*)"|'([^']*)'|([^\s;&|]+))/g;
79
+ const rmRe = /\brm\s+((?:-[a-zA-Z-]+\s+)+)([^;&|\n]+)/g;
80
+ let found = false;
81
+ for (const m of cmd.matchAll(rmRe)) {
82
+ const flags = m[1];
83
+ if (!/(^|\s)-[a-zA-Z]*r|--recursive/i.test(flags))
84
+ continue; // 재귀 삭제만 대상
85
+ const upTo = cmd.slice(0, m.index ?? 0);
86
+ // rm **이전** 의 대입만 반영 (재대입 순서 무시 방지)
87
+ const vars = new Map([['TMPDIR', process.env.TMPDIR?.replace(/\/+$/, '') || '/tmp']]);
88
+ for (const a of upTo.matchAll(assignRe))
89
+ vars.set(a[1], expand(a[2] ?? a[3] ?? a[4] ?? '', vars));
90
+ let base = cwd?.startsWith('/') ? cwd : '';
91
+ for (const c of upTo.matchAll(cdRe)) {
92
+ const d = expand(c[1] ?? c[2] ?? c[3] ?? '', vars);
93
+ base = d.startsWith('/') ? d : base ? `${base}/${d}` : '';
94
+ }
95
+ const targets = m[2].trim().split(/\s+/).filter((t) => t && t !== '--' && !t.startsWith('-'));
96
+ if (targets.length === 0)
97
+ return false;
98
+ for (const raw of targets) {
99
+ found = true;
100
+ const t = expand(raw.replace(/^["']|["']$/g, ''), vars);
101
+ if (t.includes('$'))
102
+ return false; // 미해석 변수
103
+ if (UNSAFE_TARGET_RE.test(t))
104
+ return false; // `..`, glob, brace, 백틱, $(), ~
105
+ let abs = t;
106
+ if (!abs.startsWith('/')) {
107
+ if (!base)
108
+ return false; // 상대 경로인데 cwd 를 모름
109
+ abs = `${base}/${t === '.' ? '' : t}`;
110
+ }
111
+ abs = normalizePosix(abs);
112
+ if (!roots.some((r) => abs.startsWith(r)))
113
+ return false;
114
+ // 루트 디렉터리 자체(/tmp/claude-1001 등)는 제외 — 하위만
115
+ if (!roots.some((r) => abs.length > r.length && abs.slice(r.length).includes('/')))
116
+ return false;
117
+ // symlink 탈출: 가장 깊은 **실존 조상**의 realpath 에 나머지(미존재) 경로를 다시 붙인 결과가 임시 루트 아래여야
118
+ // 한다. (CI 처럼 /tmp/claude-* 가 아직 없으면 조상은 /tmp 이고, /tmp 의 realpath(+나머지)로 판정 — v0.6.0 의
119
+ // 릴리스 CI 가 바로 이 경우에 false 를 내 실패했다.)
120
+ try {
121
+ let probe = abs;
122
+ while (probe !== '/' && !fs.existsSync(probe))
123
+ probe = probe.slice(0, probe.lastIndexOf('/')) || '/';
124
+ if (probe !== '/') {
125
+ const realAbs = fs.realpathSync(probe) + abs.slice(probe.length);
126
+ if (!roots.some((r) => realAbs.startsWith(r)))
127
+ return false;
128
+ }
129
+ }
130
+ catch {
131
+ return false;
132
+ }
133
+ }
134
+ }
135
+ return found;
136
+ }
137
+ /** `..`·glob·brace 가 섞인 재귀 삭제 — 빌트인 /tmp 예외를 우회하려는 모양. 호출자가 차단에 쓴다. */
138
+ export function isSuspiciousRm(cmd) {
139
+ if (!cmd)
140
+ return false;
141
+ const rmRe = /\brm\s+((?:-[a-zA-Z-]+\s+)+)([^;&|\n]+)/g;
142
+ for (const m of cmd.matchAll(rmRe)) {
143
+ if (!/(^|\s)-[a-zA-Z]*r|--recursive/i.test(m[1]))
144
+ continue;
145
+ for (const t of m[2].trim().split(/\s+/)) {
146
+ if (/(^|\/)\.\.(\/|$)|[{}*?[\]]|\$\(|`/.test(t) && /^\/?(tmp|private\/tmp|var\/tmp|var\/folders)(\/|$)|\/tmp\//.test(t.replace(/^["']|["']$/g, '')))
147
+ return true;
148
+ }
149
+ }
150
+ return false;
151
+ }
152
+ function normalizePosix(p) {
153
+ const parts = [];
154
+ for (const seg of p.split('/')) {
155
+ if (!seg || seg === '.')
156
+ continue;
157
+ if (seg === '..') {
158
+ parts.pop();
159
+ continue;
160
+ }
161
+ parts.push(seg);
162
+ }
163
+ return `/${parts.join('/')}`;
164
+ }
165
+ function expand(s, vars) {
166
+ return s.replace(/\$\{([A-Za-z_][A-Za-z0-9_]*)\}|\$([A-Za-z_][A-Za-z0-9_]*)/g, (whole, a, b) => {
167
+ const v = vars.get(a ?? b);
168
+ return v === undefined ? whole : v;
169
+ });
170
+ }
@@ -428,6 +428,19 @@ async function main() {
428
428
  return;
429
429
  }
430
430
  const sessionId = input.session_id ?? 'default';
431
+ // ADR-017 D2: 턴 단위 룰 관련도 → state/turn-rules-<session>.json (statusline "관련 룰 N" · status --turn).
432
+ // 프롬프트 주입에는 아무것도 보태지 않는다(토큰 비용 0). 원문 대신 sha256 앞 16자만 저장. 아래 어떤 early
433
+ // return 보다 앞에 두어 솔루션 매칭 결과와 무관하게 매 턴 기록된다. 전부 fail-open.
434
+ if (input.session_id) {
435
+ try {
436
+ const { relevantRules, writeTurnRules } = await import('../engine/rule-relevance.js');
437
+ const { loadActiveRules } = await import('../store/rule-store.js');
438
+ writeTurnRules(input.session_id, input.prompt, relevantRules(input.prompt, loadActiveRules()));
439
+ }
440
+ catch (e) {
441
+ log.debug('turn-rules 기록 실패', e);
442
+ }
443
+ }
431
444
  // Observability P2: 직전 surfaced 솔루션과 현재 프롬프트 키워드 매칭 → acted_on emit
432
445
  await detectActOnFromPriorSurface(sessionId, input.prompt.toLowerCase());
433
446
  // v1: 교정 감지 → correction-record 호출 유도 hint
@@ -34,6 +34,14 @@ interface SpikeRule {
34
34
  verifier: VerifierSpec;
35
35
  block_message?: string;
36
36
  system_tag?: string;
37
+ /** ADR-017 D0: 출처 인용용 — store 룰에서만 채워짐(project-scope 룰 포함, 재읽기 없음). */
38
+ origin?: {
39
+ source: Rule['source'];
40
+ evidence_refs: string[];
41
+ policy: string;
42
+ };
43
+ /** ADR-017 D1: precision 강등 모드. 'advise' 면 차단 대신 기록(kind:'correction'). */
44
+ enforce_mode?: 'block' | 'advise';
37
45
  }
38
46
  /**
39
47
  * 프로덕션 rule-store 로더.
@@ -51,10 +59,20 @@ export declare function rulesFromStore(rules: Rule[]): SpikeRule[];
51
59
  export declare function evaluateStop(lastAssistantMessage: string, rules: SpikeRule[]): {
52
60
  action: 'approve';
53
61
  hit: null;
62
+ passed: string[];
63
+ advised: Array<{
64
+ rule: SpikeRule;
65
+ reason: string;
66
+ }>;
54
67
  } | {
55
68
  action: 'block';
56
69
  hit: SpikeRule;
57
70
  reason: string;
71
+ passed: string[];
72
+ advised: Array<{
73
+ rule: SpikeRule;
74
+ reason: string;
75
+ }>;
58
76
  };
59
77
  /**
60
78
  * 같은 (session, rule) 조합의 연속 block 카운트. approve 가 일어나면 0 으로 초기화.