Files
lolympus-agent/docs/service-evaluation-operations.md
T

749 lines
28 KiB
Markdown
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
# lolympus-agent Service and Evaluation Operations
이 문서는 `lolympus-agent`의 운영 흐름과 evaluation 파이프라인을 한 곳에서 보기 위한 runbook이다. 실시간 응답 경로, background worker, shadow evaluation, human review, calibration, closed-loop prompt experiment까지 포함한다.
## 1. 프로세스 구성
운영 프로세스는 크게 두 개다.
| 프로세스 | 엔트리포인트 | 역할 |
| -------- | --------------------------- | ----------------------------------------------------------------------------- |
| 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를 함께 띄운다.
```bash
npm run pm2:dev
npm run pm2:test
npm run pm2:prod
```
개발 환경 단독 실행은 기존 스크립트를 사용한다.
```bash
npm run start:dev
```
## 2. Bootstrap 흐름
`src/main.ts`의 기동 순서는 다음과 같다.
1. `loadEnvironmentFromNodeEnv()`로 `env-vars/{NODE_ENV}.env` 로드
2. logger/tracing 초기화
3. NATS 연결
4. Garnet/Redis 연결
5. LLM endpoint와 provider key 구성
6. MongoDB 연결, 가능하면 room context 활성화
7. `Agent` 생성
8. `OnboardingSkill` 등록
9. `lolympus-agent.request` 구독 시작
중요한 점은 NATS가 가장 먼저 외부 TLS 연결을 시도한다는 것이다. 따라서 bootstrap fatal error가 `certificate has expired`이고 `✓ NATS connected` 로그가 없었다면 1순위 원인은 `NATS_ENDPOINT` 인증서 만료다.
## 3. 실시간 응답 흐름
본체는 NATS request/reply로 agent에 요청한다.
```text
lolympus-agent.request
-> Agent.handleRequest
-> OnboardingSkill.handle
-> AgentResponse
```
`OnboardingSkill.handle()` 내부 흐름:
1. Garnet에서 온보딩 세션 로드
2. user message와 trigger 기반 intent classify
3. session, trigger, intent로 `DerivedState` 생성
4. `shouldRespond=false`면 empty response 반환
5. `responseMode=template`이면 template fallback 응답
6. LLM 경로면 prompt build 후 orchestrator 실행
7. tier에 따라 planner/responder/critic/tool-loop 사용
8. validator로 응답 검증
9. 최종 응답 반환
10. blackboard 업데이트
11. shadow eval event를 background stream에 비동기 발행
실시간 사용자 응답은 9번에서 끝난다. Evaluation은 11번 이후 worker가 비동기로 처리한다.
## 4. Prompt와 Tool 경로
Prompt는 `src/skills/onboarding/prompts/builder.ts`가 만든다.
기본 layer:
- persona
- policy
- state
- examples
- context
`PROMPT_VARIANT_ID`가 설정되면 `src/eval/proposals/{variantId}.json` manifest를 읽어 prompt layer diff를 적용한다. 운영 반영은 env로 variant를 선택하는 방식이며, proposal 생성과 tournament는 별도 CLI에서 수행한다.
Tool loop는 `responseMode=llm-with-tools`일 때 작동한다. Built-in tool은 `src/tools/builtins/*`에 있다.
## 5. Background Worker 흐름
Worker는 `lolympus-agent:background` Redis Stream을 consumer group `bg-worker`로 읽는다.
| 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 저장 |
## 6. Shadow Evaluation 흐름
실시간 응답이 만들어지면 `ShadowEvalBus`가 background stream에 `shadow-eval` job을 발행한다.
Worker는 이 job을 받아 다음을 수행한다.
1. validator 재실행
2. LLM judge 실행
3. process trace가 있으면 process judge 실행
4. latency, tier, intent, phase, judge 결과 저장
결과는 Redis Stream에 저장된다.
```text
lolympus-agent:eval:results
```
이 Stream이 이후 evaluation 운영의 원천 데이터다.
## 7. 주기 Evaluation 작업
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` |
Slice 정의:
```text
tier × intent × phase
```
예:
```text
0:photo-question:photo-pending
1:discord-question:step1-completed
```
## 8. Redis Key Schema
주요 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 |
## 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 결과 |
`eval_archive`는 `evaluatedAt` 기준 TTL index를 가진다. 기본 보관 기간은 `EVAL_ARCHIVE_TTL_DAYS=30`이다.
## 10. Human Review 흐름
Review routing은 eval result 중 사람이 봐야 할 케이스를 큐에 넣는다.
조건:
- LLM judge overall이 낮음
- validator와 LLM judge가 불일치
- validator soft-warn
- rare slice
큐:
```text
lolympus-agent:eval:review:queue
```
라벨링:
```bash
npm run eval:review -- --limit=20
```
특정 reason만 보기:
```bash
npm run eval:review -- --reason=low-score --limit=10
```
stale pending item을 다시 큐에 넣기:
```bash
npm run eval:review -- --reset-pending
```
세션 라벨을 JSONL로 저장:
```bash
npm run eval:review -- --limit=20 --export-labeled=eval-reports/review-labels.jsonl
```
라벨 결과는 `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)를 따른다.
### 10.2 Tool Audit
Tool call은 성공과 실패 모두 `lolympus-agent:tool-calls` Stream에 남긴다. 원본 args는 저장하지 않고, 민감 키를 제거한 뒤 hash만 기록한다.
```bash
npm run tool-audit:list -- --limit=20
npm run tool-audit:list -- --skill=onboarding --since=24h
npm run tool-audit:show -- <callId>
```
Stream은 `AGENT_TOOL_AUDIT_MAX_LEN` 기준으로 trim된다. 기본값은 `100000`이다.
## 11. Calibration 흐름
Calibration은 사람 점수와 LLM judge 점수의 상관을 계산한다.
```bash
npm run eval:calibrate
```
CI나 수동 gate로 쓰려면:
```bash
npm run eval:calibrate -- --check
```
`pairs < 10`이면 표본이 부족하므로 경고만 출력하고 실패 처리하지 않는다. 충분한 라벨이 쌓이면 `EVAL_CALIBRATION_MIN_CORR` 기준으로 LLM judge 신뢰도를 감시한다.
## 12. Report와 Promotion
Slice별 약한 영역 확인:
```bash
npm run eval:report -- --worst=20
```
최근 7일 대신 다른 window:
```bash
npm run eval:report -- --worst=20 --since=24h
npm run eval:report -- --top=20 --since=30d
```
Golden candidate 확인:
```bash
npm run eval:promote -- --dry-run
```
Candidate 파일에 추가:
```bash
npm run eval:promote
```
기본 출력:
```text
src/eval/golden/onboarding/candidate.jsonl
```
Promotion 우선순위:
1. human-labeled fail
2. low-score
3. rule/LLM disagree
4. rare-slice
candidate는 바로 golden으로 승격되는 것이 아니라 사람이 직접 검토해 `onboarding/cases.jsonl`로 옮긴다.
## 13. Closed Loop 흐름
Phase 9의 closed loop는 prompt/tool 개선안을 만들고 tournament로 비교하는 흐름이다.
### 13.1 Proposal 생성
약한 slice를 지정한다.
```bash
npm run eval:propose -- --slice=tier=1,intent=photo-question,phase=photo-pending
```
archive case 수가 부족해도 강제로 실행하려면:
```bash
npm run eval:propose -- --slice=tier=1,intent=photo-question,phase=photo-pending --force
```
결과는 git-tracked proposal manifest로 저장된다.
```text
src/eval/proposals/{variantId}.json
```
### 13.2 Tournament 실행
Control과 variant를 비교한다.
```bash
npm run eval:tournament -- --variants=control,<variantId>
```
특정 archive case만 지정:
```bash
npm run eval:tournament -- --variants=control,<variantId> --case-ids=1-0,2-0
```
결과 조회:
```bash
npm run eval:tournament-results
npm run eval:tournament-results -- --variant=<variantId>
```
Tournament는 A/B 위치 편향을 줄이기 위해 variant 순서를 바꾼 match도 실행하고 ELO를 갱신한다. 결과는 MongoDB `eval_tournaments`에 저장된다.
### 13.3 운영 반영
운영 prompt에 variant를 반영하려면 env를 설정한다.
```env
PROMPT_VARIANT_ID=<variantId>
```
반영 전에는 반드시 다음을 확인한다.
```bash
npm run typecheck
npm run lint
npm run build
npm test
npm run eval -- --skip-llm-judge --no-publish-report
```
Variant 적용은 자동 머지가 아니다. 사람이 tournament 결과와 sample match를 보고 결정한다.
## 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: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 선택 |
| `AGENT_ROUTER_WEIGHTS_PATH` | unset | learned router weights path |
| `AGENT_BUDGET_LLM_COST_ENABLED` | true | LLM token cost를 request budget에 누적 |
| `AGENT_COST_AWARE_TIER_ENABLED` | true | confidence/cost-aware tier selection |
| `AGENT_SUPERVISOR_FAST_PATH_ENABLED` | true | supervisor regex fast-path 사용 |
| `SUPERVISOR_FAST_PATH_CONFIDENCE` | 0.85 | fast-path 최소 규칙 confidence |
| `AGENT_TOOL_SANDBOX_ENABLED` | false | tool context 최소 권한 강제 여부 |
| `AGENT_TOOL_AUDIT_MAX_LEN` | 100000 | tool audit Stream maxlen |
| `AGENT_NATS_ACL_MODE` | log-only | NATS subject ACL 모드 |
| `AGENT_SUPERVISOR_LLM_RESPONSE_ENABLED` | true | supervisor LLM userMessage 사용 여부 |
| `PHOENIX_OTLP_ENDPOINT` | unset | Phoenix OTLP trace endpoint |
| `PHOENIX_LOG_PROMPTS` | false | LLM prompt/completion content trace 기록 |
| `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 연속 실패 |
| `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가 있으면 우선 적용한다.
skill 이름은 대문자 env suffix로 정규화된다.
```env
ALERT_THRESHOLD_P95_LATENCY_MS=3000
ALERT_THRESHOLD_P95_LATENCY_MS_ONBOARDING=5000
ALERT_THRESHOLD_P95_LATENCY_MS_MODERATION=2000
ALERT_THRESHOLD_LLM_ERROR_RATE=0.1
ALERT_THRESHOLD_LLM_ERROR_RATE_ONBOARDING=0.2
ALERT_THRESHOLD_EVAL_SCORE_DROP_PCT=10
ALERT_THRESHOLD_DRIFT_PCT=15
```
같은 alert kind라도 `skill`이 다르면 dedupe key가 분리된다.
예를 들어 onboarding latency alert와 moderation latency alert는 서로 throttle하지 않는다.
skill이 없는 cross-system alert는 기존처럼 글로벌 dedupe를 사용한다.
### 16.2 Secret, Tool Sandbox, NATS ACL
Secret은 Infisical을 우선으로 로드한다. Infisical credential은 로컬 env 또는 IMDS에서 읽고, 새 secret env를 추가할 때는 `src/common/known-secret-keys.ts`에 함께 등록해야 로그 redaction 대상에 들어간다. LLM, embedding, Phoenix API key도 redaction 대상이다.
Tool은 `requires` 선언으로 필요한 context만 받는다. `AGENT_TOOL_SANDBOX_ENABLED=false`가 기본이라 운영 초기는 호환성을 유지한다. 1주 정도 audit을 본 뒤 false positive가 없으면 true로 전환한다.
NATS subject ACL은 `src/common/nats-skill-acl.ts`의 `DEFAULT_NATS_ACL`에서 관리한다. 기본 `AGENT_NATS_ACL_MODE=log-only`는 위반을 warn으로만 남기고 publish/request는 그대로 진행한다. 1개월 운영 후 false positive가 없으면 `enforce`로 전환한다.
### 16.3 Phoenix trace
LLM 호출, skill 실행, tool 실행 span은 OpenTelemetry trace로 남긴다.
`PHOENIX_OTLP_ENDPOINT`가 없으면 기존 설정을 따른다. 개발 환경 기본값은 trace exporter 비활성화이고, `OTEL_EXPORTER=stdout`이면 콘솔 exporter를 쓴다.
Phoenix를 로컬에서 볼 때:
```bash
docker run --rm -p 6006:6006 arizephoenix/phoenix:latest
```
Agent/worker env:
```env
PHOENIX_OTLP_ENDPOINT=http://localhost:6006/v1/traces
OTEL_SAMPLING_RATIO=1
PHOENIX_LOG_PROMPTS=false
```
`PHOENIX_OTLP_ENDPOINT`가 설정되면 `OTEL_EXPORTER=none`이어도 Phoenix OTLP exporter를 우선 사용한다.
Phoenix UI에서는 `service.name=lolympus-agent`, `gen_ai.system`, `gen_ai.request.model`, `gen_ai.usage.cost_usd`, `llm.token_count.prompt`, `llm.token_count.completion` 속성으로 LLM span을 필터링한다.
Prompt와 completion 본문은 기본적으로 기록하지 않는다.
디버깅 때문에 필요할 때만 `PHOENIX_LOG_PROMPTS=true`를 켠다. 이 경우 email, 전화번호, token/API key 형태의 값은 span 기록 전에 masking된다.
### 16.4 Prometheus scrape
Agent process는 `METRICS_PORT`에서 HTTP endpoint를 연다.
| Endpoint | 응답 |
| ---------- | -------------------------- |
| `/healthz` | `ok` |
| `/metrics` | Prometheus text exposition |
Prometheus scrape 예시:
```yaml
scrape_configs:
- job_name: lolympus-agent
static_configs:
- targets:
- 127.0.0.1:9464
```
권장 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 |
PromQL 예시:
```promql
sum by (skill) (rate(agent_handoff_total[5m]))
histogram_quantile(0.95, sum by (skill, le) (rate(agent_time_to_resolution_ms_bucket[5m])))
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.5 Slack webhook 설정
Slack incoming webhook URL을 env로 설정한다.
```env
SLACK_ALERT_WEBHOOK_URL=https://hooks.slack.com/services/...
SLACK_WEBHOOK_TIMEOUT_MS=3000
```
Webhook URL은 secret으로 취급한다. 로그 redaction 대상에 포함되어 있으며, Slack payload에는 metric, value, threshold, window, skill, suggested action만 포함하고 사용자 메시지 본문은 포함하지 않는다.
## 17. 장애 확인 Runbook
### 17.1 Bootstrap에서 `certificate has expired`
증상:
```text
[Bootstrap] Fatal startup error
message: certificate has expired
code: CERT_HAS_EXPIRED
```
`src/main.ts` 기준 NATS 연결이 첫 외부 TLS 연결이다. `✓ NATS connected` 로그가 없으면 `NATS_ENDPOINT` 인증서가 1순위 원인이다.
확인:
```bash
node --trace-warnings --import tsx src/main.ts
```
인증서 날짜 확인:
```bash
openssl s_client -connect <host>:<port> -servername <host> </dev/null 2>/dev/null \
| openssl x509 -noout -dates -subject
```
`✓ NATS connected` 이후 같은 오류가 나면 다음 후보는 Garnet 또는 MongoDB다.
### 17.2 LLM endpoint warning
증상:
```text
[LLM] Endpoint unavailable via circuit breaker
[LLM] Request error
[LLM] All endpoints failed
```
확인 순서:
1. `CLI_PROXY_API_URLS`
2. `OPENROUTER_API_KEY`, `OPENROUTER_API_URL`
3. `AGENT_LLM_API_URLS`
4. `LLAMA_SERVER_API_URL`
5. provider별 API key
`npm run eval -- --skip-llm-judge`는 LLM judge를 생략하지만 실제 응답 생성 LLM은 여전히 호출될 수 있다. endpoint가 모두 실패하면 template/fallback 경로로 통과할 수 있다.
### 17.3 MongoDB 미설정
Worker가 다음과 비슷한 로그를 남긴다.
```text
MongoDB connection string missing; eval archive/drift/promote disabled
```
영향:
- 실시간 응답은 가능
- shadow eval result Stream은 쌓임
- archive, drift, promote, calibration, tournament는 제한됨
필요 env:
```env
MONGODB_CONNECTION_STRING=
MONGODB_PROJECT_ID=
```
### 17.4 Review queue가 밀림
확인:
```bash
npm run eval:review -- --limit=5
```
stale pending item 정리:
```bash
npm run eval:review -- --reset-pending
```
같은 케이스가 반복 라우팅되면 dedupe TTL과 cursor를 확인한다.
```text
lolympus-agent:eval:review:cursor
lolympus-agent:eval:review:dedupe:{evalStreamId}
```
### 17.5 Archive stalled
`archive-stalled` alert가 뜨면 MongoDB 연결과 index 생성 권한을 확인한다.
관련 cursor:
```text
lolympus-agent:eval:archive:cursor
lolympus-agent:eval:review:label-archive:cursor
```
cursor가 진행되지 않으면 worker가 다음 tick에서 재시도한다.
## 18. 운영 원칙
- 실시간 응답 경로는 가능한 짧게 유지한다.
- Evaluation은 Redis Stream을 통해 비동기로 처리한다.
- Golden set 승격은 사람이 직접 결정한다.
- Prompt variant 운영 반영은 tournament 결과와 eval smoke를 본 뒤 결정한다.
- 자동 rollback이나 자동 merge는 하지 않는다.
- 모든 timestamp는 UTC ISO-8601을 사용한다.