@wooojin/forgen 0.6.8 → 0.6.10

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 (221) hide show
  1. package/.claude-plugin/plugin.json +1 -1
  2. package/CHANGELOG.md +27 -0
  3. package/README.ja.md +15 -10
  4. package/README.ko.md +15 -10
  5. package/README.md +19 -14
  6. package/README.zh.md +13 -8
  7. package/dist/checks/dangerous-response-pattern.d.ts +2 -1
  8. package/dist/checks/dangerous-response-pattern.js +27 -3
  9. package/dist/cli.js +133 -17
  10. package/dist/core/auto-compound-runner.js +502 -397
  11. package/dist/core/block-cli.js +7 -3
  12. package/dist/core/compound-consent.d.ts +18 -0
  13. package/dist/core/compound-consent.js +101 -6
  14. package/dist/core/compound-sweep-cli.d.ts +16 -0
  15. package/dist/core/compound-sweep-cli.js +67 -5
  16. package/dist/core/config-hooks.js +28 -10
  17. package/dist/core/correction-signals.d.ts +9 -0
  18. package/dist/core/correction-signals.js +37 -0
  19. package/dist/core/dev-cli.d.ts +1 -2
  20. package/dist/core/dev-cli.js +9 -28
  21. package/dist/core/doctor-verify.d.ts +35 -0
  22. package/dist/core/doctor-verify.js +502 -0
  23. package/dist/core/doctor.d.ts +4 -6
  24. package/dist/core/doctor.js +103 -184
  25. package/dist/core/explain-cli.js +8 -0
  26. package/dist/core/extraction-haiku.d.ts +64 -0
  27. package/dist/core/extraction-haiku.js +208 -0
  28. package/dist/core/extraction-queue.d.ts +68 -0
  29. package/dist/core/extraction-queue.js +300 -0
  30. package/dist/core/flow-status.d.ts +93 -0
  31. package/dist/core/flow-status.js +368 -0
  32. package/dist/core/harness.js +14 -42
  33. package/dist/core/inspect-cli.js +37 -13
  34. package/dist/core/lifecycle-classifier.d.ts +5 -1
  35. package/dist/core/lifecycle-classifier.js +13 -2
  36. package/dist/core/migrate-cli.d.ts +1 -1
  37. package/dist/core/migrate-cli.js +11 -11
  38. package/dist/core/migrate-tenetx.d.ts +1 -1
  39. package/dist/core/migrate-tenetx.js +2 -2
  40. package/dist/core/node-engine.d.ts +3 -0
  41. package/dist/core/node-engine.js +8 -0
  42. package/dist/core/observability-store.d.ts +15 -0
  43. package/dist/core/observability-store.js +73 -0
  44. package/dist/core/paths.d.ts +2 -0
  45. package/dist/core/paths.js +2 -0
  46. package/dist/core/rendered-rules-manifest.d.ts +7 -1
  47. package/dist/core/rendered-rules-manifest.js +45 -1
  48. package/dist/core/session-store.d.ts +13 -11
  49. package/dist/core/session-store.js +103 -119
  50. package/dist/core/settings-injector.d.ts +5 -2
  51. package/dist/core/settings-injector.js +21 -88
  52. package/dist/core/spawn.d.ts +9 -1
  53. package/dist/core/spawn.js +33 -33
  54. package/dist/core/stats-cli.d.ts +7 -0
  55. package/dist/core/stats-cli.js +66 -93
  56. package/dist/core/status-cli.d.ts +1 -1
  57. package/dist/core/status-cli.js +23 -4
  58. package/dist/core/statusline-cli.js +5 -0
  59. package/dist/core/statusline-install.d.ts +10 -2
  60. package/dist/core/statusline-install.js +27 -4
  61. package/dist/core/transcript-summary.d.ts +84 -9
  62. package/dist/core/transcript-summary.js +283 -49
  63. package/dist/core/uninstall.d.ts +4 -0
  64. package/dist/core/uninstall.js +68 -36
  65. package/dist/core/v1-bootstrap.d.ts +1 -1
  66. package/dist/core/v1-bootstrap.js +38 -9
  67. package/dist/engine/acted-on-evidence.d.ts +8 -0
  68. package/dist/engine/acted-on-evidence.js +38 -0
  69. package/dist/engine/block-judge.d.ts +3 -1
  70. package/dist/engine/block-judge.js +4 -3
  71. package/dist/engine/compound-cli.d.ts +26 -2
  72. package/dist/engine/compound-cli.js +143 -19
  73. package/dist/engine/compound-lifecycle.d.ts +36 -2
  74. package/dist/engine/compound-lifecycle.js +131 -11
  75. package/dist/engine/compound-loop.d.ts +4 -0
  76. package/dist/engine/compound-loop.js +93 -18
  77. package/dist/engine/correction-cluster-runner.d.ts +11 -1
  78. package/dist/engine/correction-cluster-runner.js +39 -15
  79. package/dist/engine/correction-clustering.d.ts +11 -0
  80. package/dist/engine/correction-clustering.js +20 -3
  81. package/dist/engine/lifecycle/lifecycle-cli.js +10 -3
  82. package/dist/engine/lifecycle/meta-reclassifier.d.ts +9 -0
  83. package/dist/engine/lifecycle/meta-reclassifier.js +15 -3
  84. package/dist/engine/lifecycle/orchestrator.js +3 -2
  85. package/dist/engine/lifecycle/signals.d.ts +19 -1
  86. package/dist/engine/lifecycle/signals.js +61 -2
  87. package/dist/engine/lifecycle/trigger-t1-correction.d.ts +1 -1
  88. package/dist/engine/lifecycle/trigger-t1-correction.js +9 -28
  89. package/dist/engine/lifecycle/trigger-t5-conflict.d.ts +8 -0
  90. package/dist/engine/lifecycle/trigger-t5-conflict.js +60 -2
  91. package/dist/engine/roi-demotion.d.ts +11 -0
  92. package/dist/engine/roi-demotion.js +50 -8
  93. package/dist/engine/rule-detectability.d.ts +39 -0
  94. package/dist/engine/rule-detectability.js +66 -0
  95. package/dist/engine/rule-project-cli.d.ts +25 -0
  96. package/dist/engine/rule-project-cli.js +148 -0
  97. package/dist/engine/rule-recovery-cli.d.ts +21 -0
  98. package/dist/engine/rule-recovery-cli.js +265 -0
  99. package/dist/engine/rule-toggle-cli.d.ts +14 -2
  100. package/dist/engine/rule-toggle-cli.js +94 -6
  101. package/dist/engine/skill-promoter.d.ts +14 -8
  102. package/dist/engine/skill-promoter.js +57 -85
  103. package/dist/engine/solution-format.d.ts +26 -1
  104. package/dist/engine/solution-format.js +65 -3
  105. package/dist/engine/solution-habit.d.ts +1 -0
  106. package/dist/engine/solution-habit.js +22 -0
  107. package/dist/engine/solution-index.d.ts +5 -0
  108. package/dist/engine/solution-index.js +32 -0
  109. package/dist/engine/solution-matcher-eval.js +4 -4
  110. package/dist/engine/solution-matcher.js +15 -13
  111. package/dist/engine/solution-scope.d.ts +11 -0
  112. package/dist/engine/solution-scope.js +19 -0
  113. package/dist/engine/solution-writer.d.ts +3 -1
  114. package/dist/engine/solution-writer.js +3 -2
  115. package/dist/engine/term-normalizer.js +49 -0
  116. package/dist/fgx.js +1 -1
  117. package/dist/forge/cli.js +51 -8
  118. package/dist/forge/evidence-processor.js +6 -0
  119. package/dist/hooks/context-guard.d.ts +0 -22
  120. package/dist/hooks/context-guard.js +22 -55
  121. package/dist/hooks/context-usage.d.ts +21 -0
  122. package/dist/hooks/context-usage.js +103 -0
  123. package/dist/hooks/dangerous-patterns.json +1 -16
  124. package/dist/hooks/db-guard.d.ts +1 -1
  125. package/dist/hooks/db-guard.js +21 -30
  126. package/dist/hooks/hook-config.d.ts +2 -0
  127. package/dist/hooks/hook-config.js +5 -1
  128. package/dist/hooks/hooks-generator.d.ts +4 -0
  129. package/dist/hooks/hooks-generator.js +10 -4
  130. package/dist/hooks/permission-handler.js +23 -3
  131. package/dist/hooks/post-tool-use.js +14 -10
  132. package/dist/hooks/pre-tool-use.d.ts +17 -3
  133. package/dist/hooks/pre-tool-use.js +145 -30
  134. package/dist/hooks/rate-limiter.js +12 -7
  135. package/dist/hooks/secret-filter.js +15 -4
  136. package/dist/hooks/session-end.d.ts +2 -2
  137. package/dist/hooks/session-end.js +13 -7
  138. package/dist/hooks/session-recovery.js +79 -50
  139. package/dist/hooks/shared/command-analyzer.d.ts +45 -0
  140. package/dist/hooks/shared/command-analyzer.js +972 -0
  141. package/dist/hooks/shared/command-parser.d.ts +5 -29
  142. package/dist/hooks/shared/command-parser.js +65 -35
  143. package/dist/hooks/shared/commit-guard.d.ts +15 -0
  144. package/dist/hooks/shared/commit-guard.js +177 -0
  145. package/dist/hooks/shared/hook-response.d.ts +12 -2
  146. package/dist/hooks/shared/hook-response.js +19 -3
  147. package/dist/hooks/shared/hook-timing.js +9 -3
  148. package/dist/hooks/shared/injection-caps.d.ts +32 -2
  149. package/dist/hooks/shared/injection-caps.js +73 -2
  150. package/dist/hooks/shared/is-main.d.ts +8 -0
  151. package/dist/hooks/shared/is-main.js +20 -0
  152. package/dist/hooks/shared/tool-response.d.ts +6 -0
  153. package/dist/hooks/shared/tool-response.js +30 -0
  154. package/dist/hooks/slop-detector.js +6 -3
  155. package/dist/hooks/solution-injector.d.ts +23 -0
  156. package/dist/hooks/solution-injector.js +102 -101
  157. package/dist/hooks/stop-guard.d.ts +11 -1
  158. package/dist/hooks/stop-guard.js +28 -11
  159. package/dist/hooks/subagent-stop-guard.js +2 -1
  160. package/dist/hooks/subagent-tracker.js +2 -1
  161. package/dist/host/capabilities-codex.js +1 -0
  162. package/dist/host/claude-shim.d.ts +24 -0
  163. package/dist/host/claude-shim.js +68 -0
  164. package/dist/host/codex-hook-shim.d.ts +3 -1
  165. package/dist/host/codex-hook-shim.js +7 -5
  166. package/dist/host/codex-notify.js +1 -1
  167. package/dist/host/codex-rules-context.d.ts +6 -4
  168. package/dist/host/codex-rules-context.js +11 -24
  169. package/dist/host/exec-host.d.ts +5 -1
  170. package/dist/host/exec-host.js +15 -4
  171. package/dist/host/install-claude.d.ts +47 -14
  172. package/dist/host/install-claude.js +302 -155
  173. package/dist/host/install-codex.d.ts +20 -0
  174. package/dist/host/install-codex.js +32 -1
  175. package/dist/host/install-opencode.d.ts +3 -1
  176. package/dist/host/install-opencode.js +6 -3
  177. package/dist/host/install-orchestrator.js +14 -1
  178. package/dist/host/opencode/translate.d.ts +1 -1
  179. package/dist/host/opencode/translate.js +5 -3
  180. package/dist/host/projection.d.ts +9 -1
  181. package/dist/host/projection.js +19 -2
  182. package/dist/mcp/server.js +5 -0
  183. package/dist/mcp/solution-reader.d.ts +5 -5
  184. package/dist/mcp/solution-reader.js +13 -35
  185. package/dist/mcp/tools.js +18 -1
  186. package/dist/renderer/inspect-renderer.js +4 -2
  187. package/dist/renderer/render-report.d.ts +22 -0
  188. package/dist/renderer/render-report.js +29 -0
  189. package/dist/renderer/rule-renderer.d.ts +28 -2
  190. package/dist/renderer/rule-renderer.js +91 -76
  191. package/dist/store/evidence-store.js +34 -6
  192. package/dist/store/rule-lifecycle.d.ts +3 -1
  193. package/dist/store/rule-lifecycle.js +10 -0
  194. package/dist/store/rule-scope.d.ts +7 -0
  195. package/dist/store/rule-scope.js +54 -0
  196. package/dist/store/rule-store.d.ts +29 -3
  197. package/dist/store/rule-store.js +110 -26
  198. package/dist/store/types.d.ts +22 -2
  199. package/dist/way/cli.d.ts +1 -0
  200. package/dist/way/cli.js +313 -0
  201. package/dist/way/compile.d.ts +22 -0
  202. package/dist/way/compile.js +408 -0
  203. package/dist/way/conflict.d.ts +2 -0
  204. package/dist/way/conflict.js +18 -0
  205. package/dist/way/draft.d.ts +43 -0
  206. package/dist/way/draft.js +335 -0
  207. package/dist/way/extract.d.ts +17 -0
  208. package/dist/way/extract.js +172 -0
  209. package/dist/way/io.d.ts +79 -0
  210. package/dist/way/io.js +425 -0
  211. package/dist/way/similar.d.ts +2 -0
  212. package/dist/way/similar.js +30 -0
  213. package/dist/way/types.d.ts +98 -0
  214. package/dist/way/types.js +2 -0
  215. package/package.json +1 -1
  216. package/plugin.json +1 -1
  217. package/scripts/postinstall.js +76 -899
  218. package/dist/core/health-cli.d.ts +0 -25
  219. package/dist/core/health-cli.js +0 -90
  220. package/dist/host/parity-harness.d.ts +0 -70
  221. package/dist/host/parity-harness.js +0 -287
