@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
@@ -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 으로 초기화.
@@ -35,7 +35,7 @@ import { atomicWriteJSON } from './shared/atomic-write.js';
35
35
  import { recordHookTiming } from './shared/hook-timing.js';
36
36
  import { isHookEnabled } from './hook-config.js';
37
37
  import { loadActiveRules } from '../store/rule-store.js';
38
- import { recordViolation, rotateIfBig } from '../engine/lifecycle/signals.js';
38
+ import { recordViolation, recordCheck, rotateIfBig } from '../engine/lifecycle/signals.js';
39
39
  import { compileSafeRegex, safeRegexTest } from './shared/safe-regex.js';
40
40
  const HOOK_NAME = 'stop-guard';
41
41
  // R6-F2: shared single source of truth.
@@ -106,6 +106,8 @@ export function rulesFromStore(rules) {
106
106
  },
107
107
  block_message: spec.block_message,
108
108
  system_tag: spec.system_tag,
109
+ origin: { source: rule.source, evidence_refs: rule.evidence_refs ?? [], policy: rule.policy },
110
+ enforce_mode: rule.enforce_mode,
109
111
  });
110
112
  }
111
113
  }
@@ -277,6 +279,9 @@ function artifactFresh(relOrAbs, maxAgeS) {
277
279
  }
278
280
  /** Pure core — 단위 테스트용. stdin/IO 없음. */
