# lolympus-agent Evaluation Stage 2 — Implementation Plan > **Audience**: Codex(또는 다른 AI 에이전트)가 self-contained하게 작업할 수 있도록 작성됨. 기존 `/Users/dahyeon/source/lolympus-agent/plan.md`의 Phase 0–5(Phase 5에서 shadow eval / judge / alert 인프라가 이미 완성됨)를 전제로 하며, 그 위에 **evaluation 깊이와 활용 폭**을 강화한다. > > **충돌 시 우선순위**: 본 문서 > `plan.md`. 단 Phase 0–5의 인터페이스/스키마/env 컨벤션은 그대로 따른다. > > **운영 runbook**: 구현 후 서비스 운영 흐름과 evaluation CLI/Redis/Mongo/장애 대응은 `docs/service-evaluation-operations.md`를 기준으로 확인한다. --- ## 1. Context (왜 이 작업) ### 문제 Phase 5 직후 evaluation 인프라는 굴러가지만 **데이터가 한쪽으로만 흐르고, 깊이가 얕고, 사람 검증이 없다**: 1. **얕은 평가 (outcome-only)** — 현재 judge는 최종 응답 텍스트 한 점만 평가. classifier 오분류, derive 잘못된 tier 결정, planner의 approach 선택 오류, tool args 오류 등 **회귀 원인이 어느 단계인지 핀포인트 불가**. 2. **데이터 활용 부재** — `lolympus-agent:eval:results` Stream이 MAXLEN=10000으로 쌓이고 잘려 나갈 뿐, alert trigger 외에 **분석/리포팅/재학습 루프 0건**. 어느 intent/tier가 약한지 가시화 안 됨. Drift detection 없음. 3. **휘발성** — Redis Stream MAXLEN 정책으로 7일 이전 데이터는 사실상 사라짐. 장기 추세 분석 불가. 4. **사람 검증 부재** — LLM judge가 곧 진실. judge 자체가 잘못 평가해도 잡을 길 없음. golden set이 정적이라 온라인 분포 변화에 따라가지 못함. 5. **개선 루프 부재** — eval이 약점을 보여줘도 prompt/tool/process 개선까지 사람이 매번 손으로 잇는다. ### 의도한 결과 - 회귀 발생 시 "어느 단계가 깨졌는지" 5분 내 식별 - shadow eval 30일치 영속 보관 + 슬라이스별 점수 가시화 - 약한 슬라이스의 케이스가 자동으로 사람 검토 큐에 들어가고, 라벨된 케이스가 golden set 후보로 자동 적립 - 약점 슬라이스에 대해 prompt/tool 개선 후보가 LLM에 의해 제안되고, A/B 토너먼트로 검증된 뒤 PR로 머지 ### 비목표 - Front-end 대시보드 구축 — 분석은 CLI 명령으로 충분 (필요 시 별도 후속 plan) - 실시간(stream) ML 학습 — judge/golden은 batch 갱신 - 다중 skill 일반화 — onboarding 단일 skill 전제 (`plan.md` §13의 결정 유지) --- ## 2. Relationship to `plan.md` (기존 인프라) ### 그대로 사용 (변경 없음) - `src/eval/{capture,anonymize,runner,cli,types,shadow-bus,shadow-worker}.ts` - `src/eval/judges/{rule-judge,llm-judge}.ts` - `src/eval/golden/onboarding.jsonl` - Redis: `lolympus-agent:eval:results`, `lolympus-agent:eval:baseline`, `lolympus-agent:background[:dlq]` - NATS: `lolympus-agent.alert`, `lolympus-agent.eval.report` - env: `SHADOW_EVAL_SAMPLING_RATE_TIER{0,1,2}`, `ALERT_THRESHOLD_*`, `LLM_JUDGE_*`, `EVAL_STREAM_MAXLEN`, `EVAL_RESULTS_TTL_SEC` - 익명화 salt 하드코딩 (`EVAL_ANON_SALT="lolympus-agent-v1"`) ### 확장 / 변경 - `shadow-bus.ts`: `ShadowEvalEnvelope`에 `process` 필드 추가 (Phase 7) - `shadow-worker.ts`: aggregator tick / persistence / drift / review-routing tick 추가 (Phase 6, 8) - `runner.ts`: per-case 결과에 `processJudge` 필드 추가 (Phase 7) - `judges/llm-judge.ts`: 변경 없음. 신규 `judges/process-judge.ts` 추가 (Phase 7) - `cli.ts`: `eval:review`, `eval:promote`, `eval:report`, `eval:tournament` 명령 추가 ### 신규 의존 - 없음. 모든 신규 기능은 이미 의존 중인 라이브러리(Redis/Garnet, MongoDB driver, Zod, `LlmClient`)로 구현 가능. --- ## 3. Target Architecture (강화 후) ``` [agent runtime] │ ┌────────────┴───────────┐ ▼ ▼ ShadowEvalEnvelope OTel span tree (+ process snapshot) (per-step trace) │ ▼ lolympus-agent:background ── stream ──┐ │ ┌───────────────┘ ▼ ShadowWorker ┌──────────────────────┼──────────────────────┐ │ │ │ [LLM judge] [Process judge] [Aggregator tick / 5m] (outcome 4축) (per-step rubric) slice = tier × intent × phase │ │ │ ▼ ▼ ▼ eval:results Stream ──┬─→ MongoDB eval_archive (24h tick: 영속) │ ├─→ Drift detector (24h vs 7d 평균) │ └→ NATS lolympus-agent.alert │ └─→ Review router └→ eval:review:queue Stream │ [npm run eval:review CLI] │ ┌───────┴────────┐ ▼ ▼ eval:review:labeled Calibration metric Stream (사람 vs LLM 상관) │ ▼ Auto-promotion (nightly) └→ src/eval/golden/onboarding.candidate.jsonl │ (사람이 batch curation → golden.jsonl PR) [Closed loop: 별도 CLI orchestration] eval:report → 약점 슬라이스 식별 (top-k) │ ▼ eval:propose → LLM이 prompt diff / tool 후보 생성 │ ▼ eval:tournament → shadow에서 두 prompt 버전 동시 실행, side-by-side LLM judge ELO 랭킹 → 승자가 PR draft 생성 ``` --- ## 4. Phase Plan 각 Phase는 **독립 PR**. 의존: 6 → 7, 6 → 8 (병렬 가능), 7+8 → 9. 개발 순서 권장: **Phase 6 → 7 → 8 → 9**. | Phase | 제목 | 추정 | |---|---|---| | 6 | Shadow data 활용 (Aggregator / Persistence / Drift / Auto-promotion) | 5–7일 | | 7 | Process-based evaluation (단계별 trace judge) | 4–5일 | | 8 | Hybrid HITL (Review CLI + Calibration) | 3–4일 | | 9 | Closed loop (prompt/tool propose + A/B tournament) | 5–7일 | 총 17–23일 (단일 개발자). --- ## 5. Phase 6 — Shadow Data 활용 ### 5.1 Critical Files - **신규**: - `src/eval/aggregator.ts` — slice별 5분 tick aggregator - `src/eval/archive.ts` — Redis Stream → MongoDB 영속화 - `src/eval/drift.ts` — 24h vs 7d 평균 회귀 감지 - `src/eval/promote.ts` — 약점 케이스를 candidate jsonl에 적재 - `src/eval/golden/onboarding.candidate.jsonl` — 자동 후보 (gitignore 안 함, 사람이 검토 후 golden으로 promote) - `src/eval/aggregator.test.ts`, `src/eval/archive.test.ts`, `src/eval/drift.test.ts`, `src/eval/promote.test.ts` - **변경**: - `src/eval/shadow-worker.ts` — `runLoop()`에 5분 tick(aggregator), 1시간 tick(archive), 24시간 tick(promote+drift) 추가 - `src/eval/cli.ts` — `eval:report`, `eval:promote` 명령 추가 - `src/common/env-loader.ts` — 신규 env 등록 (§5.6) - `src/common/known-secret-keys.ts` — `MONGODB_CONNECTION_STRING`은 이미 등록됨, 변경 없음 ### 5.2 Aggregator (`src/eval/aggregator.ts`) ```typescript export interface SliceKey { tier: 0 | 1 | 2; intent: string; phase: string; } export interface SliceMetrics { count: number; llmOverallSum: number; llmOverallCount: number; validatorRejectCount: number; validatorSoftWarnCount: number; latencySumMs: number; latencySamples: number[]; // 윈도우 내 최대 200개 샘플로 cap (P95 계산용) updatedAt: string; } export function sliceKeyToString(key: SliceKey): string { return `${key.tier}:${key.intent}:${key.phase}`; } export async function aggregateRecentEvalResults( garnetClient: GarnetClient, options: { sinceId: string; nowMs: number } ): Promise<{ lastSeenId: string; updatedSlices: number }>; ``` - shadow-worker가 5분마다 호출. `XRANGE lolympus-agent:eval:results sinceId +` 로 미aggregated entry 조회 - 각 entry를 SliceKey로 분류 → `lolympus-agent:eval:agg:{sliceKeyString}` Hash에 누적 (HINCRBY/HSET) - TTL: `EVAL_AGG_TTL_SEC` (기본 7일). 7일 지난 슬라이스는 expire 후 archive(§5.3)에서 복원 가능 - "최근 sinceId"는 `lolympus-agent:eval:agg:cursor` String에 보관 (worker 재기동 시 복원) - `eval:report` CLI가 `SCAN 0 MATCH lolympus-agent:eval:agg:* COUNT 200`으로 전 슬라이스 읽어 표 출력 ### 5.3 Persistence (`src/eval/archive.ts`) ```typescript export interface EvalArchiveEntry { streamId: string; evaluatedAt: string; // UTC ISO // 이하 stream entry 그대로 request: AgentRequest; response: AgentResponse; derived: DerivedState; classified: ClassifiedIntent; validation: ValidationResult; llmJudge: LlmJudgeResult; processJudge?: ProcessJudgeResult; // Phase 7에서 추가 latencyMs: number | null; tier: 0 | 1 | 2; } export async function archiveEvalResults( garnetClient: GarnetClient, mongoClient: MongoClient, options: { sinceId: string; nowMs: number; batchSize?: number } ): Promise<{ lastArchivedId: string; archivedCount: number }>; ``` - 1시간마다 호출. `XRANGE lolympus-agent:eval:results sinceId +` → MongoDB `eval_archive` 컬렉션 bulk insert (`{ ordered: false }`) - `streamId` unique index. 중복 insert는 silently skip - TTL index: `evaluatedAt` 기준 `EVAL_ARCHIVE_TTL_DAYS` (기본 30일) 후 자동 삭제 - "마지막 archive id"는 `lolympus-agent:eval:archive:cursor` String에 보관 - Mongo write 실패 시: warn 로그 + cursor 미업데이트 → 다음 tick 재시도. 3회 연속 실패 시 alert(`kind="archive-stalled"`) ### 5.4 Drift detection (`src/eval/drift.ts`) ```typescript export interface DriftReport { slice: SliceKey; recent24hAverage: number; recent7dAverage: number; dropPct: number; significant: boolean; // 통계적 유의성 (count ≥ 30 && drop ≥ ALERT_THRESHOLD_DRIFT_PCT) } export async function computeDriftReports( mongoClient: MongoClient, options?: { metricKey?: "llmOverall" | "validatorPassRate" } ): Promise; ``` - 24시간마다 호출. MongoDB `eval_archive`에서 24h 평균 vs 7d 평균을 slice별 aggregation - `dropPct ≥ ALERT_THRESHOLD_DRIFT_PCT` (기본 15%) && 24h 표본 수 ≥ 30 → `lolympus-agent.alert` publish (`kind="eval-drift"`, severity는 dropPct에 따라 warn/critical) - baseline alert와 별개 — baseline은 골든셋 회귀, drift는 운영 분포 회귀 ### 5.5 Auto-promotion (`src/eval/promote.ts`) ```typescript export interface PromotionCandidate { caseId: string; // anonymize된 streamId request: AgentRequest; response: AgentResponse; derived: DerivedState; llmJudge: LlmJudgeResult; reason: "low-score" | "rule-llm-disagree" | "rare-slice"; } export async function selectPromotionCandidates( mongoClient: MongoClient, options?: { limit?: number; minLowScore?: number } ): Promise; export async function appendCandidatesToJsonl( candidates: PromotionCandidate[], outputPath?: string ): Promise<{ appendedCount: number; outputPath: string }>; ``` - 24시간마다 호출. MongoDB에서 지난 24h 결과를 다음 기준으로 선정 (각 카테고리당 최대 10건): 1. **low-score**: `llmJudge.scores.overall ≤ EVAL_PROMOTE_LOW_SCORE` (기본 2) 2. **rule-llm-disagree**: `validation.status === "pass"` && `llmJudge.scores.overall ≤ 3` (또는 반대) 3. **rare-slice**: SliceKey 카운트가 `EVAL_PROMOTE_RARE_THRESHOLD` (기본 5)건 이하인 슬라이스에서 1건 - 모든 후보는 `anonymize.ts`의 함수로 다시 익명화 (이미 익명화돼 있어도 재적용 — defense in depth) - 결과를 `src/eval/golden/onboarding.candidate.jsonl`에 append (line-by-line, `EvalCaseDefinition` 포맷, `expected` 필드는 비워두고 `notes`에 promotion reason 기재) - 사람이 batch로 curation해 `onboarding.jsonl`로 옮기고 candidate에서 삭제 (수동) ### 5.6 신규 env | Key | 기본값 | 설명 | |---|---|---| | `EVAL_AGG_TICK_MS` | 300000 | aggregator tick 주기 (5분) | | `EVAL_AGG_TTL_SEC` | 604800 | slice Hash TTL (7일) | | `EVAL_AGG_LATENCY_SAMPLE_CAP` | 200 | slice당 P95 계산용 샘플 cap | | `EVAL_ARCHIVE_TICK_MS` | 3600000 | archive tick 주기 (1시간) | | `EVAL_ARCHIVE_TTL_DAYS` | 30 | MongoDB TTL index | | `EVAL_ARCHIVE_BATCH_SIZE` | 500 | 한 tick당 archive batch size | | `EVAL_DRIFT_TICK_MS` | 86400000 | drift detection tick (24시간) | | `ALERT_THRESHOLD_DRIFT_PCT` | 15 | 24h vs 7d 평균 drop 임계 (%) | | `EVAL_PROMOTE_TICK_MS` | 86400000 | promotion tick (24시간) | | `EVAL_PROMOTE_LOW_SCORE` | 2 | low-score 카테고리 임계 | | `EVAL_PROMOTE_RARE_THRESHOLD` | 5 | rare-slice 임계 카운트 | | `EVAL_PROMOTE_PER_CATEGORY_LIMIT` | 10 | 카테고리당 최대 선정 수 | ### 5.7 신규 Redis key | Key Pattern | Type | TTL | 설명 | |---|---|---|---| | `lolympus-agent:eval:agg:{tier}:{intent}:{phase}` | Hash | `EVAL_AGG_TTL_SEC` | slice별 누적 메트릭 | | `lolympus-agent:eval:agg:cursor` | String | no TTL | 마지막 aggregated stream id | | `lolympus-agent:eval:archive:cursor` | String | no TTL | 마지막 archive stream id | | `lolympus-agent:alert:dedupe:eval-drift:{sliceKey}` | String | `ALERT_RATE_LIMIT_SEC` | drift alert dedupe | ### 5.8 신규 NATS subject - 없음. drift alert는 기존 `lolympus-agent.alert` 재사용 (`kind="eval-drift"`, `kind="archive-stalled"` 추가) ### 5.9 CLI 추가 (`src/eval/cli.ts`) - `eval:report` — slice 표 출력 - `--top=20` (기본): 카운트 상위 20 slice를 점수 desc/asc로 정렬해 표시 - `--worst=10`: 점수 하위 10 slice - `--since=24h|7d|30d`: 시간 범위 (Mongo aggregate) - 출력: tier · intent · phase · count · llmOverallAvg · validatorRejectRate · p50LatencyMs · p95LatencyMs - `eval:promote` — promotion candidate를 즉시 생성 (CI/cron 외 수동 실행용) - `--dry-run`: 후보 표시만, 파일 변경 없음 - 두 명령 모두 `MongoClient` connection 필요 (env: `MONGODB_CONNECTION_STRING`) ### 5.10 검증 1. **단위 테스트**: - `aggregator.test.ts`: 가짜 stream entry 10건 → slice Hash 누적 정확성 - `archive.test.ts`: cursor 진행, 중복 streamId skip - `drift.test.ts`: 24h vs 7d 평균 계산, dropPct 임계 - `promote.test.ts`: 3개 카테고리 선정 로직, anonymize 재적용 확인 2. **통합**: - shadow-worker 부팅 후 5분 + 가짜 stream entry 50건 → `lolympus-agent:eval:agg:*` Hash ≥ 1 - 1시간 후 MongoDB `eval_archive` 컬렉션에 documents ≥ 1 - 24시간 후 `onboarding.candidate.jsonl`에 line ≥ 1 (테스트 시 tick interval env override) 3. **eval:report**: - dev 환경에서 실행 시 표 출력 + `MONGODB_CONNECTION_STRING` 미설정이면 명확한 에러 메시지 --- ## 6. Phase 7 — Process-based Evaluation ### 6.1 Critical Files - **신규**: - `src/eval/judges/process-judge.ts` — 단계별 rubric (rule + 선택적 LLM judge) - `src/skills/onboarding/runtime/trace.ts` — `ProcessTrace` 수집/직렬화 - `src/eval/judges/process-judge.test.ts` - **변경**: - `src/eval/types.ts` — `ProcessJudgeResult`, `ProcessTraceSnapshot` 추가, `EvalCaseResult.processJudge` 필드, `EvalCaseExpected.processExpected` 필드 - `src/eval/shadow-bus.ts` — `ShadowEvalEnvelope.process: ProcessTraceSnapshot` 필드 추가 - `src/eval/shadow-worker.ts` — `processShadowEval`이 `process-judge` 호출, 결과를 `eval:results` Stream에 저장 - `src/eval/runner.ts` — `evaluateCase`가 ProcessTrace 수집, `processJudge` 결과를 EvalCaseResult에 포함 - `src/skills/onboarding/skill.ts` — `handle()`이 ProcessTrace를 수집해 ShadowEvalBus에 전달 - `src/skills/onboarding/runtime/orchestrator.ts` — planner output / tool calls / critic decisions를 trace에 기록 - `src/skills/onboarding/runtime/validator.ts` — validation result를 trace에 기록 (이미 반환되고 있음, trace에 push만) ### 6.2 ProcessTrace schema (`src/skills/onboarding/runtime/trace.ts`) ```typescript export interface ProcessTraceStep { name: string; // "classify" | "derive" | "plan" | "tool-call" | "respond" | "critic" | "validate" startedAtMs: number; durationMs: number; output: T; // 단계별 output 직렬화 } export interface ProcessTraceSnapshot { steps: { classify: ProcessTraceStep<{ intent: string; confidence: number; source: "trigger" | "regex" | "llm"; }>; derive: ProcessTraceStep<{ phase: string; responseMode: string; tier: 0 | 1 | 2; shouldRespond: boolean; }>; plan?: ProcessTraceStep<{ approach: string; suggestedTools: string[]; mustInclude: string[]; mustAvoid: string[]; targetLengthChars: number; }>; toolCalls?: ProcessTraceStep<{ name: string; args: unknown; resultSummary: string; // 첫 200자 ok: boolean; }>[]; respond: ProcessTraceStep<{ draftText: string; tokensIn: number; tokensOut: number; }>; critic?: ProcessTraceStep<{ decision: "keep" | "rewrite"; rationale: string; }>; validate: ProcessTraceStep<{ status: "pass" | "soft-warn" | "reject"; reasons: string[]; }>; }; } export class ProcessTraceCollector { startStep(name: string): { finish: (output: T) => void }; snapshot(): ProcessTraceSnapshot; } ``` - `OnboardingSkill.handle()`이 collector 생성 → 각 단계 호출부에 `startStep` 주입 - ALS(`RequestContext`)에 collector 보관 — orchestrator/tool loop가 직접 import 없이 접근 - 직렬화 시 PII 우려: `args`/`draftText`는 이미 anonymize 단계 통과한 상태(`agent.ts`가 사전 anonymize 안 하므로 — 주의: `shadow-bus.publish` 직전에 `anonymizeProcessTrace(snapshot)` 강제 호출. `src/eval/anonymize.ts`에 함수 추가) ### 6.3 Process Judge (`src/eval/judges/process-judge.ts`) ```typescript export interface ProcessJudgeCheck { step: string; rule: string; // "intent-match" | "tier-appropriate" | "tools-selected-correctly" | "tool-args-valid" | "critic-decision-justified" | "validate-no-reject" passed: boolean; detail?: string; } export interface ProcessJudgeResult { checks: ProcessJudgeCheck[]; passedCount: number; totalCount: number; score: number; // passedCount / totalCount, 0..1 rationale?: string; // LLM judge 사용 시 } export function judgeProcessRule( expected: EvalCaseExpected, trace: ProcessTraceSnapshot ): ProcessJudgeResult; export async function judgeProcessWithLlm( llmClient: LlmClient, trace: ProcessTraceSnapshot, options: { request: AgentRequest; finalText: string } ): Promise; ``` - **Rule mode** (offline runner 기본): - `intent-match`: `expected.intent` vs `trace.steps.classify.output.intent` - `tier-appropriate`: `responseMode === "llm-with-tools"` 케이스에서 tier ≥ 1 인지 - `tools-selected-correctly`: `expected.processExpected?.expectedTools`와 `trace.steps.toolCalls`의 names 비교 (set equality, 단 `subset` 모드도 지원) - `tool-args-valid`: 각 tool의 args가 해당 tool의 zod schema validation 통과 (이미 `src/tools/builtins/*`에 schema 존재) - `critic-decision-justified`: tier 2이고 critic이 `keep` 결정했을 때 validate가 reject가 아닌지 - `validate-no-reject`: 마지막 validate step이 reject가 아닌지 - **LLM mode** (shadow-worker에서 `EVAL_PROCESS_LLM_JUDGE_ENABLED=true`일 때만): - tool args가 `validate-nickname` 같은 도구에 적절했는지, planner의 approach 선택이 합리적이었는지 — 텍스트 rationale 위주 - 비용 절약을 위해 sampling rate `EVAL_PROCESS_LLM_JUDGE_SAMPLING_RATE` (기본 0.1) ### 6.4 EvalCaseExpected 확장 ```typescript export interface EvalCaseExpected { intent?: string; mustIncludeAny?: string[]; mustNotInclude?: string[]; responseMode?: string; // 신규 processExpected?: { expectedTools?: string[]; toolMode?: "exact" | "subset"; // 기본 "subset" expectedApproach?: string; minSteps?: number; }; } ``` - `onboarding.jsonl`의 기존 케이스는 `processExpected` 없으면 process-judge가 해당 check를 skip(skipped flag) - `eval:capture`가 capture할 때 trace 데이터를 함께 직렬화 → curation 시 사람이 `processExpected` 채울 수 있도록 `notes`에 보조 정보 노출 ### 6.5 Shadow integration - `OnboardingSkill.handle()`이 trace collector 생성 → `shadowEvalPublisher.publish({...envelope, process: anonymizeProcessTrace(collector.snapshot())})` - `shadow-worker.processShadowEval`이 LLM mode가 활성이면 `judgeProcessWithLlm` 호출, 항상 `judgeProcessRule` 호출 - `eval:results` Stream entry에 `processJudge` (JSON), `process` (JSON, 디버깅용 trace) 필드 추가 - aggregator가 `processJudge.score`도 slice metric에 누적 (Phase 6 Hash에 `processJudgeSum`/`processJudgeCount` 필드 추가) ### 6.6 신규 env | Key | 기본값 | 설명 | |---|---|---| | `EVAL_PROCESS_LLM_JUDGE_ENABLED` | `false` | shadow-worker에서 LLM mode 활성 | | `EVAL_PROCESS_LLM_JUDGE_SAMPLING_RATE` | 0.1 | LLM mode 샘플링 | | `EVAL_PROCESS_LLM_JUDGE_MAX_TOKENS` | 256 | LLM judge max tokens | ### 6.7 검증 - `process-judge.test.ts`: 6개 rule 각각의 pass/fail 케이스 fixture - `runner.ts`의 `runOnboardingEval` 출력에 `processJudge` 필드 존재 확인 - 한 번 `npm run eval`을 돌려 기존 골든셋이 process-judge skipped(processExpected 미정의)로 통과하는지 확인 (회귀 방지) - shadow eval entry에 `processJudge` 필드 채워지는지 5분 내 확인 --- ## 7. Phase 8 — Hybrid Human-in-the-Loop ### 7.1 Critical Files - **신규**: - `src/eval/review/queue.ts` — 검토 큐 publisher / consumer - `src/eval/review/cli.ts` — interactive CLI (npm run eval:review) - `src/eval/review/calibration.ts` — 사람 vs LLM 점수 상관 계산 - `src/eval/review/queue.test.ts`, `src/eval/review/calibration.test.ts` - **변경**: - `src/eval/shadow-worker.ts` — review-routing tick 추가 (5분), 조건 충족 케이스를 review queue Stream에 publish - `src/eval/cli.ts` — `eval:review`, `eval:calibrate` 명령 추가 - `package.json` — script 추가 ### 7.2 Review queue (`src/eval/review/queue.ts`) ```typescript export interface ReviewQueueEntry { evalStreamId: string; // lolympus-agent:eval:results의 id reason: "low-score" | "rule-llm-disagree" | "validator-soft-warn" | "rare-slice"; // shadow eval entry snapshot (review CLI가 별도 lookup 안 하도록) request: AgentRequest; response: AgentResponse; derived: DerivedState; classified: ClassifiedIntent; validation: ValidationResult; llmJudge: LlmJudgeResult; processJudge?: ProcessJudgeResult; process?: ProcessTraceSnapshot; enqueuedAt: string; } export async function enqueueReviewCandidate( garnetClient: GarnetClient, entry: ReviewQueueEntry ): Promise; export async function fetchNextReviewItem( garnetClient: GarnetClient, options: { consumerName: string; blockMs?: number } ): Promise<{ streamId: string; entry: ReviewQueueEntry } | null>; export async function recordReviewLabel( garnetClient: GarnetClient, options: { streamId: string; consumerName: string; label: ReviewLabel; } ): Promise; export interface ReviewLabel { evalStreamId: string; verdict: "pass" | "fail"; humanScore: 1 | 2 | 3 | 4 | 5; rationale: string; betterResponse?: string; // 선택적, golden 후보용 reviewedBy: string; // env REVIEWER_ID 또는 git user.email reviewedAt: string; } ``` - **Routing**: shadow-worker가 5분 tick에서 최근 25분간 eval result 중 다음 조건의 케이스를 enqueue (각 카테고리당 최대 5건): - `low-score`: `llmJudge.scores.overall ≤ 2` - `rule-llm-disagree`: `validation.status === "pass" && llmJudge.scores.overall ≤ 3`, 또는 반대 - `validator-soft-warn`: `validation.status === "soft-warn"` - `rare-slice`: 7일 누적 카운트 ≤ 5인 slice의 새 entry 1건 - 각 카테고리당 dedupe: `lolympus-agent:eval:review:dedupe:{evalStreamId}` SETNX EXPIRE 7일 - Stream: `lolympus-agent:eval:review:queue` (consumer group `reviewers`, MAXLEN `EVAL_REVIEW_QUEUE_MAXLEN` 기본 500) - Label Stream: `lolympus-agent:eval:review:labeled` (MAXLEN `EVAL_REVIEW_LABEL_MAXLEN` 기본 5000, TTL은 archive 통해 영속) - 사람이 라벨링 완료 시 XACK + label Stream에 publish ### 7.3 Review CLI (`src/eval/review/cli.ts`) `npm run eval:review` (cli.ts에서 router): ``` [1/12] reason: low-score chatroom: room_2a83 / user: user_1f0c / trigger: photo-failed intent: photo-question (confidence 0.92, llm) tier: 1 / phase: discord-step / responseMode: llm [user message] 사진을 어디로 보내야 하나요? [assistant response] 디스코드 채널에 올려주시면 됩니다 :) [llm judge] overall=2 friendliness=4 accuracy=1 concision=3 scope=2 rationale: 사용자가 사진 인증을 물었는데 디스코드를 잘못 안내함 [validator] status=pass [process] classify→derive→respond→validate (no plan/tools) verdict (p=pass / f=fail / s=skip / q=quit) > humanScore (1-5) > rationale > 사진은 카톡 봇으로 보내야 함, discord와 혼동 응답 better (optional, ENTER to skip) > 사진은 이 채팅방에 직접 올려주시면 봇이 자동 인증해드려요. discord는 텍스트 인증용입니다. ``` - 명령 옵션: - `--limit=N`: 한 세션 최대 N개 (기본 20) - `--reason=low-score`: 특정 reason만 - `--export-labeled=path.jsonl`: 세션 종료 시 labeled를 jsonl로 export - `--reset-pending`: 기존 PEL을 모두 XCLAIM 후 stale 정리 (옵션, 1시간 idle 이상) - 반복문 구조: 1. `fetchNextReviewItem(blockMs=5000)` — 큐 비면 5초 대기 후 종료 2. 항목 표시 → stdin에서 verdict/score/rationale/better 수집 3. `recordReviewLabel` → XACK 4. `q` 입력 시 즉시 종료 ### 7.4 Calibration (`src/eval/review/calibration.ts`) ```typescript export interface CalibrationReport { pairs: number; pearsonOverall: number; pearsonByDim: { friendliness: number; accuracy: number; concision: number; scope: number }; meanGapOverall: number; // mean(human - llm) worstDisagreements: Array<{ evalStreamId: string; humanScore: number; llmOverall: number }>; generatedAt: string; } export async function computeCalibrationReport( mongoClient: MongoClient, garnetClient: GarnetClient, options?: { since?: string } ): Promise; ``` - `eval:calibrate` CLI가 호출 - MongoDB `eval_archive` + Redis labeled Stream(또는 archive된 label)을 evalStreamId로 join - `pearsonOverall ≤ EVAL_CALIBRATION_MIN_CORR` (기본 0.5)면 `npm run eval:calibrate --check`가 exit code 1 (CI gate에 활용 가능) - worstDisagreements top 10은 LLM judge prompt 개선의 입력으로 사용 (Phase 9의 propose에 연결) ### 7.5 Auto-promotion 연동 Phase 6의 `promote.ts`가 promotion candidate 선정 시 다음 우선순위 추가: - **labeled-fail**: `humanScore ≤ 2`인 케이스 (사람이 명시적으로 "잘못된 응답"이라 한 것 — 가장 가치 높음) - `betterResponse`가 있으면 `EvalCaseExpected.notes`에 함께 기재해 사람이 golden curation 시 참고 ### 7.6 신규 env | Key | 기본값 | 설명 | |---|---|---| | `EVAL_REVIEW_TICK_MS` | 300000 | review-routing tick (5분) | | `EVAL_REVIEW_QUEUE_MAXLEN` | 500 | review queue Stream MAXLEN | | `EVAL_REVIEW_LABEL_MAXLEN` | 5000 | labeled Stream MAXLEN | | `EVAL_REVIEW_PER_CATEGORY_LIMIT` | 5 | tick당 카테고리별 enqueue 한도 | | `EVAL_REVIEW_DEDUPE_TTL_SEC` | 604800 | enqueue dedupe TTL (7일) | | `EVAL_CALIBRATION_MIN_CORR` | 0.5 | 캘리브레이션 임계 | | `REVIEWER_ID` | (git user.email) | review CLI에서 reviewedBy 자동 채움 | ### 7.7 신규 Redis key | Key Pattern | Type | TTL | 설명 | |---|---|---|---| | `lolympus-agent:eval:review:queue` | Stream | MAXLEN `EVAL_REVIEW_QUEUE_MAXLEN` | review 대기 큐 (consumer group `reviewers`) | | `lolympus-agent:eval:review:labeled` | Stream | MAXLEN `EVAL_REVIEW_LABEL_MAXLEN` | 사람 라벨 적립 | | `lolympus-agent:eval:review:dedupe:{evalStreamId}` | String | `EVAL_REVIEW_DEDUPE_TTL_SEC` | 동일 케이스 중복 라우팅 방지 | | `lolympus-agent:eval:review:cursor` | String | no TTL | 마지막 검토 라우팅된 stream id | ### 7.8 검증 1. shadow-worker 부팅 + 가짜 low-score eval entry 5건 → 5분 내 `eval:review:queue`에 5개 enqueue 2. `npm run eval:review --limit=2` 실행 → 2건 라벨링 → labeled Stream에 2건, queue PEL 0건 3. 동일 케이스 5분 후 다시 라우팅돼도 dedupe로 skip되는지 4. `npm run eval:calibrate` — 5건 라벨로는 `pairs<10` 경고 + correlation 계산만 출력 5. `eval:review:labeled` Stream → archive 컬렉션(`eval_review_labels`)으로 영속 --- ## 8. Phase 9 — Closed Loop (Prompt/Tool 개선 자동 제안 + A/B 토너먼트) ### 8.1 Critical Files - **신규**: - `src/eval/loop/propose.ts` — 약점 슬라이스 → prompt diff / tool 후보 LLM 생성 - `src/eval/loop/tournament.ts` — shadow에서 두 prompt 버전 동시 실행 + side-by-side judge - `src/eval/loop/elo.ts` — ELO 랭킹 갱신 - `src/eval/loop/{propose,tournament,elo}.test.ts` - **변경**: - `src/eval/cli.ts` — `eval:propose`, `eval:tournament`, `eval:tournament-results` 명령 - `src/skills/onboarding/prompts/builder.ts` — variant id를 받아 layer 차이를 적용 가능하게 (이미 layer 구조면 변경 최소) - `src/skills/onboarding/skill.ts` — prompt variant 선택을 위한 hook (env / variant manifest 기반) ### 8.2 Propose (`src/eval/loop/propose.ts`) ```typescript export interface ProposalInput { slice: SliceKey; recentLabels: ReviewLabel[]; // 사람 라벨 우선 worstCases: EvalArchiveEntry[]; // top 5 low-score currentPromptSnapshot: string; // 현재 사용 중인 system prompt 텍스트 } export interface PromptVariantProposal { variantId: string; // hash 8자리 description: string; // LLM이 적은 한 줄 요약 diff: PromptLayerDiff[]; // builder.ts의 layer add/replace/remove rationale: string; expectedImprovement: string; // LLM의 가설 } export interface ToolProposal { variantId: string; description: string; toolName: string; schema: unknown; // zod schema source whyNeeded: string; } export async function proposeVariants( llmClient: LlmClient, input: ProposalInput ): Promise<{ prompts: PromptVariantProposal[]; tools: ToolProposal[] }>; ``` - `eval:propose --slice=tier=1,intent=photo-question,phase=discord-step` 실행 - LLM(`LLM_JUDGE_MODEL` 또는 `LLM_PROPOSE_MODEL` 별도 env)에 system prompt + 약점 케이스 + 현재 prompt를 넣고 prompt diff JSON을 받음 - 결과를 `proposals/{variantId}.json`에 저장 (gitignore 안 함, PR review에 활용) - Tool 제안은 별도 — 같은 intent에서 LLM이 hallucinate가 잦으면 tool화 후보로 식별 ### 8.3 Tournament (`src/eval/loop/tournament.ts`) ```typescript export interface TournamentMatch { matchId: string; variantA: string; // variantId 또는 "control" variantB: string; caseId: string; // archive entry id responseA: string; responseB: string; judgeVerdict: "A" | "B" | "tie"; judgeRationale: string; } export interface TournamentResult { variants: { id: string; elo: number; matches: number; wins: number }[]; matches: TournamentMatch[]; generatedAt: string; } export async function runTournament( llmClient: LlmClient, options: { variantIds: string[]; // ["control", "abc123"] caseIds: string[]; // archive entry ids maxMatches?: number; } ): Promise; ``` - shadow eval과 별개로 in-process로 실행 (NATS 거치지 않음, runner.ts 패턴 재사용) - 각 case에 대해 두 변형(prompt diff 적용 vs control)으로 동일 input으로 응답 생성 - LLM judge에게 (request, expected, responseA, responseB)를 주고 "A/B/tie + rationale" JSON 받음 - ELO 갱신 (`elo.ts`, K=32, initial=1500) - 결과를 MongoDB `eval_tournaments` 컬렉션에 저장. `eval:tournament-results --variant=abc123` 으로 조회 ### 8.4 Variant 적용 - `src/skills/onboarding/prompts/builder.ts`에 `applyVariant(variantId: string): PromptBuilder` 추가 - variant manifest: `proposals/{variantId}.json`을 빌드 타임에 import — 또는 env `PROMPT_VARIANT_ID`로 런타임 전환 - 토너먼트는 in-process이므로 manifest를 직접 인자로 받음 (런타임 변형 불필요) ### 8.5 신규 env | Key | 기본값 | 설명 | |---|---|---| | `LLM_PROPOSE_MODEL` | (`LLM_JUDGE_MODEL`과 동일) | propose 단계용 모델 — 더 큰 모델 권장 | | `LLM_PROPOSE_MAX_TOKENS` | 1024 | proposal output 길이 | | `EVAL_TOURNAMENT_MAX_MATCHES` | 50 | 한 토너먼트당 매치 수 | | `EVAL_TOURNAMENT_MIN_CASES` | 10 | propose 실행 위한 최소 케이스 수 | ### 8.6 PR 자동화 - `eval:propose --apply --variant=`가 통과 시: 1. 새 branch `eval/variant-{id}` 체크아웃 2. `src/eval/proposals/{id}.json` 커밋 3. `src/skills/onboarding/prompts/builder.ts`에 manifest import 라인 추가 4. PR draft 생성 (`gh pr create --draft`) - 토너먼트 결과를 PR description에 첨부 (ELO, win rate, sample matches) - **사람이 머지 결정** — 자동 머지 안 함 (`plan.md` §10의 사용자 판단 원칙 유지) ### 8.7 검증 - `propose.test.ts`: 가짜 archive entries → mocked LLM → JSON 스키마 통과 - `tournament.test.ts`: 2 variant × 5 cases → ELO 갱신 정확성, judge mock - `elo.test.ts`: 표준 ELO 공식 단위 테스트 - E2E: 실제 worst slice로 `eval:propose` → `eval:tournament` → 결과 표 확인 --- ## 9. Migration Strategy 각 Phase는 독립 PR. `plan.md` §10의 v2 직진 원칙을 그대로 따른다 (feature flag 없음, 머지 후 즉시 활성). | 순서 | PR | 가드 | |---|---|---| | 1 | Phase 6: aggregator + archive + drift + promote | `npm run eval` 회귀 0건. `MONGODB_CONNECTION_STRING` 미설정이면 archive/drift는 skip + warn (개발 환경 fallback) | | 2 | Phase 7: process-judge + trace | 기존 골든셋 통과 (processExpected 미정의는 skip). shadow eval에 `processJudge` 필드 채움 | | 3 | Phase 8: review queue + CLI + calibration | Phase 6 archive가 있어야 calibration 가능 | | 4 | Phase 9: propose + tournament | Phase 7/8 산출물(process trace + 사람 라벨)을 입력으로 사용 | 배포 후 회귀 발견 시: `plan.md` §10.6과 동일하게 사용자 판단으로 git revert. --- ## 10. Risks & Mitigations | 리스크 | 영향 | 완화 | |---|---|---| | MongoDB write 실패로 archive 누락 | 장기 분석 데이터 빈 곳 발생 | archive cursor 미업데이트로 다음 tick 재시도. 3회 연속 실패 시 alert (`kind="archive-stalled"`). Redis Stream MAXLEN까지 버퍼링 | | process trace에 PII 누출 | 개인정보 유출 | `shadow-bus.publish` 직전 `anonymizeProcessTrace()` 강제. tool args에 user nickname/userId 포함 시 자동 redaction. PR review 시 grep 기반 평문 PII 검사 | | Aggregator slice 폭발 (intent × phase 수십 종) | Redis 메모리 ↑ | `EVAL_AGG_TTL_SEC=7d`로 자동 expire. SCAN으로 `eval:agg:*` 1k 이하 유지. 1k 넘으면 alert | | LLM process-judge 비용 | CLIPROXY 호출량 ↑ | sampling 0.1 + tier 2만으로 제한 옵션 (`EVAL_PROCESS_LLM_JUDGE_TIER_FILTER`로 후속 추가 가능) | | Review CLI에서 사람이 큐에 부담 느낌 | 라벨링 안 하게 됨 | 한 세션 기본 20건 cap, 카테고리당 5건 라우팅. dedupe 7일로 같은 케이스 반복 노출 방지. 큐가 비어있으면 즉시 종료 | | Calibration 표본 부족 | 신뢰도 낮은 메트릭 | `pairs < 10`이면 경고만, 임계 검사 안 함. 표본 ≥ 30일 때부터 CI gate 가능 | | Auto-promotion이 노이즈 케이스로 candidate jsonl 오염 | curation 부담 ↑ | label-fail 우선, 카테고리당 10건 cap, anonymize 재적용. 사람이 candidate에서 골라 golden으로 옮기는 것은 항상 수동 | | Tournament 결과의 LLM judge 편향 | 잘못된 variant가 승리 | side-by-side에서 A/B 위치 swap (각 매치 50% 확률). control과 variant 둘 다 같은 케이스에서 실행해 case 분산 0 | | Variant manifest가 prompt builder를 깨뜨림 | 런타임 장애 | tournament는 in-process로 격리. 운영 prompt에 적용은 PR draft 단계에서 `npm run eval` 통과를 머지 조건 | | 4개 phase 한 번에 머지 시도 | 디버깅 어려움 | 위 §9의 순서 강제. 각 PR에 §11의 phase별 검증 통과 | --- ## 11. Verification Plan ### Phase별 (각 PR 머지 조건) | Phase | 검증 | |---|---| | 6 | `aggregator/archive/drift/promote` 단위 테스트 통과. 5분 후 `eval:agg:*` Hash ≥ 1, 1시간 후 MongoDB `eval_archive` documents ≥ 1, 24시간 후 `onboarding.candidate.jsonl` line ≥ 1. `npm run eval:report --top=20` 정상 출력. 기존 `npm run eval` 골든셋 ≥ 80% pass | | 7 | `process-judge.test.ts` 통과. `runner` 결과에 `processJudge` 필드 존재. shadow eval entry에 `processJudge` 채워짐. 기존 골든셋(processExpected 없음) 회귀 0건. `anonymizeProcessTrace`가 평문 PII 0건 | | 8 | `queue/calibration.test.ts` 통과. 가짜 low-score 5건 → 5분 내 review queue ≥ 5. `eval:review --limit=2`로 라벨링 정상 동작. 동일 케이스 dedupe 검증. `eval:calibrate` 출력 정상 | | 9 | `propose/tournament/elo.test.ts` 통과. `eval:propose --slice=...` JSON 산출. `eval:tournament` ELO 갱신 + MongoDB `eval_tournaments` 컬렉션 documents ≥ 1. PR draft 생성 명령 정상 | ### 운영 지속 검증 (Phase 6+ 활성 후) - shadow eval 24h 평균 vs 7d 평균 dropPct < 15% (drift alert 0건이 정상 상태) - review queue PEL idle ≥ 1시간 항목 5개 미만 (라벨링 진척 모니터) - calibration `pearsonOverall ≥ 0.5` (LLM judge 신뢰도) - archive 누적 documents ≥ 일평균 (worker 정상 동작) --- ## 12. Minor Decisions (확정 기본값) | 항목 | 결정 | |---|---| | Slice 정의 | `tier × intent × phase` 3-튜플. responseMode는 derive 결과로 phase에 종속이라 별도 슬라이스 안 함 | | Aggregator 메트릭 | count, llmOverallSum/Count, validatorRejectCount, validatorSoftWarnCount, latencySumMs, latencySamples (P95용 cap 200), processJudgeSum/Count | | Archive index | `{streamId: 1}` unique, `{evaluatedAt: 1}` TTL, `{tier:1, "derived.intent.kind":1, "derived.phase.kind":1, evaluatedAt:-1}` 복합 | | Drift 비교 metric | 우선 `llmOverall`. validatorPassRate는 v2 | | Process trace 직렬화 | JSON.stringify, 단 draftText/args는 600자 cap | | Review CLI 입력 검증 | verdict는 `p`/`f`/`s`/`q`만, humanScore는 1–5 정수. invalid면 재입력 prompt | | Reviewer 식별 | env `REVIEWER_ID` > `git config user.email` > `"unknown"` | | Tournament 매치 분배 | 각 case에서 (A,B), (B,A) 두 번 실행 후 평균 — position bias 완화 | | Variant 보관 위치 | `src/eval/proposals/{variantId}.json` (git-tracked) | | Tournament 동시성 | 직렬 실행 (LLM endpoint rate limit 고려). 병렬은 v2 | | 시간대 | UTC (plan.md §13 그대로) | --- ## 13. Codex Hand-off Checklist Codex가 이 plan으로 작업할 때 **Phase 6부터 순차 진행**. 각 Phase 완료 기준: - [ ] §5–8의 Phase별 신규/변경 파일 모두 구현 - [ ] `npm run typecheck && npm run lint && npm run build && npm test` 통과 - [ ] §11의 Phase별 검증 항목 통과 - [ ] env/Redis key/NATS subject 추가 시 본 문서의 신규 항목 표를 `plan.md` §6/§7/§8에 동기 (별도 PR로 plan.md 갱신 가능) - [ ] 커밋/PR 본문에 "Phase N — \" 명시 (Phase 번호는 `plan.md` Phase 0–5에 이어 6, 7, 8, 9 순) - [ ] 각 PR에서 `npm run eval` 골든셋 ≥ 80% pass 유지 **참고 문서**: - `/Users/dahyeon/source/lolympus-agent/plan.md` — Phase 0–5 원본 (충돌 시 본 문서 우선, 단 Phase 0–5 인터페이스/스키마는 그대로 따름) - 본 문서가 Evaluation Stage 2의 정본 **질문 대응**: - 본 문서에 없는 세부 결정은 `plan.md`의 Resolved Decisions와 "기존 인터페이스 유지, 최소 침습" 원칙에 부합하는 방향으로 진행. - 불가한 모순 발견 시 작업 중단하고 사용자에게 확인.