@wooojin/forgen 0.6.8 → 0.6.9
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.
- package/.claude-plugin/plugin.json +1 -1
- package/CHANGELOG.md +17 -0
- package/README.ja.md +15 -10
- package/README.ko.md +15 -10
- package/README.md +19 -14
- package/README.zh.md +13 -8
- package/dist/checks/dangerous-response-pattern.d.ts +2 -1
- package/dist/checks/dangerous-response-pattern.js +27 -3
- package/dist/cli.js +133 -17
- package/dist/core/auto-compound-runner.js +502 -397
- package/dist/core/block-cli.js +7 -3
- package/dist/core/compound-consent.d.ts +18 -0
- package/dist/core/compound-consent.js +101 -6
- package/dist/core/compound-sweep-cli.d.ts +16 -0
- package/dist/core/compound-sweep-cli.js +67 -5
- package/dist/core/config-hooks.js +28 -10
- package/dist/core/correction-signals.d.ts +9 -0
- package/dist/core/correction-signals.js +37 -0
- package/dist/core/dev-cli.d.ts +1 -2
- package/dist/core/dev-cli.js +9 -28
- package/dist/core/doctor-verify.d.ts +35 -0
- package/dist/core/doctor-verify.js +502 -0
- package/dist/core/doctor.d.ts +4 -6
- package/dist/core/doctor.js +103 -184
- package/dist/core/explain-cli.js +8 -0
- package/dist/core/extraction-haiku.d.ts +64 -0
- package/dist/core/extraction-haiku.js +208 -0
- package/dist/core/extraction-queue.d.ts +68 -0
- package/dist/core/extraction-queue.js +300 -0
- package/dist/core/flow-status.d.ts +93 -0
- package/dist/core/flow-status.js +368 -0
- package/dist/core/harness.js +14 -42
- package/dist/core/inspect-cli.js +37 -13
- package/dist/core/lifecycle-classifier.d.ts +5 -1
- package/dist/core/lifecycle-classifier.js +13 -2
- package/dist/core/migrate-cli.d.ts +1 -1
- package/dist/core/migrate-cli.js +11 -11
- package/dist/core/migrate-tenetx.d.ts +1 -1
- package/dist/core/migrate-tenetx.js +2 -2
- package/dist/core/node-engine.d.ts +3 -0
- package/dist/core/node-engine.js +8 -0
- package/dist/core/observability-store.d.ts +15 -0
- package/dist/core/observability-store.js +73 -0
- package/dist/core/paths.d.ts +2 -0
- package/dist/core/paths.js +2 -0
- package/dist/core/rendered-rules-manifest.d.ts +7 -1
- package/dist/core/rendered-rules-manifest.js +45 -1
- package/dist/core/session-store.d.ts +13 -11
- package/dist/core/session-store.js +103 -119
- package/dist/core/settings-injector.d.ts +5 -2
- package/dist/core/settings-injector.js +21 -88
- package/dist/core/spawn.d.ts +9 -1
- package/dist/core/spawn.js +33 -33
- package/dist/core/stats-cli.d.ts +7 -0
- package/dist/core/stats-cli.js +66 -93
- package/dist/core/status-cli.d.ts +1 -1
- package/dist/core/status-cli.js +23 -4
- package/dist/core/statusline-cli.js +5 -0
- package/dist/core/statusline-install.d.ts +10 -2
- package/dist/core/statusline-install.js +27 -4
- package/dist/core/transcript-summary.d.ts +84 -9
- package/dist/core/transcript-summary.js +283 -49
- package/dist/core/uninstall.d.ts +4 -0
- package/dist/core/uninstall.js +68 -36
- package/dist/core/v1-bootstrap.d.ts +1 -1
- package/dist/core/v1-bootstrap.js +38 -9
- package/dist/engine/acted-on-evidence.d.ts +8 -0
- package/dist/engine/acted-on-evidence.js +38 -0
- package/dist/engine/block-judge.d.ts +3 -1
- package/dist/engine/block-judge.js +4 -3
- package/dist/engine/compound-cli.d.ts +26 -2
- package/dist/engine/compound-cli.js +143 -19
- package/dist/engine/compound-lifecycle.d.ts +36 -2
- package/dist/engine/compound-lifecycle.js +131 -11
- package/dist/engine/compound-loop.d.ts +4 -0
- package/dist/engine/compound-loop.js +93 -18
- package/dist/engine/correction-cluster-runner.d.ts +11 -1
- package/dist/engine/correction-cluster-runner.js +39 -15
- package/dist/engine/correction-clustering.d.ts +11 -0
- package/dist/engine/correction-clustering.js +20 -3
- package/dist/engine/lifecycle/lifecycle-cli.js +10 -3
- package/dist/engine/lifecycle/meta-reclassifier.d.ts +9 -0
- package/dist/engine/lifecycle/meta-reclassifier.js +15 -3
- package/dist/engine/lifecycle/orchestrator.js +3 -2
- package/dist/engine/lifecycle/signals.d.ts +19 -1
- package/dist/engine/lifecycle/signals.js +61 -2
- package/dist/engine/lifecycle/trigger-t1-correction.d.ts +1 -1
- package/dist/engine/lifecycle/trigger-t1-correction.js +9 -28
- package/dist/engine/lifecycle/trigger-t5-conflict.d.ts +8 -0
- package/dist/engine/lifecycle/trigger-t5-conflict.js +60 -2
- package/dist/engine/roi-demotion.d.ts +11 -0
- package/dist/engine/roi-demotion.js +50 -8
- package/dist/engine/rule-detectability.d.ts +39 -0
- package/dist/engine/rule-detectability.js +66 -0
- package/dist/engine/rule-project-cli.d.ts +25 -0
- package/dist/engine/rule-project-cli.js +148 -0
- package/dist/engine/rule-recovery-cli.d.ts +21 -0
- package/dist/engine/rule-recovery-cli.js +265 -0
- package/dist/engine/rule-toggle-cli.d.ts +14 -2
- package/dist/engine/rule-toggle-cli.js +94 -6
- package/dist/engine/skill-promoter.d.ts +14 -8
- package/dist/engine/skill-promoter.js +57 -85
- package/dist/engine/solution-format.d.ts +26 -1
- package/dist/engine/solution-format.js +65 -3
- package/dist/engine/solution-habit.d.ts +1 -0
- package/dist/engine/solution-habit.js +22 -0
- package/dist/engine/solution-index.d.ts +5 -0
- package/dist/engine/solution-index.js +32 -0
- package/dist/engine/solution-matcher-eval.js +4 -4
- package/dist/engine/solution-matcher.js +15 -13
- package/dist/engine/solution-scope.d.ts +11 -0
- package/dist/engine/solution-scope.js +19 -0
- package/dist/engine/solution-writer.d.ts +3 -1
- package/dist/engine/solution-writer.js +3 -2
- package/dist/engine/term-normalizer.js +49 -0
- package/dist/fgx.js +1 -1
- package/dist/forge/cli.js +51 -8
- package/dist/forge/evidence-processor.js +6 -0
- package/dist/hooks/context-guard.d.ts +0 -22
- package/dist/hooks/context-guard.js +22 -55
- package/dist/hooks/context-usage.d.ts +21 -0
- package/dist/hooks/context-usage.js +103 -0
- package/dist/hooks/dangerous-patterns.json +1 -16
- package/dist/hooks/db-guard.d.ts +1 -1
- package/dist/hooks/db-guard.js +21 -30
- package/dist/hooks/hook-config.d.ts +2 -0
- package/dist/hooks/hook-config.js +5 -1
- package/dist/hooks/hooks-generator.d.ts +4 -0
- package/dist/hooks/hooks-generator.js +10 -4
- package/dist/hooks/permission-handler.js +23 -3
- package/dist/hooks/post-tool-use.js +14 -10
- package/dist/hooks/pre-tool-use.d.ts +17 -3
- package/dist/hooks/pre-tool-use.js +143 -30
- package/dist/hooks/rate-limiter.js +12 -7
- package/dist/hooks/secret-filter.js +15 -4
- package/dist/hooks/session-end.d.ts +2 -2
- package/dist/hooks/session-end.js +13 -7
- package/dist/hooks/session-recovery.js +79 -50
- package/dist/hooks/shared/command-analyzer.d.ts +45 -0
- package/dist/hooks/shared/command-analyzer.js +972 -0
- package/dist/hooks/shared/command-parser.d.ts +5 -29
- package/dist/hooks/shared/command-parser.js +65 -35
- package/dist/hooks/shared/commit-guard.d.ts +15 -0
- package/dist/hooks/shared/commit-guard.js +176 -0
- package/dist/hooks/shared/hook-response.d.ts +6 -0
- package/dist/hooks/shared/hook-response.js +12 -0
- package/dist/hooks/shared/hook-timing.js +9 -3
- package/dist/hooks/shared/injection-caps.d.ts +32 -2
- package/dist/hooks/shared/injection-caps.js +73 -2
- package/dist/hooks/shared/is-main.d.ts +8 -0
- package/dist/hooks/shared/is-main.js +20 -0
- package/dist/hooks/shared/tool-response.d.ts +6 -0
- package/dist/hooks/shared/tool-response.js +30 -0
- package/dist/hooks/slop-detector.js +6 -3
- package/dist/hooks/solution-injector.d.ts +23 -0
- package/dist/hooks/solution-injector.js +102 -101
- package/dist/hooks/stop-guard.d.ts +11 -1
- package/dist/hooks/stop-guard.js +28 -11
- package/dist/hooks/subagent-stop-guard.js +2 -1
- package/dist/hooks/subagent-tracker.js +2 -1
- package/dist/host/capabilities-codex.js +1 -0
- package/dist/host/claude-shim.d.ts +24 -0
- package/dist/host/claude-shim.js +68 -0
- package/dist/host/codex-hook-shim.d.ts +3 -1
- package/dist/host/codex-hook-shim.js +7 -5
- package/dist/host/codex-notify.js +1 -1
- package/dist/host/codex-rules-context.d.ts +6 -4
- package/dist/host/codex-rules-context.js +11 -24
- package/dist/host/exec-host.d.ts +5 -1
- package/dist/host/exec-host.js +15 -4
- package/dist/host/install-claude.d.ts +47 -14
- package/dist/host/install-claude.js +302 -155
- package/dist/host/install-codex.d.ts +20 -0
- package/dist/host/install-codex.js +32 -1
- package/dist/host/install-opencode.d.ts +3 -1
- package/dist/host/install-opencode.js +6 -3
- package/dist/host/install-orchestrator.js +14 -1
- package/dist/host/opencode/translate.d.ts +1 -1
- package/dist/host/opencode/translate.js +5 -3
- package/dist/host/projection.d.ts +9 -1
- package/dist/host/projection.js +19 -2
- package/dist/mcp/server.js +5 -0
- package/dist/mcp/solution-reader.d.ts +5 -5
- package/dist/mcp/solution-reader.js +13 -35
- package/dist/mcp/tools.js +18 -1
- package/dist/renderer/inspect-renderer.js +4 -2
- package/dist/renderer/render-report.d.ts +22 -0
- package/dist/renderer/render-report.js +29 -0
- package/dist/renderer/rule-renderer.d.ts +28 -2
- package/dist/renderer/rule-renderer.js +91 -76
- package/dist/store/evidence-store.js +34 -6
- package/dist/store/rule-lifecycle.d.ts +3 -1
- package/dist/store/rule-lifecycle.js +10 -0
- package/dist/store/rule-scope.d.ts +7 -0
- package/dist/store/rule-scope.js +54 -0
- package/dist/store/rule-store.d.ts +29 -3
- package/dist/store/rule-store.js +110 -26
- package/dist/store/types.d.ts +22 -2
- package/dist/way/cli.d.ts +1 -0
- package/dist/way/cli.js +313 -0
- package/dist/way/compile.d.ts +22 -0
- package/dist/way/compile.js +408 -0
- package/dist/way/conflict.d.ts +2 -0
- package/dist/way/conflict.js +18 -0
- package/dist/way/draft.d.ts +43 -0
- package/dist/way/draft.js +335 -0
- package/dist/way/extract.d.ts +17 -0
- package/dist/way/extract.js +172 -0
- package/dist/way/io.d.ts +79 -0
- package/dist/way/io.js +425 -0
- package/dist/way/similar.d.ts +2 -0
- package/dist/way/similar.js +30 -0
- package/dist/way/types.d.ts +98 -0
- package/dist/way/types.js +2 -0
- package/package.json +1 -1
- package/plugin.json +1 -1
- package/scripts/postinstall.js +76 -899
- package/dist/core/health-cli.d.ts +0 -25
- package/dist/core/health-cli.js +0 -90
- package/dist/host/parity-harness.d.ts +0 -70
- 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
|
-
|
|
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
|
-
//
|
|
110
|
-
|
|
111
|
-
|
|
112
|
-
|
|
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
|
-
|
|
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
|
-
|
|
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
|
-
|
|
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 [{
|
|
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 =
|
|
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
|
-
|
|
406
|
-
|
|
407
|
-
|
|
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
|
-
|
|
430
|
-
|
|
431
|
-
|
|
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,66 @@ async function main() {
|
|
|
479
542
|
}
|
|
480
543
|
}
|
|
481
544
|
catch { /* fail-open */ }
|
|
482
|
-
|
|
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
|
+
console.log(denyOrObserve('pre-tool-use', `[Forgen] 비밀 파일/키가 커밋 대상에 포함되어 차단했습니다:\n${lines}\n.gitignore 에 추가하거나 git reset 으로 빼고, 키가 이미 노출됐다면 폐기·재발급하세요.`));
|
|
564
|
+
return;
|
|
565
|
+
}
|
|
566
|
+
}
|
|
567
|
+
}
|
|
568
|
+
catch { /* fail-open */ }
|
|
569
|
+
}
|
|
570
|
+
const check = checkDangerousCommand(toolName, toolInput, hookCwd);
|
|
571
|
+
const bashCmd = typeof toolInput.command === 'string' ? String(toolInput.command) : '';
|
|
483
572
|
if (check.action === 'block') {
|
|
573
|
+
if (check.ruleId) {
|
|
574
|
+
try {
|
|
575
|
+
const { recordViolation } = await import('../engine/lifecycle/signals.js');
|
|
576
|
+
recordViolation({ rule_id: check.ruleId, session_id: sessionId, source: 'pre-tool-guard', kind: 'deny', message_preview: bashCmd.slice(0, 120), target_kind: 'command' });
|
|
577
|
+
}
|
|
578
|
+
catch { /* fail-open */ }
|
|
579
|
+
}
|
|
484
580
|
console.log(denyOrObserve('pre-tool-use', `[Forgen] Dangerous command blocked: ${check.description}\nCommand: ${check.command}`));
|
|
485
581
|
return;
|
|
486
582
|
}
|
|
583
|
+
if (check.action === 'ask') {
|
|
584
|
+
if (process.env.FORGEN_USER_CONFIRMED === '1') {
|
|
585
|
+
try {
|
|
586
|
+
const { recordViolation } = await import('../engine/lifecycle/signals.js');
|
|
587
|
+
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)}` });
|
|
588
|
+
}
|
|
589
|
+
catch { /* fail-open */ }
|
|
590
|
+
}
|
|
591
|
+
else {
|
|
592
|
+
console.log(ask(`${advisories.length ? `${advisories.join('\n')}\n` : ''}[Forgen] 사용자 확인 필요 — ${check.description}\n규칙: 확인 없는 재귀 삭제 금지 (임시 작업 폴더 /tmp/claude-* 는 면제).\nCommand: ${check.command}\n${ASK_NONINTERACTIVE_HINT}`));
|
|
593
|
+
return;
|
|
594
|
+
}
|
|
595
|
+
}
|
|
487
596
|
const withAdvisories = (body) => (advisories.length ? `${advisories.map((x) => `<compound-tool-warning>\n${x}\n</compound-tool-warning>`).join('\n')}${body ? `\n${body}` : ''}` : body);
|
|
488
597
|
if (check.action === 'warn') {
|
|
489
598
|
console.log(approveWithWarning(withAdvisories(`<compound-tool-warning>\n[Forgen] ⚠ Dangerous command detected: ${check.description}\nProceed with caution.\n</compound-tool-warning>`)));
|
|
490
599
|
return;
|
|
491
600
|
}
|
|
601
|
+
if (nested) {
|
|
602
|
+
console.log(approve());
|
|
603
|
+
return;
|
|
604
|
+
}
|
|
492
605
|
// Output size guard: warn when Grep is used without head_limit
|
|
493
606
|
if (toolName === 'Grep' && !toolInput?.head_limit) {
|
|
494
607
|
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 +620,7 @@ async function main() {
|
|
|
507
620
|
// 그래서 "리마인더를 보여줄 호출이 아닌" 90%에서도 디렉터리 스캔이 발생.
|
|
508
621
|
// 이제 shouldShowReminderIO를 먼저 체크해 표시 회차일 때만 스캔한다.
|
|
509
622
|
if (shouldShowReminderIO()) {
|
|
510
|
-
const reminders = getActiveReminders();
|
|
623
|
+
const reminders = getActiveReminders(sessionId);
|
|
511
624
|
if (reminders.length > 0) {
|
|
512
625
|
console.log(approveWithWarning(withAdvisories(`<compound-reminder>\n${reminders.join('\n')}\n</compound-reminder>`)));
|
|
513
626
|
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
|
-
|
|
72
|
-
|
|
73
|
-
|
|
74
|
-
|
|
75
|
-
|
|
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,
|
|
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
|
-
|
|
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
|
-
|
|
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
|
-
|
|
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
|
-
/**
|
|
20
|
-
export declare const MIN_USER_MESSAGES =
|
|
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
|
-
/**
|
|
29
|
-
export const MIN_USER_MESSAGES =
|
|
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(
|
|
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(
|
|
116
|
+
main().catch((e) => {
|
|
117
|
+
console.log(failOpenWithTracking('session-end', e));
|
|
112
118
|
});
|
|
113
119
|
}
|