@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
|
@@ -9,7 +9,8 @@
|
|
|
9
9
|
import { readStdinJSON } from './shared/read-stdin.js';
|
|
10
10
|
import { createLogger } from '../core/logger.js';
|
|
11
11
|
import { isHookEnabled, loadHookConfig } from './hook-config.js';
|
|
12
|
-
import { approve,
|
|
12
|
+
import { approve, approveWithPostToolContext, failOpenWithTracking } from './shared/hook-response.js';
|
|
13
|
+
import { stringifyToolResponse } from './shared/tool-response.js';
|
|
13
14
|
const log = createLogger('slop-detector');
|
|
14
15
|
export const SLOP_PATTERNS = [
|
|
15
16
|
{ pattern: /\/\/\s*TODO:?\s*(implement|add|fix|handle)/i, message: 'Leftover TODO comment', severity: 'warn' },
|
|
@@ -54,7 +55,7 @@ async function main() {
|
|
|
54
55
|
console.log(approve());
|
|
55
56
|
return;
|
|
56
57
|
}
|
|
57
|
-
const toolResponse = data.tool_response ?? data.toolOutput ?? '';
|
|
58
|
+
const toolResponse = stringifyToolResponse(data.tool_response ?? data.toolOutput ?? '');
|
|
58
59
|
const toolInput = data.tool_input ?? data.toolInput ?? {};
|
|
59
60
|
// 검사 대상: 도구 입력의 content/new_string + 도구 응답
|
|
60
61
|
const textsToCheck = [];
|
|
@@ -76,7 +77,9 @@ async function main() {
|
|
|
76
77
|
const icon = d.severity === 'warn' ? '⚠' : 'ℹ';
|
|
77
78
|
return `- ${icon} ${d.message}`;
|
|
78
79
|
});
|
|
79
|
-
|
|
80
|
+
// D12-B: 사용자 화면(systemMessage)에만 가던 경고를 모델에도 전달한다(additionalContext).
|
|
81
|
+
const body = `<compound-slop-warning>\n[Forgen] AI slop detected in what you just wrote:\n${lines.join('\n')}\nClean these up before reporting the task complete.\n</compound-slop-warning>`;
|
|
82
|
+
console.log(approveWithPostToolContext(body, `[Forgen] AI slop detected: ${detected.map(d => d.message).join(', ')}`));
|
|
80
83
|
}
|
|
81
84
|
else {
|
|
82
85
|
console.log(approve());
|
|
@@ -7,6 +7,29 @@
|
|
|
7
7
|
*
|
|
8
8
|
* knowledge-comes-to-you 원칙: 필요한 지식은 찾아와야 한다
|
|
9
9
|
*/
|
|
10
|
+
/** 주입 게이트 탈락 사유 (D5). solution_events(matched).meta.gate 에 기록되고 status 가 분포를 보여 준다. */
|
|
11
|
+
export type GateReason = 'below-relevance' | 'too-few-tags' | 'experiment-cap' | 'prompt-cap' | 'already-injected';
|
|
12
|
+
export type GateVerdict = 'passed' | GateReason;
|
|
13
|
+
export interface GateCandidate {
|
|
14
|
+
name: string;
|
|
15
|
+
relevance: number;
|
|
16
|
+
contextBonus?: number;
|
|
17
|
+
matchedTags: string[];
|
|
18
|
+
matchedIdentifiers?: string[];
|
|
19
|
+
status: string;
|
|
20
|
+
}
|
|
21
|
+
/**
|
|
22
|
+
* 후보별 게이트 판정 — 주입 목록과 탈락 사유를 함께 돌려준다. 게이트 조건 자체는 그대로다(완화·강화 없음):
|
|
23
|
+
* 맥락 가산 제외 relevance 하한, identifier 1개 또는 태그 2개 이상, experiment 1개 제한, 프롬프트당 개수 제한.
|
|
24
|
+
*/
|
|
25
|
+
export declare function evaluateGate<T extends GateCandidate>(candidates: readonly T[], opts: {
|
|
26
|
+
minRelevanceFor: (name: string) => number;
|
|
27
|
+
injected: ReadonlySet<string>;
|
|
28
|
+
maxPerPrompt: number;
|
|
29
|
+
}): {
|
|
30
|
+
toInject: T[];
|
|
31
|
+
verdicts: Map<string, GateVerdict>;
|
|
32
|
+
};
|
|
10
33
|
/**
|
|
11
34
|
* Minimum relevance thresholds by fitness state (2026-04-21 gate sweep).
|
|
12
35
|
*
|
|
@@ -13,7 +13,7 @@ import { readStdinJSON } from './shared/read-stdin.js';
|
|
|
13
13
|
import { isHookEnabled } from './hook-config.js';
|
|
14
14
|
import { matchSolutions } from '../engine/solution-matcher.js';
|
|
15
15
|
import { RELEVANCE_MATCH_GATE } from '../engine/relevance-gate.js';
|
|
16
|
-
import {
|
|
16
|
+
import { extractSolutionTags } from '../engine/solution-format.js';
|
|
17
17
|
import { defaultNormalizer } from '../engine/term-normalizer.js';
|
|
18
18
|
import { logMatchDecision } from '../engine/match-eval-log.js';
|
|
19
19
|
import { resolveScope } from '../core/scope-resolver.js';
|
|
@@ -32,10 +32,81 @@ import { STATE_DIR } from '../core/paths.js';
|
|
|
32
32
|
import { recordHookTiming } from './shared/hook-timing.js';
|
|
33
33
|
import { appendPending, flushAccept } from '../engine/solution-outcomes.js';
|
|
34
34
|
import { appendImplicitFeedback } from '../store/implicit-feedback-store.js';
|
|
35
|
-
import { emitSolutionEvent,
|
|
35
|
+
import { emitSolutionEvent, recordGateVerdict } from '../core/observability-store.js';
|
|
36
36
|
import { parseSolutionV3 } from '../engine/solution-format.js';
|
|
37
|
-
import { ME_SOLUTIONS } from '../core/paths.js';
|
|
38
37
|
import { buildContextTokens } from '../engine/context-signals.js';
|
|
38
|
+
/** 매치된 태그 수를 개념 단위로 센다: 같은 동의어 계열(term-normalizer 의 canonical)에 속하면 하나. 계열이 없으면 태그 자체. */
|
|
39
|
+
function distinctConcepts(tags) {
|
|
40
|
+
return new Set(tags.map((t) => defaultNormalizer.termToCanonicals.get(t.normalize('NFC'))?.[0] ?? t.toLowerCase())).size;
|
|
41
|
+
}
|
|
42
|
+
/**
|
|
43
|
+
* 후보별 게이트 판정 — 주입 목록과 탈락 사유를 함께 돌려준다. 게이트 조건 자체는 그대로다(완화·강화 없음):
|
|
44
|
+
* 맥락 가산 제외 relevance 하한, identifier 1개 또는 태그 2개 이상, experiment 1개 제한, 프롬프트당 개수 제한.
|
|
45
|
+
*/
|
|
46
|
+
export function evaluateGate(candidates, opts) {
|
|
47
|
+
const verdicts = new Map();
|
|
48
|
+
const toInject = [];
|
|
49
|
+
let experimentCount = 0;
|
|
50
|
+
for (const sol of candidates) {
|
|
51
|
+
if (opts.injected.has(sol.name)) {
|
|
52
|
+
verdicts.set(sol.name, 'already-injected');
|
|
53
|
+
continue;
|
|
54
|
+
}
|
|
55
|
+
// 맥락 가산은 순위에만 — relevance 하한 게이트는 가산 전 값으로 비교한다(맥락만으로 게이트 통과 금지).
|
|
56
|
+
if (sol.relevance - (sol.contextBonus ?? 0) < opts.minRelevanceFor(sol.name)) {
|
|
57
|
+
verdicts.set(sol.name, 'below-relevance');
|
|
58
|
+
continue;
|
|
59
|
+
}
|
|
60
|
+
const idMatches = sol.matchedIdentifiers?.length ?? 0;
|
|
61
|
+
// 같은 개념의 한영 쌍("플러그인"+"plugin", "캐시"+"cache")이 둘 다 맞았다고 태그 2개로 세지 않는다 — 동의어 사전이
|
|
62
|
+
// 늘면서 한 단어 매치가 게이트의 "2개 이상"을 혼자 통과하는 길이 생기는 것을 막는 강화다(완화 아님).
|
|
63
|
+
const tagMatches = Math.max(0, distinctConcepts(sol.matchedTags.filter((t) => !(sol.matchedIdentifiers ?? []).includes(t))));
|
|
64
|
+
// 맥락 토큰(cwd/최근 편집 파일)은 relevance 가산에만 쓰고 이 게이트의 태그 수에는 넣지 않는다.
|
|
65
|
+
// 실측(S16): 범용 프롬프트 토큰 1개 + 맥락 3개를 0.5 가중으로 합산하면 무관한 솔루션이 통과했다.
|
|
66
|
+
if (idMatches < 1 && tagMatches < 2) {
|
|
67
|
+
verdicts.set(sol.name, 'too-few-tags');
|
|
68
|
+
continue;
|
|
69
|
+
}
|
|
70
|
+
if (toInject.length >= opts.maxPerPrompt) {
|
|
71
|
+
verdicts.set(sol.name, 'prompt-cap');
|
|
72
|
+
continue;
|
|
73
|
+
}
|
|
74
|
+
if (sol.status === 'experiment') {
|
|
75
|
+
if (experimentCount >= 1) {
|
|
76
|
+
verdicts.set(sol.name, 'experiment-cap');
|
|
77
|
+
continue;
|
|
78
|
+
}
|
|
79
|
+
experimentCount++;
|
|
80
|
+
}
|
|
81
|
+
toInject.push(sol);
|
|
82
|
+
verdicts.set(sol.name, 'passed');
|
|
83
|
+
}
|
|
84
|
+
return { toInject, verdicts };
|
|
85
|
+
}
|
|
86
|
+
/** Observability P1: matched emit — top-5 후보 각각 기록. 게이트 판정(통과 또는 탈락 사유 enum)을 meta.gate 에 남긴다. */
|
|
87
|
+
function emitMatchedEvents(sessionId, allMatched, verdicts) {
|
|
88
|
+
try {
|
|
89
|
+
for (const candidate of allMatched.slice(0, 5)) {
|
|
90
|
+
// 분포는 5분 중복 제거를 거치지 않는 별도 기록으로 센다.
|
|
91
|
+
recordGateVerdict({ sessionId, solutionId: candidate.name, gate: verdicts.get(candidate.name) ?? 'already-injected' });
|
|
92
|
+
emitSolutionEvent({
|
|
93
|
+
sessionId,
|
|
94
|
+
solutionId: candidate.name,
|
|
95
|
+
eventType: 'matched',
|
|
96
|
+
signalSource: 'matcher',
|
|
97
|
+
signalScore: candidate.relevance,
|
|
98
|
+
meta: {
|
|
99
|
+
matchedTags: candidate.matchedTags,
|
|
100
|
+
matchedIdentifiers: candidate.matchedIdentifiers,
|
|
101
|
+
gate: verdicts.get(candidate.name) ?? 'already-injected',
|
|
102
|
+
},
|
|
103
|
+
});
|
|
104
|
+
}
|
|
105
|
+
}
|
|
106
|
+
catch (e) {
|
|
107
|
+
log.debug('matched emit 실패', e);
|
|
108
|
+
}
|
|
109
|
+
}
|
|
39
110
|
const MAX_SOLUTIONS_PER_SESSION = 10;
|
|
40
111
|
/**
|
|
41
112
|
* Minimum relevance thresholds by fitness state (2026-04-21 gate sweep).
|
|
@@ -261,56 +332,11 @@ function backfillCacheTagsOnDisk(cachePath, allMatched) {
|
|
|
261
332
|
}
|
|
262
333
|
}
|
|
263
334
|
}
|
|
264
|
-
|
|
265
|
-
*
|
|
266
|
-
*
|
|
335
|
+
/*
|
|
336
|
+
* prompt-keyword acted_on 경로는 제거했다 (D6). 직전에 surfaced 된 솔루션의 태그가 사용자의 **다음 프롬프트**에 하나라도
|
|
337
|
+
* 들어 있으면 acted_on 이라고 기록했는데, 이는 같은 주제를 이어 말한 것일 뿐 솔루션이 쓰였다는 증거가 아니다
|
|
338
|
+
* (실데이터: 오탐 솔루션 하나에 16건, 전부 이 경로). acted_on 은 도구 사용·커밋처럼 행동의 흔적에서만 기록한다.
|
|
267
339
|
*/
|
|
268
|
-
async function detectActOnFromPriorSurface(sessionId, promptLower) {
|
|
269
|
-
try {
|
|
270
|
-
const recentSurfaces = querySurfacedWithin(sessionId, 5);
|
|
271
|
-
if (recentSurfaces.length === 0)
|
|
272
|
-
return;
|
|
273
|
-
const seen = new Set();
|
|
274
|
-
for (const surf of recentSurfaces) {
|
|
275
|
-
if (seen.has(surf.solutionId))
|
|
276
|
-
continue;
|
|
277
|
-
seen.add(surf.solutionId);
|
|
278
|
-
// 솔루션 파일 로드 (ME_SOLUTIONS 기준)
|
|
279
|
-
const filePath = path.join(ME_SOLUTIONS, `${surf.solutionId}.md`);
|
|
280
|
-
if (!fs.existsSync(filePath))
|
|
281
|
-
continue;
|
|
282
|
-
let raw;
|
|
283
|
-
try {
|
|
284
|
-
raw = fs.readFileSync(filePath, 'utf-8');
|
|
285
|
-
}
|
|
286
|
-
catch {
|
|
287
|
-
continue;
|
|
288
|
-
}
|
|
289
|
-
const sol = parseSolutionV3(raw);
|
|
290
|
-
if (!sol)
|
|
291
|
-
continue;
|
|
292
|
-
const tags = sol.frontmatter.tags ?? [];
|
|
293
|
-
const identifiers = sol.frontmatter.identifiers ?? [];
|
|
294
|
-
if (tags.length === 0 && identifiers.length === 0)
|
|
295
|
-
continue;
|
|
296
|
-
const hit = tags.some(t => promptLower.includes(t.toLowerCase()))
|
|
297
|
-
|| identifiers.some(id => promptLower.includes(id.toLowerCase()));
|
|
298
|
-
if (!hit)
|
|
299
|
-
continue;
|
|
300
|
-
emitSolutionEvent({
|
|
301
|
-
sessionId,
|
|
302
|
-
solutionId: surf.solutionId,
|
|
303
|
-
eventType: 'acted_on',
|
|
304
|
-
signalSource: 'prompt-keyword',
|
|
305
|
-
signalScore: 0.20,
|
|
306
|
-
meta: { surface_ts: surf.ts },
|
|
307
|
-
});
|
|
308
|
-
}
|
|
309
|
-
}
|
|
310
|
-
catch (e) {
|
|
311
|
-
log.debug('detectActOnFromPriorSurface 실패', e);
|
|
312
|
-
}
|
|
313
|
-
}
|
|
314
340
|
// ── Progressive Disclosure tiers (claude-mem 스타일 index→summary→full 대응) ──
|
|
315
341
|
//
|
|
316
342
|
// forgen은 이미 Tier 3(전문)를 compound-read MCP tool로 갖고 있었다 (fs 안 읽고
|
|
@@ -416,6 +442,11 @@ export function renderSolutionTiers(sols, rawByName) {
|
|
|
416
442
|
});
|
|
417
443
|
return rendered;
|
|
418
444
|
}
|
|
445
|
+
/** `/명령`, `!셸` 로 시작하는 프롬프트는 작업 설명이 아니라 명령이다. 첫 토큰에 `/` 가 더 있으면 경로이므로 명령이 아니다. */
|
|
446
|
+
function isCommandPrompt(prompt) {
|
|
447
|
+
const first = prompt.trimStart().split(/\s/, 1)[0] ?? '';
|
|
448
|
+
return /^!/.test(first) || /^\/[^/]*$/.test(first);
|
|
449
|
+
}
|
|
419
450
|
async function main() {
|
|
420
451
|
const _hookStart = Date.now();
|
|
421
452
|
try {
|
|
@@ -429,21 +460,24 @@ async function main() {
|
|
|
429
460
|
return;
|
|
430
461
|
}
|
|
431
462
|
const sessionId = input.session_id ?? 'default';
|
|
463
|
+
// 명령 프롬프트는 솔루션 회수 대상이 아니다 (실제 표본에서 오주입의 원인).
|
|
464
|
+
if (isCommandPrompt(input.prompt)) {
|
|
465
|
+
console.log(approve());
|
|
466
|
+
return;
|
|
467
|
+
}
|
|
432
468
|
// ADR-017 D2: 턴 단위 룰 관련도 → state/turn-rules-<session>.json (statusline "관련 룰 N" · status --turn).
|
|
433
469
|
// 프롬프트 주입에는 아무것도 보태지 않는다(토큰 비용 0). 원문 대신 sha256 앞 16자만 저장. 아래 어떤 early
|
|
434
470
|
// return 보다 앞에 두어 솔루션 매칭 결과와 무관하게 매 턴 기록된다. 전부 fail-open.
|
|
435
471
|
if (input.session_id) {
|
|
436
472
|
try {
|
|
437
473
|
const { relevantRules, writeTurnRules } = await import('../engine/rule-relevance.js');
|
|
438
|
-
const {
|
|
439
|
-
writeTurnRules(input.session_id, input.prompt, relevantRules(input.prompt,
|
|
474
|
+
const { loadContextRules } = await import('../store/rule-store.js');
|
|
475
|
+
writeTurnRules(input.session_id, input.prompt, relevantRules(input.prompt, loadContextRules(input.cwd)));
|
|
440
476
|
}
|
|
441
477
|
catch (e) {
|
|
442
478
|
log.debug('turn-rules 기록 실패', e);
|
|
443
479
|
}
|
|
444
480
|
}
|
|
445
|
-
// Observability P2: 직전 surfaced 솔루션과 현재 프롬프트 키워드 매칭 → acted_on emit
|
|
446
|
-
await detectActOnFromPriorSurface(sessionId, input.prompt.toLowerCase());
|
|
447
481
|
// v1: 교정 감지 → correction-record 호출 유도 hint
|
|
448
482
|
const correctionPatterns = /하지\s*마|그렇게\s*말고|앞으로는|이렇게\s*해|stop\s+doing|don'?t\s+do|always\s+do|never\s+do|아니\s*그게\s*아니라/i;
|
|
449
483
|
if (correctionPatterns.test(input.prompt)) {
|
|
@@ -474,25 +508,6 @@ async function main() {
|
|
|
474
508
|
// matches는 새 주입 후보 (이미 injected는 제외).
|
|
475
509
|
const contextTokens = buildContextTokens(cwd, input.session_id);
|
|
476
510
|
const allMatched = matchSolutions(input.prompt, scope, cwd, contextTokens);
|
|
477
|
-
// Observability P1: matched emit — top-5 후보 각각 기록
|
|
478
|
-
try {
|
|
479
|
-
for (const candidate of allMatched.slice(0, 5)) {
|
|
480
|
-
emitSolutionEvent({
|
|
481
|
-
sessionId,
|
|
482
|
-
solutionId: candidate.name,
|
|
483
|
-
eventType: 'matched',
|
|
484
|
-
signalSource: 'matcher',
|
|
485
|
-
signalScore: candidate.relevance,
|
|
486
|
-
meta: {
|
|
487
|
-
matchedTags: candidate.matchedTags,
|
|
488
|
-
matchedIdentifiers: candidate.matchedIdentifiers,
|
|
489
|
-
},
|
|
490
|
-
});
|
|
491
|
-
}
|
|
492
|
-
}
|
|
493
|
-
catch (e) {
|
|
494
|
-
log.debug('matched emit 실패', e);
|
|
495
|
-
}
|
|
496
511
|
const matches = allMatched.filter(m => !injected.has(m.name));
|
|
497
512
|
// T3: emit a ranking-decision record for offline analysis. Fail-open —
|
|
498
513
|
// the logger swallows any error so this never blocks hook approval.
|
|
@@ -502,7 +517,7 @@ async function main() {
|
|
|
502
517
|
// experiment cap, session-cache disjoint) is intentionally NOT captured
|
|
503
518
|
// here — the field's contract is "matcher's top, not final injection set".
|
|
504
519
|
try {
|
|
505
|
-
const promptTags =
|
|
520
|
+
const promptTags = extractSolutionTags(input.prompt);
|
|
506
521
|
const normalizedQuery = defaultNormalizer.normalizeTerms(promptTags);
|
|
507
522
|
logMatchDecision({
|
|
508
523
|
source: 'hook',
|
|
@@ -524,6 +539,7 @@ async function main() {
|
|
|
524
539
|
// 기존 cache의 missing tags를 채울 수 있다. 이전엔 이 경로를 놓쳐서
|
|
525
540
|
// backfill fix가 절반만 적용된 상태였다 (Codex/code-reviewer 발견).
|
|
526
541
|
if (matches.length === 0) {
|
|
542
|
+
emitMatchedEvents(sessionId, allMatched, new Map()); // 전부 이미 주입된 후보 — 게이트 판정은 already-injected
|
|
527
543
|
const earlyCachePath = path.join(STATE_DIR, `injection-cache-${sanitizeId(sessionId)}.json`);
|
|
528
544
|
backfillCacheTagsOnDisk(earlyCachePath, allMatched);
|
|
529
545
|
console.log(approve());
|
|
@@ -568,29 +584,13 @@ async function main() {
|
|
|
568
584
|
return MIN_INJECT_RELEVANCE_COLD_START;
|
|
569
585
|
return MIN_INJECT_RELEVANCE;
|
|
570
586
|
}
|
|
571
|
-
|
|
572
|
-
|
|
573
|
-
|
|
574
|
-
|
|
575
|
-
|
|
576
|
-
|
|
577
|
-
|
|
578
|
-
continue;
|
|
579
|
-
const idMatches = sol.matchedIdentifiers?.length ?? 0;
|
|
580
|
-
const tagMatches = Math.max(0, sol.matchedTags.length - idMatches);
|
|
581
|
-
// 맥락 토큰(cwd/최근 편집 파일)은 relevance 가산에만 쓰고 이 게이트의 태그 수에는 넣지 않는다.
|
|
582
|
-
// 실측(S16): 범용 프롬프트 토큰 1개 + 맥락 3개를 0.5 가중으로 합산하면 무관한 솔루션이 통과했다.
|
|
583
|
-
if (idMatches < 1 && tagMatches < 2)
|
|
584
|
-
continue;
|
|
585
|
-
if (sol.status === 'experiment') {
|
|
586
|
-
if (experimentCount >= 1)
|
|
587
|
-
continue;
|
|
588
|
-
experimentCount++;
|
|
589
|
-
}
|
|
590
|
-
toInject.push(sol);
|
|
591
|
-
if (toInject.length >= Math.min(budget.solutionsPerPrompt, MAX_SOLUTIONS_PER_SESSION - injected.size))
|
|
592
|
-
break;
|
|
593
|
-
}
|
|
587
|
+
const gate = evaluateGate(allMatched, {
|
|
588
|
+
minRelevanceFor,
|
|
589
|
+
injected,
|
|
590
|
+
maxPerPrompt: Math.min(budget.solutionsPerPrompt, MAX_SOLUTIONS_PER_SESSION - injected.size),
|
|
591
|
+
});
|
|
592
|
+
const toInject = gate.toInject.filter(sol => !injected.has(sol.name));
|
|
593
|
+
emitMatchedEvents(sessionId, allMatched, gate.verdicts);
|
|
594
594
|
// Progressive Disclosure: 매치 랭크에 따라 Tier 0(전문)/2(요약)/1(인덱스)로 나눠 렌더.
|
|
595
595
|
// rank 순서는 toInject 자체(matchSolutions/applyRoiDemotions가 이미 relevance desc
|
|
596
596
|
// 정렬해 반환) — 여기서 별도 재정렬하지 않는다.
|
|
@@ -689,9 +689,10 @@ async function main() {
|
|
|
689
689
|
// M-3 fix: effectiveToInject(commit이 검증한 disjoint set)만 evidence 갱신 →
|
|
690
690
|
// 동시 hook이 같은 솔루션을 inject해도 한 번만 카운트됨.
|
|
691
691
|
try {
|
|
692
|
-
|
|
692
|
+
// pre-tool-use.js 를 import 하면 그 모듈의 main() 이 다시 돌아 stdout 에 JSON 이 두 개 나간다.
|
|
693
|
+
const { incrementEvidence } = await import('../engine/solution-writer.js');
|
|
693
694
|
for (const sol of effectiveToInject) {
|
|
694
|
-
|
|
695
|
+
incrementEvidence(sol.name, 'injected');
|
|
695
696
|
}
|
|
696
697
|
}
|
|
697
698
|
catch (e) {
|
|
@@ -42,6 +42,12 @@ interface SpikeRule {
|
|
|
42
42
|
};
|
|
43
43
|
/** ADR-017 D1: precision 강등 모드. 'advise' 면 차단 대신 기록(kind:'correction'). */
|
|
44
44
|
enforce_mode?: 'block' | 'advise';
|
|
45
|
+
/** D12-C 주제 게이트용: 룰의 trigger/policy. store 룰에서만 채워진다(spike 룰은 없음 → 게이트 미적용). */
|
|
46
|
+
topic?: {
|
|
47
|
+
trigger: string;
|
|
48
|
+
policy: string;
|
|
49
|
+
category: string;
|
|
50
|
+
};
|
|
45
51
|
}
|
|
46
52
|
/**
|
|
47
53
|
* 프로덕션 rule-store 로더.
|
|
@@ -56,7 +62,9 @@ interface SpikeRule {
|
|
|
56
62
|
*/
|
|
57
63
|
export declare function rulesFromStore(rules: Rule[]): SpikeRule[];
|
|
58
64
|
/** Pure core — 단위 테스트용. stdin/IO 없음. */
|
|
59
|
-
export declare function evaluateStop(lastAssistantMessage: string, rules: SpikeRule[], recentTools?: string[]
|
|
65
|
+
export declare function evaluateStop(lastAssistantMessage: string, rules: SpikeRule[], recentTools?: string[], ctx?: {
|
|
66
|
+
turnRuleIds?: ReadonlySet<string>;
|
|
67
|
+
}): {
|
|
60
68
|
action: 'approve';
|
|
61
69
|
hit: null;
|
|
62
70
|
passed: string[];
|
|
@@ -64,6 +72,7 @@ export declare function evaluateStop(lastAssistantMessage: string, rules: SpikeR
|
|
|
64
72
|
rule: SpikeRule;
|
|
65
73
|
reason: string;
|
|
66
74
|
}>;
|
|
75
|
+
offTopic: string[];
|
|
67
76
|
} | {
|
|
68
77
|
action: 'block';
|
|
69
78
|
hit: SpikeRule;
|
|
@@ -73,6 +82,7 @@ export declare function evaluateStop(lastAssistantMessage: string, rules: SpikeR
|
|
|
73
82
|
rule: SpikeRule;
|
|
74
83
|
reason: string;
|
|
75
84
|
}>;
|
|
85
|
+
offTopic: string[];
|
|
76
86
|
};
|
|
77
87
|
/**
|
|
78
88
|
* 같은 (session, rule) 조합의 연속 block 카운트. approve 가 일어나면 0 으로 초기화.
|
package/dist/hooks/stop-guard.js
CHANGED
|
@@ -34,12 +34,15 @@ import { appendImplicitFeedback } from '../store/implicit-feedback-store.js';
|
|
|
34
34
|
import { atomicWriteJSON } from './shared/atomic-write.js';
|
|
35
35
|
import { recordHookTiming } from './shared/hook-timing.js';
|
|
36
36
|
import { isHookEnabled } from './hook-config.js';
|
|
37
|
-
import {
|
|
37
|
+
import { loadEnforcedRules } from '../store/rule-store.js';
|
|
38
38
|
import { recordViolation, recordCheck, rotateIfBig } from '../engine/lifecycle/signals.js';
|
|
39
39
|
import { compileSafeRegex, safeRegexTest } from './shared/safe-regex.js';
|
|
40
|
+
import { relevantRules, readTurnRules } from '../engine/rule-relevance.js';
|
|
41
|
+
import { artifactGateIsStale, topicGateApplies, effectiveEnforceMode } from '../engine/rule-detectability.js';
|
|
40
42
|
const HOOK_NAME = 'stop-guard';
|
|
41
43
|
// R6-F2: shared single source of truth.
|
|
42
44
|
import { DEFAULT_STOP_TRIGGER_RE, DEFAULT_STOP_EXCLUDE_RE } from './shared/stop-triggers.js';
|
|
45
|
+
import { isMainModule } from './shared/is-main.js';
|
|
43
46
|
/**
|
|
44
47
|
* Stuck-loop guard 임계치.
|
|
45
48
|
* Day-3 smoke 에서 block reason 문구가 Claude 응답에 재매칭되어 6회 연속 block 된
|
|
@@ -88,7 +91,7 @@ export function rulesFromStore(rules) {
|
|
|
88
91
|
const spec = specs[i];
|
|
89
92
|
if (spec.hook !== 'Stop')
|
|
90
93
|
continue;
|
|
91
|
-
if (!spec.verifier)
|
|
94
|
+
if (!spec.verifier || artifactGateIsStale(rule, spec))
|
|
92
95
|
continue;
|
|
93
96
|
if (spec.verifier.kind !== 'self_check_prompt' && spec.verifier.kind !== 'artifact_check' && spec.verifier.kind !== 'tool_evidence' && spec.verifier.kind !== 'language_ratio')
|
|
94
97
|
continue;
|
|
@@ -107,16 +110,17 @@ export function rulesFromStore(rules) {
|
|
|
107
110
|
block_message: spec.block_message,
|
|
108
111
|
system_tag: spec.system_tag,
|
|
109
112
|
origin: { source: rule.source, evidence_refs: rule.evidence_refs ?? [], policy: rule.policy },
|
|
110
|
-
enforce_mode: rule
|
|
113
|
+
enforce_mode: effectiveEnforceMode(rule, spec),
|
|
114
|
+
topic: { trigger: rule.trigger ?? '', policy: rule.policy, category: rule.category },
|
|
111
115
|
});
|
|
112
116
|
}
|
|
113
117
|
}
|
|
114
118
|
return out;
|
|
115
119
|
}
|
|
116
120
|
/** 전체 로더 — rule-store 우선, 비어 있으면 spike fallback. */
|
|
117
|
-
function loadStopRules() {
|
|
121
|
+
function loadStopRules(cwd) {
|
|
118
122
|
try {
|
|
119
|
-
const storeRules = rulesFromStore(
|
|
123
|
+
const storeRules = rulesFromStore(loadEnforcedRules(cwd));
|
|
120
124
|
if (storeRules.length > 0)
|
|
121
125
|
return storeRules;
|
|
122
126
|
}
|
|
@@ -353,7 +357,8 @@ function artifactFresh(relOrAbs, maxAgeS) {
|
|
|
353
357
|
}
|
|
354
358
|
}
|
|
355
359
|
/** Pure core — 단위 테스트용. stdin/IO 없음. */
|
|
356
|
-
export function evaluateStop(lastAssistantMessage, rules, recentTools = []) {
|
|
360
|
+
export function evaluateStop(lastAssistantMessage, rules, recentTools = [], ctx = {}) {
|
|
361
|
+
const offTopic = [];
|
|
357
362
|
// ADR-017 D2: 실제 평가돼 통과한 룰(passed)과, D1 advise 강등으로 차단 대신 기록만 하는 룰(advised)을 함께 반환.
|
|
358
363
|
const passed = [];
|
|
359
364
|
const advised = [];
|
|
@@ -362,17 +367,28 @@ export function evaluateStop(lastAssistantMessage, rules, recentTools = []) {
|
|
|
362
367
|
continue;
|
|
363
368
|
if (!messageTriggersRule(lastAssistantMessage, rule))
|
|
364
369
|
continue;
|
|
370
|
+
// D12-C 주제 게이트: 완료 키워드만으로 self_check 를 발동하던 방식은 무관한 룰(Deadeye 디자인 룰 등)이
|
|
371
|
+
// 무관한 완료 보고를 막는 오탐을 냈다(실데이터 판정 중 오탐 다수). 룰의 policy/trigger 와 직전 응답(또는 이번 턴
|
|
372
|
+
// 프롬프트에 관련 판정된 룰)이 관련 있을 때만 발동한다.
|
|
373
|
+
if (topicGateApplies(rule.verifier.kind, rule.topic?.category) && rule.topic) {
|
|
374
|
+
const onTopic = ctx.turnRuleIds?.has(rule.id)
|
|
375
|
+
|| relevantRules(lastAssistantMessage, [{ rule_id: rule.id, trigger: rule.topic.trigger, policy: rule.topic.policy }]).length > 0;
|
|
376
|
+
if (!onTopic) {
|
|
377
|
+
offTopic.push(rule.id);
|
|
378
|
+
continue;
|
|
379
|
+
}
|
|
380
|
+
}
|
|
365
381
|
const result = evaluateVerifier(rule, recentTools, lastAssistantMessage);
|
|
366
382
|
if (result.violated) {
|
|
367
383
|
if (rule.enforce_mode === 'advise') {
|
|
368
384
|
advised.push({ rule, reason: result.reason });
|
|
369
385
|
continue;
|
|
370
386
|
}
|
|
371
|
-
return { action: 'block', hit: rule, reason: result.reason, passed, advised };
|
|
387
|
+
return { action: 'block', hit: rule, reason: result.reason, passed, advised, offTopic };
|
|
372
388
|
}
|
|
373
389
|
passed.push(rule.id);
|
|
374
390
|
}
|
|
375
|
-
return { action: 'approve', hit: null, passed, advised };
|
|
391
|
+
return { action: 'approve', hit: null, passed, advised, offTopic };
|
|
376
392
|
}
|
|
377
393
|
function blockCounterPath(sessionId, ruleId) {
|
|
378
394
|
// 파일명 안전화 — 경로 인젝션 방지
|
|
@@ -620,13 +636,14 @@ export async function main() {
|
|
|
620
636
|
return;
|
|
621
637
|
}
|
|
622
638
|
}
|
|
623
|
-
const rules = loadStopRules();
|
|
639
|
+
const rules = loadStopRules(typeof input?.cwd === 'string' ? input.cwd : undefined);
|
|
624
640
|
if (rules.length === 0) {
|
|
625
641
|
console.log(approveWithOptionalExtractionNotice());
|
|
626
642
|
return;
|
|
627
643
|
}
|
|
628
644
|
const sessionId = input?.session_id ?? 'unknown';
|
|
629
|
-
const
|
|
645
|
+
const turnRuleIds = new Set((readTurnRules(sessionId)?.rules ?? []).map((r) => r.rule_id));
|
|
646
|
+
const result = evaluateStop(lastMessage, rules, loadRecentToolNames(sessionId), { turnRuleIds });
|
|
630
647
|
// ADR-017 D2: 실제 평가된 룰의 통과를 checks.jsonl 에 기록(violations 와 분리). D1: advise 강등 룰의
|
|
631
648
|
// 위반은 kind:'correction' 으로 기록만 하고 차단하지 않는다.
|
|
632
649
|
for (const id of result.passed)
|
|
@@ -714,7 +731,7 @@ export async function main() {
|
|
|
714
731
|
recordHookTiming(HOOK_NAME, Date.now() - started, 'Stop');
|
|
715
732
|
}
|
|
716
733
|
}
|
|
717
|
-
const isMain = import.meta.url
|
|
734
|
+
const isMain = isMainModule(import.meta.url);
|
|
718
735
|
if (isMain) {
|
|
719
736
|
void main();
|
|
720
737
|
}
|
|
@@ -29,6 +29,7 @@ import { STATE_DIR } from '../core/paths.js';
|
|
|
29
29
|
import { runMetaGuards } from '../checks/_shared/meta-guard-dispatch.js';
|
|
30
30
|
import { guardModeForModel, readSessionModel } from '../checks/_shared/model-profile.js';
|
|
31
31
|
import { recordViolation } from '../engine/lifecycle/signals.js';
|
|
32
|
+
import { isMainModule } from './shared/is-main.js';
|
|
32
33
|
import { incrementBlockCount, resetBlockCount, getStuckLoopThreshold, logDriftEvent, } from './stop-guard.js';
|
|
33
34
|
const HOOK_NAME = 'subagent-stop-guard';
|
|
34
35
|
/** SubagentStop 에는 last_assistant_message 가 없으므로 transcript JSONL 을 역순 스캔. */
|
|
@@ -155,7 +156,7 @@ export async function main() {
|
|
|
155
156
|
recordHookTiming(HOOK_NAME, Date.now() - started, 'SubagentStop');
|
|
156
157
|
}
|
|
157
158
|
}
|
|
158
|
-
const isMain = import.meta.url
|
|
159
|
+
const isMain = isMainModule(import.meta.url);
|
|
159
160
|
if (isMain) {
|
|
160
161
|
void main();
|
|
161
162
|
}
|
|
@@ -16,6 +16,7 @@ import { atomicWriteJSON } from './shared/atomic-write.js';
|
|
|
16
16
|
import { approve, approveWithWarning, failOpenWithTracking } from './shared/hook-response.js';
|
|
17
17
|
import { withFileLock } from './shared/file-lock.js';
|
|
18
18
|
import { STATE_DIR } from '../core/paths.js';
|
|
19
|
+
import { isMainModule } from './shared/is-main.js';
|
|
19
20
|
/**
|
|
20
21
|
* 동시 에이전트 경고 임계값.
|
|
21
22
|
* ADR-009 §4: dynamic workflows 는 동시 16 까지 정상 사용하므로 기본값을 16 으로
|
|
@@ -128,7 +129,7 @@ async function main() {
|
|
|
128
129
|
}
|
|
129
130
|
// import.meta 가드: 직접 실행 시에만 main() — 테스트가 헬퍼를 import 할 때
|
|
130
131
|
// stdin 을 읽는 main 이 돌지 않도록 한다 (모듈 위생).
|
|
131
|
-
const isMain = import.meta.url
|
|
132
|
+
const isMain = isMainModule(import.meta.url);
|
|
132
133
|
if (isMain) {
|
|
133
134
|
main().catch((e) => {
|
|
134
135
|
process.stderr.write(`[ch-hook] ${e instanceof Error ? e.message : String(e)}\n`);
|
|
@@ -20,6 +20,7 @@ export const codexCapabilities = {
|
|
|
20
20
|
status: 'supported',
|
|
21
21
|
expression: 'PreToolUse + `hookSpecificOutput.permissionDecision:"deny"` + `permissionDecisionReason`',
|
|
22
22
|
source: 'codex-rs/hooks/schema/generated/pre-tool-use.command.output.schema.json — PreToolUsePermissionDecisionWire enum ["allow","deny","ask"]',
|
|
23
|
+
mitigation: '스키마 enum 에는 "ask" 가 있지만 Codex 0.163 런타임은 "unsupported permissionDecision:ask" 로 훅을 실패 처리한다 → projection.ts 가 ask 를 deny + 안내로 바꾼다 (가드 무력화 금지).',
|
|
23
24
|
},
|
|
24
25
|
'inject-context': {
|
|
25
26
|
status: 'supported',
|
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Claude 고정 shim `<FORGEN_HOME>/bin/forgen-run` (설치 일원화 D1).
|
|
3
|
+
*
|
|
4
|
+
* settings.json 의 hook·statusLine 과 ~/.claude.json 의 MCP 는 이 파일 경로만 가리킨다. 설치 시점의 node 절대경로와
|
|
5
|
+
* 패키지 경로는 shim **내용**에 있어서, Node 전환·재설치는 shim 만 다시 쓰고 settings 는 그대로다.
|
|
6
|
+
* 대상이나 node 를 못 찾으면 호출 종류별로 보이게 실패한다: hook=유효 JSON 경고 + exit 0,
|
|
7
|
+
* MCP=stderr + 비0 종료(stdout JSON 은 프로토콜을 깨뜨린다), statusLine=한 줄 안내.
|
|
8
|
+
* POSIX sh 전용. Windows 는 호출부가 기존 절대경로를 유지한다.
|
|
9
|
+
*/
|
|
10
|
+
import { shimSupported } from './codex-hook-shim.js';
|
|
11
|
+
export { shimSupported };
|
|
12
|
+
export declare const FORGEN_RUN_MARKER = "# forgen-managed forgen-run shim";
|
|
13
|
+
export declare const REINSTALL_HINT = "npm i -g @wooojin/forgen (or: forgen install claude)";
|
|
14
|
+
/** FORGEN_HOME 이 있으면 그 아래, 없으면 `<home>/.forgen/bin/forgen-run`. */
|
|
15
|
+
export declare function forgenRunShimPath(homeDir?: string): string;
|
|
16
|
+
/** 소유 판정용 — 명령이 forgen-run shim 을 가리키는가. */
|
|
17
|
+
export declare function isForgenRunCommand(command: string): boolean;
|
|
18
|
+
export declare function renderForgenRunShim(pkgRoot: string, nodePath: string): string;
|
|
19
|
+
export declare function writeForgenRunShim(pkgRoot: string, nodePath: string, shimPath: string): 'written' | 'unchanged' | 'foreign' | 'error';
|
|
20
|
+
/** shim 이 있으면 반환, 쓸 수 없으면(Windows/사용자 파일/쓰기 실패) null → 호출부가 절대경로로 폴백. */
|
|
21
|
+
export declare function ensureForgenRunShim(pkgRoot: string, homeDir?: string): {
|
|
22
|
+
path: string | null;
|
|
23
|
+
status: string;
|
|
24
|
+
};
|
|
@@ -0,0 +1,68 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Claude 고정 shim `<FORGEN_HOME>/bin/forgen-run` (설치 일원화 D1).
|
|
3
|
+
*
|
|
4
|
+
* settings.json 의 hook·statusLine 과 ~/.claude.json 의 MCP 는 이 파일 경로만 가리킨다. 설치 시점의 node 절대경로와
|
|
5
|
+
* 패키지 경로는 shim **내용**에 있어서, Node 전환·재설치는 shim 만 다시 쓰고 settings 는 그대로다.
|
|
6
|
+
* 대상이나 node 를 못 찾으면 호출 종류별로 보이게 실패한다: hook=유효 JSON 경고 + exit 0,
|
|
7
|
+
* MCP=stderr + 비0 종료(stdout JSON 은 프로토콜을 깨뜨린다), statusLine=한 줄 안내.
|
|
8
|
+
* POSIX sh 전용. Windows 는 호출부가 기존 절대경로를 유지한다.
|
|
9
|
+
*/
|
|
10
|
+
import * as os from 'node:os';
|
|
11
|
+
import * as path from 'node:path';
|
|
12
|
+
import { shimSupported, shq, writeManagedShim } from './codex-hook-shim.js';
|
|
13
|
+
export { shimSupported };
|
|
14
|
+
export const FORGEN_RUN_MARKER = '# forgen-managed forgen-run shim';
|
|
15
|
+
export const REINSTALL_HINT = 'npm i -g @wooojin/forgen (or: forgen install claude)';
|
|
16
|
+
/** FORGEN_HOME 이 있으면 그 아래, 없으면 `<home>/.forgen/bin/forgen-run`. */
|
|
17
|
+
export function forgenRunShimPath(homeDir = os.homedir()) {
|
|
18
|
+
const base = process.env.FORGEN_HOME ? path.resolve(process.env.FORGEN_HOME) : path.join(homeDir, '.forgen');
|
|
19
|
+
return path.join(base, 'bin', 'forgen-run');
|
|
20
|
+
}
|
|
21
|
+
/** 소유 판정용 — 명령이 forgen-run shim 을 가리키는가. */
|
|
22
|
+
export function isForgenRunCommand(command) {
|
|
23
|
+
return /[\\/]forgen-run"?(\s|$)/.test(command);
|
|
24
|
+
}
|
|
25
|
+
export function renderForgenRunShim(pkgRoot, nodePath) {
|
|
26
|
+
const hookWarn = JSON.stringify({
|
|
27
|
+
continue: true,
|
|
28
|
+
systemMessage: `forgen hooks are not running (target or node not found). Reinstall: ${REINSTALL_HINT}`,
|
|
29
|
+
});
|
|
30
|
+
return [
|
|
31
|
+
'#!/bin/sh',
|
|
32
|
+
FORGEN_RUN_MARKER,
|
|
33
|
+
'# 설치·업그레이드마다 재작성된다. settings.json / ~/.claude.json 은 이 파일 경로만 가리킨다.',
|
|
34
|
+
'# usage: forgen-run <dist 기준 상대경로> [args...]',
|
|
35
|
+
`FORGEN_PKG=${shq(pkgRoot)}`,
|
|
36
|
+
`FORGEN_NODE=${shq(nodePath)}`,
|
|
37
|
+
`FORGEN_HOOK_WARN=${shq(hookWarn)}`,
|
|
38
|
+
'rel="$1"; [ $# -gt 0 ] && shift',
|
|
39
|
+
'[ -x "$FORGEN_NODE" ] || FORGEN_NODE=$(command -v node 2>/dev/null)',
|
|
40
|
+
'# 패키지가 사라졌으면(버전 디렉터리 삭제) PATH 의 forgen 이 속한 prefix 에서 찾는다.',
|
|
41
|
+
'if [ ! -f "$FORGEN_PKG/dist/$rel" ]; then',
|
|
42
|
+
' f=$(command -v forgen 2>/dev/null)',
|
|
43
|
+
' if [ -n "$f" ] && [ -f "$(dirname "$f")/../lib/node_modules/@wooojin/forgen/dist/$rel" ]; then',
|
|
44
|
+
' FORGEN_PKG="$(dirname "$f")/../lib/node_modules/@wooojin/forgen"',
|
|
45
|
+
' fi',
|
|
46
|
+
'fi',
|
|
47
|
+
'if [ -n "$FORGEN_NODE" ] && [ -f "$FORGEN_PKG/dist/$rel" ]; then',
|
|
48
|
+
' exec "$FORGEN_NODE" "$FORGEN_PKG/dist/$rel" "$@"',
|
|
49
|
+
'fi',
|
|
50
|
+
'case "$rel" in',
|
|
51
|
+
` mcp/*) echo "forgen: MCP server not found. Reinstall: ${REINSTALL_HINT}" >&2; exit 1 ;;`,
|
|
52
|
+
' hooks/*) printf \'%s\\n\' "$FORGEN_HOOK_WARN"; exit 0 ;;',
|
|
53
|
+
` *) echo "forgen: not found. Reinstall: ${REINSTALL_HINT}"; exit 0 ;;`,
|
|
54
|
+
'esac',
|
|
55
|
+
'',
|
|
56
|
+
].join('\n');
|
|
57
|
+
}
|
|
58
|
+
export function writeForgenRunShim(pkgRoot, nodePath, shimPath) {
|
|
59
|
+
return writeManagedShim(shimPath, renderForgenRunShim(pkgRoot, nodePath), FORGEN_RUN_MARKER);
|
|
60
|
+
}
|
|
61
|
+
/** shim 이 있으면 반환, 쓸 수 없으면(Windows/사용자 파일/쓰기 실패) null → 호출부가 절대경로로 폴백. */
|
|
62
|
+
export function ensureForgenRunShim(pkgRoot, homeDir = os.homedir()) {
|
|
63
|
+
if (!shimSupported())
|
|
64
|
+
return { path: null, status: 'unsupported' };
|
|
65
|
+
const shimPath = forgenRunShimPath(homeDir);
|
|
66
|
+
const status = writeForgenRunShim(pkgRoot, process.execPath, shimPath);
|
|
67
|
+
return { path: status === 'written' || status === 'unchanged' ? shimPath : null, status };
|
|
68
|
+
}
|