@wooojin/forgen 0.2.0 → 0.2.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.
- package/CHANGELOG.md +28 -0
- package/README.ja.md +79 -14
- package/README.ko.md +89 -14
- package/README.md +77 -14
- package/README.zh.md +79 -14
- package/commands/deep-interview.md +171 -0
- package/commands/specify.md +128 -0
- package/dist/cli.js +9 -0
- package/dist/core/dashboard.d.ts +91 -0
- package/dist/core/dashboard.js +385 -0
- package/dist/core/doctor.js +151 -21
- package/dist/core/drift-score.d.ts +49 -0
- package/dist/core/drift-score.js +87 -0
- package/dist/core/mcp-config.d.ts +2 -0
- package/dist/core/mcp-config.js +6 -1
- package/dist/core/paths.d.ts +1 -1
- package/dist/core/paths.js +1 -1
- package/dist/engine/compound-export.d.ts +41 -0
- package/dist/engine/compound-export.js +169 -0
- package/dist/engine/compound-loop.js +18 -0
- package/dist/engine/solution-matcher.d.ts +23 -0
- package/dist/engine/solution-matcher.js +124 -11
- package/dist/hooks/context-guard.d.ts +10 -0
- package/dist/hooks/context-guard.js +104 -58
- package/dist/hooks/db-guard.js +2 -2
- package/dist/hooks/hook-config.d.ts +27 -1
- package/dist/hooks/hook-config.js +72 -12
- package/dist/hooks/intent-classifier.d.ts +0 -2
- package/dist/hooks/intent-classifier.js +32 -18
- package/dist/hooks/keyword-detector.js +117 -111
- package/dist/hooks/notepad-injector.js +2 -2
- package/dist/hooks/permission-handler.js +2 -2
- package/dist/hooks/post-tool-failure.js +12 -6
- package/dist/hooks/post-tool-handlers.d.ts +1 -1
- package/dist/hooks/post-tool-handlers.js +14 -11
- package/dist/hooks/post-tool-use.d.ts +11 -0
- package/dist/hooks/post-tool-use.js +184 -71
- package/dist/hooks/pre-compact.d.ts +11 -1
- package/dist/hooks/pre-compact.js +112 -37
- package/dist/hooks/pre-tool-use.js +86 -56
- package/dist/hooks/rate-limiter.js +3 -3
- package/dist/hooks/secret-filter.js +2 -2
- package/dist/hooks/session-recovery.js +256 -236
- package/dist/hooks/shared/hook-response.d.ts +4 -4
- package/dist/hooks/shared/hook-response.js +13 -24
- package/dist/hooks/shared/hook-timing.d.ts +15 -0
- package/dist/hooks/shared/hook-timing.js +64 -0
- package/dist/hooks/skill-injector.js +41 -12
- package/dist/hooks/slop-detector.js +3 -3
- package/dist/hooks/solution-injector.js +224 -197
- package/dist/hooks/subagent-tracker.js +2 -2
- package/dist/renderer/rule-renderer.js +9 -11
- package/package.json +1 -1
- package/skills/deep-interview/SKILL.md +166 -0
- package/skills/specify/SKILL.md +122 -0
|
@@ -16,14 +16,18 @@ import { createLogger } from '../core/logger.js';
|
|
|
16
16
|
import { readStdinJSON } from './shared/read-stdin.js';
|
|
17
17
|
import { atomicWriteJSON } from './shared/atomic-write.js';
|
|
18
18
|
import { loadHookConfig, isHookEnabled } from './hook-config.js';
|
|
19
|
-
import { approve, approveWithContext, approveWithWarning,
|
|
19
|
+
import { approve, approveWithContext, approveWithWarning, failOpenWithTracking } from './shared/hook-response.js';
|
|
20
20
|
import { HANDOFFS_DIR, STATE_DIR } from '../core/paths.js';
|
|
21
|
+
import { recordHookTiming } from './shared/hook-timing.js';
|
|
21
22
|
const log = createLogger('context-guard');
|
|
22
23
|
const CONTEXT_STATE_PATH = path.join(STATE_DIR, 'context-guard.json');
|
|
23
24
|
// 경고 임계값: 프롬프트 50회 또는 총 문자 수 200K 이상
|
|
24
25
|
const PROMPT_WARNING_THRESHOLD = 50;
|
|
25
26
|
const CHARS_WARNING_THRESHOLD = 200_000;
|
|
26
27
|
const WARNING_COOLDOWN_MS = 10 * 60 * 1000; // 10분 쿨다운
|
|
28
|
+
// Auto-compact 임계값: 추적된 문자 120K ≈ 실제 context ~20%
|
|
29
|
+
const AUTO_COMPACT_CHARS_THRESHOLD = 120_000;
|
|
30
|
+
const AUTO_COMPACT_COOLDOWN_MS = 5 * 60 * 1000; // 5분 쿨다운
|
|
27
31
|
/** 경고 표시 여부 판정 (순수 함수) */
|
|
28
32
|
export function shouldWarn(contextPercent, thresholds = {}) {
|
|
29
33
|
const promptThreshold = thresholds.promptThreshold ?? PROMPT_WARNING_THRESHOLD;
|
|
@@ -33,6 +37,21 @@ export function shouldWarn(contextPercent, thresholds = {}) {
|
|
|
33
37
|
return ((contextPercent.promptCount >= promptThreshold || contextPercent.totalChars >= charsThreshold) &&
|
|
34
38
|
(now - contextPercent.lastWarningAt > cooldownMs));
|
|
35
39
|
}
|
|
40
|
+
/** auto-compact 트리거 여부 판정 (순수 함수) */
|
|
41
|
+
export function shouldAutoCompact(state, thresholds = {}) {
|
|
42
|
+
const charsThreshold = thresholds.charsThreshold ?? AUTO_COMPACT_CHARS_THRESHOLD;
|
|
43
|
+
const cooldownMs = thresholds.cooldownMs ?? AUTO_COMPACT_COOLDOWN_MS;
|
|
44
|
+
const now = Date.now();
|
|
45
|
+
return state.totalChars >= charsThreshold && (now - state.lastAutoCompactAt > cooldownMs);
|
|
46
|
+
}
|
|
47
|
+
/** auto-compact 지시 메시지 생성 (순수 함수) */
|
|
48
|
+
export function buildAutoCompactMessage(totalChars) {
|
|
49
|
+
return `<forgen-auto-compact>
|
|
50
|
+
[Forgen] Context 사용량이 ${Math.round(totalChars / 1000)}K 문자에 도달했습니다 (추정 ~20%+).
|
|
51
|
+
지금 즉시 /compact를 실행하여 컨텍스트를 압축하세요. 이 지시는 자동으로 생성되었습니다.
|
|
52
|
+
현재 작업을 마무리하지 말고, 다음 응답에서 바로 compact를 실행하세요.
|
|
53
|
+
</forgen-auto-compact>`;
|
|
54
|
+
}
|
|
36
55
|
/** 경고 메시지 생성 (순수 함수) */
|
|
37
56
|
export function buildContextWarningMessage(promptCount, totalChars) {
|
|
38
57
|
return `<compound-context-warning>\n[Forgen] Context limit approaching: ${promptCount} prompts, ${Math.round(totalChars / 1000)}K characters.\nIf you have important progress, save it now:\n- Use cancelforgen to reset mode state and start a new session\n- Or continue current work (auto compaction may occur)\n</compound-context-warning>`;
|
|
@@ -48,77 +67,104 @@ function loadContextState(sessionId) {
|
|
|
48
67
|
catch (e) {
|
|
49
68
|
log.debug('context state 파일 읽기/파싱 실패', e);
|
|
50
69
|
}
|
|
51
|
-
return { promptCount: 0, totalChars: 0, lastWarningAt: 0, sessionId };
|
|
70
|
+
return { promptCount: 0, totalChars: 0, lastWarningAt: 0, lastAutoCompactAt: 0, sessionId };
|
|
52
71
|
}
|
|
53
72
|
function saveContextState(state) {
|
|
54
73
|
atomicWriteJSON(CONTEXT_STATE_PATH, state);
|
|
55
74
|
}
|
|
56
75
|
export async function main() {
|
|
57
|
-
const
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
|
|
68
|
-
|
|
69
|
-
|
|
70
|
-
|
|
71
|
-
|
|
72
|
-
|
|
73
|
-
|
|
74
|
-
|
|
75
|
-
|
|
76
|
-
|
|
77
|
-
|
|
78
|
-
|
|
79
|
-
|
|
80
|
-
|
|
81
|
-
|
|
76
|
+
const _hookStart = Date.now();
|
|
77
|
+
let _hookEvent = 'UserPromptSubmit';
|
|
78
|
+
try {
|
|
79
|
+
const input = await readStdinJSON();
|
|
80
|
+
if (!isHookEnabled('context-guard')) {
|
|
81
|
+
console.log(approve());
|
|
82
|
+
return;
|
|
83
|
+
}
|
|
84
|
+
if (!input) {
|
|
85
|
+
console.log(approve());
|
|
86
|
+
return;
|
|
87
|
+
}
|
|
88
|
+
const sessionId = input.session_id ?? 'default';
|
|
89
|
+
// Stop 훅: stop_hook_type이 있으면 처리
|
|
90
|
+
if (input.stop_hook_type) {
|
|
91
|
+
_hookEvent = 'Stop';
|
|
92
|
+
// 에러가 포함된 경우: context limit 감지
|
|
93
|
+
if (input.error) {
|
|
94
|
+
const errorMsg = input.error;
|
|
95
|
+
if (/context.*limit|token.*limit|conversation.*too.*long/i.test(errorMsg)) {
|
|
96
|
+
saveHandoff(sessionId, 'context-limit', errorMsg);
|
|
97
|
+
try {
|
|
98
|
+
const resumePath = path.join(STATE_DIR, 'pending-resume.json');
|
|
99
|
+
fs.writeFileSync(resumePath, JSON.stringify({
|
|
100
|
+
reason: 'token-limit',
|
|
101
|
+
sessionId,
|
|
102
|
+
savedAt: new Date().toISOString(),
|
|
103
|
+
cwd: process.env.FORGEN_CWD ?? process.env.COMPOUND_CWD ?? process.cwd(),
|
|
104
|
+
}, null, 2));
|
|
105
|
+
}
|
|
106
|
+
catch { /* fail-open */ }
|
|
107
|
+
console.log(approveWithWarning(`[Forgen] Context limit reached. Current state has been saved to ~/.forgen/handoffs/.\nThe previous work will be automatically recovered in the next session.`));
|
|
108
|
+
return;
|
|
82
109
|
}
|
|
83
|
-
catch { /* fail-open */ }
|
|
84
|
-
console.log(approveWithWarning(`[Forgen] Context limit reached. Current state has been saved to ~/.forgen/handoffs/.\nThe previous work will be automatically recovered in the next session.`));
|
|
85
|
-
return;
|
|
86
110
|
}
|
|
111
|
+
// 정상 종료 시: 의미 있는 세션이었으면 compound 안내/자동 트리거
|
|
112
|
+
if (input.stop_hook_type === 'user' || input.stop_hook_type === 'end_turn') {
|
|
113
|
+
const state = loadContextState(sessionId);
|
|
114
|
+
if (state.promptCount >= 20) {
|
|
115
|
+
// 20+ prompts: auto-trigger compound by writing marker
|
|
116
|
+
try {
|
|
117
|
+
fs.mkdirSync(STATE_DIR, { recursive: true });
|
|
118
|
+
const marker = { reason: 'session-end', promptCount: state.promptCount, detectedAt: new Date().toISOString() };
|
|
119
|
+
fs.writeFileSync(path.join(STATE_DIR, 'pending-compound.json'), JSON.stringify(marker));
|
|
120
|
+
}
|
|
121
|
+
catch { /* fail-open: marker write failure is non-critical */ }
|
|
122
|
+
console.log(approveWithWarning(`[Forgen] Session with ${state.promptCount} prompts ended. Compound loop will auto-trigger on next session start.`));
|
|
123
|
+
return;
|
|
124
|
+
}
|
|
125
|
+
if (state.promptCount >= 10) {
|
|
126
|
+
// 10-19 prompts: suggest /compound manually
|
|
127
|
+
console.log(approveWithWarning(`[Forgen] 이 세션에서 ${state.promptCount}개의 프롬프트를 처리했습니다. /compound 를 실행하면 이 세션의 학습 내용을 축적할 수 있습니다.`));
|
|
128
|
+
return;
|
|
129
|
+
}
|
|
130
|
+
}
|
|
131
|
+
console.log(approve());
|
|
132
|
+
return;
|
|
133
|
+
}
|
|
134
|
+
// error만 있는 경우 (stop_hook_type 없이)
|
|
135
|
+
if (input.error) {
|
|
136
|
+
console.log(approve());
|
|
137
|
+
return;
|
|
87
138
|
}
|
|
88
|
-
//
|
|
89
|
-
if (input.
|
|
139
|
+
// UserPromptSubmit 훅: 대화 길이 추적
|
|
140
|
+
if (input.prompt) {
|
|
141
|
+
const config = loadHookConfig('context-guard');
|
|
142
|
+
// maxTokens가 설정되어 있으면 chars threshold로 사용 (토큰 ≈ 4자 기준 환산)
|
|
143
|
+
const charsThreshold = typeof config?.maxTokens === 'number' ? config.maxTokens * 4 : undefined;
|
|
90
144
|
const state = loadContextState(sessionId);
|
|
91
|
-
|
|
92
|
-
|
|
93
|
-
|
|
145
|
+
state.promptCount++;
|
|
146
|
+
state.totalChars += input.prompt.length;
|
|
147
|
+
// auto-compact: 추적 문자 120K 이상이면 compact 지시 주입
|
|
148
|
+
const autoCompactThreshold = typeof config?.autoCompactChars === 'number' ? config.autoCompactChars : undefined;
|
|
149
|
+
if (shouldAutoCompact(state, autoCompactThreshold !== undefined ? { charsThreshold: autoCompactThreshold } : {})) {
|
|
150
|
+
state.lastAutoCompactAt = Date.now();
|
|
151
|
+
saveContextState(state);
|
|
152
|
+
console.log(approveWithContext(buildAutoCompactMessage(state.totalChars), 'UserPromptSubmit'));
|
|
94
153
|
return;
|
|
95
154
|
}
|
|
155
|
+
if (shouldWarn(state, charsThreshold !== undefined ? { charsThreshold } : {})) {
|
|
156
|
+
state.lastWarningAt = Date.now();
|
|
157
|
+
saveContextState(state);
|
|
158
|
+
console.log(approveWithContext(buildContextWarningMessage(state.promptCount, state.totalChars), 'UserPromptSubmit'));
|
|
159
|
+
return;
|
|
160
|
+
}
|
|
161
|
+
saveContextState(state);
|
|
96
162
|
}
|
|
97
163
|
console.log(approve());
|
|
98
|
-
return;
|
|
99
|
-
}
|
|
100
|
-
// error만 있는 경우 (stop_hook_type 없이)
|
|
101
|
-
if (input.error) {
|
|
102
|
-
console.log(approve());
|
|
103
|
-
return;
|
|
104
164
|
}
|
|
105
|
-
|
|
106
|
-
|
|
107
|
-
const config = loadHookConfig('context-guard');
|
|
108
|
-
// maxTokens가 설정되어 있으면 chars threshold로 사용 (토큰 ≈ 4자 기준 환산)
|
|
109
|
-
const charsThreshold = typeof config?.maxTokens === 'number' ? config.maxTokens * 4 : undefined;
|
|
110
|
-
const state = loadContextState(sessionId);
|
|
111
|
-
state.promptCount++;
|
|
112
|
-
state.totalChars += input.prompt.length;
|
|
113
|
-
if (shouldWarn(state, charsThreshold !== undefined ? { charsThreshold } : {})) {
|
|
114
|
-
state.lastWarningAt = Date.now();
|
|
115
|
-
saveContextState(state);
|
|
116
|
-
console.log(approveWithContext(buildContextWarningMessage(state.promptCount, state.totalChars), 'UserPromptSubmit'));
|
|
117
|
-
return;
|
|
118
|
-
}
|
|
119
|
-
saveContextState(state);
|
|
165
|
+
finally {
|
|
166
|
+
recordHookTiming('context-guard', Date.now() - _hookStart, _hookEvent);
|
|
120
167
|
}
|
|
121
|
-
console.log(approve());
|
|
122
168
|
}
|
|
123
169
|
function saveHandoff(sessionId, reason, detail) {
|
|
124
170
|
fs.mkdirSync(HANDOFFS_DIR, { recursive: true });
|
|
@@ -161,6 +207,6 @@ function saveHandoff(sessionId, reason, detail) {
|
|
|
161
207
|
if (process.argv[1] && fs.realpathSync(path.resolve(process.argv[1])) === fileURLToPath(import.meta.url)) {
|
|
162
208
|
main().catch((e) => {
|
|
163
209
|
process.stderr.write(`[ch-hook] ${e instanceof Error ? e.message : String(e)}\n`);
|
|
164
|
-
console.log(
|
|
210
|
+
console.log(failOpenWithTracking('context-guard'));
|
|
165
211
|
});
|
|
166
212
|
}
|
package/dist/hooks/db-guard.js
CHANGED
|
@@ -9,7 +9,7 @@ import * as path from 'node:path';
|
|
|
9
9
|
import { readStdinJSON } from './shared/read-stdin.js';
|
|
10
10
|
import { atomicWriteJSON } from './shared/atomic-write.js';
|
|
11
11
|
import { isHookEnabled } from './hook-config.js';
|
|
12
|
-
import { approve, approveWithWarning, deny,
|
|
12
|
+
import { approve, approveWithWarning, deny, failOpenWithTracking } from './shared/hook-response.js';
|
|
13
13
|
import { STATE_DIR } from '../core/paths.js';
|
|
14
14
|
const FAIL_COUNTER_PATH = path.join(STATE_DIR, 'db-guard-fail-counter.json');
|
|
15
15
|
const FAIL_CLOSE_THRESHOLD = 3;
|
|
@@ -101,5 +101,5 @@ async function main() {
|
|
|
101
101
|
}
|
|
102
102
|
main().catch((e) => {
|
|
103
103
|
process.stderr.write(`[ch-hook] DB Guard error: ${e instanceof Error ? e.message : String(e)}\n`);
|
|
104
|
-
console.log(
|
|
104
|
+
console.log(failOpenWithTracking('db-guard'));
|
|
105
105
|
});
|
|
@@ -1,9 +1,17 @@
|
|
|
1
1
|
/**
|
|
2
2
|
* Forgen — Hook Config Loader
|
|
3
3
|
*
|
|
4
|
-
*
|
|
4
|
+
* hook-config.json 에서 훅별 설정을 읽어 반환합니다.
|
|
5
5
|
* 파일이 없거나 읽기에 실패하면 null 을 반환합니다 (failure-tolerant).
|
|
6
6
|
*
|
|
7
|
+
* 설정 로딩 우선순위:
|
|
8
|
+
* 1. 프로젝트 레벨: {cwd}/.forgen/hook-config.json
|
|
9
|
+
* 2. 글로벌 레벨: FORGEN_HOME/hook-config.json (~/.forgen/hook-config.json)
|
|
10
|
+
* 프로젝트 설정은 글로벌 설정과 머지됩니다 (훅 단위 오버라이드).
|
|
11
|
+
* 프로젝트 설정이 없으면 글로벌 설정만 사용 (하위호환).
|
|
12
|
+
*
|
|
13
|
+
* cwd 결정: process.env.FORGEN_CWD ?? process.env.COMPOUND_CWD ?? process.cwd()
|
|
14
|
+
*
|
|
7
15
|
* 설정 형식 (hook-config.json):
|
|
8
16
|
* {
|
|
9
17
|
* "tiers": { "compound-core": { "enabled": true }, "safety": { "enabled": true }, "workflow": { "enabled": true } },
|
|
@@ -15,6 +23,24 @@
|
|
|
15
23
|
* - compound-core 티어는 tiers 설정으로 비활성화 불가 (복리화 보호)
|
|
16
24
|
* - 개별 hooks.hookName.enabled: false 로만 비활성화 가능
|
|
17
25
|
*/
|
|
26
|
+
/** 훅 설정 파일의 전체 구조 타입 */
|
|
27
|
+
export type HookConfig = Record<string, unknown>;
|
|
28
|
+
/**
|
|
29
|
+
* 프로젝트의 작업 디렉토리를 결정합니다.
|
|
30
|
+
* FORGEN_CWD → COMPOUND_CWD → process.cwd() 순서.
|
|
31
|
+
*/
|
|
32
|
+
export declare function resolveProjectCwd(): string;
|
|
33
|
+
/**
|
|
34
|
+
* 글로벌 설정과 프로젝트 설정을 머지합니다.
|
|
35
|
+
* 프로젝트 설정이 글로벌 설정을 훅 단위로 오버라이드합니다.
|
|
36
|
+
*
|
|
37
|
+
* 머지 규칙:
|
|
38
|
+
* - tiers: 프로젝트가 글로벌을 훅 단위로 오버라이드 (shallow merge)
|
|
39
|
+
* - hooks: 프로젝트가 글로벌을 훅 단위로 오버라이드 (shallow merge)
|
|
40
|
+
* - 최상위 레거시 키: 프로젝트가 글로벌을 키 단위로 오버라이드
|
|
41
|
+
* - 프로젝트에 없는 키는 글로벌에서 상속
|
|
42
|
+
*/
|
|
43
|
+
export declare function mergeHookConfigs(global: HookConfig, project: HookConfig): HookConfig;
|
|
18
44
|
/** 특정 훅의 설정을 반환합니다. 실패 시 null 반환. */
|
|
19
45
|
export declare function loadHookConfig(hookName: string): Record<string, unknown> | null;
|
|
20
46
|
/**
|
|
@@ -1,9 +1,17 @@
|
|
|
1
1
|
/**
|
|
2
2
|
* Forgen — Hook Config Loader
|
|
3
3
|
*
|
|
4
|
-
*
|
|
4
|
+
* hook-config.json 에서 훅별 설정을 읽어 반환합니다.
|
|
5
5
|
* 파일이 없거나 읽기에 실패하면 null 을 반환합니다 (failure-tolerant).
|
|
6
6
|
*
|
|
7
|
+
* 설정 로딩 우선순위:
|
|
8
|
+
* 1. 프로젝트 레벨: {cwd}/.forgen/hook-config.json
|
|
9
|
+
* 2. 글로벌 레벨: FORGEN_HOME/hook-config.json (~/.forgen/hook-config.json)
|
|
10
|
+
* 프로젝트 설정은 글로벌 설정과 머지됩니다 (훅 단위 오버라이드).
|
|
11
|
+
* 프로젝트 설정이 없으면 글로벌 설정만 사용 (하위호환).
|
|
12
|
+
*
|
|
13
|
+
* cwd 결정: process.env.FORGEN_CWD ?? process.env.COMPOUND_CWD ?? process.cwd()
|
|
14
|
+
*
|
|
7
15
|
* 설정 형식 (hook-config.json):
|
|
8
16
|
* {
|
|
9
17
|
* "tiers": { "compound-core": { "enabled": true }, "safety": { "enabled": true }, "workflow": { "enabled": true } },
|
|
@@ -19,30 +27,82 @@ import * as fs from 'node:fs';
|
|
|
19
27
|
import * as path from 'node:path';
|
|
20
28
|
import { HOOK_REGISTRY } from './hook-registry.js';
|
|
21
29
|
import { FORGEN_HOME } from '../core/paths.js';
|
|
22
|
-
const
|
|
30
|
+
const GLOBAL_CONFIG_PATH = path.join(FORGEN_HOME, 'hook-config.json');
|
|
23
31
|
/**
|
|
24
32
|
* 훅 → 티어 매핑 (hook-registry.ts에서 자동 파생).
|
|
25
33
|
* 이중 구현 방지: HOOK_REGISTRY가 단일 소스 오브 트루스.
|
|
26
34
|
*/
|
|
27
35
|
const HOOK_TIER_MAP = Object.fromEntries(HOOK_REGISTRY.map(h => [h.name, h.tier]));
|
|
36
|
+
/**
|
|
37
|
+
* 프로젝트의 작업 디렉토리를 결정합니다.
|
|
38
|
+
* FORGEN_CWD → COMPOUND_CWD → process.cwd() 순서.
|
|
39
|
+
*/
|
|
40
|
+
export function resolveProjectCwd() {
|
|
41
|
+
return process.env.FORGEN_CWD ?? process.env.COMPOUND_CWD ?? process.cwd();
|
|
42
|
+
}
|
|
43
|
+
/** JSON 파일을 파싱하여 반환. 파일 없음 또는 파싱 실패 시 null. */
|
|
44
|
+
function loadJsonFile(filePath) {
|
|
45
|
+
try {
|
|
46
|
+
if (!fs.existsSync(filePath))
|
|
47
|
+
return null;
|
|
48
|
+
return JSON.parse(fs.readFileSync(filePath, 'utf-8'));
|
|
49
|
+
}
|
|
50
|
+
catch {
|
|
51
|
+
return null;
|
|
52
|
+
}
|
|
53
|
+
}
|
|
54
|
+
/**
|
|
55
|
+
* 글로벌 설정과 프로젝트 설정을 머지합니다.
|
|
56
|
+
* 프로젝트 설정이 글로벌 설정을 훅 단위로 오버라이드합니다.
|
|
57
|
+
*
|
|
58
|
+
* 머지 규칙:
|
|
59
|
+
* - tiers: 프로젝트가 글로벌을 훅 단위로 오버라이드 (shallow merge)
|
|
60
|
+
* - hooks: 프로젝트가 글로벌을 훅 단위로 오버라이드 (shallow merge)
|
|
61
|
+
* - 최상위 레거시 키: 프로젝트가 글로벌을 키 단위로 오버라이드
|
|
62
|
+
* - 프로젝트에 없는 키는 글로벌에서 상속
|
|
63
|
+
*/
|
|
64
|
+
export function mergeHookConfigs(global, project) {
|
|
65
|
+
const merged = { ...global };
|
|
66
|
+
// tiers 머지 (shallow per-tier)
|
|
67
|
+
const globalTiers = global.tiers;
|
|
68
|
+
const projectTiers = project.tiers;
|
|
69
|
+
if (globalTiers || projectTiers) {
|
|
70
|
+
merged.tiers = { ...globalTiers, ...projectTiers };
|
|
71
|
+
}
|
|
72
|
+
// hooks 머지 (shallow per-hook)
|
|
73
|
+
const globalHooks = global.hooks;
|
|
74
|
+
const projectHooks = project.hooks;
|
|
75
|
+
if (globalHooks || projectHooks) {
|
|
76
|
+
merged.hooks = { ...globalHooks, ...projectHooks };
|
|
77
|
+
}
|
|
78
|
+
// 나머지 최상위 키: 프로젝트가 글로벌을 오버라이드
|
|
79
|
+
for (const key of Object.keys(project)) {
|
|
80
|
+
if (key === 'tiers' || key === 'hooks')
|
|
81
|
+
continue;
|
|
82
|
+
merged[key] = project[key];
|
|
83
|
+
}
|
|
84
|
+
return merged;
|
|
85
|
+
}
|
|
28
86
|
/** 프로세스 내 설정 캐시 (각 훅은 별도 프로세스이므로 수명 = 1회 실행) */
|
|
29
87
|
let _configCache;
|
|
30
|
-
/** 전체 설정 파일을
|
|
88
|
+
/** 전체 설정 파일을 파싱합니다 (글로벌 + 프로젝트 머지). 실패 시 null. 프로세스 내 캐싱. */
|
|
31
89
|
function loadFullConfig() {
|
|
32
90
|
if (_configCache !== undefined)
|
|
33
91
|
return _configCache;
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
}
|
|
39
|
-
_configCache = JSON.parse(fs.readFileSync(HOOK_CONFIG_PATH, 'utf-8'));
|
|
40
|
-
return _configCache;
|
|
41
|
-
}
|
|
42
|
-
catch {
|
|
92
|
+
const globalConfig = loadJsonFile(GLOBAL_CONFIG_PATH);
|
|
93
|
+
const projectConfigPath = path.join(resolveProjectCwd(), '.forgen', 'hook-config.json');
|
|
94
|
+
const projectConfig = loadJsonFile(projectConfigPath);
|
|
95
|
+
if (!globalConfig && !projectConfig) {
|
|
43
96
|
_configCache = null;
|
|
44
97
|
return null;
|
|
45
98
|
}
|
|
99
|
+
if (globalConfig && projectConfig) {
|
|
100
|
+
_configCache = mergeHookConfigs(globalConfig, projectConfig);
|
|
101
|
+
}
|
|
102
|
+
else {
|
|
103
|
+
_configCache = globalConfig ?? projectConfig ?? null;
|
|
104
|
+
}
|
|
105
|
+
return _configCache;
|
|
46
106
|
}
|
|
47
107
|
/** 특정 훅의 설정을 반환합니다. 실패 시 null 반환. */
|
|
48
108
|
export function loadHookConfig(hookName) {
|
|
@@ -10,5 +10,3 @@
|
|
|
10
10
|
*/
|
|
11
11
|
export type Intent = 'implement' | 'debug' | 'refactor' | 'explain' | 'review' | 'explore' | 'design' | 'general';
|
|
12
12
|
export declare function classifyIntent(prompt: string): Intent;
|
|
13
|
-
/** 프롬프트에 매칭되는 모든 의도를 반환. 없으면 ['general']. */
|
|
14
|
-
export declare function classifyAllIntents(prompt: string): Intent[];
|
|
@@ -10,9 +10,9 @@
|
|
|
10
10
|
*/
|
|
11
11
|
import { readStdinJSON } from './shared/read-stdin.js';
|
|
12
12
|
import { isHookEnabled } from './hook-config.js';
|
|
13
|
-
import { approve, approveWithContext,
|
|
13
|
+
import { approve, approveWithContext, failOpenWithTracking } from './shared/hook-response.js';
|
|
14
14
|
const INTENT_RULES = [
|
|
15
|
-
{ intent: 'implement', pattern: /(?:만들어|추가해|구현해|생성해|작성해|넣어|create|add|implement|build|write|make)
|
|
15
|
+
{ intent: 'implement', pattern: /(?:만들어|추가해|구현해|생성해|작성해|넣어|create|add|implement|build|write|make)(?:\b|(?=[가-힣\s]|$))/i },
|
|
16
16
|
{ intent: 'debug', pattern: /(?:에러|버그|안돼|안\s*되|안\s*됨|왜|고쳐|수정해|fix|bug|error|debug|문제|실패|fail|crash|broken)/i },
|
|
17
17
|
{ intent: 'refactor', pattern: /(?:리팩토링|리팩터|정리|개선|refactor|clean\s*up|improve|optimize|최적화)/i },
|
|
18
18
|
{ intent: 'explain', pattern: /(?:설명|알려|뭐야|뭔가요|어떻게|explain|what\s+is|how\s+does|why\s+does|tell\s+me)/i },
|
|
@@ -30,6 +30,29 @@ const INTENT_HINTS = {
|
|
|
30
30
|
design: 'Design task. Specify trade-offs explicitly.',
|
|
31
31
|
general: 'General request.',
|
|
32
32
|
};
|
|
33
|
+
/** Intent-specific context rules injected via additionalContext */
|
|
34
|
+
const INTENT_CONTEXT = {
|
|
35
|
+
implement: `[quality-rules]
|
|
36
|
+
- Write tests for new logic (branch coverage 83%+)
|
|
37
|
+
- Build + lint + type-check must pass before completion
|
|
38
|
+
- Prefer small incremental changes (<200 lines)
|
|
39
|
+
- Interfaces and type contracts before implementation`,
|
|
40
|
+
review: `[review-rules]
|
|
41
|
+
- Report format: [SEVERITY] file:line — issue
|
|
42
|
+
- Check: logic errors, security (OWASP), performance, maintainability
|
|
43
|
+
- Verify edge cases and error handling at system boundaries
|
|
44
|
+
- No empty catch blocks, no eslint-disable without justification`,
|
|
45
|
+
debug: `[debug-rules]
|
|
46
|
+
- Reproduce the bug first, then isolate the root cause
|
|
47
|
+
- Write a failing test that captures the bug before fixing
|
|
48
|
+
- Check for regression: does the fix break anything else?
|
|
49
|
+
- Read error messages carefully — they usually point to the cause`,
|
|
50
|
+
refactor: `[refactor-rules]
|
|
51
|
+
- Ensure all tests pass before AND after refactoring
|
|
52
|
+
- Make one structural change at a time, verify between each
|
|
53
|
+
- Preserve external behavior — refactoring changes structure, not function
|
|
54
|
+
- Avoid mixing refactoring with feature changes in the same pass`,
|
|
55
|
+
};
|
|
33
56
|
export function classifyIntent(prompt) {
|
|
34
57
|
for (const rule of INTENT_RULES) {
|
|
35
58
|
if (rule.pattern.test(prompt)) {
|
|
@@ -38,16 +61,6 @@ export function classifyIntent(prompt) {
|
|
|
38
61
|
}
|
|
39
62
|
return 'general';
|
|
40
63
|
}
|
|
41
|
-
/** 프롬프트에 매칭되는 모든 의도를 반환. 없으면 ['general']. */
|
|
42
|
-
export function classifyAllIntents(prompt) {
|
|
43
|
-
const matches = [];
|
|
44
|
-
for (const rule of INTENT_RULES) {
|
|
45
|
-
if (rule.pattern.test(prompt)) {
|
|
46
|
-
matches.push(rule.intent);
|
|
47
|
-
}
|
|
48
|
-
}
|
|
49
|
-
return matches.length > 0 ? matches : ['general'];
|
|
50
|
-
}
|
|
51
64
|
async function main() {
|
|
52
65
|
const input = await readStdinJSON();
|
|
53
66
|
if (!isHookEnabled('intent-classifier')) {
|
|
@@ -58,16 +71,17 @@ async function main() {
|
|
|
58
71
|
console.log(approve());
|
|
59
72
|
return;
|
|
60
73
|
}
|
|
61
|
-
const
|
|
62
|
-
if (
|
|
74
|
+
const intent = classifyIntent(input.prompt);
|
|
75
|
+
if (intent === 'general') {
|
|
63
76
|
console.log(approve());
|
|
64
77
|
return;
|
|
65
78
|
}
|
|
66
|
-
const
|
|
67
|
-
const
|
|
68
|
-
|
|
79
|
+
const hint = INTENT_HINTS[intent];
|
|
80
|
+
const extra = INTENT_CONTEXT[intent] ?? '';
|
|
81
|
+
const context = extra ? `[intent: ${intent}] ${hint}\n${extra}` : `[intent: ${intent}] ${hint}`;
|
|
82
|
+
console.log(approveWithContext(context, 'UserPromptSubmit'));
|
|
69
83
|
}
|
|
70
84
|
main().catch((e) => {
|
|
71
85
|
process.stderr.write(`[ch-hook] ${e instanceof Error ? e.message : String(e)}\n`);
|
|
72
|
-
console.log(
|
|
86
|
+
console.log(failOpenWithTracking('intent-classifier'));
|
|
73
87
|
});
|