[feat] 카드 카탈로그 DB 정본화 — config 결합 제거 + 학습 보존 자동반영

카드 카탈로그(negodata)가 Q-table action space 를 정의하는 정본이 되고, 카드 변경이
config 수정·학습 손실 없이 agent 에 자동 반영되는 고리를 완성.

- action space 정리: 카탈로그 전체(NGC-001~011, 11장) 고정, 견적별 선택은 축소가 아니라
  available_mask(_selection_mask) 로 처리 — action_id↔카드 대응을 견적마다 일정하게 유지해
  Q-table 학습 일관성 보장. 구 인덱스 방식(selected[action_id]) 폐기.
- ① 카탈로그 DB 정본화: action_mapping.type=db 면 registry 가 card.nego_cards(user_id NULL,
  number 순) 조회로 action_to_card 동적 구성(파일은 폴백). port/adapter(card_catalog_*).
  _base=type:db. → negodata 카드 추가/삭제 시 config 수정 불필요.
- ② 차원 변경 학습 보존 마이그레이션: migrate_active_version_dim — 겹치는 셀 복사
  (append/truncate 안전) + 새 카드 fresh. model_store.load 가 차원 불일치 시 호출.
- ③ reload 엔드포인트: /v1/catalog-refresh(테넌트) · /v1/catalog-refresh-all(전역, 화이트리스트).
- ④ 브랜드: company_profile_repo — 자동 온보딩 고객사(company_id UUID)는
  company.companies.name 으로 {company_name} 채움. 데모 테넌트는 파일 유지.
- 크로스서비스: negodata card_service 가 공용 nego 카드 변경 시 agent_notify 로 전역 리로드 알림
  (best-effort, is_test skip). config 에 agent_base_url.
- 하니스 episodes 400→600(action 11 수렴). 테스트 갱신·추가로 agent 98/98.

알려진 갭(후속): per-company 카탈로그 스코프(회사 카드도 action space 포함), 카탈로그 중간
삭제 시 카드번호 기반 마이그레이션.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
This commit is contained in:
HyeongBaeYangandClaude Fable 5 committed 2026-07-08 14:56:28 +09:00
1 parent c2760c804f
commit 18020a9e07
25 files changed
+553 -62

No files matched your search

+80 -2
View File
@@ -35,7 +35,7 @@ async def test_two_tenants_distinct_engines():
assert e1.mapper.get_card_id(0) == "NGC-A001"
assert e2.mapper.get_card_id(0) == "NGC-B001"
# 차원
assert e1.state_space_size == 162 and e1.action_space_size == 9
assert e1.state_space_size == 162 and e1.action_space_size == 11
@pytest.mark.asyncio
@@ -69,7 +69,7 @@ async def test_unregistered_company_id_auto_onboards():
reg = _registry()
# 미등록 company_id(uuid)는 _base 자동 온보딩 → 엔진 생성됨(베이스 9카드, 162 state).
eng = await reg.get_engine("00000000-0000-0000-0000-000000000001")
assert eng.action_space_size == 9 and eng.state_space_size == 162
assert eng.action_space_size == 11 and eng.state_space_size == 162
assert eng.company_id == "00000000-0000-0000-0000-000000000001"
assert reg.is_registered("ktcommerce") is True
# 빈 키만 미등록 → KeyError
@@ -97,6 +97,84 @@ def test_episode_state_is_request_scoped():
assert not hasattr(TenantEngine, "used_action_ids")
@pytest.mark.asyncio
async def test_action_space_from_db_catalog(db_engine):
"""action_mapping.type=db(_base) 면 카드 카탈로그(DB)가 action space 를 정의한다 — config 파일이 아님.
negodata 에서 카드가 추가/삭제되면 config 수정 없이 action space 가 반영됨을 의미."""
from common.enums import ErrorType
from negotiation.cards.ports.card_catalog_port import ICardCatalogRepository
class _FakeCatalog(ICardCatalogRepository):
async def get_nego_catalog(self, cdb):
return ErrorType.SUCCESS, ["NGC-001", "NGC-002", "NGC-003"] # 3장짜리 카탈로그(파일은 11장)
reg = TenantEngineRegistry(
loader=TenantConfigLoader(tenants_dir=_TENANTS_DIR, cache_ttl_seconds=0),
catalog_repo=_FakeCatalog(),
)
eng = await reg.get_engine("_base") # _base = type:db
assert eng.action_space_size == 3 # DB 카탈로그(3)가 정의 — 파일 폴백(11) 아님
assert eng.mapper.get_card_id(0) == "NGC-001"
assert eng.mapper.get_card_id(2) == "NGC-003"
assert eng.mapper.get_action_id("NGC-002") == 1
@pytest.mark.asyncio
async def test_action_space_falls_back_to_file_when_catalog_empty(db_engine):
"""카탈로그가 비면(신규/미시드 DB) 파일 action_to_card 로 폴백한다."""
from common.enums import ErrorType
from negotiation.cards.ports.card_catalog_port import ICardCatalogRepository
class _EmptyCatalog(ICardCatalogRepository):
async def get_nego_catalog(self, cdb):
return ErrorType.SUCCESS, []
reg = TenantEngineRegistry(
loader=TenantConfigLoader(tenants_dir=_TENANTS_DIR, cache_ttl_seconds=0),
catalog_repo=_EmptyCatalog(),
)
eng = await reg.get_engine("_base")
assert eng.action_space_size == 11 # 파일 폴백(11장 스냅샷)
assert eng.mapper.get_card_id(0) == "NGC-001"
@pytest.mark.asyncio
async def test_company_brand_from_db_for_auto_onboard(db_engine):
"""자동 온보딩 고객사(company_id=UUID)는 company.companies.name 으로 {company_name} 을 채운다."""
import uuid as _uuid
from common.enums import ErrorType
from tenancy.company_profile_repo import ICompanyProfileRepository
class _FakeCompany(ICompanyProfileRepository):
async def get_company_name(self, cdb, company_id):
return ErrorType.SUCCESS, "풀무원"
reg = TenantEngineRegistry(
loader=TenantConfigLoader(tenants_dir=_TENANTS_DIR, cache_ttl_seconds=0),
company_repo=_FakeCompany(),
)
eng = await reg.get_engine(str(_uuid.uuid4())) # UUID → 자동 온보딩 + 브랜드 DB
assert eng.config.resources.company_name == "풀무원"
@pytest.mark.asyncio
async def test_demo_tenant_keeps_file_brand(db_engine):
"""데모 테넌트(비-UUID)는 회사명 조회 없이 파일 브랜드 유지."""
from common.enums import ErrorType
from tenancy.company_profile_repo import ICompanyProfileRepository
class _FakeCompany(ICompanyProfileRepository):
async def get_company_name(self, cdb, company_id):
return ErrorType.SUCCESS, "USED-ONLY-IF-QUERIED"
reg = TenantEngineRegistry(
loader=TenantConfigLoader(tenants_dir=_TENANTS_DIR, cache_ttl_seconds=0),
company_repo=_FakeCompany(),
)
eng = await reg.get_engine("ktcommerce") # 비-UUID → 조회 안 함
assert eng.config.resources.company_name == "데모상사 A"
@pytest.mark.asyncio
async def test_middleware_header_missing_unregistered_registered(client):
# 헤더 누락 → 400