@wooojin/forgen 0.6.5 → 0.6.6
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 +26 -0
- package/README.ja.md +1 -1
- package/README.ko.md +1 -1
- package/README.md +1 -1
- package/README.zh.md +1 -1
- package/dist/cli.js +2 -2
- package/dist/core/block-cli.js +2 -4
- package/dist/core/dashboard.js +1 -1
- package/dist/core/explain-cli.js +3 -28
- package/dist/core/rate-limit-forecast.js +7 -1
- package/dist/core/state-gc.d.ts +14 -0
- package/dist/core/state-gc.js +47 -4
- package/dist/core/stats-cli.js +5 -5
- package/dist/core/statusline-cli.d.ts +24 -2
- package/dist/core/statusline-cli.js +125 -23
- package/dist/core/statusline-install.d.ts +8 -1
- package/dist/core/statusline-install.js +34 -3
- package/dist/engine/block-judge.js +4 -5
- package/dist/engine/context-signals.d.ts +20 -0
- package/dist/engine/context-signals.js +102 -0
- package/dist/engine/correction-cluster-runner.d.ts +3 -3
- package/dist/engine/correction-cluster-runner.js +48 -12
- package/dist/engine/correction-clustering.d.ts +27 -0
- package/dist/engine/correction-clustering.js +79 -3
- package/dist/engine/ko-colloquial.d.ts +13 -0
- package/dist/engine/ko-colloquial.js +45 -0
- package/dist/engine/lifecycle/lifecycle-cli.js +25 -5
- package/dist/engine/lifecycle/meta-reclassifier.d.ts +1 -0
- package/dist/engine/lifecycle/meta-reclassifier.js +3 -21
- package/dist/engine/lifecycle/rotated-logs.d.ts +18 -0
- package/dist/engine/lifecycle/rotated-logs.js +67 -0
- package/dist/engine/lifecycle/signals.d.ts +27 -1
- package/dist/engine/lifecycle/signals.js +55 -32
- package/dist/engine/lifecycle/types.d.ts +5 -0
- package/dist/engine/match-eval-log.d.ts +2 -0
- package/dist/engine/match-eval-log.js +1 -0
- package/dist/engine/ranking-pipeline.d.ts +9 -1
- package/dist/engine/ranking-pipeline.js +24 -2
- package/dist/engine/solution-format.d.ts +2 -0
- package/dist/engine/solution-format.js +6 -2
- package/dist/engine/solution-matcher.d.ts +5 -1
- package/dist/engine/solution-matcher.js +4 -2
- package/dist/hooks/solution-injector.js +7 -2
- package/dist/store/rule-store.d.ts +10 -0
- package/dist/store/rule-store.js +26 -2
- package/package.json +1 -1
- package/plugin.json +1 -1
- package/scripts/postinstall.js +6 -2
|
@@ -5,9 +5,9 @@
|
|
|
5
5
|
* default dry-run, --apply 시 rule 파일에 상태 전이 반영.
|
|
6
6
|
*/
|
|
7
7
|
import * as path from 'node:path';
|
|
8
|
-
import { loadAllRules, saveRule } from '../../store/rule-store.js';
|
|
8
|
+
import { loadAllRules, saveRule, syncRuleCounters } from '../../store/rule-store.js';
|
|
9
9
|
import { STATE_DIR } from '../../core/paths.js';
|
|
10
|
-
import { collectSignals,
|
|
10
|
+
import { collectSignals, deriveRuleCounters, readViolationsWindow, ROTATED_KEEP_DAYS, isConfirmedBypass, isSyntheticEntry } from './signals.js';
|
|
11
11
|
import { detect as detectT2 } from './trigger-t2-violation.js';
|
|
12
12
|
import { detect as detectT3 } from './trigger-t3-bypass.js';
|
|
13
13
|
import { detect as detectT4 } from './trigger-t4-decay.js';
|
|
@@ -23,11 +23,12 @@ export async function handleLifecycleScan(args) {
|
|
|
23
23
|
console.log('\n No rules in ~/.forgen/me/rules. Nothing to scan.\n');
|
|
24
24
|
return;
|
|
25
25
|
}
|
|
26
|
-
|
|
26
|
+
// 현재 파일 + 30일 창 안의 회전본 (rotateIfBig 직후에도 창 기록이 사라지지 않게).
|
|
27
|
+
const violations = readViolationsWindow(30, now);
|
|
27
28
|
// ADR-017 D1: bypass.jsonl(자연어 휴리스틱, 전량 오탐)은 더 이상 읽지 않는다. T3 입력은
|
|
28
29
|
// violations 의 kind:'bypass_confirmed'(사용자 명시 우회) 뿐이며 collectSignals 가 거기서 뽑는다.
|
|
29
30
|
const bypassConfirmed = violations.filter(isConfirmedBypass).length;
|
|
30
|
-
const syntheticExcluded = violations.filter((v) =>
|
|
31
|
+
const syntheticExcluded = violations.filter((v) => isSyntheticEntry(v)).length;
|
|
31
32
|
const drift = readDriftEntries();
|
|
32
33
|
const signals = new Map();
|
|
33
34
|
for (const r of rules)
|
|
@@ -42,8 +43,26 @@ export async function handleLifecycleScan(args) {
|
|
|
42
43
|
const promotionCandidates = scanSignalsForPromotion({ rules, signals, ts: now });
|
|
43
44
|
console.log(`\n Lifecycle Scan — ${rules.length} rule(s) (${apply ? 'APPLY' : 'dry-run'})\n`);
|
|
44
45
|
console.log(` Signals: violations.jsonl=${violations.length} (synthetic-session excluded ${syntheticExcluded}) bypass_confirmed=${bypassConfirmed} drift.jsonl=${drift.length}\n`);
|
|
46
|
+
// 카운터 재계산 — 룰 JSON 의 violation_count/bypass_count 는 훅 경로가 갱신하지 않는 캐시라
|
|
47
|
+
// 로그(보존 범위 전체, 회전본 포함)에서 다시 계산한다. dry-run 은 차이만 보여준다.
|
|
48
|
+
const counters = deriveRuleCounters(readViolationsWindow(ROTATED_KEEP_DAYS, now));
|
|
49
|
+
const counterDiffs = rules.filter((r) => {
|
|
50
|
+
const c = counters.get(r.rule_id);
|
|
51
|
+
return (r.lifecycle?.violation_count ?? 0) !== (c?.violation_count ?? 0) || (r.lifecycle?.bypass_count ?? 0) !== (c?.bypass_count ?? 0);
|
|
52
|
+
});
|
|
53
|
+
console.log(` Counters: ${counterDiffs.length} rule(s) differ from logs (violation_count/bypass_count)${apply ? '' : ' — --apply 로 동기화'}\n`);
|
|
54
|
+
// Meta apply 가 원본 rule 객체로 다시 저장하므로 카운터 동기화는 항상 마지막에 한다.
|
|
55
|
+
const applyCounters = () => {
|
|
56
|
+
let n = 0;
|
|
57
|
+
for (const r of counterDiffs)
|
|
58
|
+
if (syncRuleCounters(r.rule_id, counters.get(r.rule_id) ?? { violation_count: 0, bypass_count: 0 }))
|
|
59
|
+
n++;
|
|
60
|
+
return n;
|
|
61
|
+
};
|
|
45
62
|
if (events.length === 0 && demotionCandidates.length === 0 && promotionCandidates.length === 0) {
|
|
46
63
|
console.log(' No lifecycle events. System stable.\n');
|
|
64
|
+
if (apply)
|
|
65
|
+
console.log(` Counters synced: ${applyCounters()} rule(s).\n`);
|
|
47
66
|
return;
|
|
48
67
|
}
|
|
49
68
|
console.log(` Rule health events: ${events.length}`);
|
|
@@ -100,6 +119,7 @@ export async function handleLifecycleScan(args) {
|
|
|
100
119
|
}
|
|
101
120
|
if (metaEvents.length > 0)
|
|
102
121
|
appendLifecycleEvents(metaEvents, now);
|
|
103
|
-
|
|
122
|
+
const countersSynced = applyCounters();
|
|
123
|
+
console.log(`\n Applied: ${saved} rule(s) updated, ${metaEvents.length} health event(s), ${countersSynced} counter sync(s).`);
|
|
104
124
|
console.log(` Log: ${LIFECYCLE_DIR}/${new Date(now).toISOString().slice(0, 10)}.jsonl\n`);
|
|
105
125
|
}
|
|
@@ -35,6 +35,7 @@ export interface DemotionCandidate {
|
|
|
35
35
|
window_days: number;
|
|
36
36
|
current_mechs: EnforcementMech[];
|
|
37
37
|
}
|
|
38
|
+
/** drift.jsonl 현재 파일 + 30일 창 안의 회전본. */
|
|
38
39
|
export declare function readDriftEntries(driftPath?: string): DriftEntry[];
|
|
39
40
|
export declare function scanDriftForDemotion(options?: {
|
|
40
41
|
rules: Rule[];
|
|
@@ -20,6 +20,7 @@ import * as path from 'node:path';
|
|
|
20
20
|
import { initLifecycle } from '../../store/rule-lifecycle.js';
|
|
21
21
|
import { loadAllRules, saveRule } from '../../store/rule-store.js';
|
|
22
22
|
import { STATE_DIR } from '../../core/paths.js';
|
|
23
|
+
import { readJsonlWindow } from './rotated-logs.js';
|
|
23
24
|
const DRIFT_LOG_PATH = path.join(STATE_DIR, 'enforcement', 'drift.jsonl');
|
|
24
25
|
const LIFECYCLE_DIR = path.join(STATE_DIR, 'lifecycle');
|
|
25
26
|
const DEFAULT_WINDOW_DAYS = 7;
|
|
@@ -37,28 +38,9 @@ function isRecentlyClassified(rule, nowMs, cooldownMs) {
|
|
|
37
38
|
return false;
|
|
38
39
|
return nowMs - lastMs < cooldownMs;
|
|
39
40
|
}
|
|
41
|
+
/** drift.jsonl 현재 파일 + 30일 창 안의 회전본. */
|
|
40
42
|
export function readDriftEntries(driftPath = DRIFT_LOG_PATH) {
|
|
41
|
-
|
|
42
|
-
return [];
|
|
43
|
-
try {
|
|
44
|
-
const raw = fs.readFileSync(driftPath, 'utf-8');
|
|
45
|
-
return raw
|
|
46
|
-
.trim()
|
|
47
|
-
.split('\n')
|
|
48
|
-
.filter(Boolean)
|
|
49
|
-
.map((line) => {
|
|
50
|
-
try {
|
|
51
|
-
return JSON.parse(line);
|
|
52
|
-
}
|
|
53
|
-
catch {
|
|
54
|
-
return null;
|
|
55
|
-
}
|
|
56
|
-
})
|
|
57
|
-
.filter((e) => e !== null);
|
|
58
|
-
}
|
|
59
|
-
catch {
|
|
60
|
-
return [];
|
|
61
|
-
}
|
|
43
|
+
return readJsonlWindow(driftPath, 30);
|
|
62
44
|
}
|
|
63
45
|
export function scanDriftForDemotion(options = { rules: [] }) {
|
|
64
46
|
const windowDays = options.windowDays ?? DEFAULT_WINDOW_DAYS;
|
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
/** 회전본 보존 상한 — state-gc 가 적용. 개수 3개 + 60일 중 먼저 닿는 쪽. */
|
|
2
|
+
export declare const ROTATED_KEEP_MAX = 3;
|
|
3
|
+
export declare const ROTATED_KEEP_DAYS = 60;
|
|
4
|
+
export interface RotatedFile {
|
|
5
|
+
path: string;
|
|
6
|
+
mtimeMs: number;
|
|
7
|
+
size: number;
|
|
8
|
+
}
|
|
9
|
+
/** `<p>.<timestamp>` 회전본을 mtime 오름차순(오래된 것 먼저)으로 나열. */
|
|
10
|
+
export declare function listRotated(p: string): RotatedFile[];
|
|
11
|
+
/**
|
|
12
|
+
* 최근 `days` 일 창을 덮는 로그 파일 경로들(오래된 순, 현재 파일이 마지막).
|
|
13
|
+
* 회전본은 mtime(=마지막 append≈회전 시각)이 창 안일 때만 포함 — 창 밖 회전본은 창 안 기록이 없다.
|
|
14
|
+
*/
|
|
15
|
+
export declare function logFilesWithin(p: string, days: number, now?: number): string[];
|
|
16
|
+
/** 현재 파일 + 창 안 회전본을 이어 읽는다. 창 기반 리더(stats/explain/lifecycle/statusline)의 공용 진입점. */
|
|
17
|
+
export declare function readJsonlWindow<T>(p: string, days: number, now?: number): T[];
|
|
18
|
+
export declare function readJsonlSafe<T>(p: string): T[];
|
|
@@ -0,0 +1,67 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* rotateIfBig 회전본(`<file>.<timestamp>`) 나열 — fs/path 만 쓰는 경량 모듈 (state-gc 등이 signals 의 무거운 import 없이 사용).
|
|
3
|
+
*/
|
|
4
|
+
import * as fs from 'node:fs';
|
|
5
|
+
import * as path from 'node:path';
|
|
6
|
+
/** 회전본 접미사: rotateIfBig 가 붙이는 `Date.now()` 밀리초 타임스탬프. */
|
|
7
|
+
const ROTATED_SUFFIX_RE = /^\d{10,}$/;
|
|
8
|
+
/** 회전본 보존 상한 — state-gc 가 적용. 개수 3개 + 60일 중 먼저 닿는 쪽. */
|
|
9
|
+
export const ROTATED_KEEP_MAX = 3;
|
|
10
|
+
export const ROTATED_KEEP_DAYS = 60;
|
|
11
|
+
/** `<p>.<timestamp>` 회전본을 mtime 오름차순(오래된 것 먼저)으로 나열. */
|
|
12
|
+
export function listRotated(p) {
|
|
13
|
+
const dir = path.dirname(p);
|
|
14
|
+
const base = `${path.basename(p)}.`;
|
|
15
|
+
const out = [];
|
|
16
|
+
try {
|
|
17
|
+
for (const name of fs.readdirSync(dir)) {
|
|
18
|
+
if (!name.startsWith(base) || !ROTATED_SUFFIX_RE.test(name.slice(base.length)))
|
|
19
|
+
continue;
|
|
20
|
+
const full = path.join(dir, name);
|
|
21
|
+
try {
|
|
22
|
+
const st = fs.statSync(full);
|
|
23
|
+
if (st.isFile())
|
|
24
|
+
out.push({ path: full, mtimeMs: st.mtimeMs, size: st.size });
|
|
25
|
+
}
|
|
26
|
+
catch { /* raced away */ }
|
|
27
|
+
}
|
|
28
|
+
}
|
|
29
|
+
catch { /* dir missing */ }
|
|
30
|
+
return out.sort((a, b) => a.mtimeMs - b.mtimeMs);
|
|
31
|
+
}
|
|
32
|
+
/**
|
|
33
|
+
* 최근 `days` 일 창을 덮는 로그 파일 경로들(오래된 순, 현재 파일이 마지막).
|
|
34
|
+
* 회전본은 mtime(=마지막 append≈회전 시각)이 창 안일 때만 포함 — 창 밖 회전본은 창 안 기록이 없다.
|
|
35
|
+
*/
|
|
36
|
+
export function logFilesWithin(p, days, now = Date.now()) {
|
|
37
|
+
const cutoff = now - days * 24 * 3600 * 1000;
|
|
38
|
+
const files = listRotated(p).filter((r) => r.mtimeMs >= cutoff).map((r) => r.path);
|
|
39
|
+
files.push(p);
|
|
40
|
+
return files;
|
|
41
|
+
}
|
|
42
|
+
/** 현재 파일 + 창 안 회전본을 이어 읽는다. 창 기반 리더(stats/explain/lifecycle/statusline)의 공용 진입점. */
|
|
43
|
+
export function readJsonlWindow(p, days, now = Date.now()) {
|
|
44
|
+
return logFilesWithin(p, days, now).flatMap((f) => readJsonlSafe(f));
|
|
45
|
+
}
|
|
46
|
+
export function readJsonlSafe(p) {
|
|
47
|
+
if (!fs.existsSync(p))
|
|
48
|
+
return [];
|
|
49
|
+
try {
|
|
50
|
+
return fs.readFileSync(p, 'utf-8')
|
|
51
|
+
.trim()
|
|
52
|
+
.split('\n')
|
|
53
|
+
.filter(Boolean)
|
|
54
|
+
.map((line) => {
|
|
55
|
+
try {
|
|
56
|
+
return JSON.parse(line);
|
|
57
|
+
}
|
|
58
|
+
catch {
|
|
59
|
+
return null;
|
|
60
|
+
}
|
|
61
|
+
})
|
|
62
|
+
.filter((e) => e !== null);
|
|
63
|
+
}
|
|
64
|
+
catch {
|
|
65
|
+
return [];
|
|
66
|
+
}
|
|
67
|
+
}
|
|
@@ -16,6 +16,9 @@ import type { Rule } from '../../store/types.js';
|
|
|
16
16
|
*/
|
|
17
17
|
export declare function redactForReceipt(text: string): string;
|
|
18
18
|
import type { RuleSignals, ViolationEntry, BypassEntry, VerdictEntry, CheckEntry } from './types.js';
|
|
19
|
+
import { listRotated, logFilesWithin, readJsonlSafe, readJsonlWindow, ROTATED_KEEP_MAX, ROTATED_KEEP_DAYS } from './rotated-logs.js';
|
|
20
|
+
export { listRotated, logFilesWithin, readJsonlSafe, readJsonlWindow, ROTATED_KEEP_MAX, ROTATED_KEEP_DAYS };
|
|
21
|
+
export type { RotatedFile } from './rotated-logs.js';
|
|
19
22
|
/**
|
|
20
23
|
* Best-effort size-based rotation. When `p` exceeds 10MB, renames to
|
|
21
24
|
* `<p>.<timestamp>` so the next write starts fresh. Missing file or rename
|
|
@@ -24,7 +27,6 @@ import type { RuleSignals, ViolationEntry, BypassEntry, VerdictEntry, CheckEntry
|
|
|
24
27
|
* this file (drift.jsonl, acknowledgments.jsonl) reuse the same policy.
|
|
25
28
|
*/
|
|
26
29
|
export declare function rotateIfBig(p: string): void;
|
|
27
|
-
export declare function readJsonlSafe<T>(p: string): T[];
|
|
28
30
|
/**
|
|
29
31
|
* ADR-017 §2 원칙 2: 훅이 session_id 없이 호출되면 'default'/'unknown' 폴백이 기록된다.
|
|
30
32
|
* 실세션(Claude·Codex 모두 session_id 전달)에서는 나오지 않으며, 실측상 전부 테스트가
|
|
@@ -32,16 +34,27 @@ export declare function readJsonlSafe<T>(p: string): T[];
|
|
|
32
34
|
*/
|
|
33
35
|
export declare const SYNTHETIC_SESSION_IDS: ReadonlySet<string>;
|
|
34
36
|
export declare function isSyntheticSession(sessionId: unknown): boolean;
|
|
37
|
+
/** FORGEN_SYNTHETIC=1 (eval/probe 러너가 설정) 이면 기록에 synthetic:true 를 붙인다. */
|
|
38
|
+
export declare function syntheticStamp(): {
|
|
39
|
+
synthetic?: true;
|
|
40
|
+
};
|
|
41
|
+
/** 엔트리 단위 합성 판정: 명시적 synthetic 플래그 또는 합성 세션 id. */
|
|
42
|
+
export declare function isSyntheticEntry(e: {
|
|
43
|
+
synthetic?: unknown;
|
|
44
|
+
session_id?: unknown;
|
|
45
|
+
}): boolean;
|
|
35
46
|
/** 사용자 관점의 "차단": block/deny (+legacy undefined). correction/bypass_confirmed 는 아님. */
|
|
36
47
|
export declare function isBlockKind(kind: unknown): boolean;
|
|
37
48
|
/** 실세션에서 일어난 실제 차단만. stats/explain/lifecycle 이 공유하는 단일 기준. */
|
|
38
49
|
export declare function isRealBlock(e: {
|
|
39
50
|
kind?: unknown;
|
|
40
51
|
session_id?: unknown;
|
|
52
|
+
synthetic?: unknown;
|
|
41
53
|
}): boolean;
|
|
42
54
|
export declare function isConfirmedBypass(e: {
|
|
43
55
|
kind?: unknown;
|
|
44
56
|
session_id?: unknown;
|
|
57
|
+
synthetic?: unknown;
|
|
45
58
|
}): boolean;
|
|
46
59
|
export declare const RECEIPT_TTL_MS: number;
|
|
47
60
|
export declare const MATCHED_MAX = 160;
|
|
@@ -54,9 +67,12 @@ export interface RecordViolationOptions {
|
|
|
54
67
|
* 마스킹 후 전문을 24h TTL 영수증으로 남긴다(로그엔 hash 만). 실패해도 예외 없이 '' 반환.
|
|
55
68
|
*/
|
|
56
69
|
export declare function recordViolation(entry: Omit<ViolationEntry, 'at'>, opts?: RecordViolationOptions): string;
|
|
70
|
+
/** 위반 로그(현재 + 창 안 회전본). 기본 30일 = collectSignals 창. */
|
|
71
|
+
export declare function readViolationsWindow(days?: number, now?: number): ViolationEntry[];
|
|
57
72
|
export declare function readReceipt(violationId: string): string | null;
|
|
58
73
|
/** 판정 기록(append-only). 같은 violation_id 에 여러 줄이면 마지막이 유효하되 user > auto. */
|
|
59
74
|
export declare function setVerdict(entry: Omit<VerdictEntry, 'at'>): void;
|
|
75
|
+
/** 판정은 위반 이후에 기록되므로 30일 창(위반 조회 최대 창)이면 충분하다. */
|
|
60
76
|
export declare function readVerdicts(): VerdictEntry[];
|
|
61
77
|
/** violation_id → 유효 판정 (user 가 있으면 user, 없으면 마지막 auto). */
|
|
62
78
|
export declare function effectiveVerdicts(verdicts?: VerdictEntry[]): Map<string, VerdictEntry>;
|
|
@@ -84,4 +100,14 @@ export interface SignalInputs {
|
|
|
84
100
|
now?: number;
|
|
85
101
|
}
|
|
86
102
|
export declare function collectSignals(rule: Rule, inputs?: SignalInputs): RuleSignals;
|
|
103
|
+
/**
|
|
104
|
+
* 룰별 위반/우회 카운터를 로그에서 재계산 (lifecycle-scan --apply 가 룰 JSON 에 저장).
|
|
105
|
+
* 원천은 항상 로그다 — 룰 JSON 의 violation_count/bypass_count 는 이 값의 캐시일 뿐이며
|
|
106
|
+
* 보존된 로그 범위(회전본 포함) 안의 합계다. 훅 경로에서는 갱신하지 않는다.
|
|
107
|
+
*/
|
|
108
|
+
export declare function deriveRuleCounters(violations: ViolationEntry[]): Map<string, {
|
|
109
|
+
violation_count: number;
|
|
110
|
+
bypass_count: number;
|
|
111
|
+
last_violation_at?: string;
|
|
112
|
+
}>;
|
|
87
113
|
export declare function collectAllSignals(rules: Rule[], inputs?: SignalInputs): Map<string, RuleSignals>;
|
|
@@ -29,6 +29,8 @@ export function redactForReceipt(text) {
|
|
|
29
29
|
t = t.replace(/(:\/\/[^\s/:@]+:)[^\s/@]+(@)/g, '$1[REDACTED]$2');
|
|
30
30
|
return t;
|
|
31
31
|
}
|
|
32
|
+
import { listRotated, logFilesWithin, readJsonlSafe, readJsonlWindow, ROTATED_KEEP_MAX, ROTATED_KEEP_DAYS } from './rotated-logs.js';
|
|
33
|
+
export { listRotated, logFilesWithin, readJsonlSafe, readJsonlWindow, ROTATED_KEEP_MAX, ROTATED_KEEP_DAYS };
|
|
32
34
|
import { STATE_DIR as FORGEN_STATE_DIR } from '../../core/paths.js';
|
|
33
35
|
const ENFORCEMENT_DIR = path.join(FORGEN_STATE_DIR, 'enforcement');
|
|
34
36
|
const VIOLATIONS_PATH = path.join(ENFORCEMENT_DIR, 'violations.jsonl');
|
|
@@ -54,36 +56,28 @@ export function rotateIfBig(p) {
|
|
|
54
56
|
}
|
|
55
57
|
catch { /* missing → no rotate */ }
|
|
56
58
|
}
|
|
57
|
-
export function readJsonlSafe(p) {
|
|
58
|
-
if (!fs.existsSync(p))
|
|
59
|
-
return [];
|
|
60
|
-
try {
|
|
61
|
-
return fs.readFileSync(p, 'utf-8')
|
|
62
|
-
.trim()
|
|
63
|
-
.split('\n')
|
|
64
|
-
.filter(Boolean)
|
|
65
|
-
.map((line) => {
|
|
66
|
-
try {
|
|
67
|
-
return JSON.parse(line);
|
|
68
|
-
}
|
|
69
|
-
catch {
|
|
70
|
-
return null;
|
|
71
|
-
}
|
|
72
|
-
})
|
|
73
|
-
.filter((e) => e !== null);
|
|
74
|
-
}
|
|
75
|
-
catch {
|
|
76
|
-
return [];
|
|
77
|
-
}
|
|
78
|
-
}
|
|
79
59
|
/**
|
|
80
60
|
* ADR-017 §2 원칙 2: 훅이 session_id 없이 호출되면 'default'/'unknown' 폴백이 기록된다.
|
|
81
61
|
* 실세션(Claude·Codex 모두 session_id 전달)에서는 나오지 않으며, 실측상 전부 테스트가
|
|
82
62
|
* dist 훅을 spawn 한 흔적이었다(7d 차단 108건 중 78건). 모든 집계에서 제외한다.
|
|
83
63
|
*/
|
|
84
64
|
export const SYNTHETIC_SESSION_IDS = new Set(['default', 'unknown', '']);
|
|
65
|
+
/**
|
|
66
|
+
* 실 Claude Code(session_id) · Codex(thread id)는 전부 UUID 형식이다. eval/probe 하네스가 쓰는
|
|
67
|
+
* 'forgen-eval-<ts>-<rand>', 'repro-*', 'enforce-test' 등 임의 문자열은 UUID 가 아니므로 합성으로 본다.
|
|
68
|
+
* (실 ~/.forgen 데이터 검증: 비-default 세션 중 UUID 는 실세션 전부, 비-UUID 는 하네스 41건뿐.)
|
|
69
|
+
*/
|
|
70
|
+
const UUID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
|
|
85
71
|
export function isSyntheticSession(sessionId) {
|
|
86
|
-
return typeof sessionId !== 'string' || SYNTHETIC_SESSION_IDS.has(sessionId);
|
|
72
|
+
return typeof sessionId !== 'string' || SYNTHETIC_SESSION_IDS.has(sessionId) || !UUID_RE.test(sessionId);
|
|
73
|
+
}
|
|
74
|
+
/** FORGEN_SYNTHETIC=1 (eval/probe 러너가 설정) 이면 기록에 synthetic:true 를 붙인다. */
|
|
75
|
+
export function syntheticStamp() {
|
|
76
|
+
return process.env.FORGEN_SYNTHETIC === '1' ? { synthetic: true } : {};
|
|
77
|
+
}
|
|
78
|
+
/** 엔트리 단위 합성 판정: 명시적 synthetic 플래그 또는 합성 세션 id. */
|
|
79
|
+
export function isSyntheticEntry(e) {
|
|
80
|
+
return e.synthetic === true || isSyntheticSession(e.session_id);
|
|
87
81
|
}
|
|
88
82
|
/** 사용자 관점의 "차단": block/deny (+legacy undefined). correction/bypass_confirmed 는 아님. */
|
|
89
83
|
export function isBlockKind(kind) {
|
|
@@ -91,10 +85,10 @@ export function isBlockKind(kind) {
|
|
|
91
85
|
}
|
|
92
86
|
/** 실세션에서 일어난 실제 차단만. stats/explain/lifecycle 이 공유하는 단일 기준. */
|
|
93
87
|
export function isRealBlock(e) {
|
|
94
|
-
return isBlockKind(e.kind) && !
|
|
88
|
+
return isBlockKind(e.kind) && !isSyntheticEntry(e);
|
|
95
89
|
}
|
|
96
90
|
export function isConfirmedBypass(e) {
|
|
97
|
-
return e.kind === 'bypass_confirmed' && !
|
|
91
|
+
return e.kind === 'bypass_confirmed' && !isSyntheticEntry(e);
|
|
98
92
|
}
|
|
99
93
|
const RECEIPTS_DIR = path.join(ENFORCEMENT_DIR, 'receipts');
|
|
100
94
|
const VERDICTS_PATH = path.join(ENFORCEMENT_DIR, 'verdicts.jsonl');
|
|
@@ -130,7 +124,7 @@ export function recordViolation(entry, opts = {}) {
|
|
|
130
124
|
fs.mkdirSync(ENFORCEMENT_DIR, { recursive: true });
|
|
131
125
|
rotateIfBig(VIOLATIONS_PATH);
|
|
132
126
|
const violation_id = entry.violation_id ?? crypto.randomUUID();
|
|
133
|
-
const full = { at: new Date().toISOString(), violation_id, ...entry };
|
|
127
|
+
const full = { at: new Date().toISOString(), violation_id, ...entry, ...syntheticStamp() };
|
|
134
128
|
// 로그에 남는 프래그먼트/미리보기도 secret 마스킹 — 영수증만 가리고 로그에 키가 남으면 의미 없다.
|
|
135
129
|
if (typeof full.matched === 'string')
|
|
136
130
|
full.matched = redactForReceipt(full.matched);
|
|
@@ -158,6 +152,10 @@ export function recordViolation(entry, opts = {}) {
|
|
|
158
152
|
return '';
|
|
159
153
|
}
|
|
160
154
|
}
|
|
155
|
+
/** 위반 로그(현재 + 창 안 회전본). 기본 30일 = collectSignals 창. */
|
|
156
|
+
export function readViolationsWindow(days = VIOLATION_WINDOW_DAYS, now = Date.now()) {
|
|
157
|
+
return readJsonlWindow(VIOLATIONS_PATH, days, now);
|
|
158
|
+
}
|
|
161
159
|
export function readReceipt(violationId) {
|
|
162
160
|
if (!/^[A-Za-z0-9-]+$/.test(violationId))
|
|
163
161
|
return null;
|
|
@@ -173,12 +171,13 @@ export function setVerdict(entry) {
|
|
|
173
171
|
try {
|
|
174
172
|
fs.mkdirSync(ENFORCEMENT_DIR, { recursive: true });
|
|
175
173
|
rotateIfBig(VERDICTS_PATH);
|
|
176
|
-
fs.appendFileSync(VERDICTS_PATH, `${JSON.stringify({ at: new Date().toISOString(), ...entry })}\n`);
|
|
174
|
+
fs.appendFileSync(VERDICTS_PATH, `${JSON.stringify({ at: new Date().toISOString(), ...entry, ...syntheticStamp() })}\n`);
|
|
177
175
|
}
|
|
178
176
|
catch { /* best-effort */ }
|
|
179
177
|
}
|
|
178
|
+
/** 판정은 위반 이후에 기록되므로 30일 창(위반 조회 최대 창)이면 충분하다. */
|
|
180
179
|
export function readVerdicts() {
|
|
181
|
-
return
|
|
180
|
+
return readJsonlWindow(VERDICTS_PATH, VIOLATION_WINDOW_DAYS);
|
|
182
181
|
}
|
|
183
182
|
/** violation_id → 유효 판정 (user 가 있으면 user, 없으면 마지막 auto). */
|
|
184
183
|
export function effectiveVerdicts(verdicts = readVerdicts()) {
|
|
@@ -223,7 +222,7 @@ export function recordCheck(entry) {
|
|
|
223
222
|
try {
|
|
224
223
|
fs.mkdirSync(ENFORCEMENT_DIR, { recursive: true });
|
|
225
224
|
rotateIfBig(CHECKS_PATH);
|
|
226
|
-
fs.appendFileSync(CHECKS_PATH, `${JSON.stringify({ at: new Date().toISOString(), ...entry })}\n`);
|
|
225
|
+
fs.appendFileSync(CHECKS_PATH, `${JSON.stringify({ at: new Date().toISOString(), ...entry, ...syntheticStamp() })}\n`);
|
|
227
226
|
// 7일 TTL — 통과 기록은 턴마다 쌓이므로 1/50 확률로 압축(rotateIfBig 10MB 에 닿지 않게).
|
|
228
227
|
if (Math.random() < 0.02)
|
|
229
228
|
pruneChecks();
|
|
@@ -238,7 +237,7 @@ export function pruneChecks(now = Date.now()) {
|
|
|
238
237
|
catch { /* best-effort */ }
|
|
239
238
|
}
|
|
240
239
|
export function readChecks() {
|
|
241
|
-
return
|
|
240
|
+
return readJsonlWindow(CHECKS_PATH, CHECKS_TTL_MS / (24 * 3600 * 1000)).filter((c) => !isSyntheticEntry(c));
|
|
242
241
|
}
|
|
243
242
|
/** 정규식 매칭 프래그먼트 추출 — 영수증 `matched` 필드용. */
|
|
244
243
|
export function matchedFragment(re, text) {
|
|
@@ -257,7 +256,7 @@ export function recordBypass(entry) {
|
|
|
257
256
|
try {
|
|
258
257
|
fs.mkdirSync(ENFORCEMENT_DIR, { recursive: true });
|
|
259
258
|
rotateIfBig(BYPASS_PATH);
|
|
260
|
-
const full = { at: new Date().toISOString(), ...entry };
|
|
259
|
+
const full = { at: new Date().toISOString(), ...entry, ...syntheticStamp() };
|
|
261
260
|
fs.appendFileSync(BYPASS_PATH, `${JSON.stringify(full)}\n`);
|
|
262
261
|
}
|
|
263
262
|
catch (e) {
|
|
@@ -268,7 +267,7 @@ export function recordBypass(entry) {
|
|
|
268
267
|
}
|
|
269
268
|
export function collectSignals(rule, inputs = {}) {
|
|
270
269
|
const now = inputs.now ?? Date.now();
|
|
271
|
-
const allViolations = inputs.violations ??
|
|
270
|
+
const allViolations = inputs.violations ?? readViolationsWindow(VIOLATION_WINDOW_DAYS, now);
|
|
272
271
|
// ADR-017 D1/D2: T2 는 실제 차단만 센다 — 이전엔 kind 필터가 없어 메타가드 advise(correction)
|
|
273
272
|
// 와 테스트 유래(default 세션) 기록이 위반으로 집계돼 flag 를 조기 발화시켰다.
|
|
274
273
|
const violations = allViolations.filter(isRealBlock);
|
|
@@ -322,6 +321,30 @@ export function collectSignals(rule, inputs = {}) {
|
|
|
322
321
|
last_updated_days_ago: lastUpdatedDays,
|
|
323
322
|
};
|
|
324
323
|
}
|
|
324
|
+
/**
|
|
325
|
+
* 룰별 위반/우회 카운터를 로그에서 재계산 (lifecycle-scan --apply 가 룰 JSON 에 저장).
|
|
326
|
+
* 원천은 항상 로그다 — 룰 JSON 의 violation_count/bypass_count 는 이 값의 캐시일 뿐이며
|
|
327
|
+
* 보존된 로그 범위(회전본 포함) 안의 합계다. 훅 경로에서는 갱신하지 않는다.
|
|
328
|
+
*/
|
|
329
|
+
export function deriveRuleCounters(violations) {
|
|
330
|
+
const m = new Map();
|
|
331
|
+
for (const v of violations) {
|
|
332
|
+
const real = isRealBlock(v);
|
|
333
|
+
if (!real && !isConfirmedBypass(v))
|
|
334
|
+
continue;
|
|
335
|
+
const c = m.get(v.rule_id) ?? { violation_count: 0, bypass_count: 0 };
|
|
336
|
+
if (real) {
|
|
337
|
+
c.violation_count++;
|
|
338
|
+
if (!c.last_violation_at || v.at > c.last_violation_at)
|
|
339
|
+
c.last_violation_at = v.at;
|
|
340
|
+
}
|
|
341
|
+
else {
|
|
342
|
+
c.bypass_count++;
|
|
343
|
+
}
|
|
344
|
+
m.set(v.rule_id, c);
|
|
345
|
+
}
|
|
346
|
+
return m;
|
|
347
|
+
}
|
|
325
348
|
export function collectAllSignals(rules, inputs = {}) {
|
|
326
349
|
const map = new Map();
|
|
327
350
|
for (const r of rules) {
|
|
@@ -39,6 +39,8 @@ export interface ViolationEntry {
|
|
|
39
39
|
at: string;
|
|
40
40
|
rule_id: string;
|
|
41
41
|
session_id: string;
|
|
42
|
+
/** FORGEN_SYNTHETIC=1 하네스가 기록 — 모든 집계에서 제외. */
|
|
43
|
+
synthetic?: true;
|
|
42
44
|
source: 'stop-guard' | 'subagent-stop-guard' | 'pre-tool-guard' | 'post-tool-guard' | 'evidence-store' | 'manual';
|
|
43
45
|
/**
|
|
44
46
|
* block/deny = 실제 차단. correction = 메타가드 advise(기록만). bypass_confirmed = 사용자가
|
|
@@ -63,6 +65,7 @@ export interface VerdictEntry {
|
|
|
63
65
|
/** 사람 > 모델. user 판정은 auto 를 덮어쓴다. */
|
|
64
66
|
by: 'auto' | 'user';
|
|
65
67
|
reason?: string;
|
|
68
|
+
synthetic?: true;
|
|
66
69
|
}
|
|
67
70
|
/** D2: Stop 에서 실제 평가된 룰의 결과 (통과/위반). violations.jsonl 과 분리 — T2·explain 오염 방지. */
|
|
68
71
|
export interface CheckEntry {
|
|
@@ -70,6 +73,7 @@ export interface CheckEntry {
|
|
|
70
73
|
session_id: string;
|
|
71
74
|
rule_id: string;
|
|
72
75
|
result: 'pass' | 'violation';
|
|
76
|
+
synthetic?: true;
|
|
73
77
|
}
|
|
74
78
|
export interface BypassEntry {
|
|
75
79
|
at: string;
|
|
@@ -77,4 +81,5 @@ export interface BypassEntry {
|
|
|
77
81
|
session_id: string;
|
|
78
82
|
tool: string;
|
|
79
83
|
pattern_preview: string;
|
|
84
|
+
synthetic?: true;
|
|
80
85
|
}
|
|
@@ -179,6 +179,7 @@ export function logMatchDecision(input) {
|
|
|
179
179
|
})),
|
|
180
180
|
rankedTopN: input.rankedTopN.slice(0, MAX_CANDIDATES_LOGGED),
|
|
181
181
|
ts: new Date().toISOString(),
|
|
182
|
+
...(process.env.FORGEN_SYNTHETIC === '1' ? { synthetic: true } : {}),
|
|
182
183
|
};
|
|
183
184
|
// Serialize FIRST so any toJSON throw is caught before we touch disk.
|
|
184
185
|
const line = `${JSON.stringify(record)}\n`;
|
|
@@ -27,7 +27,15 @@ export interface RankedCandidate<T extends RankableSolution = RankableSolution>
|
|
|
27
27
|
relevance: number;
|
|
28
28
|
matchedTags: string[];
|
|
29
29
|
matchedIdentifiers: string[];
|
|
30
|
+
/** 맥락 토큰(cwd/최근 편집 파일)으로만 겹친 태그. matchedTags 와 분리 — 순위 가산(태그당 0.1, 상한 0.2)에만 쓰고 게이트엔 안 씀. */
|
|
31
|
+
contextMatchedTags: string[];
|
|
32
|
+
/** relevance 에 포함된 맥락 가산분. 주입 게이트는 relevance − contextBonus 로 비교한다(critic v0.6.6 SEV-2). */
|
|
33
|
+
contextBonus: number;
|
|
30
34
|
}
|
|
35
|
+
/** 맥락 태그 1개당 relevance 가산(프롬프트 태그 1개 ≈ 0.2 의 절반). */
|
|
36
|
+
export declare const CONTEXT_TAG_BONUS = 0.1;
|
|
37
|
+
/** 맥락 가산 총상한 — 맥락이 점수를 지배하지 못하게. */
|
|
38
|
+
export declare const CONTEXT_BONUS_CAP = 0.2;
|
|
31
39
|
/**
|
|
32
40
|
* Shared ranking core: tag-based relevance + identifier boost + top-5 sort.
|
|
33
41
|
*
|
|
@@ -42,4 +50,4 @@ export declare function rankCandidates<T extends RankableSolution>(promptTags: s
|
|
|
42
50
|
tfidf: number;
|
|
43
51
|
bm25: number;
|
|
44
52
|
bigram: number;
|
|
45
|
-
}): RankedCandidate<T>[];
|
|
53
|
+
}, contextTokens?: readonly string[]): RankedCandidate<T>[];
|
|
@@ -8,8 +8,13 @@
|
|
|
8
8
|
import { maskBlockedTokens } from './phrase-blocklist.js';
|
|
9
9
|
import { calculateRelevance } from './relevance-scorer.js';
|
|
10
10
|
import { expandCompoundTags, expandQueryBigrams, expandQueryKoreanStems } from './solution-format.js';
|
|
11
|
+
import { tagWeight } from './scoring-algorithms.js';
|
|
11
12
|
import { shouldRejectByR4T3Rules } from './precision-guards.js';
|
|
12
13
|
import { defaultNormalizer } from './term-normalizer.js';
|
|
14
|
+
/** 맥락 태그 1개당 relevance 가산(프롬프트 태그 1개 ≈ 0.2 의 절반). */
|
|
15
|
+
export const CONTEXT_TAG_BONUS = 0.1;
|
|
16
|
+
/** 맥락 가산 총상한 — 맥락이 점수를 지배하지 못하게. */
|
|
17
|
+
export const CONTEXT_BONUS_CAP = 0.2;
|
|
13
18
|
/**
|
|
14
19
|
* Shared ranking core: tag-based relevance + identifier boost + top-5 sort.
|
|
15
20
|
*
|
|
@@ -20,7 +25,7 @@ import { defaultNormalizer } from './term-normalizer.js';
|
|
|
20
25
|
* - top-5 by `relevance` descending.
|
|
21
26
|
* - duplicate names are NOT deduplicated.
|
|
22
27
|
*/
|
|
23
|
-
export function rankCandidates(promptTags, promptLower, solutions, ensembleWeights) {
|
|
28
|
+
export function rankCandidates(promptTags, promptLower, solutions, ensembleWeights, contextTokens = []) {
|
|
24
29
|
// R4-T2: mask blocked tokens before expansion/normalization
|
|
25
30
|
const maskedPromptTags = maskBlockedTokens(promptLower, promptTags);
|
|
26
31
|
if (maskedPromptTags.length === 0)
|
|
@@ -55,11 +60,28 @@ export function rankCandidates(promptTags, promptLower, solutions, ensembleWeigh
|
|
|
55
60
|
tagRelevance = 0;
|
|
56
61
|
tagMatches = [];
|
|
57
62
|
}
|
|
63
|
+
// 맥락 신호: 프롬프트로 이미 1개 이상 매칭된 후보에만 적용(맥락 단독 후보 생성 금지).
|
|
64
|
+
// 프롬프트 매칭 태그와 겹치는 맥락 토큰은 중복 가산하지 않는다.
|
|
65
|
+
const contextMatchedTags = [];
|
|
66
|
+
let contextBonus = 0;
|
|
67
|
+
if (contextTokens.length > 0 && tagMatches.length + matchedIdentifiers.length >= 1) {
|
|
68
|
+
const ctx = new Set(contextTokens);
|
|
69
|
+
const already = new Set([...tagMatches, ...maskedPromptTags]);
|
|
70
|
+
for (const t of solTagsExpanded) {
|
|
71
|
+
if (ctx.has(t) && !already.has(t) && !contextMatchedTags.includes(t)) {
|
|
72
|
+
contextMatchedTags.push(t);
|
|
73
|
+
contextBonus += CONTEXT_TAG_BONUS * tagWeight(t);
|
|
74
|
+
}
|
|
75
|
+
}
|
|
76
|
+
contextBonus = Math.min(contextBonus, CONTEXT_BONUS_CAP);
|
|
77
|
+
}
|
|
58
78
|
return {
|
|
59
79
|
solution: sol,
|
|
60
|
-
relevance: tagRelevance + identifierBoost,
|
|
80
|
+
relevance: tagRelevance + identifierBoost + contextBonus,
|
|
61
81
|
matchedTags: tagMatches,
|
|
62
82
|
matchedIdentifiers,
|
|
83
|
+
contextMatchedTags,
|
|
84
|
+
contextBonus,
|
|
63
85
|
};
|
|
64
86
|
})
|
|
65
87
|
.filter((c) => c.matchedTags.length + c.matchedIdentifiers.length >= 1)
|
|
@@ -76,6 +76,8 @@ export declare function parseSolutionV3(content: string): SolutionV3 | null;
|
|
|
76
76
|
export declare function serializeSolutionV3(solution: SolutionV3): string;
|
|
77
77
|
/** Check if content is in V1 format (# Title + > Type: pattern) */
|
|
78
78
|
export declare function isV1Format(content: string): boolean;
|
|
79
|
+
/** 영어 불용어 */
|
|
80
|
+
export declare const EN_STOPWORDS: Set<string>;
|
|
79
81
|
/** 한국어 일반 조사/어미 — strip 대상 (긴 것부터 매칭)
|
|
80
82
|
*
|
|
81
83
|
* term-matcher에서 재사용 가능하도록 export — 매칭 시점과 추출 시점의 stripping
|
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import * as yaml from 'js-yaml';
|
|
2
|
+
import { normalizeColloquialKo } from './ko-colloquial.js';
|
|
2
3
|
export const DEFAULT_EVIDENCE = {
|
|
3
4
|
injected: 0,
|
|
4
5
|
reflected: 0,
|
|
@@ -334,7 +335,7 @@ const KO_STOPWORDS = new Set([
|
|
|
334
335
|
'최종',
|
|
335
336
|
]);
|
|
336
337
|
/** 영어 불용어 */
|
|
337
|
-
const EN_STOPWORDS = new Set([
|
|
338
|
+
export const EN_STOPWORDS = new Set([
|
|
338
339
|
'the',
|
|
339
340
|
'and',
|
|
340
341
|
'for',
|
|
@@ -454,7 +455,10 @@ export function extractTags(text) {
|
|
|
454
455
|
for (const w of words) {
|
|
455
456
|
const isKorean = /[가-힣]/.test(w);
|
|
456
457
|
if (isKorean && w.length >= 2) {
|
|
457
|
-
const
|
|
458
|
+
const base = normalizeColloquialKo(w);
|
|
459
|
+
if (base === null)
|
|
460
|
+
continue;
|
|
461
|
+
const stem = stripKoSuffix(base);
|
|
458
462
|
if (stem.length >= 2 && !KO_STOPWORDS.has(stem)) {
|
|
459
463
|
freq.set(stem, (freq.get(stem) ?? 0) + 1);
|
|
460
464
|
}
|
|
@@ -38,5 +38,9 @@ export interface SolutionMatch {
|
|
|
38
38
|
identifiers: string[];
|
|
39
39
|
matchedTags: string[];
|
|
40
40
|
matchedIdentifiers: string[];
|
|
41
|
+
/** 맥락 토큰(cwd/최근 편집 파일)으로만 겹친 태그 — 순위 가산에만, 게이트·단독 주입 불가. */
|
|
42
|
+
contextMatchedTags?: string[];
|
|
43
|
+
/** relevance 에 포함된 맥락 가산분 (게이트 비교에서 제외). */
|
|
44
|
+
contextBonus?: number;
|
|
41
45
|
}
|
|
42
|
-
export declare function matchSolutions(prompt: string, scope: ScopeInfo, cwd: string): SolutionMatch[];
|
|
46
|
+
export declare function matchSolutions(prompt: string, scope: ScopeInfo, cwd: string, contextTokens?: readonly string[]): SolutionMatch[];
|
|
@@ -43,7 +43,7 @@ function applyCandidateExplorationBonus(entries) {
|
|
|
43
43
|
});
|
|
44
44
|
}
|
|
45
45
|
// ── Public API ──
|
|
46
|
-
export function matchSolutions(prompt, scope, cwd) {
|
|
46
|
+
export function matchSolutions(prompt, scope, cwd, contextTokens = []) {
|
|
47
47
|
const dirs = [{ dir: ME_SOLUTIONS, scope: 'me' }];
|
|
48
48
|
if (scope.team) {
|
|
49
49
|
dirs.push({ dir: path.join(PACKS_DIR, scope.team.name, 'solutions'), scope: 'team' });
|
|
@@ -54,7 +54,7 @@ export function matchSolutions(prompt, scope, cwd) {
|
|
|
54
54
|
const promptTags = extractTags(prompt);
|
|
55
55
|
const promptLower = prompt.toLowerCase();
|
|
56
56
|
const tunedWeights = loadTunedMatcherWeights();
|
|
57
|
-
const ranked = rankCandidates(promptTags, promptLower, allSolutions, tunedWeights);
|
|
57
|
+
const ranked = rankCandidates(promptTags, promptLower, allSolutions, tunedWeights, contextTokens);
|
|
58
58
|
// ADR-010 W3-1 (F2): 저 ROI 강등 — ranking-pipeline 은 순수 유지, 여기서
|
|
59
59
|
// 후처리. surfaced≫acted_on 솔루션은 ×0.5, 2윈도 연속이면 주입 제외.
|
|
60
60
|
const matches = ranked.map((c) => ({
|
|
@@ -70,6 +70,8 @@ export function matchSolutions(prompt, scope, cwd) {
|
|
|
70
70
|
identifiers: c.solution.identifiers,
|
|
71
71
|
matchedTags: [...c.matchedTags, ...c.matchedIdentifiers],
|
|
72
72
|
matchedIdentifiers: c.matchedIdentifiers,
|
|
73
|
+
contextMatchedTags: c.contextMatchedTags,
|
|
74
|
+
contextBonus: c.contextBonus,
|
|
73
75
|
}));
|
|
74
76
|
try {
|
|
75
77
|
return applyRoiDemotions(matches, loadRoiDemotions());
|