@@ -20,10 +20,12 @@ import { incrementEvidence } from '../engine/solution-writer.js';
20
20
  import { isReflectionCandidate } from './compound-reflection.js';
21
21
  import { stripPrivate } from '../engine/private-filter.js';
22
22
  import { isHookEnabled } from './hook-config.js';
23
- import { approve, approveWithWarning, denyOrObserve, failOpenWithTracking } from './shared/hook-response.js';
23
+ import { approve, approveWithWarning, ask, denyOrObserve, failOpenWithTracking } from './shared/hook-response.js';
24
24
  import { FORGEN_HOME, STATE_DIR } from '../core/paths.js';
25
25
  import { recordHookTiming } from './shared/hook-timing.js';
26
26
  import { maskQuotedContent } from './shared/command-parser.js';
27
+ import { analyzeCommand, worstFinding, MAX_COMMAND_LENGTH } from './shared/command-analyzer.js';
28
+ import { checkGitSecretsBudgeted } from './shared/commit-guard.js';
27
29
  const FAIL_COUNTER_PATH = path.join(STATE_DIR, 'pre-tool-fail-counter.json');
28
30
  const FAIL_CLOSE_THRESHOLD = 3; // 연속 3회 파싱 실패 시에만 reject
29
31
  /** RegExp 안전성 검증 (ReDoS 방지) — 매칭/비매칭 양쪽 모두 테스트 */
