Close multi-agent plan and add router shadow reporting

This commit is contained in:
dahyeon committed 2026-05-18 19:34:11 -07:00
1 parent f1b30d716d
commit 8156e8c07e
15 files changed
+1303 -204

No files matched your search

+178
View File
@@ -0,0 +1,178 @@
# lolympus-agent Multi-Agent Architecture
Last verified: Iter8 implementation branch, 2026-05-18.
## 1. 개요
`lolympus-agent`는 Lolympus 커뮤니티 운영을 돕는 NATS 메시지 드리븐 멀티 skill agent다. 실시간 요청은 `Agent.handleRequest()`로 들어오고, skill registry가 요청 skill을 찾아 `Skill.handle()`을 실행한다. 품질 관리는 shadow evaluation, MongoDB archive, human review, proposal/tournament loop로 이어진다.
운영 목표는 세 가지다.
- 실시간 응답 경로는 짧고 예측 가능하게 유지한다.
- skill, prompt, intent, resource, tool 정의는 각 `src/skills/<name>/` 폴더에 모은다.
- production과 eval은 같은 dispatch, handoff, budget 규칙을 사용한다.
## 2. 아키텍처 다이어그램
### 실시간 메시지 흐름
```text
NATS lolympus-agent.request
-> src/main.ts
-> Agent.handleRequest()
-> src/agent/dispatch.ts
-> SkillRegistry.get(request.skill)
-> Skill.handle(request, history)
-> AgentResponse
```
### Handoff 흐름
```text
Skill response
-> control token/parser or metadata.handoffRequest
-> transition-matrix validation
-> BudgetTracker
-> buildHandoffPacket()
-> dispatch target skill
-> supervisor fallback when blocked
```
`src/agent/dispatch.ts`는 production과 eval에서 모두 쓰인다. handoff chain, depth, last request는 metadata와 logger context에 남는다.
### Eval 흐름
```text
real-time response
-> ShadowEvalBus
-> lolympus-agent:background
-> ShadowWorker
-> lolympus-agent:eval:results
-> aggregation/archive/drift/review
-> propose/tournament/promote
```
### Operation 흐름
```text
supervisor handoff
-> lolympus-agent:review-queue
-> review:list/show/resolve/stats
-> resolution stream + compatibility hash
-> Slack/NATS alert
```
## 3. Skill 모델
모든 skill은 `src/skills/<name>/` 아래에 둔다. 필수 진입점은 다음과 같다.
| 파일 | 역할 |
| --------------------------------- | --------------------------------------- |
| `SKILL.md` | 사람이 읽는 capability card와 운영 설명 |
| `skill.ts` | `Skill` 구현체 |
| `intents.ts` | skill이 해석하는 intent 종류 |
| `prompt-data.ts` 또는 `prompts/*` | prompt layer, 예시, resource 연결 |
| `tools.ts` 또는 `resources/*` | skill 전용 tool/resource 정의 |
`src/skills/skill-loader.ts`가 `SKILL.md`를 읽어 `SkillManifest`로 만들고, `src/skills/validate-manifests.ts`가 문서와 코드의 일관성을 검사한다. `handoffTargets`는 `src/skills/transition-matrix.ts`에서 검증되며 self-loop와 unknown target을 막는다.
현재 핵심 skill은 `onboarding`, `moderation`, `supervisor`다. `supervisor`는 모든 skill의 fallback target이며, specialist가 처리하지 못한 요청을 review queue로 넘긴다.
## 4. Dispatch 모델
Dispatch는 `src/agent/dispatch.ts`가 담당한다.
- 응답 text 안의 control token은 parser가 제거하고 metadata로 구조화한다.
- skill이 직접 `metadata.handoffRequest`를 넣어도 같은 path로 처리된다.
- `HandoffPacket`은 원 요청, source response, handoff reason, evidence, source chain을 보존한다.
- `BudgetTracker`는 최대 handoff 수, 동일 skill 재방문, tool call, 비용 한도를 강제한다.
- transition matrix가 허용하지 않는 target은 supervisor로 reroute된다.
- budget이 막히면 `same-agent-revisit`, `max-hop`, `high-risk-action` 같은 reason으로 supervisor fallback이 만들어진다.
이 구조 덕분에 eval handoff golden도 실제 production dispatch와 같은 규칙을 검증한다.
## 5. Eval 모델
`src/eval/`은 네 계층으로 나뉜다.
| 계층 | 주요 파일 | 설명 |
| ------ | ------------------------------------ | ----------------------------------- |
| Golden | `src/eval/golden/*/cases.jsonl` | 사람이 관리하는 고정 회귀 케이스 |
| Runner | `runner.ts`, `handoff-dispatch.ts` | skill-aware eval 실행 |
| Judges | `judges/*` | rule, LLM, process, handoff 판단 |
| Loop | `archive.ts`, `promote.ts`, `loop/*` | archive 기반 개선 후보와 tournament |
Router 학습은 `src/eval/router-training.ts`가 MongoDB archive에서 training sample을 만들고, `src/skills/onboarding/runtime/router.ts`가 learned model을 저장한다. Iter8에서 추가된 `src/eval/router-shadow-report.ts`는 supervisor outcome과 shadow eval을 조인해 static router와 learned router의 divergence를 보고한다.
## 6. Observability
관측성은 세 갈래다.
- Logger context: requestId, skill, handoff chain, depth를 포함한다.
- Metrics: `src/observability/metrics.ts`가 Prometheus text exposition을 제공한다.
- Alerts: `src/observability/alert.ts`가 NATS와 Slack으로 운영 이벤트를 발행한다.
대표 metric:
| Metric | 용도 |
| ----------------------------- | ----------------------------- |
| `agent_handoff_total` | skill 간 handoff rate |
| `agent_handoff_loop_total` | loop guardrail 발생 |
| `agent_human_override_total` | supervisor/manual review 진입 |
| `agent_validator_fail_total` | validator 실패 |
| `agent_time_to_resolution_ms` | skill별 처리 시간 |
| `agent_token_cost_usd` | model/skill 비용 추정 |
`METRICS_PORT`의 `/metrics`와 `/healthz`를 scrape할 수 있다. Slack alert는 `SLACK_ALERT_WEBHOOK_URL`이 있을 때만 전송된다.
## 7. 데이터 저장소
### Garnet/Redis
| Key | Type | 용도 |
| ----------------------------------- | ------ | ------------------------------ |
| `lolympus-agent:background` | Stream | shadow eval과 summary job |
| `lolympus-agent:eval:results` | Stream | shadow eval 결과 |
| `lolympus-agent:eval:agg:*` | Hash | slice별 aggregate |
| `lolympus-agent:eval:review:queue` | Stream | eval human review |
| `lolympus-agent:review-queue` | Stream | supervisor review |
| `lolympus-agent:review-resolutions` | Stream | supervisor resolution audit |
| `lolympus-agent:review-resolved:*` | Hash | legacy compatibility read path |
| `lolympus-agent:alert:dedupe:*` | String | alert dedupe/rate limit |
### MongoDB
| Collection | 용도 |
| -------------------- | ------------------------------ |
| `eval_archive` | shadow eval 장기 archive |
| `eval_review_labels` | 사람 review label archive |
| `eval_tournaments` | prompt variant tournament 결과 |
Conversation, blackboard, summary state는 Garnet key와 TTL로 관리한다.
## 8. 확장 가이드
새 skill을 추가할 때는 다음 순서로 진행한다.
1. `src/skills/<name>/` 폴더를 만들고 `SKILL.md`, `skill.ts`, 필요한 `intents.ts`, `prompt-data.ts`, `tools.ts`를 둔다.
2. `SKILL.md`에 `name`, `domain`, `riskTier`, `canHandle`, `cannotHandle`, `handoffTargets`, `outputContract`, `triggers`를 작성한다.
3. factory/registry에 skill을 등록하고 transition matrix가 target을 인식하게 한다.
4. 필요한 resource는 skill 폴더의 `resources/`에 두고 prompt builder가 읽게 한다.
5. 최소 golden case를 `src/eval/golden/<name>/cases.jsonl`에 추가한다.
6. `npm run lint:skills`, `npm test`, 해당 skill eval smoke를 실행한다.
7. handoff가 필요한 skill이면 `src/eval/golden/handoff/cases.jsonl`에 교차 skill 케이스를 추가한다.
## 9. References
| 문서 | 의미 |
| ------------------------------------------------------------ | ------------------------------------------------------- |
| [refactor-skill-ssot.md](refactor-skill-ssot.md) | Iter1, skill/prompt/intent SSOT 시작 |
| [refactor-skill-ssot-iter2.md](refactor-skill-ssot-iter2.md) | Iter2, tool/eval path skill-aware화 |
| [refactor-skill-ssot-iter3.md](refactor-skill-ssot-iter3.md) | Iter3, eval pipeline과 SKILL.md 검증 강화 |
| [refactor-skill-ssot-iter4.md](refactor-skill-ssot-iter4.md) | Iter4, 멀티 에이전트 운영 조건 정의 |
| [refactor-skill-ssot-iter5.md](refactor-skill-ssot-iter5.md) | Iter5, bounded graph와 structured handoff |
| [refactor-skill-ssot-iter6.md](refactor-skill-ssot-iter6.md) | Iter6, supervisor review loop와 router training signals |
| [refactor-skill-ssot-iter7.md](refactor-skill-ssot-iter7.md) | Iter7, observability와 Slack alert |
| [refactor-skill-ssot-iter8.md](refactor-skill-ssot-iter8.md) | Iter8, closing iteration |
운영 runbook은 [service-evaluation-operations.md](service-evaluation-operations.md), 고도화 trigger는 [optimization-roadmap.md](optimization-roadmap.md), resolution hash sunset은 [resolution-hash-sunset-procedure.md](resolution-hash-sunset-procedure.md)를 참고한다.
+66
View File
@@ -0,0 +1,66 @@
# Optimization Roadmap
Last verified: Iter8 implementation branch, 2026-05-18.
운영 가능한 멀티 에이전트 기반은 Iter8에서 닫았다. 이 문서는 다음 고도화를 추측으로 시작하지 않기 위한 trigger 표다. Trigger는 권장 시작점이며, 최종 착수는 사람이 실제 비용, 운영 부담, 사용자 영향도를 보고 결정한다.
## Trigger Summary
| 항목 | Trigger 조건 | 측정 지표 | Plan 작성 시작 시점 |
| ------------------------- | ------------------------------------------------------- | ----------------------------------------- | ------------------------------- |
| Cost-aware routing | 월 LLM 비용이 운영 예산을 초과 | `agent_token_cost_usd` 합계 | 비용 초과가 2개월 연속 발생 |
| Parallel fan-out | handoff 평균 hop이 2.0 이상 또는 timeout 빈발 | `agent_handoff_count` p50/p95 | hop >= 2.0이 1주 지속 |
| Cross-room context | 방 사이의 동일 사용자/패턴 이슈가 반복 | 신규 metric 필요 | sensor 먼저 추가 후 데이터 확인 |
| Resolution hash sunset | dual-write 안정 2개월 + stream/hash divergence 0 | sunset 점검 script 또는 spot check | 조건 충족 후 sunset plan 실행 |
| Review queue Web UI | 일일 review queue 진입이 10건 이상 또는 운영자 2명 이상 | `agent_human_override_total` daily | 1개월 지속 |
| Runtime skill discovery | 신규 skill 배포가 주 1회 이상 | 배포 기록, `lint:skills` 변경 빈도 | 빈도 조건 충족 |
| Multi-skill orchestration | handoff chain 평균이 3 hop 이상 | `agent_handoff_count` p90, handoff golden | 평균 3 hop 이상 반복 |
| Supervisor 자동 학습 | router shadow agreement rate가 80% 미만 | `eval:router-shadow-report` | 2개 이상 window에서 80% 미만 |
## Cost-aware routing
왜 지금 안 하는가: 현재는 비용보다 correctness와 운영 가능성이 더 큰 리스크다. tier별 routing과 learned router가 이미 비용을 일부 통제한다.
시작 시 검토할 것: model별 token cost 산정, skill별 비용 dashboard, router decision의 false negative 비용, fallback 품질이다. 관련 코드는 `src/observability/metrics.ts`, `src/skills/onboarding/runtime/router.ts`, `src/eval/router-training.ts`다.
## Parallel fan-out
왜 지금 안 하는가: handoff graph가 아직 작고, 병렬 실행은 비용과 race condition을 늘린다.
시작 시 검토할 것: fan-out 대상 skill의 idempotency, response merge policy, budget accounting, timeout policy다. 관련 코드는 `src/agent/dispatch.ts`, `src/agent/budget.ts`, `src/eval/golden/handoff/cases.jsonl`다.
## Cross-room context
왜 지금 안 하는가: room 간 context가 실제로 필요한 빈도와 개인정보 리스크가 아직 수치화되지 않았다.
시작 시 검토할 것: 사용자 단위 aggregation metric, retention/TTL, opt-in 정책, PII redaction이다. 먼저 sensor와 metric을 추가하고 한 달 이상 관찰한다.
## Resolution hash sunset
왜 지금 안 하는가: Iter6에서 stream audit와 hash compatibility dual-write를 막 붙였다. 바로 제거하면 운영 rollback 경로가 좁아진다.
시작 시 검토할 것: stream과 hash의 일치율, `review:show`와 `review:stats` read path, TTL 이후 복구 가능성이다. 절차는 [resolution-hash-sunset-procedure.md](resolution-hash-sunset-procedure.md)를 따른다.
## Review queue Web UI
왜 지금 안 하는가: CLI로 충분한 규모인지 확인되지 않았다. Web UI는 인증, audit, 권한, 배포 표면을 늘린다.
시작 시 검토할 것: 일일 queue 양, 운영자 수, 자주 쓰는 resolution action, note template, audit export 필요성이다. CLI는 `src/operations/cli.ts`가 기준이다.
## Runtime skill discovery
왜 지금 안 하는가: 현재 skill 수가 적고 정적 registry가 변경 영향 파악에 유리하다.
시작 시 검토할 것: skill package format, hot reload, SKILL.md validation timing, transition matrix reload, 배포 rollback 방식이다.
## Multi-skill orchestration
왜 지금 안 하는가: 지금의 handoff는 sequential dispatch로 충분하다. orchestration graph를 일반화하면 디버깅 난도가 크게 올라간다.
시작 시 검토할 것: graph DSL, response merge, partial failure, supervisor override, eval judge 확장이다.
## Supervisor 자동 학습
왜 지금 안 하는가: supervisor routing과 userMessage는 이제 막 안정 가드를 갖췄다. 자동 학습은 충분한 resolution label과 shadow divergence evidence가 필요하다.
시작 시 검토할 것: `npm run eval:router-shadow-report -- --since=7d`, supervisor resolution action 분포, target별 false route, human note taxonomy다.
+101
View File
@@ -0,0 +1,101 @@
# Supervisor Resolution Hash Sunset Procedure
Last verified: Iter8 implementation branch, 2026-05-18.
Supervisor resolution은 현재 두 곳에 기록된다.
- Audit stream: `lolympus-agent:review-resolutions`
- Compatibility hash: `lolympus-agent:review-resolved:{reviewId}`
Hash는 기존 read path와 rollback을 위한 compatibility layer다. 실제 sunset은 최소 1-2개월 운영 후 아래 조건을 만족할 때만 진행한다.
## 선결 조건
- Dual-write 운영 기간이 2개월 이상이다.
- Stream과 hash의 resolution 데이터 일치율이 100%다.
- `review:list`, `review:show`, `review:resolve`, `review:stats`가 stream 기반 확인으로 대체 가능한 상태다.
- 최근 2주간 supervisor resolution 관련 incident가 없다.
- Sunset 실행 전 main branch의 전체 회귀가 통과한다.
권장 점검:
```bash
npm run review:stats
npm run review:list -- --include-resolved --limit=20
npm run typecheck
npm test
```
필요하면 별도 consistency script를 만든다.
```text
scripts/verify-dual-write-consistency.ts
```
이 script는 `lolympus-agent:review-resolutions`의 최신 resolution과 `lolympus-agent:review-resolved:{reviewId}` hash를 비교해 divergence를 출력해야 한다.
## Sunset 단계
### Step 1. Hash write 중단
`src/skills/supervisor/review-queue.ts`의 `resolveSupervisorReview()`에서 `setHash()`와 `expireKey()` 호출을 제거한다. Stream append는 유지한다.
검증:
```bash
npm run typecheck
npm test -- src/skills/supervisor/review-queue.test.ts src/operations/cli.test.ts
```
Rollback: 해당 commit revert. 기존 hash TTL 동안 read fallback은 유지된다.
### Step 2. Stream-only write로 1개월 운영
새 resolution은 stream에만 쌓이고, 기존 hash는 TTL까지 남는다. 이 기간 동안 `review:list/show/stats`가 정상 동작하는지 확인한다.
관찰 항목:
- unresolved item이 비정상적으로 늘지 않는가
- resolution history가 누락되지 않는가
- 운영자가 `review:show`에서 이전 resolution을 확인할 수 있는가
Rollback: `setHash()`와 `expireKey()`를 복구한다.
### Step 3. Hash read fallback 제거
`getSupervisorReview()`와 `listSupervisorReview()`에서 hash lookup을 제거하고, resolution stream join으로만 상태를 계산한다.
검증:
```bash
npm run review:list -- --include-resolved --limit=5
npm run review:stats
npm test -- src/skills/supervisor/review-queue.test.ts src/operations/cli.test.ts
```
Rollback: hash lookup 코드를 복구한다. Step 1 이후 새 데이터는 hash에 없으므로 rollback 전에 stream 기반 backfill이 필요한지 판단한다.
### Step 4. 기존 hash 정리
TTL이 짧으면 자연 만료를 기다린다. 운영상 즉시 정리가 필요하면 cleanup script를 별도 PR로 만든다.
주의: cleanup script는 반드시 dry-run을 기본값으로 둔다.
### Step 5. 상수와 문서 정리
`SUPERVISOR_RESOLVED_HASH_PREFIX` 상수와 관련 env/문서 언급을 제거한다. `docs/service-evaluation-operations.md`의 Redis key schema도 갱신한다.
검증:
```bash
rg "review-resolved|SUPERVISOR_RESOLVED_HASH_PREFIX" src docs
npm run lint
npm test
```
## Rollback 원칙
- Step 1-2는 단순 revert로 rollback 가능하다.
- Step 3 이후 rollback은 stream-to-hash backfill 필요 여부를 먼저 판단한다.
- Step 4 cleanup 이후에는 hash 데이터 복구를 기대하지 않는다.
- 모든 단계는 작은 PR로 나누고, 각 PR은 독립 revert 가능해야 한다.
+203 -102
View File
@@ -6,10 +6,10 @@
운영 프로세스는 크게 두 개다.
| 프로세스 | 엔트리포인트 | 역할 |
|---|---|---|
| agent | `src/main.ts` | NATS request/reply를 받아 실시간 온보딩 응답 생성 |
| worker | `src/workers/background.ts` | Redis Stream background job 처리, shadow eval, archive, drift, review routing |
| 프로세스 | 엔트리포인트 | 역할 |
| -------- | --------------------------- | ----------------------------------------------------------------------------- |
| agent | `src/main.ts` | NATS request/reply를 받아 실시간 온보딩 응답 생성 |
| worker | `src/workers/background.ts` | Redis Stream background job 처리, shadow eval, archive, drift, review routing |
PM2 기준으로는 `ecosystem.config.cjs`에서 agent와 worker를 함께 띄운다.
@@ -88,17 +88,17 @@ Tool loop는 `responseMode=llm-with-tools`일 때 작동한다. Built-in tool은
Worker는 `lolympus-agent:background` Redis Stream을 consumer group `bg-worker`로 읽는다.
| Job type | 처리 |
|---|---|
| `shadow-eval` | 실시간 응답을 rule/LLM/process 기준으로 평가 |
| `summarize` | 오래된 대화 일부를 요약해 summary slot에 저장 |
| Job type | 처리 |
| ------------- | --------------------------------------------- |
| `shadow-eval` | 실시간 응답을 rule/LLM/process 기준으로 평가 |
| `summarize` | 오래된 대화 일부를 요약해 summary slot에 저장 |
Worker는 pending job을 복구하고, delivery count가 한도를 넘으면 DLQ로 이동한다.
| Stream | 용도 |
|---|---|
| `lolympus-agent:background` | background job queue |
| `lolympus-agent:background:dlq` | 반복 실패 job 저장 |
| Stream | 용도 |
| ------------------------------- | -------------------- |
| `lolympus-agent:background` | background job queue |
| `lolympus-agent:background:dlq` | 반복 실패 job 저장 |
## 6. Shadow Evaluation 흐름
@@ -123,14 +123,14 @@ lolympus-agent:eval:results
Worker는 일정 간격으로 eval result를 가공한다.
| 작업 | 기본 주기 | 결과 |
|---|---:|---|
| aggregation | `EVAL_AGG_TICK_MS` 5분 | slice별 Redis Hash metric |
| archive | `EVAL_ARCHIVE_TICK_MS` 1시간 | MongoDB `eval_archive` |
| drift detection | `EVAL_DRIFT_TICK_MS` 24시간 | `eval-drift` alert |
| promotion | `EVAL_PROMOTE_TICK_MS` 24시간 | golden candidate jsonl |
| review routing | `EVAL_REVIEW_TICK_MS` 5분 | human review queue |
| review label archive | archive tick과 함께 | MongoDB `eval_review_labels` |
| 작업 | 기본 주기 | 결과 |
| -------------------- | ----------------------------: | ---------------------------- |
| aggregation | `EVAL_AGG_TICK_MS` 5분 | slice별 Redis Hash metric |
| archive | `EVAL_ARCHIVE_TICK_MS` 1시간 | MongoDB `eval_archive` |
| drift detection | `EVAL_DRIFT_TICK_MS` 24시간 | `eval-drift` alert |
| promotion | `EVAL_PROMOTE_TICK_MS` 24시간 | golden candidate jsonl |
| review routing | `EVAL_REVIEW_TICK_MS` 5분 | human review queue |
| review label archive | archive tick과 함께 | MongoDB `eval_review_labels` |
Slice 정의:
@@ -149,29 +149,29 @@ tier × intent × phase
주요 Redis/Garnet key:
| Key | Type | 용도 |
|---|---|---|
| `lolympus-agent:background` | Stream | worker job queue |
| `lolympus-agent:background:dlq` | Stream | worker dead-letter queue |
| `lolympus-agent:eval:results` | Stream | shadow eval 결과 |
| `lolympus-agent:eval:baseline` | String | 최근 안정 baseline report |
| `lolympus-agent:eval:agg:{tier}:{intent}:{phase}` | Hash | slice별 count/score/latency/process metric |
| `lolympus-agent:eval:agg:cursor` | String | aggregation cursor |
| `lolympus-agent:eval:archive:cursor` | String | eval archive cursor |
| `lolympus-agent:eval:review:queue` | Stream | human review 대기 큐 |
| `lolympus-agent:eval:review:labeled` | Stream | human review label |
| `lolympus-agent:eval:review:cursor` | String | review routing cursor |
| `lolympus-agent:eval:review:dedupe:{evalStreamId}` | String | 동일 eval result 중복 라우팅 방지 |
| `lolympus-agent:eval:review:label-archive:cursor` | String | review label archive cursor |
| `lolympus-agent:alert:dedupe:{kind}` | String | alert rate limit |
| Key | Type | 용도 |
| -------------------------------------------------- | ------ | ------------------------------------------ |
| `lolympus-agent:background` | Stream | worker job queue |
| `lolympus-agent:background:dlq` | Stream | worker dead-letter queue |
| `lolympus-agent:eval:results` | Stream | shadow eval 결과 |
| `lolympus-agent:eval:baseline` | String | 최근 안정 baseline report |
| `lolympus-agent:eval:agg:{tier}:{intent}:{phase}` | Hash | slice별 count/score/latency/process metric |
| `lolympus-agent:eval:agg:cursor` | String | aggregation cursor |
| `lolympus-agent:eval:archive:cursor` | String | eval archive cursor |
| `lolympus-agent:eval:review:queue` | Stream | human review 대기 큐 |
| `lolympus-agent:eval:review:labeled` | Stream | human review label |
| `lolympus-agent:eval:review:cursor` | String | review routing cursor |
| `lolympus-agent:eval:review:dedupe:{evalStreamId}` | String | 동일 eval result 중복 라우팅 방지 |
| `lolympus-agent:eval:review:label-archive:cursor` | String | review label archive cursor |
| `lolympus-agent:alert:dedupe:{kind}` | String | alert rate limit |
## 9. MongoDB Collections
| Collection | 생성/사용 모듈 | 용도 |
|---|---|---|
| `eval_archive` | `src/eval/archive.ts` | shadow eval 결과 장기 보관 |
| `eval_review_labels` | `src/eval/review/label-archive.ts` | 사람 라벨 장기 보관 |
| `eval_tournaments` | `src/eval/loop/tournament.ts` | prompt variant tournament 결과 |
| Collection | 생성/사용 모듈 | 용도 |
| -------------------- | ---------------------------------- | ------------------------------ |
| `eval_archive` | `src/eval/archive.ts` | shadow eval 결과 장기 보관 |
| `eval_review_labels` | `src/eval/review/label-archive.ts` | 사람 라벨 장기 보관 |
| `eval_tournaments` | `src/eval/loop/tournament.ts` | prompt variant tournament 결과 |
`eval_archive`는 `evaluatedAt` 기준 TTL index를 가진다. 기본 보관 기간은 `EVAL_ARCHIVE_TTL_DAYS=30`이다.
@@ -218,6 +218,45 @@ npm run eval:review -- --limit=20 --export-labeled=eval-reports/review-labels.js
라벨 결과는 `lolympus-agent:eval:review:labeled` Stream에 쌓이고 archive tick에서 `eval_review_labels`로 영속화된다.
### 10.1 Supervisor Review Queue
Supervisor review queue는 skill handoff가 budget, confidence, policy, validation guardrail에 걸렸을 때 운영자가 확인하는 큐다.
큐:
```text
lolympus-agent:review-queue
```
Resolution audit:
```text
lolympus-agent:review-resolutions
```
기본 workflow:
1. Slack 또는 NATS에서 `supervisor-handoff` alert를 확인한다.
2. 최근 queue를 본다.
3. 개별 review를 열어 handoff packet, source chain, reason을 확인한다.
4. 운영자 답변, reroute, dismiss 중 하나로 resolution을 기록한다.
5. `review:stats`로 pending이 줄었는지 확인한다.
```bash
npm run review:list -- --limit=10
npm run review:show -- <reviewId> --history
npm run review:resolve -- <reviewId> --action=manual-reply --note="운영자 확인 완료"
npm run review:stats
```
특정 reason만 볼 때:
```bash
npm run review:list -- --reason=low-confidence --limit=10
```
Resolution history는 stream에 쌓이며, compatibility hash는 sunset 전까지 read fallback으로 유지된다. Sunset 조건과 절차는 [resolution-hash-sunset-procedure.md](resolution-hash-sunset-procedure.md)를 따른다.
## 11. Calibration 흐름
Calibration은 사람 점수와 LLM judge 점수의 상관을 계산한다.
@@ -345,66 +384,118 @@ Variant 적용은 자동 머지가 아니다. 사람이 tournament 결과와 sam
## 14. Eval CLI 요약
| 명령 | 용도 |
|---|---|
| `npm run eval` | golden set 실행 |
| `npm run eval:capture` | MongoDB events에서 golden scaffold 추출 |
| `npm run eval:baseline` | 안정 baseline 저장 |
| `npm run eval:report` | archive slice report 출력 |
| `npm run eval:promote` | golden candidate 추출 |
| `npm run eval:review` | human review CLI |
| `npm run eval:calibrate` | 사람/LLM judge calibration |
| `npm run eval:propose` | prompt/tool improvement proposal 생성 |
| `npm run eval:tournament` | prompt variant A/B tournament 실행 |
| `npm run eval:tournament-results` | tournament 결과 조회 |
| 명령 | 용도 |
| ----------------------------------- | ---------------------------------------------- |
| `npm run eval` | golden set 실행 |
| `npm run eval:capture` | MongoDB events에서 golden scaffold 추출 |
| `npm run eval:baseline` | 안정 baseline 저장 |
| `npm run eval:report` | archive slice report 출력 |
| `npm run eval:promote` | golden candidate 추출 |
| `npm run eval:review` | human review CLI |
| `npm run eval:calibrate` | 사람/LLM judge calibration |
| `npm run eval:propose` | prompt/tool improvement proposal 생성 |
| `npm run eval:tournament` | prompt variant A/B tournament 실행 |
| `npm run eval:tournament-results` | tournament 결과 조회 |
| `npm run eval:train-router` | archive 기반 learned router weights 생성 |
| `npm run eval:router-shadow-report` | static router와 learned router divergence 보고 |
### 14.1 자주 쓰는 명령 Cheat Sheet
평가:
```bash
npm run eval -- --set=onboarding/cases --skip-llm-judge
npm run eval:moderation -- --skip-llm-judge
npm run eval:handoff -- --skip-llm-judge
npm run eval:report -- --worst=20 --since=7d
npm run eval:propose -- --slice=tier=1,intent=status-question,phase=deadline-near
npm run eval:tournament -- --variants=control,<variantId> --max-matches=50
```
학습과 shadow 비교:
```bash
npm run eval:train-router -- --output=.local/router-weights.json --force
npm run eval:router-shadow-report -- --since=7d --weights=.local/router-weights.json
```
운영:
```bash
npm run review:list -- --limit=10
npm run review:show -- <reviewId> --history
npm run review:resolve -- <reviewId> --action=dismiss --note="중복"
npm run review:stats
```
검증:
```bash
npm run typecheck
npm run lint
npm run lint:skills
npm test
```
## 15. 주요 Env
| Env | 기본값 | 용도 |
|---|---:|---|
| `EVAL_STREAM_MAXLEN` | 10000 | eval results Stream maxlen |
| `EVAL_AGG_TICK_MS` | 300000 | aggregation tick |
| `EVAL_AGG_TTL_SEC` | 604800 | slice metric TTL |
| `EVAL_ARCHIVE_TICK_MS` | 3600000 | archive tick |
| `EVAL_ARCHIVE_TTL_DAYS` | 30 | archive TTL days |
| `EVAL_DRIFT_TICK_MS` | 86400000 | drift tick |
| `EVAL_PROMOTE_TICK_MS` | 86400000 | promotion tick |
| `EVAL_REVIEW_TICK_MS` | 300000 | review routing tick |
| `EVAL_REVIEW_QUEUE_MAXLEN` | 500 | review queue maxlen |
| `EVAL_REVIEW_LABEL_MAXLEN` | 5000 | review label Stream maxlen |
| `EVAL_REVIEW_DEDUPE_TTL_SEC` | 604800 | review dedupe TTL |
| `EVAL_CALIBRATION_MIN_CORR` | 0.5 | calibration gate |
| `REVIEWER_ID` | git user.email | human review 식별자 |
| `LLM_PROPOSE_MODEL` | `LLM_JUDGE_MODEL` | proposal model |
| `LLM_PROPOSE_MAX_TOKENS` | 1024 | proposal max tokens |
| `EVAL_TOURNAMENT_MAX_MATCHES` | 50 | tournament match cap |
| `EVAL_TOURNAMENT_MIN_CASES` | 10 | proposal 최소 archive cases |
| `PROMPT_VARIANT_ID` | unset | 운영 prompt variant 선택 |
| `METRICS_PORT` | 9464 | Prometheus `/metrics` HTTP endpoint port |
| `SLACK_ALERT_WEBHOOK_URL` | unset | alert Slack incoming webhook URL |
| `SLACK_WEBHOOK_TIMEOUT_MS` | 3000 | Slack webhook POST timeout |
| `ALERT_THRESHOLD_P95_LATENCY_MS` | 3000 | 글로벌 p95 latency alert 기준 |
| `ALERT_THRESHOLD_EVAL_SCORE_DROP_PCT` | 10 | 글로벌 eval score drop alert 기준 |
| `ALERT_THRESHOLD_LLM_ERROR_RATE` | 0.1 | 글로벌 LLM judge error rate alert 기준 |
| `ALERT_THRESHOLD_DRIFT_PCT` | 15 | 글로벌 drift alert 기준 |
| Env | 기본값 | 용도 |
| --------------------------------------- | ----------------: | ---------------------------------------- |
| `EVAL_STREAM_MAXLEN` | 10000 | eval results Stream maxlen |
| `EVAL_AGG_TICK_MS` | 300000 | aggregation tick |
| `EVAL_AGG_TTL_SEC` | 604800 | slice metric TTL |
| `EVAL_ARCHIVE_TICK_MS` | 3600000 | archive tick |
| `EVAL_ARCHIVE_TTL_DAYS` | 30 | archive TTL days |
| `EVAL_DRIFT_TICK_MS` | 86400000 | drift tick |
| `EVAL_PROMOTE_TICK_MS` | 86400000 | promotion tick |
| `EVAL_REVIEW_TICK_MS` | 300000 | review routing tick |
| `EVAL_REVIEW_QUEUE_MAXLEN` | 500 | review queue maxlen |
| `EVAL_REVIEW_LABEL_MAXLEN` | 5000 | review label Stream maxlen |
| `EVAL_REVIEW_DEDUPE_TTL_SEC` | 604800 | review dedupe TTL |
| `EVAL_CALIBRATION_MIN_CORR` | 0.5 | calibration gate |
| `REVIEWER_ID` | git user.email | human review 식별자 |
| `LLM_PROPOSE_MODEL` | `LLM_JUDGE_MODEL` | proposal model |
| `LLM_PROPOSE_MAX_TOKENS` | 1024 | proposal max tokens |
| `EVAL_TOURNAMENT_MAX_MATCHES` | 50 | tournament match cap |
| `EVAL_TOURNAMENT_MIN_CASES` | 10 | proposal 최소 archive cases |
| `PROMPT_VARIANT_ID` | unset | 운영 prompt variant 선택 |
| `AGENT_ROUTER_WEIGHTS_PATH` | unset | learned router weights path |
| `AGENT_SUPERVISOR_LLM_RESPONSE_ENABLED` | true | supervisor LLM userMessage 사용 여부 |
| `METRICS_PORT` | 9464 | Prometheus `/metrics` HTTP endpoint port |
| `SLACK_ALERT_WEBHOOK_URL` | unset | alert Slack incoming webhook URL |
| `SLACK_WEBHOOK_TIMEOUT_MS` | 3000 | Slack webhook POST timeout |
| `ALERT_THRESHOLD_P95_LATENCY_MS` | 3000 | 글로벌 p95 latency alert 기준 |
| `ALERT_THRESHOLD_EVAL_SCORE_DROP_PCT` | 10 | 글로벌 eval score drop alert 기준 |
| `ALERT_THRESHOLD_LLM_ERROR_RATE` | 0.1 | 글로벌 LLM judge error rate alert 기준 |
| `ALERT_THRESHOLD_DRIFT_PCT` | 15 | 글로벌 drift alert 기준 |
## 16. Alert와 Monitoring
Worker는 다음 종류의 alert를 보낼 수 있다.
| Alert kind | 의미 |
|---|---|
| `latency` | 최근 shadow eval latency p95 초과 |
| `llm-error-rate` | LLM judge 실패율 상승 |
| `eval-score-drop` | baseline 대비 eval score 하락 |
| `eval-drift` | 24h vs 7d slice score drift |
| `endpoint-down` | LLM circuit breaker open |
| `archive-stalled` | MongoDB archive 연속 실패 |
| Alert kind | 의미 |
| -------------------- | --------------------------------- |
| `latency` | 최근 shadow eval latency p95 초과 |
| `llm-error-rate` | LLM judge 실패율 상승 |
| `eval-score-drop` | baseline 대비 eval score 하락 |
| `eval-drift` | 24h vs 7d slice score drift |
| `endpoint-down` | LLM circuit breaker open |
| `archive-stalled` | MongoDB archive 연속 실패 |
| `supervisor-handoff` | supervisor review queue 진입 |
Alert는 `lolympus-agent.alert` NATS subject로 발행되고, dedupe key로 rate limit된다.
`SLACK_ALERT_WEBHOOK_URL`이 설정되어 있으면 같은 alert가 Slack incoming webhook으로도 전송된다.
Slack 전송은 NATS publish 이후 비동기로 실행되므로 Slack 장애가 agent 응답 경로를 막지 않는다.
Alert 처리 workflow:
1. Slack 메시지의 `kind`, `skill`, `metric`, `value`, `threshold`, `window`를 확인한다.
2. `supervisor-handoff`면 `review:list`와 `review:show`로 packet을 확인한다.
3. `latency`면 `/metrics`의 p95 panel과 최근 deploy를 확인한다.
4. `llm-error-rate`나 `endpoint-down`이면 LLM endpoint env와 circuit breaker 로그를 확인한다.
5. `eval-score-drop` 또는 `eval-drift`면 `eval:report`, archive sample, golden smoke를 확인한다.
6. 조치 후 dedupe window가 끝나도 반복되는지 본다.
### 16.1 Skill별 threshold
Alert threshold는 글로벌 env를 기본으로 쓰고, skill별 env가 있으면 우선 적용한다.
@@ -430,9 +521,9 @@ skill이 없는 cross-system alert는 기존처럼 글로벌 dedupe를 사용한
Agent process는 `METRICS_PORT`에서 HTTP endpoint를 연다.
| Endpoint | 응답 |
|---|---|
| `/healthz` | `ok` |
| Endpoint | 응답 |
| ---------- | -------------------------- |
| `/healthz` | `ok` |
| `/metrics` | Prometheus text exposition |
Prometheus scrape 예시:
@@ -447,18 +538,18 @@ scrape_configs:
권장 dashboard panel:
| Metric | 권장 panel |
|---|---|
| `agent_handoff_total` | skill/from/to/reason별 handoff rate |
| `agent_handoff_loop_total` | skill별 loop 발생 수 |
| `agent_human_override_total` | supervisor/manual review 유입 |
| `agent_missed_escalation_total` | skill별 missed escalation |
| `agent_routing_accuracy_total` | eval routing accuracy |
| `agent_unnecessary_escalation_total` | skill별 unnecessary escalation |
| `agent_validator_fail_total` | skill/stage별 validator fail |
| `agent_handoff_count` | skill별 request당 handoff histogram |
| `agent_time_to_resolution_ms` | skill별 처리 시간 histogram |
| `agent_token_cost_usd` | skill/model별 token cost histogram |
| Metric | 권장 panel |
| ------------------------------------ | ----------------------------------- |
| `agent_handoff_total` | skill/from/to/reason별 handoff rate |
| `agent_handoff_loop_total` | skill별 loop 발생 수 |
| `agent_human_override_total` | supervisor/manual review 유입 |
| `agent_missed_escalation_total` | skill별 missed escalation |
| `agent_routing_accuracy_total` | eval routing accuracy |
| `agent_unnecessary_escalation_total` | skill별 unnecessary escalation |
| `agent_validator_fail_total` | skill/stage별 validator fail |
| `agent_handoff_count` | skill별 request당 handoff histogram |
| `agent_time_to_resolution_ms` | skill별 처리 시간 histogram |
| `agent_token_cost_usd` | skill/model별 token cost histogram |
PromQL 예시:
@@ -468,6 +559,16 @@ histogram_quantile(0.95, sum by (skill, le) (rate(agent_time_to_resolution_ms_bu
sum by (skill, stage) (rate(agent_validator_fail_total[5m]))
```
운영 SLI 권장 시작점:
| SLI | 권장 시작값 |
| -------------------------- | -------------------: |
| request p95 latency | 3초 이하 |
| supervisor escalation rate | skill별 일 10건 이하 |
| LLM judge error rate | 10% 이하 |
| eval drift | 15% 이하 |
| archive stalled | 3회 연속 실패 0건 |
### 16.3 Slack webhook 설정
Slack incoming webhook URL을 env로 설정한다.