279
281
  export function evaluateStop(lastAssistantMessage, rules) {
282
+ // ADR-017 D2: 실제 평가돼 통과한 룰(passed)과, D1 advise 강등으로 차단 대신 기록만 하는 룰(advised)을 함께 반환.
283
+ const passed = [];
284
+ const advised = [];
280
285
  for (const rule of rules) {
281
286
  if (rule.hook !== 'Stop')
282
287
  continue;
@@ -284,10 +289,15 @@ export function evaluateStop(lastAssistantMessage, rules) {
284
289
  continue;
285
290
  const result = evaluateVerifier(rule);
286
291
  if (result.violated) {
287
- return { action: 'block', hit: rule, reason: result.reason };
292
+ if (rule.enforce_mode === 'advise') {
293
+ advised.push({ rule, reason: result.reason });
294
+ continue;
295
+ }
296
+ return { action: 'block', hit: rule, reason: result.reason, passed, advised };
288
297
  }
298
+ passed.push(rule.id);
289
299
  }
290
- return { action: 'approve', hit: null };
300
+ return { action: 'approve', hit: null, passed, advised };
291
301
  }
292
302
  function blockCounterPath(sessionId, ruleId) {
293
303
  // 파일명 안전화 — 경로 인젝션 방지
@@ -512,15 +522,22 @@ export async function main() {
512
522
  const completionGuardMode = guardModeForModel(readSessionModel(sanitizeId(sessionId)));
513
523
  const results = runMetaGuards({ lastMessage, recentTools, minMeasurements: 1, completionGuardMode });
514
524
  for (const r of results) {
515
- recordViolation({
525
+ const violationId = recordViolation({
516
526
  rule_id: `builtin:${r.shortId}`,
517
527
  session_id: sessionId,
518
528
  source: 'stop-guard',
519
529
  kind: r.kind,
520
530
  message_preview: lastMessage.slice(0, 120),
521
- });
531
+ matched: r.reason.slice(0, 160),
532
+ target_kind: 'response',
533
+ }, r.kind === 'block' ? { receipt_text: lastMessage } : {});
522
534
  if (r.kind !== 'block')
523
535
  continue;
536
+ try {
537
+ const { spawnBlockJudge } = await import('../engine/block-judge.js');
538
+ spawnBlockJudge(violationId, sessionId);
539
+ }
540
+ catch { /* fail-open */ }
524
541
  const reasonText = `[forgen:stop-guard/${r.shortId}] ${r.reason}
525
542
 
526
543
  (Override this turn: set FORGEN_USER_CONFIRMED=1 (audited).)`;
@@ -535,6 +552,13 @@ export async function main() {
535
552
  }
536
553
  const result = evaluateStop(lastMessage, rules);
537
554
  const sessionId = input?.session_id ?? 'unknown';
555
+ // ADR-017 D2: 실제 평가된 룰의 통과를 checks.jsonl 에 기록(violations 와 분리). D1: advise 강등 룰의
556
+ // 위반은 kind:'correction' 으로 기록만 하고 차단하지 않는다.
557
+ for (const id of result.passed)
558
+ recordCheck({ session_id: sessionId, rule_id: id, result: 'pass' });
559
+ for (const a of result.advised) {
560
+ recordViolation({ rule_id: a.rule.id, session_id: sessionId, source: 'stop-guard', kind: 'correction', message_preview: lastMessage.slice(0, 120), matched: a.reason.slice(0, 160), target_kind: 'response' });
561
+ }
538
562
  if (result.action === 'approve') {
539
563
  // R9-PA2: 같은 session 에 pending block 이 있었다면 retract→pass 루프가
540
564
  // 실제 작동한 것 — acknowledgment 이벤트로 기록. block-count 는 cleanup.
@@ -543,12 +567,13 @@ export async function main() {
543
567
  return;
544
568
  }
545
569
  const { hit, reason } = result;
570
+ recordCheck({ session_id: sessionId, rule_id: hit.id, result: 'violation' });
546
571
  // R7-U1: FORGEN_USER_CONFIRMED=1 으로 사용자가 명시적 우회 → audit 기록 후 approve.
547
572
  // pre-tool-use 와 동일한 탈출 경로 일관성 확보.
548
573
  if (process.env.FORGEN_USER_CONFIRMED === '1') {
549
574
  recordViolation({
550
575
  rule_id: hit.id, session_id: sessionId, source: 'stop-guard',
551
- kind: 'correction',
576
+ kind: 'bypass_confirmed', // ADR-017 D1: 사용자 명시 우회 전용 kind (T3 입력)
552
577
  message_preview: `[FORGEN_USER_CONFIRMED=1 bypass] ${lastMessage.slice(0, 100)}`,
553
578
  });
554
579
  console.log(approveWithOptionalExtractionNotice());
@@ -556,18 +581,38 @@ export async function main() {
556
581
  }
557
582
  // T2 signal: block 은 rule 위반 증거 — violations.jsonl 에 기록.
558
583
  // (stuck-loop force approve 는 아래에서 처리되므로 실제 block 시에만 기록)
559
- recordViolation({
584
+ const violationId = recordViolation({
560
585
  rule_id: hit.id,
561
586
  session_id: sessionId,
562
587
  source: 'stop-guard',
563
588
  kind: 'block',
564
589
  message_preview: lastMessage.slice(0, 120),
565
- });
590
+ matched: reason.slice(0, 160),
591
+ target_kind: 'response',
592
+ }, { receipt_text: lastMessage });
593
+ try {
594
+ const { spawnBlockJudge } = await import('../engine/block-judge.js');
595
+ spawnBlockJudge(violationId, sessionId);
596
+ }
597
+ catch { /* fail-open */ }
566
598
  // G8 + R4-UX1 + R7-U1/U2: 브랜드 prefix + 사람-읽기 동사 기반 override 힌트.
567
599
  // pre-tool-use 와 일관된 FORGEN_USER_CONFIRMED=1 탈출구 + 영구 비활성화 CLI 노출.
568
- const reasonWithHint = `[forgen:stop-guard/${hit.id.slice(0, 8)}] ${reason}
600
+ // ADR-017 D0: 룰의 출처 교정(날짜·문장)을 인용 — "내가 그렇게 말했지"를 차단 순간에 보이게.
601
+ // block 경로에서만 동적 import (approve 경로의 Stop 훅 지연에 0 비용 — critic SEV-2-b).
602
+ const origin = await (async () => {
603
+ try {
604
+ if (!hit.origin)
605
+ return '';
606
+ const { originLine } = await import('../store/rule-origin.js');
607
+ return originLine(hit.origin);
608
+ }
609
+ catch {
610
+ return '';
611
+ }
612
+ })();
613
+ const reasonWithHint = `[forgen:stop-guard/${hit.id.slice(0, 8)}] ${reason}${origin ? `\n${origin}` : ''}
569
614
 
570
- (Override this turn: set FORGEN_USER_CONFIRMED=1 (audited). Disable rule permanently: \`forgen suppress-rule ${hit.id}\`. See recent blocks: \`forgen status --blocks\`.)`;
615
+ (Override this turn: set FORGEN_USER_CONFIRMED=1 (audited). Disable rule permanently: \`forgen suppress-rule ${hit.id}\`. See recent blocks: \`forgen status --blocks\`. 오탐이면: \`forgen block ${violationId.slice(0, 8)} --fp\`)`;
571
616
  const count = incrementBlockCount(sessionId, hit.id);
572
617
  const threshold = getStuckLoopThreshold();
573
618
  if (count > threshold) {
@@ -18,7 +18,7 @@ import * as fs from 'node:fs';
18
18
  import * as os from 'node:os';
19
19
  import * as path from 'node:path';
20
20
  import { generateHooksJson } from '../hooks/hooks-generator.js';
21
- import { hasManagedSkillMarker } from './managed-marker.js';
21
+ import { hasManagedSkillMarker, installSkillFile, removeOwnedDevGuideSkills } from './managed-marker.js';
22
22
  const PLUGIN_KEY = 'forgen@forgen-local';
23
23
  const FORGEN_MANAGED_MARKER = '<!-- forgen-managed -->';
24
24
  function readPkgVersion(pkgRoot) {
@@ -266,40 +266,14 @@ function installDevGuideSkills(opts) {
266
266
  return { skillsPath: skillsDir, skillsInstalled: entries.length, skillsRemoved: 0 };
267
267
  }
268
268
  fs.mkdirSync(skillsDir, { recursive: true });
269
- // Remove stale forgen-* skill dirs (idempotent re-install, do not touch user's own skills)
270
- let removed = 0;
271
- for (const entry of fs.readdirSync(skillsDir)) {
272
- if (!entry.startsWith(FORGEN_SKILL_PREFIX))
273
- continue;
274
- const fullPath = path.join(skillsDir, entry);
275
- if (fs.statSync(fullPath).isDirectory()) {
276
- fs.rmSync(fullPath, { recursive: true, force: true });
277
- removed += 1;
278
- }
279
- }
280
- // Install each skill via symlink → cpSync fallback (mirrors plugin cache pattern)
269
+ // stale 정리 — forgen 이 설치한 dev-guide 스킬만 (패키지가 제공하는 이름 / dev-guide 를 가리키는 심링크).
270
+ // 이전엔 `forgen-*` 디렉토리를 이름만 보고 재귀 삭제해 사용자가 만든 스킬까지 지웠다 (ADR-016 0.5.9).
271
+ const removed = removeOwnedDevGuideSkills(skillsDir, pkgRoot);
272
+ // 설치 — 이미 있는 것(사용자 심링크 디렉토리, 남아 있는 SKILL.md)은 덮어쓰지 않는다.
281
273
  let installed = 0;
282
274
  for (const { name, src } of entries) {
283
- const targetDir = path.join(skillsDir, name);
284
- fs.mkdirSync(targetDir, { recursive: true });
285
- const targetFile = path.join(targetDir, 'SKILL.md');
286
- let linked = false;
287
- let symlinkErr = null;
288
- try {
289
- fs.symlinkSync(src, targetFile, 'file');
290
- linked = true;
291
- }
292
- catch (e) {
293
- symlinkErr = e;
294
- }
295
- if (!linked && symlinkErr) {
296
- const code = symlinkErr.code ?? 'UNKNOWN';
297
- process.stderr.write(`[forgen] symlink ${src} → ${targetFile} failed (${code}); falling back to copyFile.\n`);
298
- }
299
- if (!linked) {
300
- fs.copyFileSync(src, targetFile);
301
- }
302
- installed += 1;
275
+ if (installSkillFile(src, skillsDir, name))
276
+ installed += 1;
303
277
  }
304
278
  return { skillsPath: skillsDir, skillsInstalled: installed, skillsRemoved: removed };
305
279
  }
@@ -199,7 +199,29 @@ export declare function upsertForgenRulesInAgentsMd(opts: {
199
199
  }): {
200
200
  injected: boolean;
201
201
  };
202
- /** AGENTS.md 의 forgen 블록 제거 (uninstall). 블록뿐이던 파일은 삭제한다. */
202
+ export declare function readAgentsMdInstalls(hostDir: string): string[];
203
+ export declare function recordAgentsMdInstall(hostDir: string, agentsMdPath: string): void;
204
+ export declare function clearAgentsMdInstalls(hostDir: string): void;
205
+ /**
206
+ * 기록된 경로 + 지금의 cwd 경로에서 forgen 블록을 걷어낸다.
207
+ * 쓰지 못한 경로(읽기 전용 등)는 `failed` 로 돌려주고 **기록에 남긴다** — 다음 uninstall 이 다시 시도할 수 있게.
208
+ */
209
+ export declare function removeForgenRulesEverywhere(opts: {
210
+ hostDir: string;
211
+ cwdAgentsMdPath: string;
212
+ dryRun: boolean;
213
+ }): {
214
+ cleaned: string[];
215
+ failed: Array<{
216
+ path: string;
217
+ error: string;
218
+ }>;
219
+ };
220
+ /**
221
+ * AGENTS.md 의 forgen 블록 제거 (uninstall). 블록뿐이던 파일은 삭제한다.
222
+ * BEGIN/END 마커가 각각 한 줄로, 순서대로 있을 때만 동작한다 (블록이 여러 개면 전부 제거).
223
+ * 읽을 수 없으면 no-op, 쓸 수 없으면 throw — 호출부가 보고한다.
224
+ */
203
225
  export declare function removeForgenRulesFromAgentsMd(opts: {
204
226
  agentsMdPath: string;
205
227
  dryRun: boolean;