@@ -66,11 +68,8 @@ function loadDangerousPatterns() {
66
68
  }
67
69
  }
68
70
  catch {
69
- // JSON 로드 실패 시 하드코딩 폴백 (최소 안전장치)
70
- results.push(
71
- // v0.4.1 false-positive fix: /tmp, /var/folders, /var/tmp 같은 임시 경로는
72
- // 일반 개발에서 매일 정리 대상. 위험한 시스템 경로만 blacklist.
73
- { pattern: /rm\s+(-rf|-fr)\s+(\/(?!tmp\b|var\/folders\b|var\/tmp\b)|~)/, description: 'rm -rf on root/home path', severity: 'block' }, { pattern: /curl\s+.*\|\s*(ba)?sh/, description: 'curl pipe to shell', severity: 'block' }, { pattern: /:\(\)\s*\{\s*:\|:&\s*\}\s*;:/, description: 'fork bomb', severity: 'block' });
71
+ // JSON 로드 실패 시 하드코딩 폴백 (최소 안전장치). 나머지 위험 명령은 command-analyzer 가 담당.
72
+ results.push({ pattern: /:\(\)\s*\{\s*:\|:&\s*\}\s*;:/, description: 'fork bomb', severity: 'block' });
74
73
  }
75
74
  // 2. 사용자 커스텀 패턴 (~/.compound/dangerous-patterns.json)
