@wooojin/forgen 0.5.8 → 0.6.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/.claude-plugin/plugin.json +1 -1
- package/CHANGELOG.md +102 -0
- package/README.ja.md +12 -0
- package/README.ko.md +12 -0
- package/README.md +12 -0
- package/README.zh.md +12 -0
- package/dist/checks/_shared/model-profile.d.ts +1 -1
- package/dist/checks/_shared/model-profile.js +9 -5
- package/dist/cli.js +32 -3
- package/dist/core/auto-compound-runner.js +20 -43
- package/dist/core/block-cli.d.ts +1 -0
- package/dist/core/block-cli.js +41 -0
- package/dist/core/explain-cli.js +29 -1
- package/dist/core/inspect-cli.js +9 -8
- package/dist/core/rate-limit-forecast.d.ts +113 -0
- package/dist/core/rate-limit-forecast.js +236 -0
- package/dist/core/state-gc.js +3 -0
- package/dist/core/stats-cli.d.ts +15 -0
- package/dist/core/stats-cli.js +50 -16
- package/dist/core/status-cli.d.ts +18 -1
- package/dist/core/status-cli.js +51 -2
- package/dist/core/statusline-cli.d.ts +58 -13
- package/dist/core/statusline-cli.js +164 -201
- package/dist/core/uninstall.js +10 -1
- package/dist/core/v1-bootstrap.js +7 -1
- package/dist/engine/block-judge-cli.d.ts +2 -0
- package/dist/engine/block-judge-cli.js +11 -0
- package/dist/engine/block-judge.d.ts +68 -0
- package/dist/engine/block-judge.js +248 -0
- package/dist/engine/correction-cluster-runner.d.ts +67 -0
- package/dist/engine/correction-cluster-runner.js +242 -5
- package/dist/engine/correction-clustering.d.ts +15 -0
- package/dist/engine/correction-clustering.js +24 -0
- package/dist/engine/lifecycle/lifecycle-cli.js +7 -4
- package/dist/engine/lifecycle/signals.d.ts +59 -2
- package/dist/engine/lifecycle/signals.js +193 -4
- package/dist/engine/lifecycle/trigger-t3-bypass.d.ts +5 -3
- package/dist/engine/lifecycle/trigger-t3-bypass.js +6 -4
- package/dist/engine/lifecycle/types.d.ts +29 -1
- package/dist/engine/mined-rule-merge-cli.d.ts +11 -0
- package/dist/engine/mined-rule-merge-cli.js +67 -0
- package/dist/engine/rule-relevance.d.ts +72 -0
- package/dist/engine/rule-relevance.js +183 -0
- package/dist/engine/rule-toggle-cli.d.ts +5 -0
- package/dist/engine/rule-toggle-cli.js +30 -0
- package/dist/fgx.js +1 -1
- package/dist/forge/evidence-processor.js +2 -0
- package/dist/hooks/post-tool-use.js +9 -14
- package/dist/hooks/pre-tool-use.js +71 -8
- package/dist/hooks/shared/command-parser.d.ts +11 -0
- package/dist/hooks/shared/command-parser.js +120 -0
- package/dist/hooks/solution-injector.js +13 -0
- package/dist/hooks/stop-guard.d.ts +18 -0
- package/dist/hooks/stop-guard.js +55 -10
- package/dist/host/install-claude.js +7 -33
- package/dist/host/install-codex.d.ts +23 -1
- package/dist/host/install-codex.js +128 -49
- package/dist/host/install-opencode.d.ts +5 -0
- package/dist/host/install-opencode.js +9 -6
- package/dist/host/managed-marker.d.ts +22 -0
- package/dist/host/managed-marker.js +79 -0
- package/dist/host/uninstall-codex.d.ts +2 -0
- package/dist/host/uninstall-codex.js +12 -9
- package/dist/host/uninstall-opencode.d.ts +36 -0
- package/dist/host/uninstall-opencode.js +141 -0
- package/dist/mcp/tools.js +7 -1
- package/dist/renderer/inspect-renderer.js +23 -6
- package/dist/renderer/rule-renderer.js +4 -2
- package/dist/store/evidence-store.js +37 -2
- package/dist/store/profile-score.d.ts +55 -0
- package/dist/store/profile-score.js +100 -0
- package/dist/store/profile-store.d.ts +22 -5
- package/dist/store/profile-store.js +42 -6
- package/dist/store/rule-origin.d.ts +39 -0
- package/dist/store/rule-origin.js +84 -0
- package/dist/store/types.d.ts +24 -0
- package/package.json +1 -1
- package/plugin.json +1 -1
- package/scripts/postinstall.js +76 -42
package/dist/mcp/tools.js
CHANGED
|
@@ -271,10 +271,11 @@ export function registerTools(server) {
|
|
|
271
271
|
.describe('Correction type: fix-now (immediate), prefer-from-now (long-term), avoid-this (strong avoidance)'),
|
|
272
272
|
message: z.string().describe('What the user wants changed — the correction in natural language'),
|
|
273
273
|
target: z.string().describe('What is being corrected — the specific behavior, pattern, or output'),
|
|
274
|
+
user_quote: z.string().optional().describe('The user\'s own words that prompted this correction, verbatim (not paraphrased). Shown back to the user as "what you said" when the rule later blocks or applies. Omit if you cannot quote verbatim.'),
|
|
274
275
|
axis_hint: z.enum(['quality_safety', 'autonomy', 'judgment_philosophy', 'communication_style']).nullable()
|
|
275
276
|
.describe('Which personalization axis this correction relates to (null if unclear)'),
|
|
276
277
|
},
|
|
277
|
-
}, async ({ session_id, kind, message, target, axis_hint }) => {
|
|
278
|
+
}, async ({ session_id, kind, message, target, axis_hint, user_quote }) => {
|
|
278
279
|
try {
|
|
279
280
|
// v1 session_id를 환경변수에서 가져옴 (하네스가 설정)
|
|
280
281
|
const effectiveSessionId = session_id || process.env.FORGEN_SESSION_ID || 'unknown';
|
|
@@ -291,12 +292,17 @@ export function registerTools(server) {
|
|
|
291
292
|
const privateNote = (strippedTarget.hadPrivate || cleanMessage !== message)
|
|
292
293
|
? '\n(참고: <private> 범위는 기록에서 제외됨)'
|
|
293
294
|
: '';
|
|
295
|
+
// ADR-017 D0: 사용자 원문도 <private> 필터. 통째로 private 이면 저장하지 않는다.
|
|
296
|
+
const cleanQuote = typeof user_quote === 'string' && user_quote.trim() && !isFullyPrivate(user_quote)
|
|
297
|
+
? stripPrivate(user_quote).cleaned.trim()
|
|
298
|
+
: '';
|
|
294
299
|
const result = processCorrection({
|
|
295
300
|
session_id: effectiveSessionId,
|
|
296
301
|
kind: kind,
|
|
297
302
|
message: cleanMessage,
|
|
298
303
|
target: cleanTarget,
|
|
299
304
|
axis_hint: axis_hint,
|
|
305
|
+
...(cleanQuote ? { user_quote: cleanQuote } : {}),
|
|
300
306
|
});
|
|
301
307
|
// Outcome tracking (Phase 1): attribute this correction to any
|
|
302
308
|
// pending injections in the session. Fail-open — attribution is a
|
|
@@ -4,7 +4,20 @@
|
|
|
4
4
|
* forgen inspect profile/rules/evidence/session 출력 생성.
|
|
5
5
|
* Authoritative spec: docs/plans/2026-04-03-forgen-rule-renderer-spec.md §6
|
|
6
6
|
*/
|
|
7
|
+
import { axisDirection, AXIS_POLES } from '../store/profile-score.js';
|
|
7
8
|
import { initLocaleFromConfig, getLocale, qualityName, autonomyName, judgmentName, communicationName, trustName } from '../i18n/index.js';
|
|
9
|
+
/** 축 방향 라벨 — 팩 이름을 locale 로 변환. mid 는 "중간/mid" (미학습 아님). */
|
|
10
|
+
function dirLabel(axis, score, l) {
|
|
11
|
+
const d = axisDirection(score);
|
|
12
|
+
if (d === 'mid')
|
|
13
|
+
return l === 'ko' ? '중간' : 'mid';
|
|
14
|
+
const pack = d === 'low' ? AXIS_POLES[axis].lowPack : AXIS_POLES[axis].highPack;
|
|
15
|
+
const name = axis === 'quality_safety' ? qualityName(pack, l)
|
|
16
|
+
: axis === 'autonomy' ? autonomyName(pack, l)
|
|
17
|
+
: axis === 'judgment_philosophy' ? judgmentName(pack, l)
|
|
18
|
+
: communicationName(pack, l);
|
|
19
|
+
return l === 'ko' ? `${name} 쪽` : `→ ${name}`;
|
|
20
|
+
}
|
|
8
21
|
export function renderProfile(profile) {
|
|
9
22
|
initLocaleFromConfig();
|
|
10
23
|
const l = getLocale();
|
|
@@ -17,11 +30,12 @@ export function renderProfile(profile) {
|
|
|
17
30
|
`Communication pack: ${communicationName(profile.base_packs.communication_pack, l)}`,
|
|
18
31
|
`Trust policy: ${trustName(profile.trust_preferences.desired_policy, l)} (source: ${profile.trust_preferences.source})`,
|
|
19
32
|
'',
|
|
20
|
-
|
|
21
|
-
` 품질/안전: ${profile.axes.quality_safety.score.toFixed(2)} (confidence: ${profile.axes.quality_safety.confidence.toFixed(2)})`,
|
|
22
|
-
` 자율성: ${profile.axes.autonomy.score.toFixed(2)} (confidence: ${profile.axes.autonomy.confidence.toFixed(2)})`,
|
|
23
|
-
` 판단철학: ${profile.axes.judgment_philosophy.score.toFixed(2)} (confidence: ${profile.axes.judgment_philosophy.confidence.toFixed(2)})`,
|
|
24
|
-
` 커뮤니케이션: ${profile.axes.communication_style.score.toFixed(2)} (confidence: ${profile.axes.communication_style.confidence.toFixed(2)})`,
|
|
33
|
+
`── 4축 상위 score ── (score = confidence × facet 위치 + (1 − confidence) × 0.5; 0=${l === 'ko' ? '왼쪽 팩' : 'left pack'}, 1=${l === 'ko' ? '오른쪽 팩' : 'right pack'})`,
|
|
34
|
+
` 품질/안전: ${profile.axes.quality_safety.score.toFixed(2)} ${dirLabel('quality_safety', profile.axes.quality_safety.score, l)} (confidence: ${profile.axes.quality_safety.confidence.toFixed(2)})`,
|
|
35
|
+
` 자율성: ${profile.axes.autonomy.score.toFixed(2)} ${dirLabel('autonomy', profile.axes.autonomy.score, l)} (confidence: ${profile.axes.autonomy.confidence.toFixed(2)})`,
|
|
36
|
+
` 판단철학: ${profile.axes.judgment_philosophy.score.toFixed(2)} ${dirLabel('judgment_philosophy', profile.axes.judgment_philosophy.score, l)} (confidence: ${profile.axes.judgment_philosophy.confidence.toFixed(2)})`,
|
|
37
|
+
` 커뮤니케이션: ${profile.axes.communication_style.score.toFixed(2)} ${dirLabel('communication_style', profile.axes.communication_style.score, l)} (confidence: ${profile.axes.communication_style.confidence.toFixed(2)})`,
|
|
38
|
+
` Last reclass: ${profile.metadata.last_reclassification_at ?? 'never'}`,
|
|
25
39
|
'',
|
|
26
40
|
'── Quality facets ──',
|
|
27
41
|
` verification_depth: ${profile.axes.quality_safety.facets.verification_depth.toFixed(2)}`,
|
|
@@ -53,7 +67,10 @@ export function renderRules(rules) {
|
|
|
53
67
|
if (active.length > 0) {
|
|
54
68
|
lines.push(`── Active rules (${active.length}) ──`);
|
|
55
69
|
for (const r of active) {
|
|
56
|
-
|
|
70
|
+
// ADR-017 (critic): T2/T3 가 올린 flag 는 이전에 어디에도 안 보였다 — 여기서 가시화.
|
|
71
|
+
const flag = (r.lifecycle?.phase === 'flagged' ? ' ⚑ flagged (repeated violations/overrides — review)' : '')
|
|
72
|
+
+ (r.enforce_mode === 'advise' ? ' ⚠ advise (precision 강등 — 차단 안 함; 복귀: forgen rule enforce <id>)' : '');
|
|
73
|
+
lines.push(` [${r.category}/${r.strength}] ${r.render_key} — ${r.policy}${flag}`);
|
|
57
74
|
lines.push(` source: ${r.source} | evidence: ${r.evidence_refs.length}`);
|
|
58
75
|
}
|
|
59
76
|
}
|
|
@@ -6,6 +6,7 @@
|
|
|
6
6
|
*
|
|
7
7
|
* 파이프라인: filter → dedupe(render_key) → group(category) → order → template → budget
|
|
8
8
|
*/
|
|
9
|
+
import { originTag } from '../store/rule-origin.js';
|
|
9
10
|
import { initLocaleFromConfig, getLocale, RULE_RENDERER } from '../i18n/index.js';
|
|
10
11
|
export const DEFAULT_CONTEXT = {
|
|
11
12
|
surface: 'session_start',
|
|
@@ -63,9 +64,10 @@ function dedupeByRenderKey(rules) {
|
|
|
63
64
|
function ruleToText(rule) {
|
|
64
65
|
// AI-optimized: [category|strength] 태그로 축약하여 토큰 절감
|
|
65
66
|
// hard 강도는 태그 생략 (Must Not 섹션이 이미 의미를 전달)
|
|
67
|
+
// ADR-017 D0: explicit 교정 룰엔 출처 날짜 꼬리표 — 사용자가 "내가 언제 말한 것" 을 식별.
|
|
66
68
|
if (rule.strength === 'hard')
|
|
67
|
-
return rule.policy
|
|
68
|
-
return `[${rule.category}|${rule.strength}] ${rule.policy}`;
|
|
69
|
+
return `${rule.policy}${originTag(rule)}`;
|
|
70
|
+
return `[${rule.category}|${rule.strength}] ${rule.policy}${originTag(rule)}`;
|
|
69
71
|
}
|
|
70
72
|
function trustPolicySummary(policy) {
|
|
71
73
|
const s = RULE_RENDERER[getLocale()];
|
|
@@ -15,7 +15,8 @@ import { classify, applyProposal } from '../engine/enforce-classifier.js';
|
|
|
15
15
|
import { detect as detectT1 } from '../engine/lifecycle/trigger-t1-correction.js';
|
|
16
16
|
import { foldEvents } from '../engine/lifecycle/orchestrator.js';
|
|
17
17
|
import { appendLifecycleEvents } from '../engine/lifecycle/meta-reclassifier.js';
|
|
18
|
-
import { laplaceConfidence, strengthForConfidence } from '../engine/correction-clustering.js';
|
|
18
|
+
import { findMostSimilarRule, laplaceConfidence, strengthForConfidence } from '../engine/correction-clustering.js';
|
|
19
|
+
import { recordMinedObservation } from '../engine/correction-cluster-runner.js';
|
|
19
20
|
import { withFileLockSync } from '../hooks/shared/file-lock.js';
|
|
20
21
|
function evidencePath(evidenceId) {
|
|
21
22
|
return path.join(ME_BEHAVIOR, `${evidenceId}.json`);
|
|
@@ -182,7 +183,12 @@ export function loadPromotionCandidates() {
|
|
|
182
183
|
const AUTO_MINED_PREFIX = 'auto:';
|
|
183
184
|
const AUTO_MINED_TTL_MS = 21 * 24 * 60 * 60 * 1000; // 21일
|
|
184
185
|
const AUTO_MINED_MAX_LIVE = 30;
|
|
185
|
-
/**
|
|
186
|
+
/**
|
|
187
|
+
* 채굴(behavior_inference) 룰 은퇴: TTL 초과 + 총량 상한 초과분(오래된 순).
|
|
188
|
+
* ADR-017 D3 캡 재정의: 총량 상한은 *개념(클러스터) 수* 기준 — loadActiveRules() 가 status
|
|
189
|
+
* 'active' 만 반환하므로 병합/링크로 superseded 된 원본은 상한 계산에서 자연히 제외되고,
|
|
190
|
+
* 통합 룰 1개가 개념 1개로 집계된다. (status 필터를 넓히면 이 보장이 깨진다.)
|
|
191
|
+
*/
|
|
186
192
|
function retireStaleAutoMinedRules(now) {
|
|
187
193
|
const auto = loadActiveRules().filter((r) => r.scope === 'me' && r.source === 'behavior_inference' && r.render_key?.startsWith(AUTO_MINED_PREFIX));
|
|
188
194
|
const byAge = auto
|
|
@@ -244,6 +250,35 @@ export function promoteSessionCandidates(sessionId) {
|
|
|
244
250
|
// evidence 를 영구히 반환하므로, 이 마커가 없으면 재-sweep 마다 같은 evidence 가
|
|
245
251
|
// 무한 재처리된다.
|
|
246
252
|
const alreadyConsumed = (candidate.candidate_rule_refs ?? []).length > 0;
|
|
253
|
+
// ADR-017 D3 — 채굴 경로 사전 중복 검사(render_key 조회 *앞*): 같은 개념의 active 룰이
|
|
254
|
+
// 이미 있으면 새 render_key 변형으로 룰을 늘리지 않는다. 의미 매칭은 클러스터링과
|
|
255
|
+
// 같은 term 매칭(policySimilarity ≥ τ)을 재사용한다.
|
|
256
|
+
// - 채굴 룰과 매칭 → 그 룰의 evidence_refs 에 추가(strength 'default' 고정).
|
|
257
|
+
// - explicit 룰과 매칭 → 룰을 만들지 않고 explicit 의 mined_observations 만 +1
|
|
258
|
+
// (evidence_refs 합산 금지 — ADR-013 불변식).
|
|
259
|
+
// 같은 evidence 의 재관측(alreadyConsumed)은 아래 기존 경로와 동일하게 no-op.
|
|
260
|
+
if (autoMined && !alreadyConsumed) {
|
|
261
|
+
const activeMe = loadActiveRules().filter((r) => r.scope === 'me');
|
|
262
|
+
const match = findMostSimilarRule(candidate.summary, activeMe);
|
|
263
|
+
if (match) {
|
|
264
|
+
const hit = match.rule;
|
|
265
|
+
if (hit.source === 'behavior_inference') {
|
|
266
|
+
const evidenceRefs = hit.evidence_refs.includes(candidate.evidence_id)
|
|
267
|
+
? hit.evidence_refs
|
|
268
|
+
: [...hit.evidence_refs, candidate.evidence_id];
|
|
269
|
+
saveRule({ ...hit, evidence_refs: evidenceRefs, strength: 'default' });
|
|
270
|
+
promoted++;
|
|
271
|
+
}
|
|
272
|
+
else {
|
|
273
|
+
recordMinedObservation(hit, 1);
|
|
274
|
+
}
|
|
275
|
+
saveEvidence({
|
|
276
|
+
...candidate,
|
|
277
|
+
candidate_rule_refs: [...(candidate.candidate_rule_refs ?? []), hit.rule_id],
|
|
278
|
+
});
|
|
279
|
+
continue;
|
|
280
|
+
}
|
|
281
|
+
}
|
|
247
282
|
// (A) render_key upsert identity — status 무관 기존 rule 조회. TTL/cap 로
|
|
248
283
|
// retire(status='removed')된 render_key 도 여기서 발견되어 "재생성"이 아니라
|
|
249
284
|
// "재활성화"된다 — 새 rule_id/created_at 을 절대 새로 만들지 않는다.
|
|
@@ -0,0 +1,55 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Forgen v1 — Profile axis score (ADR-017 §6-8)
|
|
3
|
+
*
|
|
4
|
+
* 4축 `score` 는 v0.1.0 부터 스키마·표시만 있고 산출 로직이 없었다 (0.5 리터럴 고정).
|
|
5
|
+
* 새 스펙 없이 기존 facet 카탈로그(src/preset/facet-catalog.ts)에서 도출한다:
|
|
6
|
+
*
|
|
7
|
+
* - 각 축의 양 끝 팩 centroid 를 0 과 1 로 둔다 (onboarding.ts 의 score→pack 방향과 동일):
|
|
8
|
+
* quality_safety 보수형(0) → 속도형(1)
|
|
9
|
+
* autonomy 확인 우선형(0) → 자율 실행형(1)
|
|
10
|
+
* judgment_philosophy 최소변경형(0) → 구조적접근형(1)
|
|
11
|
+
* communication_style 간결형(0) → 상세형(1)
|
|
12
|
+
* - 현재 facet 벡터를 그 선분에 투영한 t (0~1 clamp) 가 "facet 위치".
|
|
13
|
+
* - score = confidence × t + (1 − confidence) × NEUTRAL_ANCHOR
|
|
14
|
+
* (profile-store.ts bumpAxisConfidence 주석의 공식 그대로, neutral_anchor = 0.5).
|
|
15
|
+
*
|
|
16
|
+
* confidence 가 낮으면 0.5 근처에 머물고, 교정이 쌓여 confidence 가 오르면 facet 위치를
|
|
17
|
+
* 더 강하게 반영한다. 순수 함수 — IO 없음. 저장은 profile-store 가 담당.
|
|
18
|
+
*/
|
|
19
|
+
import type { Profile } from './types.js';
|
|
20
|
+
export type AxisKey = keyof Profile['axes'];
|
|
21
|
+
export declare const AXIS_KEYS: readonly AxisKey[];
|
|
22
|
+
export declare const NEUTRAL_ANCHOR = 0.5;
|
|
23
|
+
/** 축별 양 끝 팩 (low → 0, high → 1). lowPack/highPack 은 팩 키 — 표시 라벨은 렌더러가 locale 로 변환. */
|
|
24
|
+
export declare const AXIS_POLES: Record<AxisKey, {
|
|
25
|
+
low: Record<string, number>;
|
|
26
|
+
high: Record<string, number>;
|
|
27
|
+
lowPack: string;
|
|
28
|
+
highPack: string;
|
|
29
|
+
}>;
|
|
30
|
+
/**
|
|
31
|
+
* facet 벡터를 low→high 선분에 투영한 위치 t ∈ [0,1].
|
|
32
|
+
* 카탈로그에 없는 facet 키는 무시하고, 숫자가 아닌 값은 low 값으로 간주(중립).
|
|
33
|
+
*/
|
|
34
|
+
export declare function projectFacets(facets: Record<string, unknown>, low: Record<string, number>, high: Record<string, number>): number;
|
|
35
|
+
export declare function computeAxisScore(axis: AxisKey, facets: Record<string, unknown>, confidence: number): number;
|
|
36
|
+
export interface RecomputeResult {
|
|
37
|
+
changed: boolean;
|
|
38
|
+
/** 축별 (이전 → 이후). 변동 없는 축도 포함. */
|
|
39
|
+
deltas: Record<AxisKey, {
|
|
40
|
+
before: number;
|
|
41
|
+
after: number;
|
|
42
|
+
}>;
|
|
43
|
+
}
|
|
44
|
+
/**
|
|
45
|
+
* profile.axes.*.score 를 재계산해 **mutate** 하고, 하나라도 바뀌면
|
|
46
|
+
* metadata.last_reclassification_at 을 now 로 기록한다. 저장은 호출자 몫.
|
|
47
|
+
*/
|
|
48
|
+
export declare function recomputeProfileScores(profile: Profile, now?: Date): RecomputeResult;
|
|
49
|
+
/**
|
|
50
|
+
* 방향 판정: 0.5 ± 0.1 은 'mid', 그 밖은 가까운 극('low'|'high'). 라벨 문자열은 렌더러가
|
|
51
|
+
* locale 에 맞춰 만든다 (critic: 하드코딩 한국어 라벨은 en 사용자에게 혼합 출력).
|
|
52
|
+
* 주의 — 'mid' 는 "미학습" 이 아니다. facet 이 서로 반대 방향이면(예: verification_depth 1.0
|
|
53
|
+
* 이지만 stop_threshold 0.25) 투영이 중간으로 수렴한다.
|
|
54
|
+
*/
|
|
55
|
+
export declare function axisDirection(score: number): 'low' | 'mid' | 'high';
|
|
@@ -0,0 +1,100 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Forgen v1 — Profile axis score (ADR-017 §6-8)
|
|
3
|
+
*
|
|
4
|
+
* 4축 `score` 는 v0.1.0 부터 스키마·표시만 있고 산출 로직이 없었다 (0.5 리터럴 고정).
|
|
5
|
+
* 새 스펙 없이 기존 facet 카탈로그(src/preset/facet-catalog.ts)에서 도출한다:
|
|
6
|
+
*
|
|
7
|
+
* - 각 축의 양 끝 팩 centroid 를 0 과 1 로 둔다 (onboarding.ts 의 score→pack 방향과 동일):
|
|
8
|
+
* quality_safety 보수형(0) → 속도형(1)
|
|
9
|
+
* autonomy 확인 우선형(0) → 자율 실행형(1)
|
|
10
|
+
* judgment_philosophy 최소변경형(0) → 구조적접근형(1)
|
|
11
|
+
* communication_style 간결형(0) → 상세형(1)
|
|
12
|
+
* - 현재 facet 벡터를 그 선분에 투영한 t (0~1 clamp) 가 "facet 위치".
|
|
13
|
+
* - score = confidence × t + (1 − confidence) × NEUTRAL_ANCHOR
|
|
14
|
+
* (profile-store.ts bumpAxisConfidence 주석의 공식 그대로, neutral_anchor = 0.5).
|
|
15
|
+
*
|
|
16
|
+
* confidence 가 낮으면 0.5 근처에 머물고, 교정이 쌓여 confidence 가 오르면 facet 위치를
|
|
17
|
+
* 더 강하게 반영한다. 순수 함수 — IO 없음. 저장은 profile-store 가 담당.
|
|
18
|
+
*/
|
|
19
|
+
import { QUALITY_CENTROIDS, AUTONOMY_CENTROIDS, JUDGMENT_CENTROIDS, COMMUNICATION_CENTROIDS, } from '../preset/facet-catalog.js';
|
|
20
|
+
export const AXIS_KEYS = [
|
|
21
|
+
'quality_safety',
|
|
22
|
+
'autonomy',
|
|
23
|
+
'judgment_philosophy',
|
|
24
|
+
'communication_style',
|
|
25
|
+
];
|
|
26
|
+
export const NEUTRAL_ANCHOR = 0.5;
|
|
27
|
+
/** facet 인터페이스는 index signature 가 없어 Record 로 넓힌다 (값은 전부 number). */
|
|
28
|
+
const rec = (f) => f;
|
|
29
|
+
/** 축별 양 끝 팩 (low → 0, high → 1). lowPack/highPack 은 팩 키 — 표시 라벨은 렌더러가 locale 로 변환. */
|
|
30
|
+
export const AXIS_POLES = {
|
|
31
|
+
quality_safety: { low: rec(QUALITY_CENTROIDS.보수형), high: rec(QUALITY_CENTROIDS.속도형), lowPack: '보수형', highPack: '속도형' },
|
|
32
|
+
autonomy: { low: rec(AUTONOMY_CENTROIDS['확인 우선형']), high: rec(AUTONOMY_CENTROIDS['자율 실행형']), lowPack: '확인 우선형', highPack: '자율 실행형' },
|
|
33
|
+
judgment_philosophy: { low: rec(JUDGMENT_CENTROIDS.최소변경형), high: rec(JUDGMENT_CENTROIDS.구조적접근형), lowPack: '최소변경형', highPack: '구조적접근형' },
|
|
34
|
+
communication_style: { low: rec(COMMUNICATION_CENTROIDS.간결형), high: rec(COMMUNICATION_CENTROIDS.상세형), lowPack: '간결형', highPack: '상세형' },
|
|
35
|
+
};
|
|
36
|
+
const clamp01 = (v) => Math.max(0, Math.min(1, v));
|
|
37
|
+
/**
|
|
38
|
+
* facet 벡터를 low→high 선분에 투영한 위치 t ∈ [0,1].
|
|
39
|
+
* 카탈로그에 없는 facet 키는 무시하고, 숫자가 아닌 값은 low 값으로 간주(중립).
|
|
40
|
+
*/
|
|
41
|
+
export function projectFacets(facets, low, high) {
|
|
42
|
+
let dot = 0;
|
|
43
|
+
let len2 = 0;
|
|
44
|
+
for (const k of Object.keys(low)) {
|
|
45
|
+
const d = high[k] - low[k];
|
|
46
|
+
if (!Number.isFinite(d))
|
|
47
|
+
continue;
|
|
48
|
+
const raw = facets[k];
|
|
49
|
+
const f = typeof raw === 'number' && Number.isFinite(raw) ? raw : low[k];
|
|
50
|
+
dot += (f - low[k]) * d;
|
|
51
|
+
len2 += d * d;
|
|
52
|
+
}
|
|
53
|
+
if (len2 === 0)
|
|
54
|
+
return NEUTRAL_ANCHOR;
|
|
55
|
+
return clamp01(dot / len2);
|
|
56
|
+
}
|
|
57
|
+
export function computeAxisScore(axis, facets, confidence) {
|
|
58
|
+
const { low, high } = AXIS_POLES[axis];
|
|
59
|
+
const t = projectFacets(facets, low, high);
|
|
60
|
+
const c = Number.isFinite(confidence) ? clamp01(confidence) : 0;
|
|
61
|
+
return clamp01(c * t + (1 - c) * NEUTRAL_ANCHOR);
|
|
62
|
+
}
|
|
63
|
+
/**
|
|
64
|
+
* profile.axes.*.score 를 재계산해 **mutate** 하고, 하나라도 바뀌면
|
|
65
|
+
* metadata.last_reclassification_at 을 now 로 기록한다. 저장은 호출자 몫.
|
|
66
|
+
*/
|
|
67
|
+
export function recomputeProfileScores(profile, now = new Date()) {
|
|
68
|
+
const deltas = {};
|
|
69
|
+
let changed = false;
|
|
70
|
+
for (const axis of AXIS_KEYS) {
|
|
71
|
+
const a = profile.axes[axis];
|
|
72
|
+
const before = typeof a?.score === 'number' ? a.score : NEUTRAL_ANCHOR;
|
|
73
|
+
if (!a?.facets) {
|
|
74
|
+
deltas[axis] = { before, after: before };
|
|
75
|
+
continue;
|
|
76
|
+
}
|
|
77
|
+
const after = Number((computeAxisScore(axis, a.facets, a.confidence)).toFixed(4));
|
|
78
|
+
deltas[axis] = { before, after };
|
|
79
|
+
if (Math.abs(after - before) > 1e-9) {
|
|
80
|
+
a.score = after;
|
|
81
|
+
changed = true;
|
|
82
|
+
}
|
|
83
|
+
}
|
|
84
|
+
if (changed)
|
|
85
|
+
profile.metadata.last_reclassification_at = now.toISOString();
|
|
86
|
+
return { changed, deltas };
|
|
87
|
+
}
|
|
88
|
+
/**
|
|
89
|
+
* 방향 판정: 0.5 ± 0.1 은 'mid', 그 밖은 가까운 극('low'|'high'). 라벨 문자열은 렌더러가
|
|
90
|
+
* locale 에 맞춰 만든다 (critic: 하드코딩 한국어 라벨은 en 사용자에게 혼합 출력).
|
|
91
|
+
* 주의 — 'mid' 는 "미학습" 이 아니다. facet 이 서로 반대 방향이면(예: verification_depth 1.0
|
|
92
|
+
* 이지만 stop_threshold 0.25) 투영이 중간으로 수렴한다.
|
|
93
|
+
*/
|
|
94
|
+
export function axisDirection(score) {
|
|
95
|
+
if (score < 0.4)
|
|
96
|
+
return 'low';
|
|
97
|
+
if (score > 0.6)
|
|
98
|
+
return 'high';
|
|
99
|
+
return 'mid';
|
|
100
|
+
}
|
|
@@ -6,10 +6,27 @@
|
|
|
6
6
|
*/
|
|
7
7
|
import type { Profile, QualityPack, AutonomyPack, JudgmentPack, CommunicationPack, TrustPolicy } from './types.js';
|
|
8
8
|
import type { HostId } from '../core/trust-layer-intent.js';
|
|
9
|
+
import { type RecomputeResult } from './profile-score.js';
|
|
9
10
|
export declare function createProfile(userId: string, qualityPack: QualityPack, autonomyPack: AutonomyPack, trustPolicy: TrustPolicy, trustSource: Profile['trust_preferences']['source'], judgmentPack?: JudgmentPack, communicationPack?: CommunicationPack): Profile;
|
|
10
11
|
export declare function loadProfile(): Profile | null;
|
|
11
12
|
export declare function loadProfileRaw(): unknown;
|
|
12
13
|
export declare function saveProfile(profile: Profile): void;
|
|
14
|
+
/**
|
|
15
|
+
* ADR-017 §6-8: facet 또는 confidence 가 바뀐 뒤에는 반드시 이 경로로 저장한다.
|
|
16
|
+
* 4축 score 를 재계산(profile-score.ts)하고 last_reclassification_at 을 기록한 뒤 저장.
|
|
17
|
+
* facet/confidence 를 건드리는 코드 쓰기(bumpAxisConfidence, auto-compound profile_delta)는
|
|
18
|
+
* saveProfile 직접 호출 대신 이 함수를 쓴다 — raw write 로 우회하면 score 가 다시 고정된다
|
|
19
|
+
* (v0.1.0~0.5.9 결함의 원인). 주의: calibrate 스킬(skills/calibrate)은 Claude 세션이 파일을
|
|
20
|
+
* 직접 편집하는 설계라 이 경로를 타지 않는다 — 그 경우 다음 bump/auto-compound 또는
|
|
21
|
+
* SessionStart 까지 score 가 stale 일 수 있다.
|
|
22
|
+
*/
|
|
23
|
+
export declare function saveProfileRecomputed(profile: Profile): RecomputeResult;
|
|
24
|
+
/**
|
|
25
|
+
* 1회성 마이그레이션: score 산출 로직이 없던 버전에서 만들어진 프로필은
|
|
26
|
+
* last_reclassification_at 이 null 이다. 그 경우에만 재계산·저장하고 결과를 반환.
|
|
27
|
+
* (SessionStart bootstrap 이 호출. 이미 계산된 프로필은 건드리지 않는다.)
|
|
28
|
+
*/
|
|
29
|
+
export declare function recomputeIfNeverReclassified(): RecomputeResult | null;
|
|
13
30
|
/**
|
|
14
31
|
* File existence probe. NOTE: this returns `true` even if the on-disk
|
|
15
32
|
* file is legacy/invalid — callers that need "valid v1 profile present"
|
|
@@ -34,12 +51,12 @@ export declare function isV1Profile(data: unknown): data is Profile;
|
|
|
34
51
|
/**
|
|
35
52
|
* D2 fix (2026-04-27): explicit_correction 누적 시 해당 축의 confidence 를 점진
|
|
36
53
|
* 상승시킨다. facet 값은 건드리지 않음 (회귀 위험 최소화) — confidence 가 score
|
|
37
|
-
* 집계 공식 (confidence ×
|
|
38
|
-
* 라서, 사용자가 명시 교정을 누적한 축은 score 가 facet
|
|
54
|
+
* 집계 공식 (confidence × facet_pos + (1-confidence) × neutral_anchor) 의 가중치
|
|
55
|
+
* 라서, 사용자가 명시 교정을 누적한 축은 score 가 facet 위치를 더 강하게 반영.
|
|
39
56
|
*
|
|
40
|
-
* 자기증거: autonomy explicit_correction 6건이 score 를 못
|
|
41
|
-
* 갱신
|
|
42
|
-
*
|
|
57
|
+
* 자기증거: autonomy explicit_correction 6건이 score 를 못 움직였음. 원인은 두 겹 —
|
|
58
|
+
* (1) facet 갱신 경로 부재, (2) **score 집계 공식 자체가 미구현**(2026-10-06 ADR-017 §1.5b
|
|
59
|
+
* 확인: v0.1.0 부터 score 는 0.5 리터럴 고정). (2)는 profile-score.ts 가 해결.
|
|
43
60
|
*
|
|
44
61
|
* delta 기본 0.02 — 6건 누적 시 +0.12 → 0.45 → 0.57 (의미 있는 변동 가시화).
|
|
45
62
|
* clamp 0~1.
|
|
@@ -8,6 +8,7 @@ import * as fs from 'node:fs';
|
|
|
8
8
|
import { FORGE_PROFILE } from '../core/paths.js';
|
|
9
9
|
import { atomicWriteJSON, safeReadJSON } from '../hooks/shared/atomic-write.js';
|
|
10
10
|
import { qualityCentroid, autonomyCentroid, judgmentCentroid, communicationCentroid, } from '../preset/facet-catalog.js';
|
|
11
|
+
import { recomputeProfileScores } from './profile-score.js';
|
|
11
12
|
const MODEL_VERSION = '2.0';
|
|
12
13
|
export function createProfile(userId, qualityPack, autonomyPack, trustPolicy, trustSource, judgmentPack = '균형형', communicationPack = '균형형') {
|
|
13
14
|
const now = new Date().toISOString();
|
|
@@ -55,6 +56,40 @@ export function saveProfile(profile) {
|
|
|
55
56
|
profile.metadata.updated_at = new Date().toISOString();
|
|
56
57
|
atomicWriteJSON(FORGE_PROFILE, profile, { pretty: true });
|
|
57
58
|
}
|
|
59
|
+
/**
|
|
60
|
+
* ADR-017 §6-8: facet 또는 confidence 가 바뀐 뒤에는 반드시 이 경로로 저장한다.
|
|
61
|
+
* 4축 score 를 재계산(profile-score.ts)하고 last_reclassification_at 을 기록한 뒤 저장.
|
|
62
|
+
* facet/confidence 를 건드리는 코드 쓰기(bumpAxisConfidence, auto-compound profile_delta)는
|
|
63
|
+
* saveProfile 직접 호출 대신 이 함수를 쓴다 — raw write 로 우회하면 score 가 다시 고정된다
|
|
64
|
+
* (v0.1.0~0.5.9 결함의 원인). 주의: calibrate 스킬(skills/calibrate)은 Claude 세션이 파일을
|
|
65
|
+
* 직접 편집하는 설계라 이 경로를 타지 않는다 — 그 경우 다음 bump/auto-compound 또는
|
|
66
|
+
* SessionStart 까지 score 가 stale 일 수 있다.
|
|
67
|
+
*/
|
|
68
|
+
export function saveProfileRecomputed(profile) {
|
|
69
|
+
const r = recomputeProfileScores(profile);
|
|
70
|
+
saveProfile(profile);
|
|
71
|
+
return r;
|
|
72
|
+
}
|
|
73
|
+
/**
|
|
74
|
+
* 1회성 마이그레이션: score 산출 로직이 없던 버전에서 만들어진 프로필은
|
|
75
|
+
* last_reclassification_at 이 null 이다. 그 경우에만 재계산·저장하고 결과를 반환.
|
|
76
|
+
* (SessionStart bootstrap 이 호출. 이미 계산된 프로필은 건드리지 않는다.)
|
|
77
|
+
*/
|
|
78
|
+
export function recomputeIfNeverReclassified() {
|
|
79
|
+
const profile = loadProfile();
|
|
80
|
+
if (!profile)
|
|
81
|
+
return null;
|
|
82
|
+
// 키 누락(구버전 파일)도 null 로 취급 — `!== null` 만 보면 영구 스킵된다 (critic).
|
|
83
|
+
if (profile.metadata.last_reclassification_at)
|
|
84
|
+
return null;
|
|
85
|
+
const r = recomputeProfileScores(profile);
|
|
86
|
+
// "1회" 불변식: 계산 결과가 저장값과 같아 changed=false 여도 실행 사실을 스탬프한다.
|
|
87
|
+
// 안 그러면 매 SessionStart 마다 재계산·재저장을 반복한다 (critic SEV-2).
|
|
88
|
+
if (!profile.metadata.last_reclassification_at)
|
|
89
|
+
profile.metadata.last_reclassification_at = new Date().toISOString();
|
|
90
|
+
saveProfile(profile);
|
|
91
|
+
return r;
|
|
92
|
+
}
|
|
58
93
|
/**
|
|
59
94
|
* File existence probe. NOTE: this returns `true` even if the on-disk
|
|
60
95
|
* file is legacy/invalid — callers that need "valid v1 profile present"
|
|
@@ -98,12 +133,12 @@ export function isV1Profile(data) {
|
|
|
98
133
|
/**
|
|
99
134
|
* D2 fix (2026-04-27): explicit_correction 누적 시 해당 축의 confidence 를 점진
|
|
100
135
|
* 상승시킨다. facet 값은 건드리지 않음 (회귀 위험 최소화) — confidence 가 score
|
|
101
|
-
* 집계 공식 (confidence ×
|
|
102
|
-
* 라서, 사용자가 명시 교정을 누적한 축은 score 가 facet
|
|
136
|
+
* 집계 공식 (confidence × facet_pos + (1-confidence) × neutral_anchor) 의 가중치
|
|
137
|
+
* 라서, 사용자가 명시 교정을 누적한 축은 score 가 facet 위치를 더 강하게 반영.
|
|
103
138
|
*
|
|
104
|
-
* 자기증거: autonomy explicit_correction 6건이 score 를 못
|
|
105
|
-
* 갱신
|
|
106
|
-
*
|
|
139
|
+
* 자기증거: autonomy explicit_correction 6건이 score 를 못 움직였음. 원인은 두 겹 —
|
|
140
|
+
* (1) facet 갱신 경로 부재, (2) **score 집계 공식 자체가 미구현**(2026-10-06 ADR-017 §1.5b
|
|
141
|
+
* 확인: v0.1.0 부터 score 는 0.5 리터럴 고정). (2)는 profile-score.ts 가 해결.
|
|
107
142
|
*
|
|
108
143
|
* delta 기본 0.02 — 6건 누적 시 +0.12 → 0.45 → 0.57 (의미 있는 변동 가시화).
|
|
109
144
|
* clamp 0~1.
|
|
@@ -119,7 +154,8 @@ export function bumpAxisConfidence(axis, delta = 0.02) {
|
|
|
119
154
|
if (next === target.confidence)
|
|
120
155
|
return false;
|
|
121
156
|
target.confidence = next;
|
|
122
|
-
|
|
157
|
+
// ADR-017: confidence 는 score 공식의 가중치이므로 바뀌면 score 를 재계산한다.
|
|
158
|
+
saveProfileRecomputed(profile);
|
|
123
159
|
return true;
|
|
124
160
|
}
|
|
125
161
|
export function getDefaultHost() {
|
|
@@ -0,0 +1,39 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Rule origin — "이 룰은 언제 어떤 교정에서 생겼는가" (ADR-017 D0)
|
|
3
|
+
*
|
|
4
|
+
* 체감의 가장 싼 레버: 차단 메시지와 룰 렌더에 룰의 출처 교정(날짜·종류·문장)을 붙인다.
|
|
5
|
+
* explicit_correction 룰만 대상 — 채굴 룰(behavior_inference)은 사용자가 한 말이 아니므로
|
|
6
|
+
* 인용하지 않는다(ADR-013 provenance 차등).
|
|
7
|
+
*
|
|
8
|
+
* 정직성 (critic D0 SEV-2-a): evidence.summary 는 correction-record 를 호출한 **모델이 쓴 문장**이고
|
|
9
|
+
* 실데이터 12/12 에서 rule.policy 와 동일하다. 그래서
|
|
10
|
+
* - raw_payload.user_quote (사용자 발화 원문, 2026-10-06 부터 저장) 가 있을 때만 "당신의 말" 로 인용하고
|
|
11
|
+
* - 없으면 "교정 기록 YYYY-MM-DD (kind)" 만 표기한다. summary 가 policy 와 같으면 인용문을 생략한다
|
|
12
|
+
* (같은 문장을 두 번 보여주는 중복 방지).
|
|
13
|
+
*
|
|
14
|
+
* 비용: evidence 파일 1개를 safeReadJSON 으로 직접 읽는다 — evidence-store 모듈 그래프(lifecycle·
|
|
15
|
+
* classifier 등 18모듈)를 끌어오지 않는다 (critic SEV-2-b). 모든 경로 fail-open(null).
|
|
16
|
+
*/
|
|
17
|
+
import type { Rule } from './types.js';
|
|
18
|
+
export interface RuleOrigin {
|
|
19
|
+
/** YYYY-MM-DD (evidence timestamp 기준). */
|
|
20
|
+
date: string;
|
|
21
|
+
/** correction-record kind: fix-now | prefer-from-now | avoid-this (없으면 undefined). */
|
|
22
|
+
kind?: string;
|
|
23
|
+
/** 인용할 문장. 사용자 원문(user_quote)이 있으면 그것, 없고 summary 가 policy 와 다르면 summary, 같으면 ''. */
|
|
24
|
+
quote: string;
|
|
25
|
+
/** quote 의 출처 — 'user'(발화 원문) | 'summary'(모델 요약) | 'none'. */
|
|
26
|
+
quoteSource: 'user' | 'summary' | 'none';
|
|
27
|
+
}
|
|
28
|
+
export declare const MAX_QUOTE = 90;
|
|
29
|
+
/** 한 줄·안전한 인용문: 공백 정규화, 제어문자·꺾쇠·백틱 제거, 길이 제한 (critic SEV-2-c). */
|
|
30
|
+
export declare function sanitizeQuote(raw: string): string;
|
|
31
|
+
type OriginRule = Pick<Rule, 'source' | 'evidence_refs'> & {
|
|
32
|
+
policy?: string;
|
|
33
|
+
};
|
|
34
|
+
export declare function ruleOrigin(rule: OriginRule): RuleOrigin | null;
|
|
35
|
+
/** 차단/안내 메시지용 한 줄. 출처가 없으면 ''. */
|
|
36
|
+
export declare function originLine(rule: OriginRule): string;
|
|
37
|
+
/** 룰 렌더(v1-rules.md 등)용 짧은 꼬리표. 토큰 절감을 위해 날짜만. 출처 없으면 ''. */
|
|
38
|
+
export declare function originTag(rule: OriginRule): string;
|
|
39
|
+
export {};
|
|
@@ -0,0 +1,84 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Rule origin — "이 룰은 언제 어떤 교정에서 생겼는가" (ADR-017 D0)
|
|
3
|
+
*
|
|
4
|
+
* 체감의 가장 싼 레버: 차단 메시지와 룰 렌더에 룰의 출처 교정(날짜·종류·문장)을 붙인다.
|
|
5
|
+
* explicit_correction 룰만 대상 — 채굴 룰(behavior_inference)은 사용자가 한 말이 아니므로
|
|
6
|
+
* 인용하지 않는다(ADR-013 provenance 차등).
|
|
7
|
+
*
|
|
8
|
+
* 정직성 (critic D0 SEV-2-a): evidence.summary 는 correction-record 를 호출한 **모델이 쓴 문장**이고
|
|
9
|
+
* 실데이터 12/12 에서 rule.policy 와 동일하다. 그래서
|
|
10
|
+
* - raw_payload.user_quote (사용자 발화 원문, 2026-10-06 부터 저장) 가 있을 때만 "당신의 말" 로 인용하고
|
|
11
|
+
* - 없으면 "교정 기록 YYYY-MM-DD (kind)" 만 표기한다. summary 가 policy 와 같으면 인용문을 생략한다
|
|
12
|
+
* (같은 문장을 두 번 보여주는 중복 방지).
|
|
13
|
+
*
|
|
14
|
+
* 비용: evidence 파일 1개를 safeReadJSON 으로 직접 읽는다 — evidence-store 모듈 그래프(lifecycle·
|
|
15
|
+
* classifier 등 18모듈)를 끌어오지 않는다 (critic SEV-2-b). 모든 경로 fail-open(null).
|
|
16
|
+
*/
|
|
17
|
+
import * as path from 'node:path';
|
|
18
|
+
import { ME_BEHAVIOR } from '../core/paths.js';
|
|
19
|
+
import { safeReadJSON } from '../hooks/shared/atomic-write.js';
|
|
20
|
+
export const MAX_QUOTE = 90;
|
|
21
|
+
/** 한 줄·안전한 인용문: 공백 정규화, 제어문자·꺾쇠·백틱 제거, 길이 제한 (critic SEV-2-c). */
|
|
22
|
+
export function sanitizeQuote(raw) {
|
|
23
|
+
// 제어문자(0x00-0x1f, 0x7f)는 문자 코드로 걸러낸다 — 정규식 리터럴의 제어문자 escape 는 biome 이 금지.
|
|
24
|
+
const noCtrl = Array.from(raw, (ch) => { const c = ch.charCodeAt(0); return c < 0x20 || c === 0x7f ? ' ' : ch; }).join('');
|
|
25
|
+
const oneLine = noCtrl
|
|
26
|
+
.replace(/[<>`]/g, '')
|
|
27
|
+
.replace(/\s+/g, ' ')
|
|
28
|
+
.trim();
|
|
29
|
+
return oneLine.length > MAX_QUOTE ? `${oneLine.slice(0, MAX_QUOTE - 1)}…` : oneLine;
|
|
30
|
+
}
|
|
31
|
+
function readEvidence(id) {
|
|
32
|
+
if (!/^[A-Za-z0-9_-]+$/.test(id))
|
|
33
|
+
return null; // 경로 인젝션 방지
|
|
34
|
+
return safeReadJSON(path.join(ME_BEHAVIOR, `${id}.json`), null);
|
|
35
|
+
}
|
|
36
|
+
export function ruleOrigin(rule) {
|
|
37
|
+
try {
|
|
38
|
+
if (rule.source !== 'explicit_correction')
|
|
39
|
+
return null;
|
|
40
|
+
// 가장 최근 교정 — append 순이 아니라 timestamp 로 고른다 (클러스터링으로 refs 가 늘면 순서 보장 없음).
|
|
41
|
+
let best = null;
|
|
42
|
+
for (const id of rule.evidence_refs ?? []) {
|
|
43
|
+
const ev = readEvidence(id);
|
|
44
|
+
if (ev?.type !== 'explicit_correction' || typeof ev.timestamp !== 'string')
|
|
45
|
+
continue;
|
|
46
|
+
if (!best || ev.timestamp > best.timestamp)
|
|
47
|
+
best = ev;
|
|
48
|
+
}
|
|
49
|
+
if (!best)
|
|
50
|
+
return null;
|
|
51
|
+
const date = best.timestamp.slice(0, 10);
|
|
52
|
+
if (!date)
|
|
53
|
+
return null;
|
|
54
|
+
const kind = typeof best.raw_payload?.kind === 'string' ? best.raw_payload.kind : undefined;
|
|
55
|
+
const userQuote = typeof best.raw_payload?.user_quote === 'string' ? sanitizeQuote(best.raw_payload.user_quote) : '';
|
|
56
|
+
if (userQuote)
|
|
57
|
+
return { date, kind, quote: userQuote, quoteSource: 'user' };
|
|
58
|
+
const summary = typeof best.summary === 'string' ? sanitizeQuote(best.summary) : '';
|
|
59
|
+
const policy = typeof rule.policy === 'string' ? sanitizeQuote(rule.policy) : '';
|
|
60
|
+
if (summary && summary !== policy)
|
|
61
|
+
return { date, kind, quote: summary, quoteSource: 'summary' };
|
|
62
|
+
return { date, kind, quote: '', quoteSource: 'none' };
|
|
63
|
+
}
|
|
64
|
+
catch {
|
|
65
|
+
return null;
|
|
66
|
+
}
|
|
67
|
+
}
|
|
68
|
+
/** 차단/안내 메시지용 한 줄. 출처가 없으면 ''. */
|
|
69
|
+
export function originLine(rule) {
|
|
70
|
+
const o = ruleOrigin(rule);
|
|
71
|
+
if (!o)
|
|
72
|
+
return '';
|
|
73
|
+
const kind = o.kind ? ` (${o.kind})` : '';
|
|
74
|
+
if (o.quoteSource === 'user')
|
|
75
|
+
return `[forgen] 이 룰의 출처 — ${o.date} 당신의 말${kind}: "${o.quote}"`;
|
|
76
|
+
if (o.quoteSource === 'summary')
|
|
77
|
+
return `[forgen] 이 룰의 출처 — ${o.date} 교정 기록${kind}: "${o.quote}"`;
|
|
78
|
+
return `[forgen] 이 룰의 출처 — ${o.date} 교정 기록${kind}`;
|
|
79
|
+
}
|
|
80
|
+
/** 룰 렌더(v1-rules.md 등)용 짧은 꼬리표. 토큰 절감을 위해 날짜만. 출처 없으면 ''. */
|
|
81
|
+
export function originTag(rule) {
|
|
82
|
+
const o = ruleOrigin(rule);
|
|
83
|
+
return o ? ` (교정 ${o.date})` : '';
|
|
84
|
+
}
|
package/dist/store/types.d.ts
CHANGED
|
@@ -106,6 +106,11 @@ export interface Rule {
|
|
|
106
106
|
* ADR-001 §Data Model.
|
|
107
107
|
*/
|
|
108
108
|
enforce_via?: EnforceSpec[];
|
|
109
|
+
/**
|
|
110
|
+
* ADR-017 D1: precision 자동 강등. 'advise' 면 Mech-A/B 가 차단 대신 기록(kind:'correction')만 한다.
|
|
111
|
+
* 하드 룰(strength 'hard')과 builtin 은 자동으로 'advise' 가 되지 않는다. 미지정 = 'block'.
|
|
112
|
+
*/
|
|
113
|
+
enforce_mode?: 'block' | 'advise';
|
|
109
114
|
/**
|
|
110
115
|
* Lifecycle 상태. optional — 기존 rule 은 load 시 phase='active' 로 auto-initialize.
|
|
111
116
|
* ADR-002 §Data Model.
|
|
@@ -117,6 +122,20 @@ export interface Rule {
|
|
|
117
122
|
* 통합 rule 쪽에는 설정되지 않는다(원본에만). ADR-010 W3-2.
|
|
118
123
|
*/
|
|
119
124
|
clustered_into?: string;
|
|
125
|
+
/**
|
|
126
|
+
* ADR-017 D3: 채굴(behavior_inference) 룰과 explicit 룰이 같은 개념일 때의 *링크*.
|
|
127
|
+
* 흡수가 아니다 — evidence_refs/strength 는 양쪽 모두 불변(ADR-013 불변식).
|
|
128
|
+
* - explicit 룰 쪽: 이 룰과 같은 개념으로 링크된 채굴 rule_id 목록.
|
|
129
|
+
* - 채굴 룰 쪽: 링크 대상 explicit rule_id(1개). status 'superseded' + clustered_into 와 함께
|
|
130
|
+
* 설정되어 렌더에서 숨겨지고 `forgen rule unmerge` 로 복원된다.
|
|
131
|
+
*/
|
|
132
|
+
related_to?: string[];
|
|
133
|
+
/**
|
|
134
|
+
* ADR-017 D3: explicit 룰에만 설정. 이 룰과 같은 개념이 이후 세션에서 *채굴*로 관측된 횟수
|
|
135
|
+
* (링크된 채굴 룰의 evidence 수 + 사전 중복 검사에서 흡수된 채굴 evidence 수).
|
|
136
|
+
* evidence_refs 에 합산하지 않으므로 strength 산출에 영향을 주지 않는다.
|
|
137
|
+
*/
|
|
138
|
+
mined_observations?: number;
|
|
120
139
|
}
|
|
121
140
|
export type EvidenceType = 'explicit_correction' | 'behavior_observation' | 'session_summary';
|
|
122
141
|
export interface Evidence {
|
|
@@ -240,6 +259,11 @@ export interface CorrectionRequest {
|
|
|
240
259
|
message: string;
|
|
241
260
|
target: string;
|
|
242
261
|
axis_hint: 'quality_safety' | 'autonomy' | 'judgment_philosophy' | 'communication_style' | null;
|
|
262
|
+
/**
|
|
263
|
+
* ADR-017 D0 (2026-10-06): 사용자 발화 **원문** (모델이 정리한 message 와 구분). 있을 때만
|
|
264
|
+
* 차단 메시지가 "당신의 말" 로 인용한다. <private> 필터 후 저장.
|
|
265
|
+
*/
|
|
266
|
+
user_quote?: string;
|
|
243
267
|
}
|
|
244
268
|
export interface CorrectionResult {
|
|
245
269
|
temporary_rule: Rule | null;
|
package/package.json
CHANGED
package/plugin.json
CHANGED