초기 커밋 — 협상 AI 에이전트 정본: 엔진·데모 콘솔·측정 인프라·증빙

- server/: FastAPI 협상 엔진 (5라운드, Q-Table/UCB, 페르소나 계측, :53117)
- frontend/: 데모 콘솔 (React+Tailwind → nginx, /api 프록시)
- eval/·testdata/: 지표 8종 측정 하네스 + 재현 가능 테스트셋
- results/: 측정 증빙 (지표별 result+provenance, raw 원본 동결+SHA256)
  ① 86.0 · ② 76.0 · ③ 5.99% · ⑥ p95 3.61ms · ⑦ 611만/년 · ⑧ 91/100 · ⑨ 99.71 · ⑩ 97.99
- docker-compose.yml + run.sh: backend+frontend 일괄 기동

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_0112XUWF4bc3gGrEt8vsYCzy
This commit is contained in:
민헌andClaude Fable 5 committed 2026-08-31 13:09:52 +09:00
commit dfb9ad6e66
268 files changed
+164241

No files matched your search

View File
Whitespace-only changes.
+76
View File
@@ -0,0 +1,76 @@
"""계측 기능 테스트 — ⑩ 긴장도·페르소나, ⑦ 계약 데이터화."""
import json
import sys
from pathlib import Path
sys.path.insert(0, str(Path(__file__).resolve().parents[1]))
from config.config_models import AppConfig, InstrumentConfig, ProfilingConfig
from router.v1.nego.protocol import NegotiationRequest
from services.negotiation.engine import ChatEngine
from services.negotiation.tension import estimate_tension, select_persona
SNAP = {"rq_type": "재협상", "session_id": "T-1", "index": 5, "user_input": "예",
"item_price": 163600.0, "revenue": 163600.0, "dist": "R", "partners_yn": "없음",
"partners": 0, "anchor": 8099.0, "target": 8180.0, "initial": 9000.0,
"input": 9000.0, "iteration": 0, "is_new_quote": True, "profiling": False}
def make_engine(tmp_path):
config = AppConfig(
profiling=ProfilingConfig(enabled=False),
instrument=InstrumentConfig(
tension_log=str(tmp_path / "tension.jsonl"),
response_time_log="",
contracts_log=str(tmp_path / "contracts.jsonl"),
),
)
return ChatEngine(config), tmp_path
def test_persona_bands():
assert select_persona(0.9)["name"] == "단호한 압박형"
assert select_persona(0.5)["name"] == "균형 협상형"
assert select_persona(0.1)["name"] == "우호적 마무리형"
def test_estimate_tension_zones():
# PZ1/PZ2(지표 ≥ 80) → 0, 초기제안가 = 최대 긴장 근사
assert estimate_tension(99, 8180, 9000) == 0.0
assert estimate_tension(34, 8180, 9000) > 0.5
def test_tension_log_has_persona(tmp_path):
engine, tmp = make_engine(tmp_path)
req = NegotiationRequest(**dict(SNAP, step="가격협상_확인"))
res = engine.process_request(req)
assert res.step == "가격협상"
rows = [json.loads(x) for x in (tmp / "tension.jsonl").read_text().splitlines()]
assert rows, "긴장도 로그 미기록"
row = rows[-1]
assert 0.0 <= row["predicted"] <= 1.0
assert row["persona"] in ("단호한 압박형", "균형 협상형", "우호적 마무리형")
assert isinstance(row["indicator"], int)
def test_contract_logged_on_completion(tmp_path):
engine, tmp = make_engine(tmp_path)
# 1% 와일드카드 수락 → 협상완료 (입력가 8000 ≤ 앵커 8099로 진입)
req = NegotiationRequest(**dict(SNAP, step="wild_card_1pct", user_input="예",
input=8000.0))
res = engine.process_request(req)
assert res.step == "협상완료"
rows = [json.loads(x) for x in (tmp / "contracts.jsonl").read_text().splitlines()]
assert len(rows) == 1
rec = rows[0]
assert rec["final_price"] == 7920 # 8000 × 0.99
assert rec["reduction_pct"] is not None
assert rec["rq_type"] == "재협상"
def test_contract_not_logged_midway(tmp_path):
engine, tmp = make_engine(tmp_path)
engine.process_request(NegotiationRequest(**dict(SNAP, step="시작", index=0)))
assert not (tmp / "contracts.jsonl").exists() or \
not (tmp / "contracts.jsonl").read_text().strip()
+121
View File
@@ -0,0 +1,121 @@
"""서버 스모크 테스트 — 엔진 기동, 고정/동적 스텝, 계측 응답."""
import sys
from pathlib import Path
sys.path.insert(0, str(Path(__file__).resolve().parents[1]))
import pytest
from fastapi.testclient import TestClient
from router.router import app
client = TestClient(app)
# 04 bench와 동일 형태의 가격협상 진입 요청
HEAVY_BODY = {
"rq_type": "재협상", "session_id": "TEST-01", "step": "가격협상_확인", "index": 5,
"user_input": "예", "item_price": 163600, "revenue": 163600, "dist": "R",
"partners_yn": "없음", "partners": 0, "anchor": 8099, "target": 8180,
"initial": 9000, "input": 9000, "iteration": 0, "is_new_quote": True,
"profiling": False,
}
def test_health():
res = client.get("/health")
assert res.status_code == 200
assert res.json()["status"] == "OK"
def test_config_endpoint():
res = client.get("/v1/nego/config")
assert res.status_code == 200
body = res.json()
assert body["server"] == "NEGO_AGENT"
assert body["cards"] > 0
def test_fixed_step_start():
res = client.post("/v1/nego/chat", json={
"rq_type": "재협상", "session_id": "TEST-00", "step": "시작", "index": 0,
})
assert res.status_code == 200
body = res.json()
assert body["step"] == "서비스안내"
assert body["script"]
# KT 지칭이 응답에 없어야 한다
assert "kt" not in body["script"].lower()
def test_dynamic_step_price_negotiation():
"""가격협상_확인 [예] + 입력가 ≤ 앵커 → 와일드카드(1% 추가 네고) 진입."""
body = dict(HEAVY_BODY, user_input="8000", step="가격협상_재입력", index=4)
res = client.post("/v1/nego/chat", json=body)
assert res.status_code == 200
assert res.json()["step"] == "가격협상_확인"
res2 = client.post("/v1/nego/chat", json=dict(HEAVY_BODY, input=8000))
assert res2.status_code == 200
out = res2.json()
# 입력가(8000) ≤ 앵커(8099) + 유형 A → wild_card_1pct 스텝으로 전이
assert out["step"] == "wild_card_1pct"
assert out["script"]
def test_dynamic_step_card_selection():
"""입력가 > 앵커 상태의 가격협상_확인 [예] → '가격협상' 동적 스텝 — 카드 선택 + 지표 계산."""
res = client.post("/v1/nego/chat", json=HEAVY_BODY)
assert res.status_code == 200
out = res.json()
assert out["chat_metadata"]["card_id"]
assert out["script"]
assert out["chat_metadata"]["indicator_value"] is not None
def test_response_time_header():
res = client.get("/health")
assert "x-response-time-ms" in res.headers
def test_cards_are_plain_text():
"""카드 정본은 평문 script만 갖는다 — Slate(editor_script)·KT 종속 변수 없음."""
import json
from common.paths import RESOURCES_DIR
nego = json.load(open(RESOURCES_DIR / "cards" / "nego_card.json", encoding="utf-8"))
for card in nego["cards"]:
assert set(card.keys()) == {"card_id", "card_name", "script"}
assert "dss_count" not in card["script"]
assert "kt" not in card["script"].lower()
assert "그룹사" not in card["script"]
wild = json.load(open(RESOURCES_DIR / "cards" / "wild_card.json", encoding="utf-8"))
for config in wild.values():
assert "editor_script" not in config
def test_card_variable_substitution_and_hidden():
"""card_data 값은 치환되고, 값이 없는 변수 문장은 숨겨진다."""
from services.cards.completer import CardScriptCompleter
from services.cards.repository import CardScriptRepository
from router.v1.nego.protocol import NegotiationCardData
completer = CardScriptCompleter(CardScriptRepository())
# 값이 있으면 치환
out = completer.execute("NC26-007", NegotiationCardData(payment_terms="입고 후 30일 이내 현금 지급"))
assert "입고 후 30일 이내 현금 지급" in out
assert "{payment_terms}" not in out
# 값이 없으면 해당 문장 Hidden — 나머지 문장은 유지
out2 = completer.execute("NC26-007", None)
assert "payment_terms" not in out2
assert "공급 가능한 가격" in out2
def test_session_invalidate():
res = client.post("/v1/nego/session/invalidate",
json={"session_id": "TEST-01", "reason": "테스트"})
assert res.status_code == 200
assert res.json()["status"] == "ok"