76
75
  try {
@@ -97,26 +96,61 @@ function loadDangerousPatterns() {
97
96
  }
98
97
  /** 위험 Bash 명령어 패턴 (패키지 내장 + 사용자 커스텀 병합) */
99
98
  export const DANGEROUS_PATTERNS = loadDangerousPatterns();
99
+ const DELETE_FINDING_IDS = new Set(['rm-recursive', 'find-delete', 'find-exec-rm', 'script-delete']);
100
100
  const REMINDER_INTERVAL = 10; // 10회 호출당 1회 리마인더
101
101
  const REMINDER_COUNTER_PATH = path.join(STATE_DIR, 'reminder-counter.json');
102
- /** 위험 명령어 검사 (순수 함수) */
103
- export function checkDangerousCommand(toolName, toolInput) {
102
+ /**
103
+ * 위험 명령어 검사 (순수 함수).
104
+ *
105
+ * D12-A: 명령 문자열 전체에 정규식을 대던 방식을 버리고 command-analyzer 의 실제 파싱 결과를 쓴다.
106
+ * - block: 되돌릴 수 없는 파괴(루트/홈 재귀 삭제, mkfs, 장치 쓰기, 다운로드→셸) — 항상 차단
107
+ * - ask : 기본 룰 "사용자 확인 없는 rm -rf 금지" — 임시(claude-*) 경로가 아닌 재귀 삭제는 확인을 요청
108
+ * - warn : 정책 유지(git reset --hard, git clean -f, force push, chmod 777, eval)
109
+ * 정규식 테이블(dangerous-patterns.json + 사용자 커스텀)은 파서가 모르는 잔여 패턴(fork bomb 등)에만 쓴다.
110
+ */
111
+ /**
112
+ * ask 응답 문구 꼬리 — 비대화형(`claude -p`, CI)에서는 승인해 줄 사람이 없다. 호스트가 ask 를 지원하지 않아
113
+ * deny 로 투영되는 경우(Codex/OpenCode)에도 같은 안내가 사유에 실려 간다.
114
+ */
115
+ export const ASK_NONINTERACTIVE_HINT = '비대화형(claude -p/CI)이면 승인할 사람이 없습니다 — 의도한 작업이면 FORGEN_USER_CONFIRMED=1 을 설정해 다시 실행하세요 (우회는 violations.jsonl 에 기록됨).';
116
+ export function checkDangerousCommand(toolName, toolInput, cwd) {
104
117
  if (toolName !== 'Bash')
105
118
  return { action: 'pass' };
106
119
  const command = typeof toolInput === 'string'
107
120
  ? toolInput
108
121
  : (toolInput.command ?? '');
109
- // v0.4.1 (2026-04-24) quote-aware built-in scan:
110
- // 기본은 masked (quote/heredoc 본문 제거) — shell 실행 토큰 검사. 하지만
111
- // `python -c "..."` / `eval "..."` 처럼 quote 안 본문이 실 payload 로 실행되는
112
- // 패턴은 match_target:raw 로 지정해 원본 command 전체 검사.
122
+ // 상한 초과는 정규식 경로(이차 시간 위험)까지 가지 않고 곧바로 확인 요청 — 시간 초과로 fail-open 되지 않게.
123
+ if (command.length > MAX_COMMAND_LENGTH) {
124
+ return { action: 'ask', description: `command too long to analyze (${command.length} > ${MAX_COMMAND_LENGTH} chars)`, command: command.slice(0, 100), ruleId: 'builtin:analysis-limit' };
125
+ }
126
+ const analysis = analyzeCommand(command, { cwd });
127
+ const worst = worstFinding(analysis.findings);
113
128
  const maskedCommand = maskQuotedContent(command);
129
+ let regexWarn = null;
114
130
  for (const { pattern, description, severity, matchTarget } of DANGEROUS_PATTERNS) {
115
131
  const target = matchTarget === 'raw' ? command : maskedCommand;
116
- if (pattern.test(target)) {
117
- return { action: severity, description, command: command.slice(0, 100) };
118
- }
132
+ if (!pattern.test(target))
133
+ continue;
134
+ if (severity === 'block')
135
+ return { action: 'block', description, command: command.slice(0, 100) };
136
+ regexWarn ??= { description };
137
+ }
138
+ // SQL: db-guard 와 같은 분석기 기준(실행 문맥의 SQL 텍스트만). 이전 정규식 테이블의 drop/truncate 항목을 대체.
139
+ for (const text of analysis.sqlTexts) {
140
+ if (/drop\s+(?:table|database)/i.test(text))
141
+ return { action: 'block', description: 'DROP TABLE/DATABASE', command: command.slice(0, 100) };
142
+ }
143
+ if (worst && (worst.action === 'block' || worst.action === 'deny')) {
144
+ return { action: 'block', description: worst.description, command: command.slice(0, 100), ruleId: `builtin:${worst.id}` };
119
145
  }
146
+ if (worst?.action === 'ask')
147
+ return { action: 'ask', description: worst.description, command: command.slice(0, 100), ruleId: `builtin:${worst.id}` };
148
+ if (worst?.action === 'warn')
149
+ return { action: 'warn', description: worst.description, command: command.slice(0, 100) };
150
+ if (analysis.sqlTexts.some((t) => /truncate\s+table/i.test(t)))
151
+ return { action: 'warn', description: 'TRUNCATE TABLE', command: command.slice(0, 100) };
152
+ if (regexWarn)
153
+ return { action: 'warn', description: regexWarn.description, command: command.slice(0, 100) };
120
154
  return { action: 'pass' };
121
155
  }
122
156
  /** 카운터 기반 리마인더 표시 여부 판정 (순수 함수 — I/O 없음) */
@@ -143,7 +177,7 @@ function shouldShowReminderIO() {
143
177
  }
144
178
  }
145
179
  /** 활성 모드 상태를 리마인더로 수집 */
146
- function getActiveReminders() {
180
+ function getActiveReminders(sessionId) {
147
181
  const reminders = [];
148
182
  if (!fs.existsSync(STATE_DIR))
149
183
  return reminders;
@@ -153,7 +187,8 @@ function getActiveReminders() {
153
187
  continue;
154
188
  try {
155
189
  const data = JSON.parse(fs.readFileSync(path.join(STATE_DIR, f), 'utf-8'));
156
- if (data.active) {
190
+ // H6: 다른 세션이 켠 모드를 이 세션의 리마인더로 보여주지 않는다.
191
+ if (data.active && data.sessionId === sessionId) {
157
192
  const mode = f.replace('-state.json', '');
158
193
  reminders.push(`[${mode}] mode active`);
159
194
  }
@@ -354,10 +389,24 @@ async function main() {
354
389
  const sessionId = data.session_id ?? 'default';
355
390
  // ADR-017 §6-2: 상대 경로 rm 대상 해석용 (Claude Code 훅 stdin 의 cwd).
356
391
  const hookCwd = typeof data.cwd === 'string' ? String(data.cwd) : undefined;
392
+ // 입력 상한: 너무 긴 Bash 명령은 이후 어떤 분석(정규식·파서)도 돌리지 않고 확인을 요청한다 (훅 timeout 3초 안에 끝내기 위해).
393
+ // 시간 초과로 fail-open 되는 것보다 사람이 한 번 보는 쪽이 안전하다.
394
+ if (toolName === 'Bash' && typeof toolInput.command === 'string'
395
+ && toolInput.command.length > MAX_COMMAND_LENGTH) {
396
+ if (process.env.FORGEN_USER_CONFIRMED !== '1') {
397
+ const len = toolInput.command.length;
398
+ console.log(ask(`[Forgen] 사용자 확인 필요 — command too long to analyze (${len} > ${MAX_COMMAND_LENGTH} chars)\n${ASK_NONINTERACTIVE_HINT}`));
399
+ return;
400
+ }
401
+ console.log(approve());
402
+ return;
403
+ }
357
404
  // ADR-008 / codex-integration.md — Codex `approval_policy=auto` 에서
358
405
  // PermissionRequest 가 dispatch 안 되는 갭 보완. 모든 tool call 을
359
406
  // permissions-<id>.jsonl 에 supplement 로 append (source='pre-tool-use').
360
- if (toolName)
407
+ // D12-D: 중첩(추출) 실행에서는 위험 차단만 유지하고 학습·로그 부수효과는 건너뛴다.
408
+ const nested = process.env.FORGEN_NESTED_RUN === '1';
409
+ if (toolName && !nested)
361
410
  logToolCallSupplement(sessionId, toolName);
362
411
  // ADR-001 Mech-A PreToolUse dispatcher — 사용자가 정의한 rule 이 빌트인 위험-명령 감지보다 먼저.
363
412
  // 이렇게 해야 rule.block_message (맥락 있는 안내) 가 제네릭 "Dangerous command blocked" 대신 노출됨.
@@ -365,13 +414,13 @@ async function main() {
365
414
  // ADR-017 D1: advise 강등 룰의 안내 메시지 — 차단 판정이 모두 끝난 뒤 승인 응답에 합쳐 출력한다.
366
415
  const advisories = [];
367
416
  try {
368
- const [{ loadActiveRules }, { recordViolation, matchedFragment }, { compileSafeRegex, safeRegexTest }, { preprocessForMatch, isTempOnlyRm, isSuspiciousRm },] = await Promise.all([
417
+ const [{ loadEnforcedRules }, { recordViolation, matchedFragment }, { compileSafeRegex, safeRegexTest }, { preprocessForMatch },] = await Promise.all([
369
418
  import('../store/rule-store.js'),
370
419
  import('../engine/lifecycle/signals.js'),
371
420
  import('./shared/safe-regex.js'),
372
421
  import('./shared/command-parser.js'),
373
422
  ]);
374
- const rules = loadActiveRules();
423
+ const rules = loadEnforcedRules(hookCwd);
375
424
  const command = typeof toolInput.command === 'string'
376
425
  ? String(toolInput.command)
377
426
  : '';
@@ -402,9 +451,17 @@ async function main() {
402
451
  // 걸린 경우는 막지 않는다 — 같은 명령 안의 변수 대입까지 한 단계 해석해 대상이 전부 임시 경로일 때만.
403
452
  // critic D1 SEV-1: 예외는 **매칭된 토큰 자체가 rm** 일 때만 (pattern.includes('rm') 은 terraform 룰까지 껐다).
404
453
  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;
454
+ // D12-A: rm 계열 판정은 command-analyzer 가 한다 — 정규식은 `rm -r -f`·`bash -c`·`xargs` 를 놓치고
455
+ // 따옴표 속 문자열을 잡는다. 파서가 "삭제 없음/임시 경로"로 보면 룰도 통과, root/home 이면 룰 deny(영수증 포함),
456
+ // 그 외 재귀 삭제는 기본 룰 "확인 없는 rm -rf 금지"에 따라 차단 대신 사용자 확인 요청(ask).
457
+ let askOnly = false;
458
+ if (/^\s*rm\b/.test(matchTok)) {
459
+ const worstDel = worstFinding(analyzeCommand(command, { cwd: hookCwd }).findings.filter((f) => DELETE_FINDING_IDS.has(f.id)));
460
+ if (!worstDel) {
461
+ log.debug(`rule ${rule.rule_id}: no real recursive delete (temp-only/quoted) — exempt`);
462
+ continue;
463
+ }
464
+ askOnly = worstDel.action === 'ask';
408
465
  }
409
466
  const requiresFlag = v.params?.requires_flag;
410
467
  const confirmed = process.env.FORGEN_USER_CONFIRMED === '1';
@@ -425,12 +482,14 @@ async function main() {
425
482
  continue;
426
483
  }
427
484
  if (requiresFlag && !confirmed) {
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);
485
+ const violationId = recordViolation({ rule_id: rule.rule_id, session_id: sessionId, source: 'pre-tool-guard', kind: askOnly ? 'correction' : 'deny', message_preview: command.slice(0, 120), matched: matchedFrag, target_kind: 'command' }, { receipt_text: command });
486
+ if (!askOnly) {
487
+ try {
488
+ const { spawnBlockJudge } = await import('../engine/block-judge.js');
489
+ spawnBlockJudge(violationId, sessionId);
490
+ }
491
+ catch { /* fail-open */ }
432
492
  }
433
- catch { /* fail-open */ }
434
493
  const baseMsg = spec.block_message ?? `[${rule.rule_id}] policy violation: ${rule.policy.slice(0, 120)}`;
435
494
  // ADR-017 D0: 룰의 출처 교정 인용.
436
495
  const origin = await (async () => {
@@ -443,6 +502,10 @@ async function main() {
443
502
  }
444
503
  })();
445
504
  // G8: override 힌트 — FORGEN_USER_CONFIRMED=1 으로 사용자 명시 승인 가능, 감사 로그 기록됨.
505
+ if (askOnly) {
506
+ console.log(ask(`${baseMsg}\n[Forgen] 사용자 확인 필요 — 이 재귀 삭제를 진행해도 되는지 승인해 주세요.${origin ? `\n${origin}` : ''}\n${ASK_NONINTERACTIVE_HINT}`));
507
+ return;
508
+ }
446
509
  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)`;
447
510
  console.log(denyOrObserve('pre-tool-use', msgWithHint));
448
511
  return;
@@ -479,16 +542,68 @@ async function main() {
479
542
  }
480
543
  }
481
544
  catch { /* fail-open */ }
482
- const check = checkDangerousCommand(toolName, toolInput);
545
+ // D12-B: git add/commit 이 비밀 파일·키를 넣으려 하면 (실제 staged/untracked 내용 확인 후) 차단.
546
+ if (toolName === 'Bash' && typeof toolInput.command === 'string') {
547
+ try {
548
+ const gitOps = analyzeCommand(String(toolInput.command), { cwd: hookCwd }).gitOps;
549
+ if (gitOps.some((o) => o.sub === 'add' || o.sub === 'commit')) {
550
+ const { hits: secretHits, timedOut } = checkGitSecretsBudgeted(gitOps, hookCwd, Number(process.env.FORGEN_COMMIT_GUARD_BUDGET_MS) || undefined);
551
+ if (timedOut && secretHits.length === 0 && process.env.FORGEN_USER_CONFIRMED !== '1') {
552
+ // 2초 예산 안에 비밀 검사를 끝내지 못했다 — 검사 안 된 커밋을 통과시키지 않는다.
553
+ console.log(ask(`[Forgen] 사용자 확인 필요 — git add/commit 의 비밀 검사가 시간 예산(2초) 안에 끝나지 않았습니다 (저장소가 크거나 git 이 느림). 커밋 대상에 .env·키가 없는지 확인해 주세요.\n${ASK_NONINTERACTIVE_HINT}`));
554
+ return;
555
+ }
556
+ if (secretHits.length > 0) {
557
+ const lines = secretHits.slice(0, 10).map((h) => ` - ${h.file} (${h.reasons.join(', ')})`).join('\n');
558
+ try {
559
+ const { recordViolation } = await import('../engine/lifecycle/signals.js');
560
+ recordViolation({ rule_id: 'builtin:commit-secret', session_id: sessionId, source: 'pre-tool-guard', kind: 'deny', message_preview: `git secret files: ${secretHits.map((h) => h.file).slice(0, 5).join(', ')}`, target_kind: 'command' });
561
+ }
562
+ catch { /* fail-open */ }
563
+ // 이름·패턴 기반 판단이라 오탐이 있을 수 있다 → 조용히 막지 않고 사유를 보여주며 사용자에게 묻는다
564
+ // (사용자 교정 2026-11-06: "멈추면 안되는 거지. 차라리 물어봐야지 사용자한테").
565
+ console.log(ask(`[Forgen] 사용자 확인 필요 — 비밀 파일/키로 보이는 항목이 커밋 대상에 있습니다:\n${lines}\n예시값만 담긴 템플릿이면 승인하고, 진짜 비밀이면 거부한 뒤 .gitignore 추가 또는 git reset 으로 빼세요. 키가 이미 노출됐다면 폐기·재발급하세요.\n${ASK_NONINTERACTIVE_HINT}`));
566
+ return;
567
+ }
568
+ }
569
+ }
570
+ catch { /* fail-open */ }
571
+ }
572
+ const check = checkDangerousCommand(toolName, toolInput, hookCwd);
573
+ const bashCmd = typeof toolInput.command === 'string' ? String(toolInput.command) : '';
483
574
  if (check.action === 'block') {
575
+ if (check.ruleId) {
576
+ try {
577
+ const { recordViolation } = await import('../engine/lifecycle/signals.js');
578
+ recordViolation({ rule_id: check.ruleId, session_id: sessionId, source: 'pre-tool-guard', kind: 'deny', message_preview: bashCmd.slice(0, 120), target_kind: 'command' });
579
+ }
580
+ catch { /* fail-open */ }
581
+ }
484
582
  console.log(denyOrObserve('pre-tool-use', `[Forgen] Dangerous command blocked: ${check.description}\nCommand: ${check.command}`));
485
583
  return;
486
584
  }
585
+ if (check.action === 'ask') {
586
+ if (process.env.FORGEN_USER_CONFIRMED === '1') {
587
+ try {
588
+ const { recordViolation } = await import('../engine/lifecycle/signals.js');
589
+ recordViolation({ rule_id: check.ruleId ?? 'builtin:ask', session_id: sessionId, source: 'pre-tool-guard', kind: 'bypass_confirmed', message_preview: `[FORGEN_USER_CONFIRMED=1 bypass] ${bashCmd.slice(0, 120)}` });
590
+ }
591
+ catch { /* fail-open */ }
592
+ }
593
+ else {
594
+ console.log(ask(`${advisories.length ? `${advisories.join('\n')}\n` : ''}[Forgen] 사용자 확인 필요 — ${check.description}\n규칙: 확인 없는 재귀 삭제 금지 (임시 작업 폴더 /tmp/claude-* 는 면제).\nCommand: ${check.command}\n${ASK_NONINTERACTIVE_HINT}`));
595
+ return;
596
+ }
597
+ }
487
598
  const withAdvisories = (body) => (advisories.length ? `${advisories.map((x) => `<compound-tool-warning>\n${x}\n</compound-tool-warning>`).join('\n')}${body ? `\n${body}` : ''}` : body);
488
599
  if (check.action === 'warn') {
489
600
  console.log(approveWithWarning(withAdvisories(`<compound-tool-warning>\n[Forgen] ⚠ Dangerous command detected: ${check.description}\nProceed with caution.\n</compound-tool-warning>`)));
490
601
  return;
491
602
  }
603
+ if (nested) {
604
+ console.log(approve());
605
+ return;
606
+ }
492
607
  // Output size guard: warn when Grep is used without head_limit
493
608
  if (toolName === 'Grep' && !toolInput?.head_limit) {
494
609
  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>`)));
@@ -507,7 +622,7 @@ async function main() {
507
622
  // 그래서 "리마인더를 보여줄 호출이 아닌" 90%에서도 디렉터리 스캔이 발생.
508
623
  // 이제 shouldShowReminderIO를 먼저 체크해 표시 회차일 때만 스캔한다.
509
624
  if (shouldShowReminderIO()) {
510
- const reminders = getActiveReminders();
625
+ const reminders = getActiveReminders(sessionId);
511
626
  if (reminders.length > 0) {
512
627
  console.log(approveWithWarning(withAdvisories(`<compound-reminder>\n${reminders.join('\n')}\n</compound-reminder>`)));
513
628
  return;
@@ -9,6 +9,7 @@ import * as fs from 'node:fs';
9
9
  import * as path from 'node:path';
10
10
  import { readStdinJSON } from './shared/read-stdin.js';
11
11
  import { atomicWriteJSON } from './shared/atomic-write.js';
12
+ import { withFileLockSync } from './shared/file-lock.js';
12
13
  import { isHookEnabled } from './hook-config.js';
13
14
  import { approve, denyOrObserve, failOpenWithTracking } from './shared/hook-response.js';
14
15
  import { STATE_DIR } from '../core/paths.js';
@@ -55,7 +56,7 @@ async function main() {
55
56
  const data = await readStdinJSON(1500); // Must finish within plugin.json timeout (2000ms)
56
57
  if (!data) {
57
58
  // stdin 파싱 실패 — 통과 (rate limiter는 fail-open)
58
- console.log(failOpenWithTracking('rate-limiter'));
59
+ console.log(failOpenWithTracking('rate-limiter', new Error('stdin parse failed or empty — rate limit not evaluated')));
59
60
  return;
60
61
  }
61
62
  if (!isHookEnabled('rate-limiter')) {
@@ -68,12 +69,16 @@ async function main() {
68
69
  console.log(approve());
69
70
  return;
70
71
  }
71
- const state = loadRateLimitState();
72
- const { exceeded, count, updatedState } = checkRateLimit(state);
73
- // 거부된 호출은 상태를 저장하지 않음 (윈도우 누적 방지)
74
- if (!exceeded) {
75
- saveRateLimitState(updatedState);
76
- }
72
+ // H8: load → check → save 가 락 없이 돌아 동시 호출 20회 중 15건만 기록됐다(마지막 쓴 쪽이 이김).
73
+ // 락 안에서 읽고-판정하고-쓴다. 락/쓰기 실패는 삼키지 않고 main().catch 가 사유와 함께 기록한다(fail-open).
74
+ const { exceeded, count } = withFileLockSync(RATE_LIMIT_PATH, () => {
75
+ const state = loadRateLimitState();
76
+ const r = checkRateLimit(state);
77
+ // 거부된 호출은 상태를 저장하지 않음 (윈도우 누적 방지)
78
+ if (!r.exceeded)
79
+ saveRateLimitState(r.updatedState);
80
+ return r;
81
+ }, { timeoutMs: 1200 });
77
82
  if (exceeded) {
78
83
  console.log(denyOrObserve('rate-limiter', `[Forgen] Rate limit exceeded (${count}/${DEFAULT_LIMIT}/min). Wait before retrying.`));
79
84
  return;
@@ -11,9 +11,11 @@ import { fileURLToPath } from 'node:url';
11
11
  import { HookError } from '../core/errors.js';
12
12
  import { readStdinJSON } from './shared/read-stdin.js';
13
13
  import { isHookEnabled } from './hook-config.js';
14
- import { approve, approveWithWarning, failOpenWithTracking } from './shared/hook-response.js';
14
+ import { approve, approveWithPostToolContext, failOpenWithTracking } from './shared/hook-response.js';
15
+ import { stringifyToolResponse } from './shared/tool-response.js';
15
16
  export const SECRET_PATTERNS = [
16
- { name: 'API Key', pattern: /(sk|pk|api[_-]?key)[_-][\w\-.]{20,}/i },
17
+ // 단어 중간 매칭 방지: risk_/task-/disk- 의 sk_ sk- 는 키가 아니다. `_` 앞(MY_API_KEY_…)은 허용하려고 \b 대신 영숫자 lookbehind.
18
+ { name: 'API Key', pattern: /(?<![A-Za-z0-9])(sk|pk|api[_-]?key)[_-][\w\-.]{20,}/i },
17
19
  { name: 'AWS Access Key', pattern: /AKIA[\w]{16}/ },
18
20
  { name: 'Token/Bearer/JWT', pattern: /(token|bearer|jwt)[=:\s]["']?[\w\-.]{20,}/i },
19
21
  { name: 'Password', pattern: /(password|passwd|pwd)\s*[=:]\s*["']?[^\s"']{8,}/i },
@@ -67,7 +69,8 @@ export async function main() {
67
69
  return;
68
70
  }
69
71
  const toolName = data.tool_name ?? data.toolName ?? '';
70
- const toolResponse = data.tool_response ?? data.toolOutput ?? '';
72
+ // H3: Bash 는 {stdout, stderr, …} 객체로 온다 — 문자열 리프를 모아 스캔한다.
73
+ const toolResponse = stringifyToolResponse(data.tool_response ?? data.toolOutput ?? '');
71
74
  const toolInput = data.tool_input ?? data.toolInput ?? {};
72
75
  // Write/Edit/Bash 도구만 검사
73
76
  if (!['Write', 'Edit', 'Bash'].includes(toolName)) {
@@ -79,8 +82,16 @@ export async function main() {
79
82
  const textToScan = `${inputStr}\n${toolResponse}`;
80
83
  const secrets = detectSecrets(textToScan);
81
84
  if (secrets.length > 0) {
85
+ // 비밀 "값"은 어디에도 싣지 않는다 — 패턴 이름만 모델·사용자·로그에 전달한다.
82
86
  const names = secrets.map(s => s.name).join(', ');
83
- console.log(approveWithWarning(`<compound-security-warning>\n[Forgen] ⚠ Sensitive information exposure detected: ${names}\nThe output may contain secrets. Please review.\n</compound-security-warning>`));
87
+ const inOutput = detectSecrets(toolResponse).length > 0;
88
+ const context = ['<compound-security-warning>',
89
+ `[Forgen secret-filter] 방금 ${toolName} ${inOutput ? '출력' : '입력'}에서 민감 정보 패턴이 탐지됐다: ${names}.`,
90
+ '- 값을 답변, 커밋, 파일, 메모리에 옮겨 적지 말 것. 필요하면 환경변수 이름으로만 참조한다.',
91
+ '- 이미 외부에 노출됐을 수 있으면 사용자에게 키 폐기·재발급을 안내한다.',
92
+ '</compound-security-warning>',
93
+ ].join('\n');
94
+ console.log(approveWithPostToolContext(context, `[Forgen] ⚠ Sensitive information detected: ${names}`));
84
95
  return;
85
96
  }
86
97
  console.log(approve());
@@ -16,8 +16,8 @@
16
16
  * 새 이벤트 추가는 기존 훅의 신뢰를 깨지 않는다 (이 훅 1개만 `/hooks` 승인 필요).
17
17
  * - fail-open: 어떤 실패도 종료를 막지 않는다.
18
18
  */
19
- /** session-recovery 와 동일 임계값 — 짧은 세션은 compound 가치가 없다. */
20
- export declare const MIN_USER_MESSAGES = 10;
19
+ /** D9: 임계값 1 — 짧은 세션에도 교정 승급·sessions.db 인덱싱이 필요하다. Haiku 추출 여부는 러너가 판단. */
20
+ export declare const MIN_USER_MESSAGES = 1;
21
21
  export interface SessionEndInput {
22
22
  session_id?: string;
23
23
  transcript_path?: string;
@@ -22,11 +22,11 @@ import { fileURLToPath } from 'node:url';
22
22
  import { createLogger } from '../core/logger.js';
23
23
  import { readStdinJSON } from './shared/read-stdin.js';
24
24
  import { isHookEnabled } from './hook-config.js';
25
- import { approve } from './shared/hook-response.js';
25
+ import { approve, failOpenWithTracking } from './shared/hook-response.js';
26
26
  import { recordHookTiming } from './shared/hook-timing.js';
27
27
  const log = createLogger('session-end');
28
- /** session-recovery 와 동일 임계값 — 짧은 세션은 compound 가치가 없다. */
29
- export const MIN_USER_MESSAGES = 10;
28
+ /** D9: 임계값 1 — 짧은 세션에도 교정 승급·sessions.db 인덱싱이 필요하다. Haiku 추출 여부는 러너가 판단. */
29
+ export const MIN_USER_MESSAGES = 1;
30
30
  /** 앞 N바이트만 읽는 상한. critic 2026-10-01: 239MB transcript 전체 스트리밍은 3.2s → 예산 초과로 SIGKILL. */
31
31
  export const COUNT_SCAN_BYTES = 200 * 1024;
32
32
  /**
@@ -90,24 +90,30 @@ export async function main() {
90
90
  log.debug('user message count 실패', e);
91
91
  }
92
92
  }
93
+ // 앞 200KB 에 사용자 메시지가 없어도(큰 도구 출력으로 시작하는 세션) 파일이 더 크면 러너를 돌린다.
94
+ try {
95
+ if (count === 0 && transcript && fs.statSync(transcript).size > COUNT_SCAN_BYTES)
96
+ count = 1;
97
+ }
98
+ catch { /* ignore */ }
93
99
  if (shouldRunSessionEndCompound(input, count)) {
94
100
  const cwd = input.cwd ?? process.cwd();
95
101
  const sessionId = input.session_id ?? path.basename(transcript, '.jsonl');
96
- const status = runAutoCompound(cwd, transcript, sessionId, count);
102
+ const status = runAutoCompound(cwd, transcript, sessionId, count, true);
97
103
  log.debug(`SessionEnd auto-compound: ${status} (reason=${input.reason ?? '?'}, msgs=${count})`);
98
104
  }
99
105
  console.log(approve());
100
106
  }
101
107
  catch (e) {
102
108
  log.debug('session-end 실패 (fail-open)', e);
103
- console.log(approve());
109
+ console.log(failOpenWithTracking('session-end', e));
104
110
  }
105
111
  finally {
106
112
  recordHookTiming('session-end', Date.now() - start, 'SessionEnd');
107
113
  }
108
114
  }
109
115
  if (process.argv[1] && fs.realpathSync(path.resolve(process.argv[1])) === fileURLToPath(import.meta.url)) {
110
- main().catch(() => {
111
- console.log(approve());
116
+ main().catch((e) => {
117
+ console.log(failOpenWithTracking('session-end', e));
112
118
  });
113
119
  }