@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
|
@@ -5,9 +5,8 @@
|
|
|
5
5
|
* Handles reading, merging hooks, trust policy, and atomic write.
|
|
6
6
|
*/
|
|
7
7
|
import * as fs from 'node:fs';
|
|
8
|
-
import
|
|
9
|
-
import {
|
|
10
|
-
import { getHostRuntime } from '../host/host-runtime.js';
|
|
8
|
+
import { ensureForgenRunShim } from '../host/claude-shim.js';
|
|
9
|
+
import { applyForgenSettings } from '../host/install-claude.js';
|
|
11
10
|
import { ConfigError } from './errors.js';
|
|
12
11
|
import { createLogger } from './logger.js';
|
|
13
12
|
import { acquireLock, atomicWriteFileSync, CLAUDE_DIR, readSettingsSafely, releaseLock, rollbackSettings, SETTINGS_BACKUP_PATH, SETTINGS_PATH, } from './settings-lock.js';
|
|
@@ -50,78 +49,6 @@ function readSettingsWithBackup() {
|
|
|
50
49
|
}
|
|
51
50
|
return settings;
|
|
52
51
|
}
|
|
53
|
-
/** Apply forgen statusLine only if user hasn't set a custom one.
|
|
54
|
-
* Migration: 'forgen me' → 'forgen statusline' (multi-line dump → compact HUD). */
|
|
55
|
-
function applyStatusLine(settings) {
|
|
56
|
-
const existing = settings.statusLine;
|
|
57
|
-
// 기존에 'forgen me'로 주입된 경우 → 'forgen statusline'으로 자동 마이그레이션
|
|
58
|
-
if (existing?.command === 'forgen me') {
|
|
59
|
-
settings.statusLine = { type: 'command', command: 'forgen statusline' };
|
|
60
|
-
return;
|
|
61
|
-
}
|
|
62
|
-
const isForgenOwned = !existing || !existing.command || existing.command.startsWith('forgen');
|
|
63
|
-
if (isForgenOwned) {
|
|
64
|
-
settings.statusLine = { type: 'command', command: 'forgen statusline' };
|
|
65
|
-
}
|
|
66
|
-
}
|
|
67
|
-
/** Check if a settings.json hook entry was installed by forgen. */
|
|
68
|
-
function isForgenHookEntry(entry, pkgRoot) {
|
|
69
|
-
const distHooksPath = path.join(pkgRoot, 'dist', 'hooks');
|
|
70
|
-
const matchesPath = (cmd) => cmd.includes(distHooksPath) || /[\\/]dist[\\/]hooks[\\/].*\.js/.test(cmd);
|
|
71
|
-
if (typeof entry.command === 'string' && matchesPath(entry.command))
|
|
72
|
-
return true;
|
|
73
|
-
const hooks = entry.hooks;
|
|
74
|
-
return (Array.isArray(hooks) &&
|
|
75
|
-
hooks.some((h) => typeof h.command === 'string' && matchesPath(h.command)));
|
|
76
|
-
}
|
|
77
|
-
/** Strip existing forgen hooks from settings, merge fresh hooks.json. */
|
|
78
|
-
function mergeHooksIntoSettings(settings, runtime, cwd, pkgRoot) {
|
|
79
|
-
const hooksConfig = settings.hooks ?? {};
|
|
80
|
-
// Remove existing forgen hooks (clean slate before re-inject)
|
|
81
|
-
for (const [event, entries] of Object.entries(hooksConfig)) {
|
|
82
|
-
if (!Array.isArray(entries))
|
|
83
|
-
continue;
|
|
84
|
-
const filtered = entries.filter((h) => !isForgenHookEntry(h, pkgRoot));
|
|
85
|
-
if (filtered.length === 0)
|
|
86
|
-
delete hooksConfig[event];
|
|
87
|
-
else
|
|
88
|
-
hooksConfig[event] = filtered;
|
|
89
|
-
}
|
|
90
|
-
try {
|
|
91
|
-
const host = getHostRuntime(runtime);
|
|
92
|
-
if (host.hookInjectionStrategy === 'generate') {
|
|
93
|
-
const generated = generateHooksJson({ cwd, runtime, pluginRoot: path.join(pkgRoot, 'dist') });
|
|
94
|
-
for (const [event, handlers] of Object.entries(generated.hooks)) {
|
|
95
|
-
if (!hooksConfig[event])
|
|
96
|
-
hooksConfig[event] = [];
|
|
97
|
-
hooksConfig[event].push(...handlers);
|
|
98
|
-
}
|
|
99
|
-
}
|
|
100
|
-
else {
|
|
101
|
-
// 'pre-baked-file': pkgRoot/hooks/hooks.json 읽고 ${CLAUDE_PLUGIN_ROOT} 치환
|
|
102
|
-
const hooksJsonPath = path.join(pkgRoot, 'hooks', 'hooks.json');
|
|
103
|
-
if (fs.existsSync(hooksJsonPath)) {
|
|
104
|
-
const hooksJson = JSON.parse(fs.readFileSync(hooksJsonPath, 'utf-8'));
|
|
105
|
-
const hooksData = hooksJson.hooks;
|
|
106
|
-
if (hooksData) {
|
|
107
|
-
const resolved = JSON.parse(JSON.stringify(hooksData).replace(/\$\{CLAUDE_PLUGIN_ROOT\}/g, pkgRoot));
|
|
108
|
-
for (const [event, handlers] of Object.entries(resolved)) {
|
|
109
|
-
if (!hooksConfig[event])
|
|
110
|
-
hooksConfig[event] = [];
|
|
111
|
-
hooksConfig[event].push(...handlers);
|
|
112
|
-
}
|
|
113
|
-
}
|
|
114
|
-
}
|
|
115
|
-
}
|
|
116
|
-
}
|
|
117
|
-
catch (e) {
|
|
118
|
-
log.debug('hooks.json 로드 실패', e);
|
|
119
|
-
}
|
|
120
|
-
settings.hooks = Object.keys(hooksConfig).length > 0 ? hooksConfig : undefined;
|
|
121
|
-
if (settings.hooks && Object.keys(settings.hooks).length === 0) {
|
|
122
|
-
delete settings.hooks;
|
|
123
|
-
}
|
|
124
|
-
}
|
|
125
52
|
/** Apply v1 trust policy → permissions (deny/ask lists). */
|
|
126
53
|
export function applyTrustPolicyPermissions(settings, v1Result) {
|
|
127
54
|
if (!v1Result.session)
|
|
@@ -147,23 +74,29 @@ export function applyTrustPolicyPermissions(settings, v1Result) {
|
|
|
147
74
|
}
|
|
148
75
|
/**
|
|
149
76
|
* Inject forgen settings into Claude Code settings.json.
|
|
150
|
-
* Coordinates: read/backup →
|
|
77
|
+
* Coordinates: read/backup → shim → hooks/statusLine (install-claude 와 같은 함수) → trust policy → atomic write.
|
|
78
|
+
*
|
|
79
|
+
* 세션 env(FORGEN_CWD 등)는 settings.json 에 쓰지 않는다 — 래퍼가 자식 프로세스 env 로 넘긴다(spawn.ts).
|
|
80
|
+
* 이전 버전이 남긴 FORGEN_* env 는 applyForgenSettings 가 지운다. 내용이 바뀐 경우에만 쓴다.
|
|
151
81
|
*/
|
|
152
|
-
export function injectSettings(
|
|
82
|
+
export function injectSettings(_env, v1Result, _runtime, _cwd, pkgRoot) {
|
|
153
83
|
fs.mkdirSync(CLAUDE_DIR, { recursive: true });
|
|
154
84
|
acquireLock();
|
|
155
|
-
const settings = readSettingsWithBackup();
|
|
156
|
-
// Merge env vars
|
|
157
|
-
settings.env = { ...(settings.env ?? {}), ...env };
|
|
158
|
-
applyStatusLine(settings);
|
|
159
|
-
mergeHooksIntoSettings(settings, runtime, cwd, pkgRoot);
|
|
160
|
-
applyTrustPolicyPermissions(settings, v1Result);
|
|
161
85
|
try {
|
|
162
|
-
|
|
163
|
-
|
|
164
|
-
|
|
165
|
-
|
|
166
|
-
|
|
86
|
+
const settings = readSettingsWithBackup();
|
|
87
|
+
const before = JSON.stringify(settings);
|
|
88
|
+
const shim = ensureForgenRunShim(pkgRoot);
|
|
89
|
+
applyForgenSettings(settings, pkgRoot, shim.path);
|
|
90
|
+
applyTrustPolicyPermissions(settings, v1Result);
|
|
91
|
+
if (JSON.stringify(settings) !== before || !fs.existsSync(SETTINGS_PATH)) {
|
|
92
|
+
try {
|
|
93
|
+
atomicWriteFileSync(SETTINGS_PATH, JSON.stringify(settings, null, 2));
|
|
94
|
+
}
|
|
95
|
+
catch (err) {
|
|
96
|
+
rollbackSettings();
|
|
97
|
+
throw err;
|
|
98
|
+
}
|
|
99
|
+
}
|
|
167
100
|
}
|
|
168
101
|
finally {
|
|
169
102
|
releaseLock();
|
package/dist/core/spawn.d.ts
CHANGED
|
@@ -16,6 +16,12 @@ import type { RuntimeHost } from './types.js';
|
|
|
16
16
|
* 단일 함수에서 둘 다 처리 — schema 자동 감지.
|
|
17
17
|
*/
|
|
18
18
|
export declare function countUserMessages(transcriptPath: string): Promise<number>;
|
|
19
|
+
/**
|
|
20
|
+
* Observability P2: commit-diff acted_on signal.
|
|
21
|
+
* 세션 시작 이후 생성된 commit 들의 diff 를 scan 하여 surfaced 솔루션과 키워드 매칭.
|
|
22
|
+
* 프라이버시: commit sha 는 SHA1 해시 12char prefix 만 저장, diff/path 내용 미저장.
|
|
23
|
+
*/
|
|
24
|
+
export declare function scanCommitDiffForActedOn(sessionId: string, cwd: string, sessionStartTime: number): Promise<void>;
|
|
19
25
|
/** runAutoCompound 결과 — sweep(무인 cron)이 실제 spawn 만 기록하도록 상태 반환. */
|
|
20
26
|
export type AutoCompoundStatus = 'spawned' | 'skipped-inflight' | 'skipped-dedup' | 'failed';
|
|
21
27
|
/**
|
|
@@ -48,7 +54,9 @@ export declare function releaseAutoCompoundInflight(sessionId: string): void;
|
|
|
48
54
|
* 로그로 남긴다 — 다음 실패 모드를 디버그 가능하게 만드는 전제 조건.
|
|
49
55
|
*/
|
|
50
56
|
export declare function autoCompoundLogPath(sessionId: string): string;
|
|
51
|
-
export declare function runAutoCompound(cwd: string, transcriptPath: string, sessionId: string, promptCount?: number
|
|
57
|
+
export declare function runAutoCompound(cwd: string, transcriptPath: string, sessionId: string, promptCount?: number,
|
|
58
|
+
/** 세션 종료/이전 세션 복구 경로 — 새 내용이 적어도 Haiku 추출을 돌린다 (러너 6번째 인자). */
|
|
59
|
+
final?: boolean): AutoCompoundStatus;
|
|
52
60
|
/**
|
|
53
61
|
* Plan B-1: 세션 transcript 사후 스캔으로 rate-limit 감지.
|
|
54
62
|
*
|
package/dist/core/spawn.js
CHANGED
|
@@ -7,11 +7,14 @@ import { fileURLToPath } from 'node:url';
|
|
|
7
7
|
import { buildEnv } from './config-injector.js';
|
|
8
8
|
import { loadGlobalConfig } from './global-config.js';
|
|
9
9
|
import { createLogger } from './logger.js';
|
|
10
|
-
import { STATE_DIR
|
|
10
|
+
import { STATE_DIR } from './paths.js';
|
|
11
|
+
import { defaultSolutionDirs } from '../engine/solution-index.js';
|
|
11
12
|
import { getHostRuntime } from '../host/host-runtime.js';
|
|
12
13
|
import { sendNotification } from './notify.js';
|
|
13
14
|
import { querySurfacedWithin, emitSolutionEvent } from './observability-store.js';
|
|
14
15
|
import { parseSolutionV3 } from '../engine/solution-format.js';
|
|
16
|
+
import { actedOnEvidence } from '../engine/acted-on-evidence.js';
|
|
17
|
+
import { sessionNeedsRun, transcriptSignature, RUNNER_LOCK_TTL_MS } from './extraction-queue.js';
|
|
15
18
|
const log = createLogger('spawn');
|
|
16
19
|
/** Phase 2: host-runtime 어댑터 위임. */
|
|
17
20
|
function findRuntimeLauncher(runtime) {
|
|
@@ -147,7 +150,7 @@ export async function countUserMessages(transcriptPath) {
|
|
|
147
150
|
* 세션 시작 이후 생성된 commit 들의 diff 를 scan 하여 surfaced 솔루션과 키워드 매칭.
|
|
148
151
|
* 프라이버시: commit sha 는 SHA1 해시 12char prefix 만 저장, diff/path 내용 미저장.
|
|
149
152
|
*/
|
|
150
|
-
async function scanCommitDiffForActedOn(sessionId, cwd, sessionStartTime) {
|
|
153
|
+
export async function scanCommitDiffForActedOn(sessionId, cwd, sessionStartTime) {
|
|
151
154
|
try {
|
|
152
155
|
const surfaces = querySurfacedWithin(sessionId, 30); // 30분 window
|
|
153
156
|
if (surfaces.length === 0)
|
|
@@ -176,14 +179,14 @@ async function scanCommitDiffForActedOn(sessionId, cwd, sessionStartTime) {
|
|
|
176
179
|
catch {
|
|
177
180
|
continue;
|
|
178
181
|
}
|
|
179
|
-
const
|
|
182
|
+
const addedLines = diff.split('\n').filter((l) => l.startsWith('+') && !l.startsWith('+++')).join('\n');
|
|
180
183
|
const shaHash = crypto.createHash('sha1').update(sha).digest('hex').slice(0, 12);
|
|
181
184
|
for (const surf of surfaces) {
|
|
182
185
|
const dedupKey = `${shaHash}:${surf.solutionId}`;
|
|
183
186
|
if (seen.has(dedupKey))
|
|
184
187
|
continue;
|
|
185
|
-
const filePath = path.join(
|
|
186
|
-
if (!
|
|
188
|
+
const filePath = defaultSolutionDirs(cwd).map((d) => path.join(d.dir, `${surf.solutionId}.md`)).find((f) => fs.existsSync(f));
|
|
189
|
+
if (!filePath)
|
|
187
190
|
continue;
|
|
188
191
|
let raw;
|
|
189
192
|
try {
|
|
@@ -199,9 +202,9 @@ async function scanCommitDiffForActedOn(sessionId, cwd, sessionStartTime) {
|
|
|
199
202
|
const identifiers = sol.frontmatter.identifiers ?? [];
|
|
200
203
|
if (tags.length === 0 && identifiers.length === 0)
|
|
201
204
|
continue;
|
|
202
|
-
|
|
203
|
-
|
|
204
|
-
if (!
|
|
205
|
+
// 추가된 줄(+)만 본다 — 삭제된 코드·커밋 메시지·맥락 줄에 우연히 있는 단어는 행동의 증거가 아니다. 기준은 acted-on-evidence.ts.
|
|
206
|
+
const ev = actedOnEvidence({ tags, identifiers }, addedLines);
|
|
207
|
+
if (!ev.ok)
|
|
205
208
|
continue;
|
|
206
209
|
seen.add(dedupKey);
|
|
207
210
|
emitSolutionEvent({
|
|
@@ -210,7 +213,7 @@ async function scanCommitDiffForActedOn(sessionId, cwd, sessionStartTime) {
|
|
|
210
213
|
eventType: 'acted_on',
|
|
211
214
|
signalSource: 'commit-diff',
|
|
212
215
|
signalScore: 0.30,
|
|
213
|
-
meta: { commit_sha_hash: shaHash, surface_ts: surf.ts },
|
|
216
|
+
meta: { commit_sha_hash: shaHash, surface_ts: surf.ts, evidence: ev.hits.slice(0, 4) },
|
|
214
217
|
});
|
|
215
218
|
}
|
|
216
219
|
}
|
|
@@ -223,12 +226,12 @@ async function scanCommitDiffForActedOn(sessionId, cwd, sessionStartTime) {
|
|
|
223
226
|
* 세션 종료 후 자동 compound 추출 + USER.md 업데이트.
|
|
224
227
|
* auto-compound-runner.ts를 동기 실행하여 솔루션 추출 + 사용자 패턴 관찰.
|
|
225
228
|
*/
|
|
226
|
-
//
|
|
227
|
-
|
|
228
|
-
//
|
|
229
|
+
// per-session in-flight start-gate TTL — 러너 최악 소요보다 길어야 한다. 러너는 호출당 120s 타임아웃으로 새 구간 3단계 + 대기열
|
|
230
|
+
// 재시도 3단계(최대 12분)에 후처리까지 돌 수 있어 예전 10분은 최악보다 짧았다(표식이 만료된 사이 두 번째 러너가 뜸).
|
|
231
|
+
// 러너 락과 같은 30분으로 맞추고, 러너는 종료 시 표식을 직접 푼다. ADR-011 리뷰 SEV-1:
|
|
229
232
|
// 완료-게이트 단일슬롯 마커는 sweep↔Stop 훅 / 다중세션 double-spawn 을 못 막는다.
|
|
230
233
|
// 세션별 start-gate 로 spawn 전에 표식해 이중실행(중복 Haiku 과금)을 차단.
|
|
231
|
-
const AUTO_COMPOUND_INFLIGHT_TTL_MS =
|
|
234
|
+
const AUTO_COMPOUND_INFLIGHT_TTL_MS = RUNNER_LOCK_TTL_MS; // 30min
|
|
232
235
|
/** 세션별 in-flight 마커 경로 (파일명 안전화). */
|
|
233
236
|
function inflightPathFor(sessionId) {
|
|
234
237
|
return path.join(STATE_DIR, 'compound-inflight', `${sessionId.replace(/[^a-zA-Z0-9_-]/g, '_')}.json`);
|
|
@@ -312,21 +315,22 @@ export function releaseAutoCompoundInflight(sessionId) {
|
|
|
312
315
|
export function autoCompoundLogPath(sessionId) {
|
|
313
316
|
return path.join(STATE_DIR, 'auto-compound', `${sessionId.replace(/[^a-zA-Z0-9_-]/g, '_')}.log`);
|
|
314
317
|
}
|
|
315
|
-
export function runAutoCompound(cwd, transcriptPath, sessionId, promptCount = 0
|
|
318
|
+
export function runAutoCompound(cwd, transcriptPath, sessionId, promptCount = 0,
|
|
319
|
+
/** 세션 종료/이전 세션 복구 경로 — 새 내용이 적어도 Haiku 추출을 돌린다 (러너 6번째 인자). */
|
|
320
|
+
final = false) {
|
|
321
|
+
if (process.env.FORGEN_DOCTOR_PROBE === '1')
|
|
322
|
+
return 'skipped-dedup'; // doctor 프로브는 스폰 금지
|
|
316
323
|
const now = Date.now();
|
|
317
|
-
// 1.
|
|
324
|
+
// 1. 같은 세션을 이미 처리했고 transcript 가 그 뒤로 자라지 않았으면 건너뜀 (D9: 크기 기반 멱등).
|
|
325
|
+
// 예전엔 "5분 이내 완료"만 보아 마지막 교정이 5분 안에 들어오면 종료 시 승급이 누락됐다.
|
|
318
326
|
try {
|
|
319
|
-
|
|
320
|
-
|
|
321
|
-
|
|
322
|
-
if (Number.isFinite(last) && now - last < AUTO_COMPOUND_DEDUP_COOLDOWN_MS) {
|
|
323
|
-
log.debug('auto-compound skip: 최근 동일 세션 run 존재 (dedup)');
|
|
324
|
-
return 'skipped-dedup';
|
|
325
|
-
}
|
|
327
|
+
if (!sessionNeedsRun(sessionId, fs.statSync(transcriptPath).size, { sig: transcriptSignature(transcriptPath) })) {
|
|
328
|
+
log.debug('auto-compound skip: 마지막 실행 이후 transcript 변화 없음 (dedup)');
|
|
329
|
+
return 'skipped-dedup';
|
|
326
330
|
}
|
|
327
331
|
}
|
|
328
332
|
catch {
|
|
329
|
-
/*
|
|
333
|
+
/* 이력 없음/stat 실패 — 진행 (fail-open). */
|
|
330
334
|
}
|
|
331
335
|
// 2. per-session in-flight start-gate (공유 헬퍼).
|
|
332
336
|
if (!claimAutoCompoundInflight(sessionId, now)) {
|
|
@@ -350,7 +354,7 @@ export function runAutoCompound(cwd, transcriptPath, sessionId, promptCount = 0)
|
|
|
350
354
|
// cron sparse PATH 의 /bin/node 로 해석돼 러너의 process.execPath 가 달라지고,
|
|
351
355
|
// 러너가 forgen(nvm 형제 바이너리)을 절대경로로 못 찾아 solution write 가 ENOENT 로
|
|
352
356
|
// 실패한다. execPath 를 물려주면 러너가 sweep 과 같은 node(=forgen 형제)를 상속한다.
|
|
353
|
-
const child = spawn(process.execPath, [runnerPath, cwd, transcriptPath, sessionId, String(promptCount)], {
|
|
357
|
+
const child = spawn(process.execPath, [runnerPath, cwd, transcriptPath, sessionId, String(promptCount), ...(final ? ['final'] : [])], {
|
|
354
358
|
cwd,
|
|
355
359
|
detached: true,
|
|
356
360
|
stdio: logFd !== undefined ? ['ignore', logFd, logFd] : 'ignore',
|
|
@@ -358,7 +362,8 @@ export function runAutoCompound(cwd, transcriptPath, sessionId, promptCount = 0)
|
|
|
358
362
|
child.unref();
|
|
359
363
|
if (logFd !== undefined)
|
|
360
364
|
fs.closeSync(logFd); // child가 dup — 부모 측 fd는 닫아도 안전
|
|
361
|
-
|
|
365
|
+
// stderr: pre-compact/session-end hook 의 stdout 은 JSON 1개여야 한다 (H10) — 안내는 stderr 로.
|
|
366
|
+
process.stderr.write('\n[forgen] 세션 분석을 백그라운드로 시작했습니다 (자동 compound) — 결과는 다음 세션 시작 시 반영됩니다.\n');
|
|
362
367
|
return 'spawned';
|
|
363
368
|
}
|
|
364
369
|
catch (e) {
|
|
@@ -547,14 +552,9 @@ export async function spawnClaude(args, context, runtime = 'claude') {
|
|
|
547
552
|
}
|
|
548
553
|
// 3. Observability P2: commit-diff acted_on scan
|
|
549
554
|
await scanCommitDiffForActedOn(sessionId, context.cwd, sessionStartTime);
|
|
550
|
-
// 4. 자동 compound
|
|
551
|
-
|
|
552
|
-
|
|
553
|
-
runAutoCompound(context.cwd, transcript, sessionId);
|
|
554
|
-
}
|
|
555
|
-
else {
|
|
556
|
-
console.log(`[forgen] 세션이 짧아 auto-compound 생략 (${userMsgCount} messages)`);
|
|
557
|
-
}
|
|
555
|
+
// 4. 자동 compound — D9: 길이와 무관하게 러너를 돌린다(교정 승급·인덱싱은 짧은 세션에도 필요).
|
|
556
|
+
// Haiku 추출 여부는 러너가 새 내용의 양으로 판단한다.
|
|
557
|
+
runAutoCompound(context.cwd, transcript, sessionId, 0, true);
|
|
558
558
|
}
|
|
559
559
|
}
|
|
560
560
|
catch (e) {
|
package/dist/core/stats-cli.d.ts
CHANGED
|
@@ -1,8 +1,14 @@
|
|
|
1
1
|
export interface StatsSnapshot {
|
|
2
2
|
activeRules: number;
|
|
3
3
|
suppressedRules: number;
|
|
4
|
+
/** 사용자가 직접 한 교정 (hook 기록) */
|
|
4
5
|
correctionsTotal: number;
|
|
5
6
|
corrections7d: number;
|
|
7
|
+
/** Haiku 채굴 추론 — 사용자 발화가 아님 */
|
|
8
|
+
minedTotal: number;
|
|
9
|
+
mined7d: number;
|
|
10
|
+
/** 읽기 실패·깨진 파일 경고 (0건과 구분) */
|
|
11
|
+
readErrors: string[];
|
|
6
12
|
blocks7d: number;
|
|
7
13
|
/** ADR-017 §2 원칙 1: 집계에서 제외된 합성 세션(default/unknown) 기록 수 — 누락을 가시화. */
|
|
8
14
|
syntheticExcluded7d: number;
|
|
@@ -20,6 +26,7 @@ export interface StatsSnapshot {
|
|
|
20
26
|
recallMcp: number;
|
|
21
27
|
surfaced: number;
|
|
22
28
|
referenced: number;
|
|
29
|
+
/** 오늘 새로 저장된 솔루션·룰 (흐름의 "저장"과 같은 정의) */
|
|
23
30
|
extractedToday: number;
|
|
24
31
|
};
|
|
25
32
|
philosophy?: {
|
package/dist/core/stats-cli.js
CHANGED
|
@@ -7,8 +7,8 @@
|
|
|
7
7
|
*/
|
|
8
8
|
import * as fs from 'node:fs';
|
|
9
9
|
import * as path from 'node:path';
|
|
10
|
-
import { loadAllRules } from '../store/rule-store.js';
|
|
11
|
-
import {
|
|
10
|
+
import { loadAllRules, scanRuleFiles } from '../store/rule-store.js';
|
|
11
|
+
import { readEvidenceCounts, readSavedTimes, countSince, formatLastExtraction, unreadable, haikuStatus, isInjectedRecall, logFilesWithRotated } from './flow-status.js';
|
|
12
12
|
import { STATE_DIR, ME_DIR } from './paths.js';
|
|
13
13
|
import { readJsonlWindow, isRealBlock, isConfirmedBypass, isSyntheticEntry, precisionByRule, readVerdicts } from '../engine/lifecycle/signals.js';
|
|
14
14
|
import { computeFixFeatRatio, formatFixRatio } from './git-stats.js';
|
|
@@ -34,6 +34,10 @@ function readJsonl(p) {
|
|
|
34
34
|
}
|
|
35
35
|
return out;
|
|
36
36
|
}
|
|
37
|
+
/** 회전본(.1/.2/타임스탬프)까지 이어 읽는다. */
|
|
38
|
+
function readJsonlRotated(p) {
|
|
39
|
+
return logFilesWithRotated(p).flatMap((f) => readJsonl(f));
|
|
40
|
+
}
|
|
37
41
|
function countWithin(entries, days, tsKey = 'at') {
|
|
38
42
|
const cutoff = Date.now() - days * MS_PER_DAY;
|
|
39
43
|
let n = 0;
|
|
@@ -66,38 +70,6 @@ function readLifecycleRetired(days) {
|
|
|
66
70
|
}
|
|
67
71
|
return n;
|
|
68
72
|
}
|
|
69
|
-
function readLastExtraction() {
|
|
70
|
-
// v0.4.1 파일명 정합: auto-compound-runner 는 last-auto-compound.json 에 기록.
|
|
71
|
-
// 이전 코드가 last-extraction.json 을 찾아 "never" 가 만성적으로 표시됨 —
|
|
72
|
-
// 실은 매 auto-compound 세션마다 값이 업데이트되고 있는데도 stats 에 반영 X.
|
|
73
|
-
const candidates = ['last-auto-compound.json', 'last-extraction.json'];
|
|
74
|
-
let p = null;
|
|
75
|
-
for (const name of candidates) {
|
|
76
|
-
const candidate = path.join(STATE_DIR, name);
|
|
77
|
-
if (fs.existsSync(candidate)) {
|
|
78
|
-
p = candidate;
|
|
79
|
-
break;
|
|
80
|
-
}
|
|
81
|
-
}
|
|
82
|
-
if (!p)
|
|
83
|
-
return 'never';
|
|
84
|
-
try {
|
|
85
|
-
const data = JSON.parse(fs.readFileSync(p, 'utf-8'));
|
|
86
|
-
const ts = data.completedAt ?? data.timestamp ?? data.date;
|
|
87
|
-
if (!ts)
|
|
88
|
-
return 'never';
|
|
89
|
-
const diffDays = Math.floor((Date.now() - Date.parse(ts)) / MS_PER_DAY);
|
|
90
|
-
const dateStr = new Date(ts).toISOString().slice(0, 10);
|
|
91
|
-
if (diffDays === 0)
|
|
92
|
-
return `${dateStr} (today)`;
|
|
93
|
-
if (diffDays === 1)
|
|
94
|
-
return `${dateStr} (yesterday)`;
|
|
95
|
-
return `${dateStr} (${diffDays}d ago)`;
|
|
96
|
-
}
|
|
97
|
-
catch {
|
|
98
|
-
return 'unknown';
|
|
99
|
-
}
|
|
100
|
-
}
|
|
101
73
|
/** H3: 오늘 (local midnight ~ now) 기준 assist 카운트. */
|
|
102
74
|
function computeAssistToday() {
|
|
103
75
|
const startOfDay = new Date();
|
|
@@ -106,7 +78,7 @@ function computeAssistToday() {
|
|
|
106
78
|
// ADR-017 §1.5a: 이전엔 match-eval-log 의 오늘 entry 수 전체를 "Recall hits" 로 셌다 —
|
|
107
79
|
// 후보 0건·mcp 쿼리·vitest 픽스처(7d 773건 중 351건)까지 포함돼 "25회 recall 에 0 surfaced"
|
|
108
80
|
// 라는 틀린 그림을 만들었다. hit = source:hook 이고 후보 ≥1. attempts = hook 전체.
|
|
109
|
-
const matchLog =
|
|
81
|
+
const matchLog = readJsonlRotated(path.join(STATE_DIR, 'match-eval-log.jsonl'));
|
|
110
82
|
let recallHits = 0;
|
|
111
83
|
let recallAttempts = 0;
|
|
112
84
|
let recallMcp = 0;
|
|
@@ -121,7 +93,7 @@ function computeAssistToday() {
|
|
|
121
93
|
if (e.source !== 'hook')
|
|
122
94
|
continue;
|
|
123
95
|
recallAttempts++;
|
|
124
|
-
if (
|
|
96
|
+
if (isInjectedRecall(e))
|
|
125
97
|
recallHits++;
|
|
126
98
|
}
|
|
127
99
|
// surfaced + referenced — 같은 스트림 1회 loop 로.
|
|
@@ -137,20 +109,8 @@ function computeAssistToday() {
|
|
|
137
109
|
else if (e.type === 'recall_referenced')
|
|
138
110
|
referenced++;
|
|
139
111
|
}
|
|
140
|
-
// extracted today:
|
|
141
|
-
|
|
142
|
-
try {
|
|
143
|
-
if (fs.existsSync(SOLUTIONS_DIR)) {
|
|
144
|
-
for (const f of fs.readdirSync(SOLUTIONS_DIR)) {
|
|
145
|
-
if (!f.endsWith('.md'))
|
|
146
|
-
continue;
|
|
147
|
-
const stat = fs.statSync(path.join(SOLUTIONS_DIR, f));
|
|
148
|
-
if (stat.mtimeMs >= cutoffMs)
|
|
149
|
-
extractedToday++;
|
|
150
|
-
}
|
|
151
|
-
}
|
|
152
|
-
}
|
|
153
|
-
catch { /* fail-open */ }
|
|
112
|
+
// extracted today: 솔루션 frontmatter created 기준 (mtime 은 touch·cp 로 바뀐다)
|
|
113
|
+
const extractedToday = readSavedTimes().times.filter((t) => t >= cutoffMs).length;
|
|
154
114
|
return { recallHits, recallAttempts, recallMcp, surfaced, referenced, extractedToday };
|
|
155
115
|
}
|
|
156
116
|
/** v0.4.1: forge-profile 에서 고도화 지표 추출. 파일 없거나 깨지면 undefined. */
|
|
@@ -177,17 +137,27 @@ function computePhilosophy() {
|
|
|
177
137
|
}
|
|
178
138
|
}
|
|
179
139
|
export function computeStats() {
|
|
180
|
-
const
|
|
140
|
+
const ruleScan = scanRuleFiles();
|
|
141
|
+
const rules = ruleScan.dirError ? [] : loadAllRules();
|
|
181
142
|
const activeRules = rules.filter((r) => r.status === 'active').length;
|
|
182
143
|
const suppressedRules = rules.filter((r) => r.status === 'suppressed').length;
|
|
183
|
-
//
|
|
184
|
-
//
|
|
185
|
-
|
|
186
|
-
const
|
|
187
|
-
const
|
|
188
|
-
const
|
|
189
|
-
const
|
|
190
|
-
const
|
|
144
|
+
// 교정은 출처별로 분리: 사용자가 직접 한 것(hook)과 Haiku 채굴 추론(auto-compound-miner).
|
|
145
|
+
// 합쳐서 "Corrections 271" 로 표시하면 실제 사용자 교정 39건이 묻힌다.
|
|
146
|
+
const evidence = readEvidenceCounts();
|
|
147
|
+
const correctionsTotal = evidence.user.times.length;
|
|
148
|
+
const corrections7d = countSince(evidence.user.times, 7);
|
|
149
|
+
const minedTotal = evidence.mined.times.length;
|
|
150
|
+
const mined7d = countSince(evidence.mined.times, 7);
|
|
151
|
+
const readErrors = [];
|
|
152
|
+
if (evidence.user.error)
|
|
153
|
+
readErrors.push(`behavior 디렉터리: ${evidence.user.error}`);
|
|
154
|
+
const stateErr = unreadable(ENFORCEMENT_DIR);
|
|
155
|
+
if (stateErr)
|
|
156
|
+
readErrors.push(`state/enforcement: ${stateErr}`);
|
|
157
|
+
if (ruleScan.dirError)
|
|
158
|
+
readErrors.push(`룰 디렉터리: ${ruleScan.dirError}`);
|
|
159
|
+
if (ruleScan.broken.length > 0)
|
|
160
|
+
readErrors.push(`깨진 룰 파일 ${ruleScan.broken.length}개 (${ruleScan.broken.slice(0, 2).map((b) => b.file).join(', ')}${ruleScan.broken.length > 2 ? ' …' : ''}) — 룰 수에 포함되지 않음`);
|
|
191
161
|
const violations = readJsonlWindow(path.join(ENFORCEMENT_DIR, 'violations.jsonl'), 30);
|
|
192
162
|
// v0.4.1 historical false-positive 제거: pre-0.4.1 bypass-detector 가 Write/Edit
|
|
193
163
|
// content 의 quote 본문까지 raw 매칭해서 bypass 로 오기록. 실 관찰: L1-no-rm-rf
|
|
@@ -209,13 +179,16 @@ export function computeStats() {
|
|
|
209
179
|
suppressedRules,
|
|
210
180
|
correctionsTotal,
|
|
211
181
|
corrections7d,
|
|
182
|
+
minedTotal,
|
|
183
|
+
mined7d,
|
|
184
|
+
readErrors,
|
|
212
185
|
blocks7d: countWithin(realBlocks, 7),
|
|
213
186
|
syntheticExcluded7d: countWithin(violations.filter((e) => isSyntheticEntry(e)), 7),
|
|
214
187
|
acks7d: countWithin(acks, 7),
|
|
215
188
|
bypass7d: countWithin(bypass, 7),
|
|
216
189
|
drift7d: countWithin(drift, 7),
|
|
217
190
|
retired7d: readLifecycleRetired(7),
|
|
218
|
-
lastExtraction:
|
|
191
|
+
lastExtraction: formatLastExtraction(),
|
|
219
192
|
assistToday: computeAssistToday(),
|
|
220
193
|
philosophy: computePhilosophy(),
|
|
221
194
|
solutionHealth: computeSolutionHealth(),
|
|
@@ -249,7 +222,7 @@ function computeSolutionHealth() {
|
|
|
249
222
|
}
|
|
250
223
|
catch { /* fail-open */ }
|
|
251
224
|
const cutoff7d = Date.now() - 7 * MS_PER_DAY;
|
|
252
|
-
const matchLog =
|
|
225
|
+
const matchLog = readJsonlRotated(path.join(STATE_DIR, 'match-eval-log.jsonl'));
|
|
253
226
|
const matchedLocalNames = new Set();
|
|
254
227
|
for (const e of matchLog) {
|
|
255
228
|
const ts = typeof e.ts === 'string' ? Date.parse(e.ts) : NaN;
|
|
@@ -311,34 +284,27 @@ function computeWeeklyTrend(violations) {
|
|
|
311
284
|
if (Number.isFinite(ts) && ts >= lastWeekStart && ts < thisWeekStart)
|
|
312
285
|
blocksLastWeek++;
|
|
313
286
|
}
|
|
314
|
-
const matchLog =
|
|
287
|
+
const matchLog = readJsonlRotated(path.join(STATE_DIR, 'match-eval-log.jsonl'));
|
|
315
288
|
let recallsThisWeek = 0;
|
|
316
289
|
let recallsLastWeek = 0;
|
|
317
290
|
for (const e of matchLog) {
|
|
318
291
|
const ts = typeof e.ts === 'string' ? Date.parse(e.ts) : NaN;
|
|
319
|
-
if (!Number.isFinite(ts))
|
|
320
|
-
continue;
|
|
292
|
+
if (!Number.isFinite(ts) || !isInjectedRecall(e))
|
|
293
|
+
continue; // 흐름의 "주입"·Today 의 Recall hits 와 같은 정의
|
|
321
294
|
if (ts >= thisWeekStart)
|
|
322
295
|
recallsThisWeek++;
|
|
323
296
|
else if (ts >= lastWeekStart)
|
|
324
297
|
recallsLastWeek++;
|
|
325
298
|
}
|
|
299
|
+
// 저장 수: 흐름의 "저장"과 같은 정의 — 솔루션 created + 룰 created_at (파일 mtime 아님)
|
|
326
300
|
let extractionsThisWeek = 0;
|
|
327
301
|
let extractionsLastWeek = 0;
|
|
328
|
-
|
|
329
|
-
if (
|
|
330
|
-
|
|
331
|
-
|
|
332
|
-
|
|
333
|
-
const mtime = fs.statSync(path.join(SOLUTIONS_DIR, f)).mtimeMs;
|
|
334
|
-
if (mtime >= thisWeekStart)
|
|
335
|
-
extractionsThisWeek++;
|
|
336
|
-
else if (mtime >= lastWeekStart)
|
|
337
|
-
extractionsLastWeek++;
|
|
338
|
-
}
|
|
339
|
-
}
|
|
302
|
+
for (const t of readSavedTimes().times) {
|
|
303
|
+
if (t >= thisWeekStart)
|
|
304
|
+
extractionsThisWeek++;
|
|
305
|
+
else if (t >= lastWeekStart)
|
|
306
|
+
extractionsLastWeek++;
|
|
340
307
|
}
|
|
341
|
-
catch { /* fail-open */ }
|
|
342
308
|
return { blocksThisWeek, blocksLastWeek, recallsThisWeek, recallsLastWeek, extractionsThisWeek, extractionsLastWeek };
|
|
343
309
|
}
|
|
344
310
|
function padNum(n, width = 4) {
|
|
@@ -350,14 +316,15 @@ export function renderStats(s) {
|
|
|
350
316
|
lines.push(' forgen — trust layer status');
|
|
351
317
|
lines.push(' ───────────────────────────');
|
|
352
318
|
lines.push(` Active rules ${padNum(s.activeRules)} (${s.suppressedRules} suppressed)`);
|
|
353
|
-
lines.push(` Corrections (
|
|
319
|
+
lines.push(` Corrections (you) ${padNum(s.correctionsTotal)} (+${s.corrections7d} last 7d) — 당신이 직접 한 교정`);
|
|
320
|
+
lines.push(` Mined (Haiku) ${padNum(s.minedTotal)} (+${s.mined7d} last 7d) — 대화에서 추론한 후보, 당신의 발화 아님`);
|
|
321
|
+
for (const e of s.readErrors)
|
|
322
|
+
lines.push(` ⚠ 읽기 문제: ${e}`);
|
|
354
323
|
lines.push('');
|
|
355
324
|
lines.push(' Last 7 days');
|
|
356
325
|
// R9-PA2: ack rate = block→retract→pass 루프가 실제 작동한 비율.
|
|
357
|
-
|
|
358
|
-
|
|
359
|
-
: '';
|
|
360
|
-
lines.push(` Blocks ${padNum(s.blocks7d)} — times Claude was asked to retract ${ackRateLabel}`);
|
|
326
|
+
// ack/block 비율은 서로 다른 로그를 나눈 값이라 의미가 없어 표시하지 않는다 (건수만).
|
|
327
|
+
lines.push(` Blocks ${padNum(s.blocks7d)} — times Claude was asked to retract`);
|
|
361
328
|
lines.push(` Acknowledgments ${padNum(s.acks7d)} — block → retract → pass loops`);
|
|
362
329
|
lines.push(` Bypass (confirmed) ${padNum(s.bypass7d)} — FORGEN_USER_CONFIRMED=1 overrides (audited)`);
|
|
363
330
|
if (s.syntheticExcluded7d > 0)
|
|
@@ -369,11 +336,8 @@ export function renderStats(s) {
|
|
|
369
336
|
lines.push(' Today (assist)');
|
|
370
337
|
lines.push(` Recall hits ${padNum(s.assistToday.recallHits)} — 후보가 나온 recall (hook 시도 ${s.assistToday.recallAttempts} · mcp ${s.assistToday.recallMcp})`);
|
|
371
338
|
lines.push(` Surfaced ${padNum(s.assistToday.surfaced)} — 실제 주입된 솔루션 수`);
|
|
372
|
-
|
|
373
|
-
|
|
374
|
-
: '';
|
|
375
|
-
lines.push(` Referenced ${padNum(s.assistToday.referenced)} — Claude 응답에 인용됨${ratio}`);
|
|
376
|
-
lines.push(` Extracted ${padNum(s.assistToday.extractedToday)} — 오늘 새로 저장된 패턴`);
|
|
339
|
+
lines.push(` Referenced ${padNum(s.assistToday.referenced)} — Claude 응답에 인용됨`);
|
|
340
|
+
lines.push(` Saved ${padNum(s.assistToday.extractedToday)} — 오늘 새로 저장된 솔루션·룰 (흐름의 저장과 같은 기준)`);
|
|
377
341
|
lines.push('');
|
|
378
342
|
// v0.4.1 철학 고도화 단면 — "개인화가 어디까지 학습됐나" 1섹션.
|
|
379
343
|
if (s.philosophy) {
|
|
@@ -406,13 +370,18 @@ export function renderStats(s) {
|
|
|
406
370
|
lines.push(' Solutions');
|
|
407
371
|
lines.push(` Total ${padNum(sh.total)} ${statusParts}`);
|
|
408
372
|
lines.push(` Avg confidence ${sh.avgConfidence.toFixed(2)}`);
|
|
409
|
-
lines.push(`
|
|
373
|
+
lines.push(` Matched (7d) ${padNum(Math.round(sh.utilization7d * sh.total))} — 최근 7일에 한 번이라도 매칭된 솔루션 (전체 ${sh.total})`);
|
|
410
374
|
lines.push('');
|
|
411
375
|
}
|
|
412
376
|
// v0.5.0: Top rules (7d) + ADR-017 D1 precision
|
|
413
377
|
if (s.topRules7d.length > 0) {
|
|
414
378
|
lines.push(' Top rules (7d) precision (judged / unjudged)');
|
|
415
|
-
const adviseRules = new Set(
|
|
379
|
+
const adviseRules = new Set((() => { try {
|
|
380
|
+
return loadAllRules();
|
|
381
|
+
}
|
|
382
|
+
catch {
|
|
383
|
+
return [];
|
|
384
|
+
} })().filter((r) => r.enforce_mode === 'advise').map((r) => r.rule_id));
|
|
416
385
|
const pmap = new Map(s.precision7d.map((p) => [p.rule_id, p]));
|
|
417
386
|
for (const r of s.topRules7d) {
|
|
418
387
|
const p = pmap.get(r.name);
|
|
@@ -421,8 +390,12 @@ export function renderStats(s) {
|
|
|
421
390
|
lines.push(` ${padNum(r.count)}x ${r.name.padEnd(28).slice(0, 28)}${prec}${advise}`);
|
|
422
391
|
}
|
|
423
392
|
const unjudged = s.precision7d.reduce((n, p) => n + p.unjudged, 0);
|
|
424
|
-
if (unjudged > 0)
|
|
425
|
-
|
|
393
|
+
if (unjudged > 0) {
|
|
394
|
+
const h = haikuStatus();
|
|
395
|
+
const how = h.state === 'off' ? '자동 판정(Haiku)이 꺼져 있어 사람이 판정해야 합니다: forgen block <id> --ok|--fp'
|
|
396
|
+
: h.state === 'on' ? '자동 판정 대기 중' : `자동 판정 불가 (${h.detail})`;
|
|
397
|
+
lines.push(` ${C_DIM}unjudged ${unjudged} — ${how}${C_RESET}`);
|
|
398
|
+
}
|
|
426
399
|
lines.push('');
|
|
427
400
|
}
|
|
428
401
|
// v0.5.0: Weekly trend
|
|
@@ -436,8 +409,8 @@ export function renderStats(s) {
|
|
|
436
409
|
};
|
|
437
410
|
lines.push(' Weekly trend (this vs last)');
|
|
438
411
|
lines.push(` Blocks ${padNum(wt.blocksThisWeek)} → ${padNum(wt.blocksLastWeek, 2)} prev (${trendArrow(wt.blocksThisWeek, wt.blocksLastWeek)})`);
|
|
439
|
-
lines.push(`
|
|
440
|
-
lines.push(`
|
|
412
|
+
lines.push(` Recall hits ${padNum(wt.recallsThisWeek)} → ${padNum(wt.recallsLastWeek, 2)} prev (${trendArrow(wt.recallsThisWeek, wt.recallsLastWeek)})`);
|
|
413
|
+
lines.push(` Saved ${padNum(wt.extractionsThisWeek)} → ${padNum(wt.extractionsLastWeek, 2)} prev (${trendArrow(wt.extractionsThisWeek, wt.extractionsLastWeek)})`);
|
|
441
414
|
lines.push('');
|
|
442
415
|
lines.push(` Last extraction: ${s.lastExtraction}`);
|
|
443
416
|
lines.push('');
|
|
@@ -6,7 +6,7 @@
|
|
|
6
6
|
* 통합해 표면을 줄이고 진입점을 일원화한다. 기존 render/compute 함수는 재사용만
|
|
7
7
|
* 하고 재작성하지 않는다.
|
|
8
8
|
*
|
|
9
|
-
* forgen status 요약 (
|
|
9
|
+
* forgen status 요약 (학습 흐름 6단계 + one-screen stats)
|
|
10
10
|
* forgen status --compound compound 상태 + 최근 회상 이력
|
|
11
11
|
* forgen status --profile 4축 프로필 + 최근 교정
|
|
12
12
|
* forgen status --rules 활성 룰
|