@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
|
@@ -11,6 +11,7 @@
|
|
|
11
11
|
*/
|
|
12
12
|
import * as fs from 'node:fs';
|
|
13
13
|
import * as path from 'node:path';
|
|
14
|
+
import { fileURLToPath } from 'node:url';
|
|
14
15
|
import { execFileSync, execFile } from 'node:child_process';
|
|
15
16
|
import { promisify } from 'node:util';
|
|
16
17
|
const execFileAsync = promisify(execFile);
|
|
@@ -20,101 +21,16 @@ import { isSelfReferentialEcho } from './config-injector.js';
|
|
|
20
21
|
import { redactSecrets } from '../hooks/secret-filter.js';
|
|
21
22
|
import { stripPrivate } from '../engine/private-filter.js';
|
|
22
23
|
import { createEvidence, saveEvidence, promoteSessionCandidates } from '../store/evidence-store.js';
|
|
23
|
-
import { isHaikuCompoundEnabled } from './compound-consent.js';
|
|
24
|
-
import {
|
|
24
|
+
import { isHaikuCompoundEnabled, getHaikuConsentState } from './compound-consent.js';
|
|
25
|
+
import { digestTranscriptFile, renderDigest } from './transcript-summary.js';
|
|
26
|
+
import { getCursor, setCursor, markRun, enqueue, claimDue, completeEntry, acquireRunnerLock, releaseRunnerLock, transcriptSignature, resetIfReplaced, getDonePhases, setDonePhases } from './extraction-queue.js';
|
|
27
|
+
import { releaseAutoCompoundInflight } from './spawn.js';
|
|
28
|
+
import { projectKeyFor } from '../store/rule-scope.js';
|
|
29
|
+
import { reopenIfReExtracted } from '../engine/compound-lifecycle.js';
|
|
30
|
+
import { callHaiku, probeClaudeAvailability, writeHaikuStatus, appendExtractionEvent } from './extraction-haiku.js';
|
|
25
31
|
import { loadProfile } from '../store/profile-store.js';
|
|
26
32
|
import { FORGEN_HOME, ME_DIR } from './paths.js';
|
|
27
33
|
import { classifyBehaviorKind, mapKindToAxisRefs } from './behavior-classifier.js';
|
|
28
|
-
/** Auto-compound에 사용할 모델 — background 추출이므로 haiku로 충분 */
|
|
29
|
-
const COMPOUND_MODEL = 'haiku';
|
|
30
|
-
/**
|
|
31
|
-
* Host-aware exec retry — feat/codex-support P2-3 (Phase 2 critic fix).
|
|
32
|
-
*
|
|
33
|
-
* 보안 회귀 방지: Claude 분기는 *args 그대로* execFileSync 호출 → P1-S1 의
|
|
34
|
-
* `--allowedTools Bash(forgen compound:*)` sandbox hardening 보존.
|
|
35
|
-
* Codex 분기에서만 -p prompt 추출 → execHost (codex 는 --allowedTools 모름).
|
|
36
|
-
*
|
|
37
|
-
* Codex retry 정책 fix: ETIMEDOUT 시 sleep 후 retry 는 *Claude only*. Codex 는
|
|
38
|
-
* 60-90s response 가 정상이라 timeout 누적 retry 가 무의미 (즉시 fail).
|
|
39
|
-
*/
|
|
40
|
-
function execClaudeRetry(args, opts) {
|
|
41
|
-
const mod = createRequire(import.meta.url)('../host/exec-host.js');
|
|
42
|
-
// profile.default_host 로 host 결정 (lazy load)
|
|
43
|
-
const profileMod = createRequire(import.meta.url)('../store/profile-store.js');
|
|
44
|
-
const resolved = profileMod.resolveDefaultHost();
|
|
45
|
-
const host = resolved === 'codex' ? 'codex' : 'claude';
|
|
46
|
-
if (host === 'claude') {
|
|
47
|
-
// Claude 측은 기존 보안 hardening 보존: --allowedTools 등 args 그대로 전달.
|
|
48
|
-
const TRANSIENT = /ETIMEDOUT|ECONNRESET|ECONNREFUSED|EPIPE/;
|
|
49
|
-
const MAX_ATTEMPTS = 2;
|
|
50
|
-
for (let attempt = 1; attempt <= MAX_ATTEMPTS; attempt++) {
|
|
51
|
-
try {
|
|
52
|
-
return execFileSync('claude', mod.withNestedRunClaudeArgs(args), {
|
|
53
|
-
...opts,
|
|
54
|
-
env: { ...process.env, ...(opts.env ?? {}), ...mod.NESTED_RUN_ENV },
|
|
55
|
-
});
|
|
56
|
-
}
|
|
57
|
-
catch (e) {
|
|
58
|
-
const msg = e instanceof Error ? e.message : String(e);
|
|
59
|
-
const match = msg.match(TRANSIENT);
|
|
60
|
-
if (attempt < MAX_ATTEMPTS && match) {
|
|
61
|
-
process.stderr.write(`[forgen-auto-compound] ${match[0]} on attempt ${attempt}/${MAX_ATTEMPTS}, retrying in 3s (auto-recovery)...\n`);
|
|
62
|
-
Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, 3000);
|
|
63
|
-
continue;
|
|
64
|
-
}
|
|
65
|
-
if (match) {
|
|
66
|
-
process.stderr.write(`[forgen-auto-compound] ${match[0]} after ${attempt}/${MAX_ATTEMPTS} attempts — giving up (fail-open)\n`);
|
|
67
|
-
}
|
|
68
|
-
throw e;
|
|
69
|
-
}
|
|
70
|
-
}
|
|
71
|
-
throw new Error('unreachable');
|
|
72
|
-
}
|
|
73
|
-
// host === 'codex' — prompt 만 추출 (codex 는 --allowedTools 등 미인식).
|
|
74
|
-
const pIdx = args.indexOf('-p');
|
|
75
|
-
if (pIdx === -1 || !args[pIdx + 1]) {
|
|
76
|
-
throw new Error('execClaudeRetry: codex host requires -p prompt argument');
|
|
77
|
-
}
|
|
78
|
-
const prompt = args[pIdx + 1];
|
|
79
|
-
const modelIdx = args.indexOf('--model');
|
|
80
|
-
const model = modelIdx !== -1 ? args[modelIdx + 1] : undefined;
|
|
81
|
-
const r = mod.execHost({
|
|
82
|
-
prompt,
|
|
83
|
-
model,
|
|
84
|
-
host: 'codex',
|
|
85
|
-
timeout: typeof opts.timeout === 'number' ? opts.timeout : 60000,
|
|
86
|
-
cwd: typeof opts.cwd === 'string' ? opts.cwd : undefined,
|
|
87
|
-
});
|
|
88
|
-
return r.message;
|
|
89
|
-
}
|
|
90
|
-
/**
|
|
91
|
-
* 0.4.6 perf #12 — async 변형. 3 LLM 호출 (solution / user-pattern / learning) 을
|
|
92
|
-
* Promise.allSettled 로 병렬 실행하여 wall-clock 을 sum → max 로 단축 (~3x).
|
|
93
|
-
*
|
|
94
|
-
* 0.4.6 에서는 adaptive cooldown 으로 wasted runs 차단을 우선 적용했고, 호출부
|
|
95
|
-
* full parallelization 은 0.4.7 로 분리 (refactor surface 큼 — solution call 의
|
|
96
|
-
* `--allowedTools` sandbox 와 file-write 순서 invariant 검증 필요).
|
|
97
|
-
*
|
|
98
|
-
* 본 함수는 0.4.7 작업의 foundation 으로 박제 — export 하여 unused warning 회피.
|
|
99
|
-
* 동작은 sync 버전과 동일: Claude/Codex 분기 + retry on transient.
|
|
100
|
-
*/
|
|
101
|
-
/**
|
|
102
|
-
* ADR-012 D: Haiku transcript-요약 추출은 **opt-in**. 동의 없으면 '' 반환 → 각 추출 phase 는
|
|
103
|
-
* fail-open(try/catch)이라 아무것도 쓰지 않고, 뒤의 `promoteSessionCandidates`(결정론·egress 0)
|
|
104
|
-
* 만 남는다. "우리는 당신 몰래 API 로 보내지 않는다".
|
|
105
|
-
*/
|
|
106
|
-
let haikuOptOutNoticeShown = false;
|
|
107
|
-
function extractViaHaiku(args, opts) {
|
|
108
|
-
if (!isHaikuCompoundEnabled()) {
|
|
109
|
-
if (!haikuOptOutNoticeShown) {
|
|
110
|
-
process.stderr.write('[forgen-auto-compound] Haiku 추출 opt-in 비활성 — 결정론 룰 승급만 수행 ' +
|
|
111
|
-
'(활성: `forgen compound consent on`)\n');
|
|
112
|
-
haikuOptOutNoticeShown = true;
|
|
113
|
-
}
|
|
114
|
-
return '';
|
|
115
|
-
}
|
|
116
|
-
return execClaudeRetry(args, opts);
|
|
117
|
-
}
|
|
118
34
|
export async function execClaudeRetryAsync(args, opts) {
|
|
119
35
|
const mod = createRequire(import.meta.url)('../host/exec-host.js');
|
|
120
36
|
const profileMod = createRequire(import.meta.url)('../store/profile-store.js');
|
|
@@ -161,8 +77,43 @@ export async function execClaudeRetryAsync(args, opts) {
|
|
|
161
77
|
}
|
|
162
78
|
const [, , cwd, transcriptPath, sessionId] = process.argv;
|
|
163
79
|
if (!cwd || !transcriptPath || !sessionId) {
|
|
80
|
+
try {
|
|
81
|
+
appendExtractionEvent({ ok: false, sessionId: String(sessionId ?? ''), error: 'missing-args (cwd/transcript/session)' });
|
|
82
|
+
}
|
|
83
|
+
catch { /* 기록 실패는 무시 */ }
|
|
164
84
|
process.exit(1);
|
|
165
85
|
}
|
|
86
|
+
/** 추출 없이 일찍 끝나는 경로도 사유와 함께 남긴다 — status 가 "실행은 됐는데 입력이 부족했다"를 "실행 안 됨"과 구분한다. */
|
|
87
|
+
function exitSkipped(reason) {
|
|
88
|
+
try {
|
|
89
|
+
appendExtractionEvent({ ok: true, skipped: reason, sessionId: String(sessionId) });
|
|
90
|
+
}
|
|
91
|
+
catch { /* 기록 실패는 무시 */ }
|
|
92
|
+
process.exit(0);
|
|
93
|
+
}
|
|
94
|
+
// ── 세션별 러너 락: 같은 세션을 두 러너가 동시에 처리해 Haiku 를 두 번 부르거나 솔루션을 중복 저장하지 않게 한다. ──
|
|
95
|
+
// spawn 쪽 in-flight 표식(TTL)은 시작 시점 게이트일 뿐이다. 러너 자신이 잡는 락이 최종 방어선이고, 종료 시 락과 표식을 함께 푼다.
|
|
96
|
+
if (transcriptPath !== '-') {
|
|
97
|
+
let locked = false;
|
|
98
|
+
try {
|
|
99
|
+
locked = acquireRunnerLock(String(sessionId));
|
|
100
|
+
}
|
|
101
|
+
catch {
|
|
102
|
+
locked = true; /* 락 인프라 실패는 막지 않는다(fail-open) */
|
|
103
|
+
}
|
|
104
|
+
if (!locked)
|
|
105
|
+
exitSkipped('runner-locked');
|
|
106
|
+
process.on('exit', () => {
|
|
107
|
+
try {
|
|
108
|
+
releaseRunnerLock(String(sessionId));
|
|
109
|
+
}
|
|
110
|
+
catch { /* 무시 */ }
|
|
111
|
+
try {
|
|
112
|
+
releaseAutoCompoundInflight(String(sessionId));
|
|
113
|
+
}
|
|
114
|
+
catch { /* 무시 */ }
|
|
115
|
+
});
|
|
116
|
+
}
|
|
166
117
|
const SOLUTIONS_DIR = path.join(ME_DIR, 'solutions');
|
|
167
118
|
const BEHAVIOR_DIR = path.join(ME_DIR, 'behavior');
|
|
168
119
|
/** Lightweight quality gate for auto-extracted solution files */
|
|
@@ -176,20 +127,20 @@ function parseTags(content) {
|
|
|
176
127
|
return match[1].split(',').map(t => t.trim().replace(/"/g, '').replace(/'/g, '')).filter(Boolean);
|
|
177
128
|
}
|
|
178
129
|
/** Gate 3 (dedup): check tag overlap with existing solutions */
|
|
179
|
-
function
|
|
130
|
+
function findDuplicate(newContent, existingFiles) {
|
|
180
131
|
const newTags = parseTags(newContent);
|
|
181
132
|
if (newTags.length === 0)
|
|
182
|
-
return
|
|
183
|
-
for (const [, existingContent] of existingFiles) {
|
|
133
|
+
return null;
|
|
134
|
+
for (const [file, existingContent] of existingFiles) {
|
|
184
135
|
const existingTags = parseTags(existingContent);
|
|
185
136
|
if (existingTags.length === 0)
|
|
186
137
|
continue;
|
|
187
138
|
const overlap = newTags.filter(t => existingTags.includes(t));
|
|
188
139
|
const overlapRatio = overlap.length / Math.max(newTags.length, existingTags.length, 1);
|
|
189
140
|
if (overlapRatio >= 0.7)
|
|
190
|
-
return
|
|
141
|
+
return file;
|
|
191
142
|
}
|
|
192
|
-
return
|
|
143
|
+
return null;
|
|
193
144
|
}
|
|
194
145
|
function validateSolutionFiles(dirBefore) {
|
|
195
146
|
let removed = 0;
|
|
@@ -225,9 +176,24 @@ function validateSolutionFiles(dirBefore) {
|
|
|
225
176
|
continue;
|
|
226
177
|
}
|
|
227
178
|
// Gate 3: dedup — reject if 70%+ tag overlap with existing solutions
|
|
228
|
-
|
|
179
|
+
const dupOf = findDuplicate(content, existingSolutions);
|
|
180
|
+
if (dupOf) {
|
|
181
|
+
// 중복 상대가 은퇴한 솔루션이면 (D6): 내용이 비슷할 때만 복귀시키고 새 추출은 버린다.
|
|
182
|
+
// 태그만 겹치고 내용이 다르면 새 추출을 버리지 않는다 (은퇴본은 매칭에서 빠져 있으므로 공존해도 된다).
|
|
183
|
+
const dupName = path.basename(dupOf, '.md');
|
|
184
|
+
let outcome = 'none';
|
|
185
|
+
try {
|
|
186
|
+
outcome = reopenIfReExtracted(dupName, content);
|
|
187
|
+
}
|
|
188
|
+
catch { /* 무시 */ }
|
|
189
|
+
if (outcome === 'different') {
|
|
190
|
+
existingSolutions.set(file, content);
|
|
191
|
+
continue;
|
|
192
|
+
}
|
|
229
193
|
fs.unlinkSync(filePath);
|
|
230
194
|
removed++;
|
|
195
|
+
if (outcome === 'reopened')
|
|
196
|
+
process.stderr.write(`[forgen-auto-compound] reopened retired solution: ${dupOf}\n`);
|
|
231
197
|
continue;
|
|
232
198
|
}
|
|
233
199
|
// Accepted — add to existing pool so subsequent new files dedup against it too
|
|
@@ -243,10 +209,6 @@ function validateSolutionFiles(dirBefore) {
|
|
|
243
209
|
}
|
|
244
210
|
return removed;
|
|
245
211
|
}
|
|
246
|
-
/** 파일 → 요약. 순수 로직은 transcript-summary 모듈(테스트 가능). */
|
|
247
|
-
function extractSummary(filePath, maxChars = 8000) {
|
|
248
|
-
return summarizeTranscript(fs.readFileSync(filePath, 'utf-8'), maxChars);
|
|
249
|
-
}
|
|
250
212
|
/**
|
|
251
213
|
* 기존 behavior 파일에 유사 패턴이 있으면 observedCount를 +1 증가.
|
|
252
214
|
* 유사도는 같은 kind + 내용 키워드 50%+ 겹침으로 판단.
|
|
@@ -293,133 +255,90 @@ function mergeOrCreateBehavior(dir, newContent, kind, today) {
|
|
|
293
255
|
}
|
|
294
256
|
// 0.4.6 perf #12 — adaptive cooldown 시그널 (declared early for hoisting).
|
|
295
257
|
let userPatternFound = false;
|
|
296
|
-
|
|
297
|
-
|
|
298
|
-
|
|
299
|
-
|
|
300
|
-
|
|
301
|
-
|
|
302
|
-
|
|
303
|
-
|
|
304
|
-
|
|
305
|
-
|
|
306
|
-
|
|
307
|
-
|
|
308
|
-
// 축. 이 auto-compound-runner 는 학습 코퍼스의 *주 자동 캡처 경로* — 세션 종료마다
|
|
309
|
-
// 전체 트랜스크립트를 추출 LLM 으로 보내고 behavior/solution 으로 파생한다. 사용자가
|
|
310
|
-
// <private> 로 표시한 범위를 LLM 송신·behavior write 전에 제거해야 "안심하고 교정"
|
|
311
|
-
// 약속이 주 경로에서 지켜진다.
|
|
312
|
-
const { cleaned: summary, hadPrivate } = stripPrivate(redactedSummary);
|
|
313
|
-
if (hadPrivate) {
|
|
314
|
-
process.stderr.write(`[forgen-auto-compound] excluded <private> range(s) before send (privacy)\n`);
|
|
315
|
-
}
|
|
316
|
-
if (summary.length < 200)
|
|
317
|
-
process.exit(0);
|
|
318
|
-
// 보안: 프롬프트 인젝션이 포함된 transcript는 분석하지 않음
|
|
319
|
-
if (containsPromptInjection(summary)) {
|
|
320
|
-
process.exit(0);
|
|
321
|
-
}
|
|
322
|
-
// 기존 솔루션 목록 (중복 방지)
|
|
323
|
-
let existingList = '';
|
|
324
|
-
const solDir = path.join(FORGEN_HOME, 'me', 'solutions');
|
|
325
|
-
if (fs.existsSync(solDir)) {
|
|
326
|
-
const names = fs.readdirSync(solDir).filter(f => f.endsWith('.md')).map(f => f.replace('.md', '')).slice(-30);
|
|
327
|
-
if (names.length > 0)
|
|
328
|
-
existingList = `\n\n이미 축적된 솔루션 (중복 추출 금지):\n${names.join(', ')}`;
|
|
329
|
-
}
|
|
330
|
-
// 기존 behavior 파일 목록 (중복 패턴 방지)
|
|
331
|
-
let existingBehaviorPatterns = '';
|
|
332
|
-
if (fs.existsSync(BEHAVIOR_DIR)) {
|
|
333
|
-
const behaviorFiles = fs.readdirSync(BEHAVIOR_DIR).filter(f => f.endsWith('.md')).slice(-10);
|
|
334
|
-
if (behaviorFiles.length > 0) {
|
|
335
|
-
const snippets = behaviorFiles.map(f => {
|
|
336
|
-
try {
|
|
337
|
-
return fs.readFileSync(path.join(BEHAVIOR_DIR, f), 'utf-8').slice(0, 200);
|
|
338
|
-
}
|
|
339
|
-
catch {
|
|
340
|
-
return '';
|
|
341
|
-
}
|
|
342
|
-
}).filter(Boolean);
|
|
343
|
-
existingBehaviorPatterns = `\n\n기존 behavior 패턴 (중복 추가 금지):\n${snippets.join('\n---\n')}`;
|
|
344
|
-
}
|
|
345
|
-
}
|
|
346
|
-
// 1단계: 솔루션 추출
|
|
347
|
-
// 보안: transcript 요약에 filterSolutionContent 적용하여 프롬프트 인젝션 방어
|
|
348
|
-
const scanResult = filterSolutionContent(summary);
|
|
349
|
-
if (scanResult.verdict === 'block') {
|
|
350
|
-
process.stderr.write('[forgen-auto-compound] transcript blocked by injection filter\n');
|
|
351
|
-
process.exit(0);
|
|
352
|
-
}
|
|
353
|
-
if (scanResult.verdict === 'warn') {
|
|
354
|
-
process.stderr.write(`[forgen-auto-compound] injection warning: ${scanResult.findings.map(f => f.patternId).join(', ')}\n`);
|
|
258
|
+
// 추출 이벤트 기록(status 흐름 표시용): Haiku 호출이 실패했는지 마지막에 함께 남긴다.
|
|
259
|
+
let haikuError = null;
|
|
260
|
+
const sid = String(sessionId);
|
|
261
|
+
/** 6번째 인자 'final' = 세션 종료/이전 세션 복구 경로 → 새 내용이 적어도 Haiku 를 돌린다. Stop(턴 단위)은 새 사용자 발화 3개 미만이면 건너뛴다. */
|
|
262
|
+
const isFinal = process.argv[6] === 'final';
|
|
263
|
+
const queueOnly = transcriptPath === '-';
|
|
264
|
+
const MIN_NEW_USER_MSGS_FOR_PARTIAL = 3;
|
|
265
|
+
class SkipExtraction extends Error {
|
|
266
|
+
reason;
|
|
267
|
+
constructor(reason) {
|
|
268
|
+
super(reason);
|
|
269
|
+
this.reason = reason;
|
|
355
270
|
}
|
|
356
|
-
|
|
357
|
-
|
|
358
|
-
const
|
|
271
|
+
}
|
|
272
|
+
function snapshotSolutions() {
|
|
273
|
+
const s = new Set();
|
|
359
274
|
try {
|
|
360
275
|
if (fs.existsSync(SOLUTIONS_DIR)) {
|
|
361
|
-
for (const f of fs.readdirSync(SOLUTIONS_DIR))
|
|
276
|
+
for (const f of fs.readdirSync(SOLUTIONS_DIR))
|
|
362
277
|
if (f.endsWith('.md'))
|
|
363
|
-
|
|
364
|
-
}
|
|
278
|
+
s.add(f);
|
|
365
279
|
}
|
|
366
280
|
}
|
|
367
281
|
catch { /* ignore */ }
|
|
368
|
-
|
|
369
|
-
|
|
370
|
-
|
|
371
|
-
|
|
372
|
-
|
|
373
|
-
|
|
374
|
-
|
|
375
|
-
|
|
376
|
-
|
|
377
|
-
|
|
378
|
-
|
|
379
|
-
각 항목을 정확히 아래 한 줄 형식으로만 출력하세요 (다른 설명 없이, 코드블록도 불필요):
|
|
380
|
-
forgen compound --solution "제목" "설명 (무엇 + 왜 + 어떻게 적용)"
|
|
282
|
+
return s;
|
|
283
|
+
}
|
|
284
|
+
/** 이 러너 실행의 솔루션 저장 시 Context 칸에 넣을 출처 (적용 조건은 모델이 준 값과 합친다). */
|
|
285
|
+
function solutionContext(condition) {
|
|
286
|
+
const where = path.basename(cwd) || cwd;
|
|
287
|
+
const when = new Date().toISOString().slice(0, 10);
|
|
288
|
+
const src = `출처: ${where} 프로젝트 세션 ${sid.slice(0, 8)} (${when}), auto-compound`;
|
|
289
|
+
return condition ? `${condition}\n\n${src}` : src;
|
|
290
|
+
}
|
|
291
|
+
const SOLUTION_PROMPT_HEAD = `다음은 Claude Code 세션 대화 요약입니다 (사용자 발화와 어시스턴트 발화만, 시간순. 긴 세션은 교정 지점과 끝부분 위주로 중간이 생략됨).
|
|
292
|
+
다음 세션에서 **다른 작업에도 다시 쓸 수 있는** 교훈을 최대 3개 뽑아주세요.
|
|
381
293
|
|
|
382
|
-
|
|
383
|
-
|
|
384
|
-
추출할 것이 없으면 "추출할 패턴 없음"이라고만 답하세요.
|
|
385
|
-
최대 3개. 피상적인 관찰(예: "TypeScript를 사용함")은 제외. 기존 솔루션과 중복 금지.${existingList}
|
|
294
|
+
각 항목을 정확히 아래 한 줄 형식으로만 출력하세요 (다른 설명·코드블록 없이):
|
|
295
|
+
forgen compound --solution "제목" "본문" "적용 조건" ["범위"]
|
|
386
296
|
|
|
387
|
-
|
|
388
|
-
|
|
389
|
-
|
|
390
|
-
|
|
391
|
-
|
|
392
|
-
|
|
393
|
-
|
|
394
|
-
|
|
395
|
-
|
|
297
|
+
작성 규칙:
|
|
298
|
+
- 제목: 상황을 일반화한 검색 가능한 이름 (예: "react-high-frequency-event-raf-throttle"). 특정 파일·컴포넌트·함수 이름을 제목에 쓰지 말 것.
|
|
299
|
+
- 본문: "이런 상황에서는 이렇게 한다" 형식, 150~400자. 행동(무엇을 한다) + 근거(왜) + 주의(깨지는 경우·함정)를 모두 넣을 것.
|
|
300
|
+
- 적용 조건: 이 교훈이 해당하는 상황을 한 문장으로.
|
|
301
|
+
- 범위(선택): 이 교훈이 이 프로젝트의 구조·관례·도메인에 묶여 있어 다른 프로젝트에서는 맞지 않으면 "이 프로젝트", 어디서나 쓸 수 있으면 생략.
|
|
302
|
+
- 근거는 사용자가 교정한 지점, 실패 후 해결한 지점, 판단 기준이 드러난 지점에서 찾을 것.
|
|
303
|
+
- 제외: 사용자의 첫 지시나 작업 목표를 그대로 옮겨 적은 것, 이번 세션에서만 의미 있는 진행 상황·일정·파일 목록, 피상적 관찰(예: "TypeScript를 사용함"), 이미 있는 솔루션과 중복.
|
|
304
|
+
추출할 것이 없으면 "추출할 패턴 없음"이라고만 답하세요.`;
|
|
305
|
+
function phaseSolution(summary, attempt, sessId = sid) {
|
|
306
|
+
let existingList = '';
|
|
307
|
+
const solDir = path.join(FORGEN_HOME, 'me', 'solutions');
|
|
308
|
+
if (fs.existsSync(solDir)) {
|
|
309
|
+
const names = fs.readdirSync(solDir).filter(f => f.endsWith('.md')).map(f => f.replace('.md', '')).slice(-30);
|
|
310
|
+
if (names.length > 0)
|
|
311
|
+
existingList = `\n\n이미 축적된 솔루션 (중복 추출 금지):\n${names.join(', ')}`;
|
|
396
312
|
}
|
|
397
|
-
|
|
398
|
-
|
|
313
|
+
const solutionsBefore = snapshotSolutions();
|
|
314
|
+
const r = callHaiku('solution', `${SOLUTION_PROMPT_HEAD}${existingList}\n\n---\n${summary}\n---`, { cwd, attempt, sessionId: sessId });
|
|
315
|
+
if (!r.ok)
|
|
316
|
+
return { ok: false, retriable: r.retriable, reason: r.reason, outcome: r.outcome };
|
|
317
|
+
const solutionOutput = r.output;
|
|
318
|
+
// 모델 출력에서 `--solution "제목" "본문" ["적용 조건"]` 을 파싱해 forgen 을 직접 실행(결정론적).
|
|
319
|
+
// forgen 은 이 러너와 같은 패키지의 cli.js 를 같은 node 로 직접 호출 — sparse PATH·다른 버전의 전역 forgen 의존 제거.
|
|
399
320
|
const nodeBinDir = path.dirname(process.execPath);
|
|
400
|
-
const
|
|
401
|
-
|
|
402
|
-
: 'forgen';
|
|
403
|
-
const solutionArgRe = /--solution\s+"((?:[^"\\]|\\.)+)"\s+"((?:[^"\\]|\\.)+)"/g;
|
|
321
|
+
const cliJs = path.join(path.dirname(fileURLToPath(import.meta.url)), '..', 'cli.js');
|
|
322
|
+
const solutionArgRe = /--solution\s+"((?:[^"\\]|\\.)+)"\s+"((?:[^"\\]|\\.)+)"(?:\s+"((?:[^"\\]|\\.)*)")?(?:\s+"((?:[^"\\]|\\.)*)")?/g;
|
|
404
323
|
let match;
|
|
405
324
|
let extractedCount = 0;
|
|
406
325
|
// biome-ignore lint/suspicious/noAssignInExpressions: regex exec 루프 관용구
|
|
407
326
|
while ((match = solutionArgRe.exec(solutionOutput)) !== null && extractedCount < 3) {
|
|
408
327
|
const title = match[1].replace(/\\"/g, '"').trim();
|
|
409
328
|
const rawContent = match[2].replace(/\\"/g, '"').trim();
|
|
329
|
+
const condition = (match[3] ?? '').replace(/\\"/g, '"').trim();
|
|
330
|
+
const projectOnly = (match[4] ?? '').trim() === '이 프로젝트';
|
|
331
|
+
const projectKey = projectOnly ? projectKeyFor(cwd) : null;
|
|
410
332
|
if (!title || rawContent.length < 20)
|
|
411
333
|
continue;
|
|
412
|
-
// 보안(argument confusion): title/content 는 untrusted 모델 출력이다. execFileSync
|
|
413
|
-
//
|
|
414
|
-
|
|
415
|
-
// '-' 로 시작하지 않으므로 대시-선두 값은 스킵한다. (handleCompound 의 위치인자 파서가
|
|
416
|
-
// startsWith('--') 를 필터하는 것에 더해 러너에서 원천 차단.)
|
|
417
|
-
if (title.startsWith('-') || rawContent.startsWith('-')) {
|
|
334
|
+
// 보안(argument confusion): title/content 는 untrusted 모델 출력이다. execFileSync 인자로 넘기므로
|
|
335
|
+
// 셸 인젝션은 없지만 '-' 로 시작하면 forgen 의 인자 파서가 플래그로 오해석할 수 있다 → 스킵.
|
|
336
|
+
if (title.startsWith('-') || rawContent.startsWith('-') || condition.startsWith('-')) {
|
|
418
337
|
process.stderr.write('[forgen-auto-compound] solution: dash-leading title/content, skipping (arg-confusion guard)\n');
|
|
419
338
|
continue;
|
|
420
339
|
}
|
|
421
340
|
// 모델 출력은 untrusted transcript 파생 — 저장 전 injection/exfil 필터(defense in depth).
|
|
422
|
-
if (containsPromptInjection(`${title} ${rawContent}`)) {
|
|
341
|
+
if (containsPromptInjection(`${title} ${rawContent} ${condition}`)) {
|
|
423
342
|
process.stderr.write('[forgen-auto-compound] solution: injection detected in LLM output, skipping\n');
|
|
424
343
|
continue;
|
|
425
344
|
}
|
|
@@ -429,9 +348,7 @@ ${sanitizedSummary.slice(0, 6000)}
|
|
|
429
348
|
continue;
|
|
430
349
|
}
|
|
431
350
|
try {
|
|
432
|
-
|
|
433
|
-
// 명령 인젝션 불가. FORGEN_HOME 등 env 는 그대로 상속되어 올바른 스토어에 기록된다.
|
|
434
|
-
execFileSync(forgenBin, ['compound', '--solution', title, contentScan.sanitized], {
|
|
351
|
+
execFileSync(process.execPath, [cliJs, 'compound', '--solution', title, contentScan.sanitized, '--context', solutionContext(filterSolutionContent(condition).sanitized), ...(projectKey ? ['--project', projectKey] : [])], {
|
|
435
352
|
cwd,
|
|
436
353
|
timeout: 20_000,
|
|
437
354
|
stdio: ['ignore', 'ignore', 'pipe'],
|
|
@@ -448,7 +365,25 @@ ${sanitizedSummary.slice(0, 6000)}
|
|
|
448
365
|
if (removedCount > 0) {
|
|
449
366
|
process.stderr.write(`[forgen-auto-compound] quality gate removed ${removedCount} low-quality solution(s)\n`);
|
|
450
367
|
}
|
|
451
|
-
|
|
368
|
+
return { ok: true, retriable: false };
|
|
369
|
+
}
|
|
370
|
+
function phaseBehavior(summary, attempt, sessId = sid) {
|
|
371
|
+
// 기존 behavior 파일 목록 (중복 패턴 방지)
|
|
372
|
+
let existingBehaviorPatterns = '';
|
|
373
|
+
if (fs.existsSync(BEHAVIOR_DIR)) {
|
|
374
|
+
const behaviorFiles = fs.readdirSync(BEHAVIOR_DIR).filter(f => f.endsWith('.md')).slice(-10);
|
|
375
|
+
if (behaviorFiles.length > 0) {
|
|
376
|
+
const snippets = behaviorFiles.map(f => {
|
|
377
|
+
try {
|
|
378
|
+
return fs.readFileSync(path.join(BEHAVIOR_DIR, f), 'utf-8').slice(0, 200);
|
|
379
|
+
}
|
|
380
|
+
catch {
|
|
381
|
+
return '';
|
|
382
|
+
}
|
|
383
|
+
}).filter(Boolean);
|
|
384
|
+
existingBehaviorPatterns = `\n\n기존 behavior 패턴 (중복 추가 금지):\n${snippets.join('\n---\n')}`;
|
|
385
|
+
}
|
|
386
|
+
}
|
|
452
387
|
const userPrompt = `다음 대화에서 사용자의 작업 습관, 커뮤니케이션 스타일, 기술 선호도를 분석해주세요.
|
|
453
388
|
|
|
454
389
|
관찰된 패턴을 다음 형식으로 1~3개만 출력해주세요 (없으면 "관찰된 패턴 없음"):
|
|
@@ -467,84 +402,64 @@ ${sanitizedSummary.slice(0, 6000)}
|
|
|
467
402
|
기존 패턴과 중복이면 건너뛰세요.${existingBehaviorPatterns}
|
|
468
403
|
|
|
469
404
|
---
|
|
470
|
-
${
|
|
405
|
+
${summary}
|
|
471
406
|
---`;
|
|
472
|
-
|
|
473
|
-
|
|
474
|
-
|
|
475
|
-
|
|
476
|
-
|
|
477
|
-
|
|
478
|
-
|
|
479
|
-
|
|
480
|
-
|
|
481
|
-
|
|
482
|
-
|
|
483
|
-
|
|
484
|
-
|
|
485
|
-
|
|
486
|
-
|
|
487
|
-
//
|
|
488
|
-
|
|
489
|
-
|
|
490
|
-
|
|
491
|
-
|
|
492
|
-
|
|
493
|
-
|
|
494
|
-
|
|
495
|
-
|
|
496
|
-
|
|
497
|
-
|
|
498
|
-
|
|
499
|
-
if (userResult && !isInjection && !isEcho && !userResult.includes('관찰된 패턴 없음') && userResult.trim().length > 10) {
|
|
500
|
-
userPatternFound = true; // 0.4.6 perf #12 — adaptive cooldown 시그널
|
|
501
|
-
fs.mkdirSync(BEHAVIOR_DIR, { recursive: true });
|
|
502
|
-
const today = new Date().toISOString().split('T')[0];
|
|
503
|
-
const trimmed = userResult.trim();
|
|
504
|
-
// 카테고리에 따라 kind 분류 — D1'' (2026-04-27): quality/autonomy 라벨 추가.
|
|
505
|
-
// 이전 3분기(workflow/thinking/preference)는 quality_safety/autonomy 축으로
|
|
506
|
-
// 가는 자동 신호를 communication_style 로 흡수해 626건 중 자동 추출 0건이
|
|
507
|
-
// 이 두 축에 닿지 못했음. 5분기로 확장. (분류 로직은 behavior-classifier.ts)
|
|
508
|
-
const kind = classifyBehaviorKind(trimmed);
|
|
509
|
-
// 기존 유사 패턴이 있으면 observedCount 누적
|
|
510
|
-
const merged = mergeOrCreateBehavior(BEHAVIOR_DIR, trimmed, kind, today);
|
|
511
|
-
if (!merged) {
|
|
512
|
-
const slug = `auto-${today}-${kind}`;
|
|
513
|
-
const behaviorPath = path.join(BEHAVIOR_DIR, `${slug}.md`);
|
|
514
|
-
if (!fs.existsSync(behaviorPath)) {
|
|
515
|
-
const content = `---\nname: "${slug}"\nversion: 1\nkind: "${kind}"\nobservedCount: 1\nconfidence: 0.6\ntags: ["auto-observed", "${kind}"]\ncreated: "${today}"\nupdated: "${today}"\nsource: "auto-compound"\n---\n\n## Content\n${trimmed}\n`;
|
|
516
|
-
fs.writeFileSync(behaviorPath, content);
|
|
517
|
-
}
|
|
407
|
+
const r = callHaiku('behavior', userPrompt, { cwd, attempt, sessionId: sessId });
|
|
408
|
+
if (!r.ok)
|
|
409
|
+
return { ok: false, retriable: r.retriable, reason: r.reason, outcome: r.outcome };
|
|
410
|
+
const userResult = r.output;
|
|
411
|
+
// B4 security hardening (2026-04-09): 모델 출력도 디스크에 쓰기 전 prompt-injection 필터를 통과시킨다.
|
|
412
|
+
const isInjection = userResult ? containsPromptInjection(userResult.trim()) : false;
|
|
413
|
+
if (isInjection) {
|
|
414
|
+
process.stderr.write(`[forgen-auto-compound] behavior: injection detected in LLM output, skipping write\n`);
|
|
415
|
+
}
|
|
416
|
+
// ADR-010 W1-2 캡처 사이드 에코 차단: Claude-voice 에코를 저장 전에 거른다.
|
|
417
|
+
const isEcho = userResult ? isSelfReferentialEcho(userResult.trim()) : false;
|
|
418
|
+
if (isEcho && !isInjection) {
|
|
419
|
+
process.stderr.write(`[forgen-auto-compound] behavior: assistant-voice echo detected, skipping write\n`);
|
|
420
|
+
}
|
|
421
|
+
if (userResult && !isInjection && !isEcho && !userResult.includes('관찰된 패턴 없음') && userResult.trim().length > 10) {
|
|
422
|
+
userPatternFound = true; // 0.4.6 perf #12 — adaptive cooldown 시그널
|
|
423
|
+
fs.mkdirSync(BEHAVIOR_DIR, { recursive: true });
|
|
424
|
+
const today = new Date().toISOString().split('T')[0];
|
|
425
|
+
const trimmed = userResult.trim();
|
|
426
|
+
const kind = classifyBehaviorKind(trimmed);
|
|
427
|
+
const merged = mergeOrCreateBehavior(BEHAVIOR_DIR, trimmed, kind, today);
|
|
428
|
+
if (!merged) {
|
|
429
|
+
const slug = `auto-${today}-${kind}`;
|
|
430
|
+
const behaviorPath = path.join(BEHAVIOR_DIR, `${slug}.md`);
|
|
431
|
+
if (!fs.existsSync(behaviorPath)) {
|
|
432
|
+
const content = `---\nname: "${slug}"\nversion: 1\nkind: "${kind}"\nobservedCount: 1\nconfidence: 0.6\ntags: ["auto-observed", "${kind}"]\ncreated: "${today}"\nupdated: "${today}"\nsource: "auto-compound"\n---\n\n## Content\n${trimmed}\n`;
|
|
433
|
+
fs.writeFileSync(behaviorPath, content);
|
|
518
434
|
}
|
|
519
|
-
// behavior_observation evidence 저장 (mismatch detector 신호 확대)
|
|
520
|
-
const behaviorEvidence = createEvidence({
|
|
521
|
-
type: 'behavior_observation',
|
|
522
|
-
session_id: sessionId,
|
|
523
|
-
source_component: 'auto-compound-runner',
|
|
524
|
-
summary: trimmed.slice(0, 200),
|
|
525
|
-
axis_refs: mapKindToAxisRefs(kind),
|
|
526
|
-
confidence: 0.6,
|
|
527
|
-
raw_payload: { kind, observedCount: 1 },
|
|
528
|
-
});
|
|
529
|
-
saveEvidence(behaviorEvidence);
|
|
530
435
|
}
|
|
436
|
+
// behavior_observation evidence 저장 (mismatch detector 신호 확대)
|
|
437
|
+
const behaviorEvidence = createEvidence({
|
|
438
|
+
type: 'behavior_observation',
|
|
439
|
+
session_id: sid,
|
|
440
|
+
source_component: 'auto-compound-runner',
|
|
441
|
+
summary: trimmed.slice(0, 200),
|
|
442
|
+
axis_refs: mapKindToAxisRefs(kind),
|
|
443
|
+
confidence: 0.6,
|
|
444
|
+
raw_payload: { kind, observedCount: 1 },
|
|
445
|
+
});
|
|
446
|
+
saveEvidence(behaviorEvidence);
|
|
531
447
|
}
|
|
532
|
-
|
|
533
|
-
|
|
534
|
-
|
|
535
|
-
|
|
536
|
-
|
|
537
|
-
|
|
538
|
-
|
|
539
|
-
|
|
540
|
-
|
|
541
|
-
|
|
542
|
-
|
|
543
|
-
|
|
544
|
-
|
|
545
|
-
|
|
546
|
-
|
|
547
|
-
const learningSummaryPrompt = `다음 Claude Code 세션 대화를 분석하여 사용자의 개인화 학습 요약을 JSON으로 출력해주세요.
|
|
448
|
+
return { ok: true, retriable: false };
|
|
449
|
+
}
|
|
450
|
+
async function phaseLearning(summary, attempt, sessId = sid) {
|
|
451
|
+
const V1_PROFILE = path.join(ME_DIR, 'forge-profile.json');
|
|
452
|
+
const V1_EVIDENCE_DIR = path.join(ME_DIR, 'behavior');
|
|
453
|
+
if (!fs.existsSync(V1_PROFILE))
|
|
454
|
+
return { ok: true, retriable: false };
|
|
455
|
+
const currentProfile = loadProfile();
|
|
456
|
+
let profileContext = '';
|
|
457
|
+
if (currentProfile) {
|
|
458
|
+
const qf = currentProfile.axes.quality_safety.facets;
|
|
459
|
+
const af = currentProfile.axes.autonomy.facets;
|
|
460
|
+
profileContext = `\n현재 프로필:\n- 팩: quality=${currentProfile.base_packs.quality_pack}, autonomy=${currentProfile.base_packs.autonomy_pack}\n- quality_safety facets: verification_depth=${qf.verification_depth.toFixed(2)}, stop_threshold=${qf.stop_threshold.toFixed(2)}, change_conservatism=${qf.change_conservatism.toFixed(2)}\n- autonomy facets: confirmation_independence=${af.confirmation_independence.toFixed(2)}, assumption_tolerance=${af.assumption_tolerance.toFixed(2)}, scope_expansion_tolerance=${af.scope_expansion_tolerance.toFixed(2)}, approval_threshold=${af.approval_threshold.toFixed(2)}\n`;
|
|
461
|
+
}
|
|
462
|
+
const learningSummaryPrompt = `다음 Claude Code 세션 대화를 분석하여 사용자의 개인화 학습 요약을 JSON으로 출력해주세요.
|
|
548
463
|
${profileContext}
|
|
549
464
|
출력 형식 (JSON만, 설명 없이):
|
|
550
465
|
{
|
|
@@ -577,121 +492,308 @@ ${profileContext}
|
|
|
577
492
|
- 학습할 것이 없으면 모든 값을 빈 배열/null/0.0으로.
|
|
578
493
|
|
|
579
494
|
---
|
|
580
|
-
${
|
|
495
|
+
${summary}
|
|
581
496
|
---`;
|
|
582
|
-
|
|
583
|
-
|
|
584
|
-
|
|
585
|
-
|
|
586
|
-
|
|
587
|
-
|
|
588
|
-
|
|
589
|
-
|
|
590
|
-
|
|
591
|
-
|
|
592
|
-
|
|
593
|
-
|
|
594
|
-
|
|
595
|
-
|
|
596
|
-
|
|
597
|
-
|
|
598
|
-
|
|
599
|
-
|
|
600
|
-
|
|
601
|
-
|
|
602
|
-
|
|
603
|
-
|
|
604
|
-
|
|
605
|
-
|
|
606
|
-
|
|
607
|
-
|
|
608
|
-
|
|
609
|
-
|
|
610
|
-
|
|
611
|
-
|
|
612
|
-
|
|
613
|
-
|
|
614
|
-
|
|
615
|
-
|
|
616
|
-
|
|
617
|
-
|
|
618
|
-
|
|
619
|
-
|
|
620
|
-
|
|
621
|
-
|
|
622
|
-
|
|
623
|
-
|
|
624
|
-
|
|
625
|
-
|
|
626
|
-
|
|
627
|
-
|
|
628
|
-
|
|
629
|
-
|
|
630
|
-
|
|
631
|
-
|
|
632
|
-
|
|
633
|
-
|
|
634
|
-
|
|
497
|
+
const r = callHaiku('learning', learningSummaryPrompt, { cwd, attempt, sessionId: sessId });
|
|
498
|
+
if (!r.ok)
|
|
499
|
+
return { ok: false, retriable: r.retriable, reason: r.reason, outcome: r.outcome };
|
|
500
|
+
const learningResult = r.output;
|
|
501
|
+
const jsonMatch = learningResult.match(/\{[\s\S]*\}/);
|
|
502
|
+
if (!jsonMatch)
|
|
503
|
+
return { ok: true, retriable: false };
|
|
504
|
+
let parsed; // eslint-disable-line @typescript-eslint/no-explicit-any
|
|
505
|
+
try {
|
|
506
|
+
parsed = JSON.parse(jsonMatch[0]);
|
|
507
|
+
}
|
|
508
|
+
catch (e) {
|
|
509
|
+
process.stderr.write(`[forgen-auto-compound] session learning JSON parse: ${e instanceof Error ? e.message : String(e)}\n`);
|
|
510
|
+
return { ok: true, retriable: false };
|
|
511
|
+
}
|
|
512
|
+
// session_summary evidence 저장 (mismatch detector용)
|
|
513
|
+
if (parsed.pack_direction || parsed.corrections?.length > 0 || parsed.observations?.length > 0) {
|
|
514
|
+
const evidenceId = `sess-summary-${sid.slice(0, 8)}`;
|
|
515
|
+
const evidence = {
|
|
516
|
+
evidence_id: evidenceId,
|
|
517
|
+
type: 'session_summary',
|
|
518
|
+
session_id: sid,
|
|
519
|
+
timestamp: new Date().toISOString(),
|
|
520
|
+
source_component: 'auto-compound-runner',
|
|
521
|
+
summary: `corrections: ${parsed.corrections?.length ?? 0}, observations: ${parsed.observations?.length ?? 0}`,
|
|
522
|
+
axis_refs: parsed.pack_direction ? [parsed.pack_direction.includes('quality') ? 'quality_safety' : 'autonomy'] : [],
|
|
523
|
+
candidate_rule_refs: [],
|
|
524
|
+
confidence: 0.7,
|
|
525
|
+
raw_payload: {
|
|
526
|
+
pack_direction: parsed.pack_direction,
|
|
527
|
+
corrections: parsed.corrections,
|
|
528
|
+
observations: parsed.observations,
|
|
529
|
+
},
|
|
530
|
+
};
|
|
531
|
+
fs.mkdirSync(V1_EVIDENCE_DIR, { recursive: true });
|
|
532
|
+
fs.writeFileSync(path.join(V1_EVIDENCE_DIR, `${evidenceId}.json`), JSON.stringify(evidence, null, 2));
|
|
533
|
+
}
|
|
534
|
+
// ADR-013: 채굴된 교정을 **승급 가능 Evidence** 로 emit. auto_mined → promoteSessionCandidates 가
|
|
535
|
+
// **advisory-only**(차단 불가) + "auto:" 네임스페이스 + 생성나이 은퇴로 승급.
|
|
536
|
+
// 안전: (a) run 당 최대 3개, (b) policy 를 injection 필터 통과, (c) policy≥20 + target 필수.
|
|
537
|
+
const MAX_MINED_PER_RUN = 3;
|
|
538
|
+
let minedCorrections = 0;
|
|
539
|
+
for (const c of (parsed.corrections ?? [])) {
|
|
540
|
+
if (minedCorrections >= MAX_MINED_PER_RUN)
|
|
541
|
+
break;
|
|
542
|
+
if (!c || typeof c !== 'object')
|
|
543
|
+
continue;
|
|
544
|
+
const policy = typeof c.policy === 'string' ? c.policy.trim() : '';
|
|
545
|
+
const target = typeof c.target === 'string' ? c.target.trim() : '';
|
|
546
|
+
const kind = c.kind === 'avoid-this' ? 'avoid-this' : 'prefer-from-now';
|
|
547
|
+
const axis = typeof c.axis === 'string' ? c.axis : null;
|
|
548
|
+
if (policy.length < 20 || !target)
|
|
549
|
+
continue;
|
|
550
|
+
if (containsPromptInjection(policy) || containsPromptInjection(target)) {
|
|
551
|
+
process.stderr.write('[forgen-auto-compound] skipped mined correction (injection filter)\n');
|
|
552
|
+
continue;
|
|
553
|
+
}
|
|
554
|
+
const ev = createEvidence({
|
|
555
|
+
type: 'explicit_correction',
|
|
556
|
+
session_id: sid,
|
|
557
|
+
source_component: 'auto-compound-miner',
|
|
558
|
+
summary: policy,
|
|
559
|
+
axis_refs: axis ? [axis] : [],
|
|
560
|
+
confidence: 0.55, // ①(실시간)보다 낮게 — 채굴 불확실성 반영
|
|
561
|
+
raw_payload: { kind, target, axis_hint: axis, auto_mined: true },
|
|
562
|
+
});
|
|
563
|
+
saveEvidence(ev);
|
|
564
|
+
minedCorrections++;
|
|
565
|
+
}
|
|
566
|
+
if (minedCorrections > 0) {
|
|
567
|
+
process.stderr.write(`[forgen-auto-compound] mined ${minedCorrections} correction(s) (advisory-only, capped, age-retired)\n`);
|
|
568
|
+
}
|
|
569
|
+
// facet delta 적용 — ADR-017: raw JSON write 금지. profile-store 경유로 score 재계산.
|
|
570
|
+
if (parsed.profile_delta) {
|
|
571
|
+
const { loadProfile: lp, saveProfileRecomputed } = await import('../store/profile-store.js');
|
|
572
|
+
const profile = lp();
|
|
573
|
+
const clamp = (v) => Math.max(0.0, Math.min(1.0, v));
|
|
574
|
+
let changed = false;
|
|
575
|
+
if (profile) {
|
|
576
|
+
const axes = ['quality_safety', 'autonomy', 'judgment_philosophy', 'communication_style'];
|
|
577
|
+
for (const axis of axes) {
|
|
578
|
+
const d = parsed.profile_delta[axis];
|
|
579
|
+
if (!d)
|
|
580
|
+
continue;
|
|
581
|
+
const f = profile.axes[axis].facets;
|
|
582
|
+
for (const [k, v] of Object.entries(d)) {
|
|
583
|
+
if (typeof v === 'number' && Math.abs(v) > 0.001 && Object.hasOwn(f, k)) { // hasOwn: 프로토타입 키 차단
|
|
584
|
+
f[k] = clamp(f[k] + v);
|
|
585
|
+
changed = true;
|
|
635
586
|
}
|
|
636
|
-
const ev = createEvidence({
|
|
637
|
-
type: 'explicit_correction',
|
|
638
|
-
session_id: sessionId,
|
|
639
|
-
source_component: 'auto-compound-miner',
|
|
640
|
-
summary: policy,
|
|
641
|
-
axis_refs: axis ? [axis] : [],
|
|
642
|
-
confidence: 0.55, // ①(실시간)보다 낮게 — 채굴 불확실성 반영
|
|
643
|
-
raw_payload: { kind, target, axis_hint: axis, auto_mined: true },
|
|
644
|
-
});
|
|
645
|
-
saveEvidence(ev);
|
|
646
|
-
minedCorrections++;
|
|
647
587
|
}
|
|
648
|
-
|
|
649
|
-
|
|
588
|
+
}
|
|
589
|
+
}
|
|
590
|
+
if (profile && changed) {
|
|
591
|
+
const rr = saveProfileRecomputed(profile);
|
|
592
|
+
const moved = Object.entries(rr.deltas).filter(([, d]) => Math.abs(d.after - d.before) > 1e-9).map(([k, d]) => `${k} ${d.before.toFixed(2)}→${d.after.toFixed(2)}`);
|
|
593
|
+
process.stderr.write(`[forgen-auto-compound] profile facets updated from session learning${moved.length ? ` (score: ${moved.join(', ')})` : ''}\n`);
|
|
594
|
+
}
|
|
595
|
+
}
|
|
596
|
+
return { ok: true, retriable: false };
|
|
597
|
+
}
|
|
598
|
+
/**
|
|
599
|
+
* 단계들을 순서대로 호출한다. 첫 실패에서 멈춘다 — 같은 환경에서 다음 호출도 같은 이유로 실패할 가능성이 높고,
|
|
600
|
+
* 실패 호출마다 최대 타임아웃을 기다리면 러너가 무한정 길어진다. 남은 단계(실패한 단계 포함)를 돌려준다.
|
|
601
|
+
*/
|
|
602
|
+
async function runPhases(summary, phases, attempt, sessId = sid) {
|
|
603
|
+
for (let i = 0; i < phases.length; i++) {
|
|
604
|
+
let r;
|
|
605
|
+
try {
|
|
606
|
+
r = phases[i] === 'solution' ? phaseSolution(summary, attempt, sessId)
|
|
607
|
+
: phases[i] === 'behavior' ? phaseBehavior(summary, attempt, sessId)
|
|
608
|
+
: await phaseLearning(summary, attempt, sessId);
|
|
609
|
+
}
|
|
610
|
+
catch (e) {
|
|
611
|
+
r = { ok: false, retriable: false, reason: e instanceof Error ? e.message.slice(0, 160) : String(e), outcome: 'error' };
|
|
612
|
+
process.stderr.write(`[forgen-auto-compound] ${phases[i]} phase: ${r.reason}\n`);
|
|
613
|
+
}
|
|
614
|
+
if (!r.ok)
|
|
615
|
+
return { remaining: phases.slice(i), fail: r };
|
|
616
|
+
}
|
|
617
|
+
return { remaining: [] };
|
|
618
|
+
}
|
|
619
|
+
const ALL_PHASES = ['solution', 'behavior', 'learning'];
|
|
620
|
+
let skipReason = null;
|
|
621
|
+
let indexFailed = false; // 인덱싱 실패 시 markRun 을 하지 않아 다음 트리거가 다시 시도한다
|
|
622
|
+
let extractedSolutionsCount = 0;
|
|
623
|
+
let promotedCount = 0;
|
|
624
|
+
const solutionsAtStart = snapshotSolutions();
|
|
625
|
+
const runStartSize = (() => { try {
|
|
626
|
+
return fs.statSync(transcriptPath).size;
|
|
627
|
+
}
|
|
628
|
+
catch {
|
|
629
|
+
return 0;
|
|
630
|
+
} })();
|
|
631
|
+
try {
|
|
632
|
+
// ── D9: 결정론 승급을 가장 먼저 — 메시지 수·요약 길이·Haiku·인젝션 게이트와 무관하게 세션당 최소 1회.
|
|
633
|
+
// 재실행은 멱등(candidate_rule_refs 소비 마커). 짧은 세션/Haiku 불가 환경에서도 교정이 룰이 된다.
|
|
634
|
+
if (!queueOnly) {
|
|
635
|
+
try {
|
|
636
|
+
promotedCount = promoteSessionCandidates(sid);
|
|
637
|
+
if (promotedCount > 0) {
|
|
638
|
+
process.stderr.write(`[forgen-auto-compound] promoted ${promotedCount} correction(s) to permanent rules\n`);
|
|
639
|
+
}
|
|
640
|
+
}
|
|
641
|
+
catch (e) {
|
|
642
|
+
process.stderr.write(`[forgen-auto-compound] rule promotion: ${e instanceof Error ? e.message : String(e)}\n`);
|
|
643
|
+
}
|
|
644
|
+
// ── D9: sessions.db 인덱싱 (증분·멱등). `claude`/`codex` 직접 실행도 여기서 기록된다.
|
|
645
|
+
try {
|
|
646
|
+
const { indexTranscript } = await import('./session-store.js');
|
|
647
|
+
const idx = await indexTranscript(cwd, transcriptPath, sid);
|
|
648
|
+
if (idx)
|
|
649
|
+
process.stderr.write(`[forgen-auto-compound] indexed +${idx.added} message(s) into sessions.db\n`);
|
|
650
|
+
else
|
|
651
|
+
indexFailed = true;
|
|
652
|
+
}
|
|
653
|
+
catch (e) {
|
|
654
|
+
indexFailed = true;
|
|
655
|
+
process.stderr.write(`[forgen-auto-compound] session index: ${e instanceof Error ? e.message : String(e)}\n`);
|
|
656
|
+
}
|
|
657
|
+
}
|
|
658
|
+
// transcript 가 같은 크기로 교체됐으면(앞부분 지문이 다름) 커서를 처음으로 되돌려 새 내용을 처음부터 읽는다.
|
|
659
|
+
const runSig = queueOnly ? '' : transcriptSignature(transcriptPath);
|
|
660
|
+
if (!queueOnly && resetIfReplaced(sid, runSig)) {
|
|
661
|
+
appendExtractionEvent({ kind: 'transcript-replaced', sessionId: sid });
|
|
662
|
+
}
|
|
663
|
+
// ── D3/D4: 새 부분만 요약해 Haiku 추출. 어떤 건너뜀이든 아래 결정론 꼬리(클러스터링·메타·GC·ROI·수명주기)는 계속 돈다.
|
|
664
|
+
let freshFailed = false;
|
|
665
|
+
if (!queueOnly) {
|
|
666
|
+
try {
|
|
667
|
+
const consent = getHaikuConsentState();
|
|
668
|
+
if (!consent.enabled)
|
|
669
|
+
throw new SkipExtraction(`haiku-disabled:${consent.source}`);
|
|
670
|
+
const cursor = getCursor(sid);
|
|
671
|
+
const digest = await digestTranscriptFile(transcriptPath, cursor);
|
|
672
|
+
if (digest.items.length === 0) {
|
|
673
|
+
setCursor(sid, digest.endOffset); // 읽을 거리가 없는 구간(도구 결과·주입뿐)은 다시 읽지 않는다
|
|
674
|
+
throw new SkipExtraction('no-new-content');
|
|
675
|
+
}
|
|
676
|
+
if (!isFinal && digest.userMessages < MIN_NEW_USER_MSGS_FOR_PARTIAL && digest.correctionCandidates === 0) {
|
|
677
|
+
throw new SkipExtraction('partial-too-small'); // 커서는 두어 다음 번에 합쳐서 처리
|
|
678
|
+
}
|
|
679
|
+
const rawSummary = renderDigest(digest);
|
|
680
|
+
if (rawSummary.length < 200)
|
|
681
|
+
throw new SkipExtraction('input-too-short');
|
|
682
|
+
// R5-G2 (P0 security): 외부 송신 전 API key / 토큰 / 비밀번호 / private key 를 [REDACTED:...] 로 치환.
|
|
683
|
+
const { redacted: redactedSummary, hits: secretHits } = redactSecrets(rawSummary);
|
|
684
|
+
if (secretHits.length > 0) {
|
|
685
|
+
process.stderr.write(`[forgen-auto-compound] redacted ${secretHits.length} secret(s) before send: ${secretHits.map((s) => s.name).join(', ')}\n`);
|
|
686
|
+
}
|
|
687
|
+
// W2-5 (private 태그): <private> 범위를 LLM 송신·behavior write 전에 제거.
|
|
688
|
+
const { cleaned: summary, hadPrivate } = stripPrivate(redactedSummary);
|
|
689
|
+
if (hadPrivate) {
|
|
690
|
+
process.stderr.write(`[forgen-auto-compound] excluded <private> range(s) before send (privacy)\n`);
|
|
691
|
+
}
|
|
692
|
+
if (summary.length < 200)
|
|
693
|
+
throw new SkipExtraction('input-too-short-after-redaction');
|
|
694
|
+
// 보안: 프롬프트 인젝션이 포함된 transcript는 분석하지 않음 (이 구간은 소비 처리 — 재시도해도 같다)
|
|
695
|
+
if (containsPromptInjection(summary)) {
|
|
696
|
+
setCursor(sid, digest.endOffset);
|
|
697
|
+
throw new SkipExtraction('prompt-injection-blocked');
|
|
698
|
+
}
|
|
699
|
+
const scanResult = filterSolutionContent(summary);
|
|
700
|
+
if (scanResult.verdict === 'block') {
|
|
701
|
+
process.stderr.write('[forgen-auto-compound] transcript blocked by injection filter\n');
|
|
702
|
+
setCursor(sid, digest.endOffset);
|
|
703
|
+
throw new SkipExtraction('injection-filter-blocked');
|
|
704
|
+
}
|
|
705
|
+
if (scanResult.verdict === 'warn') {
|
|
706
|
+
process.stderr.write(`[forgen-auto-compound] injection warning: ${scanResult.findings.map(f => f.patternId).join(', ')}\n`);
|
|
707
|
+
}
|
|
708
|
+
const sanitizedSummary = scanResult.sanitized;
|
|
709
|
+
// 호출 가능 여부(미설치·미로그인)는 호출 전에 판정 — 모델 호출 없이 `claude auth status` 로 확인.
|
|
710
|
+
if ((await import('../store/profile-store.js')).resolveDefaultHost() !== 'codex') {
|
|
711
|
+
const av = probeClaudeAvailability();
|
|
712
|
+
if (!av.available) {
|
|
713
|
+
writeHaikuStatus({ ok: false, outcome: 'unavailable', reason: av.reason });
|
|
714
|
+
throw new SkipExtraction(`haiku-unavailable:${av.reason ?? ''}`);
|
|
650
715
|
}
|
|
651
|
-
|
|
652
|
-
|
|
653
|
-
|
|
654
|
-
|
|
655
|
-
|
|
656
|
-
|
|
657
|
-
|
|
658
|
-
|
|
659
|
-
|
|
660
|
-
|
|
661
|
-
|
|
662
|
-
|
|
663
|
-
|
|
664
|
-
|
|
665
|
-
|
|
666
|
-
|
|
667
|
-
|
|
668
|
-
|
|
669
|
-
|
|
670
|
-
|
|
671
|
-
}
|
|
672
|
-
}
|
|
673
|
-
if (profile && changed) {
|
|
674
|
-
const r = saveProfileRecomputed(profile);
|
|
675
|
-
const moved = Object.entries(r.deltas).filter(([, d]) => Math.abs(d.after - d.before) > 1e-9).map(([k, d]) => `${k} ${d.before.toFixed(2)}→${d.after.toFixed(2)}`);
|
|
676
|
-
process.stderr.write(`[forgen-auto-compound] profile facets updated from session learning${moved.length ? ` (score: ${moved.join(', ')})` : ''}\n`);
|
|
677
|
-
}
|
|
716
|
+
}
|
|
717
|
+
// 같은 구간에서 이미 성공한 단계는 다시 부르지 않는다 (앞 단계만 성공하고 뒤에서 막힌 뒤 재실행되는 경우).
|
|
718
|
+
const alreadyDone = getDonePhases(sid, digest.endOffset);
|
|
719
|
+
const res = await runPhases(sanitizedSummary, ALL_PHASES.filter((ph) => !alreadyDone.includes(ph)), 0);
|
|
720
|
+
if (res.remaining.length > 0) {
|
|
721
|
+
freshFailed = true;
|
|
722
|
+
haikuError = res.fail?.reason ?? 'haiku failure';
|
|
723
|
+
if (res.fail?.retriable) {
|
|
724
|
+
// 이 구간은 마스킹된 요약째 대기열로 — 커서를 넘긴다(유실 0). 다음 세션 시작/종료에서 재시도.
|
|
725
|
+
const { dropped } = enqueue({ sessionId: sid, cwd, summary: sanitizedSummary, phases: res.remaining, error: haikuError });
|
|
726
|
+
for (const d of dropped)
|
|
727
|
+
appendExtractionEvent({ kind: 'queue-drop', sessionId: d.sessionId, reason: 'queue-limit-or-age', attempts: d.attempts });
|
|
728
|
+
setCursor(sid, digest.endOffset);
|
|
729
|
+
setDonePhases(sid, digest.endOffset, []);
|
|
730
|
+
appendExtractionEvent({ kind: 'queued', sessionId: sid, phases: res.remaining, reason: haikuError });
|
|
731
|
+
}
|
|
732
|
+
else {
|
|
733
|
+
// 미설치·미로그인: 재시도해도 같다. 커서를 두어 로그인 후 같은 구간을 처리한다.
|
|
734
|
+
skipReason = `haiku-unavailable:${haikuError}`;
|
|
735
|
+
setDonePhases(sid, digest.endOffset, ALL_PHASES.filter((ph) => !res.remaining.includes(ph)));
|
|
678
736
|
}
|
|
679
737
|
}
|
|
738
|
+
else {
|
|
739
|
+
setCursor(sid, digest.endOffset);
|
|
740
|
+
setDonePhases(sid, digest.endOffset, []);
|
|
741
|
+
}
|
|
742
|
+
}
|
|
743
|
+
catch (e) {
|
|
744
|
+
if (e instanceof SkipExtraction) {
|
|
745
|
+
skipReason = e.reason;
|
|
746
|
+
process.stderr.write(`[forgen-auto-compound] extraction skipped: ${e.reason}\n`);
|
|
747
|
+
}
|
|
748
|
+
else {
|
|
749
|
+
throw e;
|
|
750
|
+
}
|
|
680
751
|
}
|
|
681
752
|
}
|
|
682
|
-
|
|
683
|
-
|
|
753
|
+
// ── D4: 대기열 재시도 (러너 1회당 1건, 방금 새 호출이 실패했다면 건너뜀 — 같은 환경에서 또 기다리지 않는다)
|
|
754
|
+
if (!freshFailed && isHaikuCompoundEnabled() && !(skipReason ?? '').startsWith('haiku-unavailable')) {
|
|
755
|
+
try {
|
|
756
|
+
const entry = claimDue();
|
|
757
|
+
if (entry) {
|
|
758
|
+
const res = await runPhases(entry.summary, entry.phases, entry.attempts + 1, entry.sessionId);
|
|
759
|
+
const failReason = res.fail?.reason ?? 'haiku failure';
|
|
760
|
+
const retriable = res.fail ? res.fail.retriable : false;
|
|
761
|
+
const done = completeEntry(entry.id, res.remaining, res.remaining.length > 0 ? failReason : undefined); // 남은 단계는 보존(미설치여도 유실 없음), 시도 상한에서만 폐기
|
|
762
|
+
appendExtractionEvent({ kind: 'queue-retry', sessionId: entry.sessionId, attempt: entry.attempts + 1, ok: res.remaining.length === 0, remaining: res.remaining, ...(res.remaining.length > 0 ? { reason: failReason } : {}), dropped: done.dropped });
|
|
763
|
+
if (res.remaining.length > 0 && !retriable)
|
|
764
|
+
haikuError ??= failReason;
|
|
765
|
+
}
|
|
766
|
+
}
|
|
767
|
+
catch (e) {
|
|
768
|
+
process.stderr.write(`[forgen-auto-compound] queue retry: ${e instanceof Error ? e.message : String(e)}\n`);
|
|
769
|
+
}
|
|
684
770
|
}
|
|
685
|
-
//
|
|
686
|
-
|
|
687
|
-
|
|
688
|
-
|
|
689
|
-
|
|
690
|
-
|
|
771
|
+
// 처리 끝 표시 — 추출 결과가 확정된 **뒤**에만 찍는다. 동의 OFF·미로그인으로 못 넘긴 구간이 남았으면 그 사유를 함께 남겨,
|
|
772
|
+
// 켜지거나 로그인하면 같은 구간을 다시 처리하게 한다 (예전엔 추출 전에 찍어 그 구간이 영영 건너뛰어졌다).
|
|
773
|
+
if (!queueOnly && !indexFailed) {
|
|
774
|
+
try {
|
|
775
|
+
const blocked = (skipReason ?? '').startsWith('haiku-disabled') ? 'haiku-disabled'
|
|
776
|
+
: (skipReason ?? '').startsWith('haiku-unavailable') ? 'haiku-unavailable'
|
|
777
|
+
: null;
|
|
778
|
+
markRun(sid, runStartSize, { sig: runSig, blocked });
|
|
691
779
|
}
|
|
780
|
+
catch { /* 표시 실패는 다음 트리거가 다시 돈다 */ }
|
|
692
781
|
}
|
|
693
|
-
|
|
694
|
-
|
|
782
|
+
// Step 4: 추출 단계에서 새로 생긴 채굴 교정까지 포함해 한 번 더 승급(멱등).
|
|
783
|
+
if (!queueOnly) {
|
|
784
|
+
try {
|
|
785
|
+
promotedCount += promoteSessionCandidates(sid);
|
|
786
|
+
if (promotedCount > 0) {
|
|
787
|
+
process.stderr.write(`[forgen-auto-compound] promoted ${promotedCount} correction(s) to permanent rules (total this run)\n`);
|
|
788
|
+
}
|
|
789
|
+
}
|
|
790
|
+
catch (e) {
|
|
791
|
+
process.stderr.write(`[forgen-auto-compound] rule promotion: ${e instanceof Error ? e.message : String(e)}\n`);
|
|
792
|
+
}
|
|
793
|
+
}
|
|
794
|
+
if (queueOnly) {
|
|
795
|
+
appendExtractionEvent({ ok: !haikuError, queueOnly: true, ...(haikuError ? { error: haikuError.slice(0, 200) } : {}) });
|
|
796
|
+
process.exit(0);
|
|
695
797
|
}
|
|
696
798
|
// Step 4b (W3-2): 교정 클러스터링 — 같은 원칙을 N회 교정해 흩어진 룰을 1개 명명 룰로
|
|
697
799
|
// 통합하고 강도를 반복 신호(Laplace)로 승급. 승급 직후 같은 패스에서 실행. fail-open.
|
|
@@ -707,14 +809,11 @@ ${sanitizedSummary.slice(0, 4000)}
|
|
|
707
809
|
catch (e) {
|
|
708
810
|
process.stderr.write(`[forgen-auto-compound] correction clustering: ${e instanceof Error ? e.message : String(e)}\n`);
|
|
709
811
|
}
|
|
710
|
-
// H2:
|
|
711
|
-
// solutionsBefore 스냅샷 vs 현재 디스크 상태 차분 → "N개 패턴 학습됨" 1줄.
|
|
712
|
-
let extractedSolutionsCount = 0;
|
|
812
|
+
// H2: 이번 실행 전후 솔루션 차분 → Stop hook 알림용 "N개 패턴 학습됨".
|
|
713
813
|
try {
|
|
714
814
|
if (fs.existsSync(SOLUTIONS_DIR)) {
|
|
715
|
-
const
|
|
716
|
-
|
|
717
|
-
if (!solutionsBefore.has(f))
|
|
815
|
+
for (const f of fs.readdirSync(SOLUTIONS_DIR)) {
|
|
816
|
+
if (f.endsWith('.md') && !solutionsAtStart.has(f))
|
|
718
817
|
extractedSolutionsCount++;
|
|
719
818
|
}
|
|
720
819
|
}
|
|
@@ -725,7 +824,7 @@ ${sanitizedSummary.slice(0, 4000)}
|
|
|
725
824
|
// Step 5: meta-learning (HyperAgents-inspired self-tuning)
|
|
726
825
|
try {
|
|
727
826
|
const { runMetaLearning } = await import('../engine/meta-learning/runner.js');
|
|
728
|
-
const metaResult = runMetaLearning(
|
|
827
|
+
const metaResult = runMetaLearning(sid, cwd);
|
|
729
828
|
if (metaResult.qualityScore) {
|
|
730
829
|
process.stderr.write(`[forgen-meta] session quality: ${metaResult.qualityScore.overallScore}/100\n`);
|
|
731
830
|
}
|
|
@@ -797,7 +896,7 @@ ${sanitizedSummary.slice(0, 4000)}
|
|
|
797
896
|
const statePath = path.join(FORGEN_HOME, 'state', 'last-auto-compound.json');
|
|
798
897
|
fs.mkdirSync(path.dirname(statePath), { recursive: true });
|
|
799
898
|
fs.writeFileSync(statePath, JSON.stringify({
|
|
800
|
-
sessionId,
|
|
899
|
+
sessionId: sid,
|
|
801
900
|
completedAt: new Date().toISOString(),
|
|
802
901
|
extractedSolutions: extractedSolutionsCount,
|
|
803
902
|
promotedRules: promotedCount,
|
|
@@ -807,7 +906,13 @@ ${sanitizedSummary.slice(0, 4000)}
|
|
|
807
906
|
promptCount: Number(process.argv[5] ?? 0) || 0,
|
|
808
907
|
noticeShown: false,
|
|
809
908
|
}));
|
|
909
|
+
appendExtractionEvent({ ok: !haikuError, sessionId: sid, extractedSolutions: extractedSolutionsCount, promotedRules: promotedCount, ...(skipReason ? { skipped: skipReason } : {}), ...(haikuError ? { error: haikuError.slice(0, 200) } : {}) });
|
|
810
910
|
}
|
|
811
911
|
catch (e) {
|
|
812
|
-
|
|
912
|
+
const msg = e instanceof Error ? e.message : String(e);
|
|
913
|
+
process.stderr.write(`[forgen-auto-compound] ${msg}\n`);
|
|
914
|
+
try {
|
|
915
|
+
appendExtractionEvent({ ok: false, sessionId: sid, error: msg.slice(0, 200) });
|
|
916
|
+
}
|
|
917
|
+
catch { /* 기록 실패는 무시 */ }
|
|
813
918
|
}
|