Compare commits

...

4 commits

Author SHA1 Message Date
Yun Chan
ed3252ede0 상태판·가이드와 검증 증거를 동기화
Some checks failed
API contract / OpenAPI type drift (push) Failing after 1m17s
2026-09-01 11:45:27 +09:00
Yun Chan
d6d9dc5f61 NAS 정식 스택과 배포 파이프라인 도구를 고정 2026-09-01 11:45:23 +09:00
Yun Chan
f1b80676c1 케이스 이어하기 UI와 공통 탭·이미지 복구를 반영 2026-09-01 11:45:23 +09:00
Yun Chan
72353ecd82 회기 연속성과 멀티 케이스 계약을 영속화 2026-09-01 11:45:16 +09:00
95 changed files with 6760 additions and 612 deletions

View file

@ -119,7 +119,10 @@ class Settings(BaseSettings):
validation_alias="EVALUATOR_SEMANTIC_CACHE_MAX_ENTRIES",
)
session_evaluation_timeout: float = Field(
default=0.0,
# deep-loop은 전체 축어록·구조화 출력을 생성하므로 실시간/일반 HTTP 120초와
# 분리한다. 이 값은 생성 deadline이고, 호출부가 gateway 초기화·응답 수신 여유를
# 별도로 더한다.
default=300.0,
validation_alias="SESSION_EVALUATION_TIMEOUT",
)
session_evaluation_recovery_limit: int = Field(

View file

@ -28,7 +28,15 @@ from ..deps import Principal, Role, require_role
from ..engine_client import EngineError, engine_client
from ..runtime_policy import runtime_fallback_allowed
from ..session_evaluation_input import enriched_masked_turns
from ..session_read_model import StageLabel, stage_label_or_none
from ..session_evaluation_timeout import (
session_evaluation_transport_timeout_seconds,
)
from ..session_read_model import (
ReviewEvaluationFailure,
StageLabel,
stage_label_or_none,
teacher_evaluation_failure,
)
from ..services import evaluator
from ..services.evaluator import SessionEvaluation, TurnEvaluation
from ..store import InProcSession
@ -51,12 +59,13 @@ class TurnReevaluateRequest(BaseModel):
class EvaluationSummary(BaseModel):
"""회기 평가 조회 응답(분포 + deep 결과 합본)."""
"""회기 평가 조회 응답(분포 + deep 결과 합본, provider 오류 원문 제외)."""
session_id: str
stage: StageLabel | None = None
status: str | None = None
error: str | None = None
failure: ReviewEvaluationFailure | None = None
durable: bool = False
deep: Optional[dict[str, Any]] = None
distribution: dict[str, Any] = Field(default_factory=dict)
@ -108,6 +117,15 @@ def _session_evaluation_error_status(error: str) -> int:
return status.HTTP_502_BAD_GATEWAY
def _safe_session_evaluation_retry_detail() -> str:
"""재시도 HTTP 응답에서는 provider 예외 원문을 내보내지 않는다.
원인은 durable evaluation record에 서버 전용으로 보존하고, 교수자 화면은 review의
안전 분류(evaluationFailure)로 다음 행동만 안내한다.
"""
return "AI 평가를 완료하지 못했습니다. 최신 평가 상태를 확인해 주세요."
# ════════════════════════════════════════════════════════════════════════════
# 회기 deep-loop 재평가 트리거 (교수자/관리자)
# ════════════════════════════════════════════════════════════════════════════
@ -120,7 +138,8 @@ async def reevaluate_session(
"""회기 전체 deep-loop 재평가(슈퍼바이저 rationale/critique + 개선점 + 대안발화).
저장된 마스킹 축어록을 evaluator.evaluate_session 으로 평가한다.
엔진 장애는 503 으로 변환(평가는 비치명적이지만 트리거는 사용자 명시 요청이라 에러 노출).
엔진 장애는 503으로 변환한다. provider 예외 원문은 durable 기록에만 남기고 HTTP에는
안전한 안내만 반환한다.
"""
sess = await _load_session_or_404(session_id, principal)
counselor_identity = getattr(sess, "learner_label", None)
@ -144,6 +163,7 @@ async def reevaluate_session(
theory_mode=_theory_mode_of(sess),
scope=body.scope if body.scope in ("session_end", "stage_transition") else "session_end",
audit_hook=session_persistence.record_llm_call_audit,
timeout=session_evaluation_transport_timeout_seconds(),
)
except EngineError as e:
detail = f"engine unavailable: {e}"
@ -163,7 +183,10 @@ async def reevaluate_session(
session_id,
write.error,
)
raise HTTPException(status.HTTP_503_SERVICE_UNAVAILABLE, detail=detail)
raise HTTPException(
status.HTTP_503_SERVICE_UNAVAILABLE,
detail=_safe_session_evaluation_retry_detail(),
)
write = session_persistence.SessionEvaluationWrite.from_result(
session_id=session_id,
@ -178,7 +201,10 @@ async def reevaluate_session(
logger.error("%s: session_id=%s status=%s", detail, session_id, write.status)
raise HTTPException(status.HTTP_503_SERVICE_UNAVAILABLE, detail=detail)
if result.error:
raise HTTPException(_session_evaluation_error_status(result.error), detail=result.error)
raise HTTPException(
_session_evaluation_error_status(result.error),
detail=_safe_session_evaluation_retry_detail(),
)
return result
@ -256,7 +282,10 @@ async def reevaluate_turn(
)
learner.evaluation = result_payload
if result.error:
raise HTTPException(_session_evaluation_error_status(result.error), detail=result.error)
raise HTTPException(
_session_evaluation_error_status(result.error),
detail=_safe_session_evaluation_retry_detail(),
)
return result
@ -285,13 +314,18 @@ async def get_session_evaluation(
distribution={},
)
payload = record.get("payload")
deep = payload if isinstance(payload, dict) else {}
deep = dict(payload) if isinstance(payload, dict) else {}
# SessionEvaluation.to_dict()에는 server-side error가 함께 저장된다. deep 객체도
# 교수자 API 경계에서는 같은 원칙으로 제거한다.
deep.pop("error", None)
distribution = deep.get("distribution")
failure = teacher_evaluation_failure(record)
return EvaluationSummary(
session_id=session_id,
stage=_summary_stage(record.get("stage") or deep.get("stage")),
status=str(record.get("status") or "") or None,
error=str(record.get("error") or "") or None,
error=_safe_session_evaluation_retry_detail() if failure is not None else None,
failure=failure,
durable=durable,
deep=deep,
distribution=distribution if isinstance(distribution, dict) else {},

View file

@ -15,6 +15,7 @@ import secrets
import time
from datetime import datetime
from typing import Literal, Optional
from uuid import UUID
from fastapi import APIRouter, HTTPException, Request, status
from pydantic import BaseModel, Field, field_validator
@ -28,6 +29,12 @@ from ..engine_client import EngineError, engine_client
from ..persona_repository import get_catalog_persona
from ..runtime_policy import require_runtime_fallback_allowed
from ..session_evaluation_input import enriched_masked_turns
from ..session_evaluation_timeout import (
session_evaluation_outer_timeout_seconds,
session_evaluation_timeout_seconds as _session_evaluation_timeout_seconds,
session_evaluation_stale_after_seconds,
session_evaluation_transport_timeout_seconds,
)
from ..services import (
evaluator,
feedback_policy,
@ -44,11 +51,14 @@ from ..services import (
state_machine,
)
from ..session_read_model import (
CaseMemoryPreview,
CaseProgressStats,
LearnerCaseListResponse,
LearnerCaseSummary,
LearnerDashboardResponse,
LearnerSessionsResponse,
LearnerSessionSummary,
LEARNER_VISIBLE_AI_ROLE,
MISSING_SESSION_EVALUATION_GRACE_SECONDS,
ReviewCaseWorksheet,
ReviewCaseWorksheetSaveRequest,
ReviewWorksheetItem as ReviewWorksheetItem,
@ -96,6 +106,10 @@ EndStateValue = str | int | float | bool | None | dict[str, float]
class SessionStartRequest(BaseModel):
persona_code: str = Field(..., examples=["P1"])
theory_mode: TheoryMode = "humanistic"
# continue는 선택한 사례의 압축 기억을 이어 받고, fresh는 새 case_id/S1으로 시작한다.
# 구클라이언트는 기존 동작을 보존하도록 continue가 기본이다.
start_mode: Literal["continue", "fresh"] = "continue"
case_id: UUID | None = None
# 이번 회기 목표 단계(2026-07-13 회의 P1). 회의 권장은 2개 수준이지만
# 소유자 지시(2026-07-15)로 1~4개까지 자유 선택을 허용한다.
# 빈 리스트는 구계약 클라이언트 호환용 — 준비 페이지는 항상 1개 이상을 보낸다.
@ -127,6 +141,7 @@ class SessionStartResponse(BaseModel):
duration_limit_seconds: int = 0
warning_before_end_seconds: int = 0
learner_feedback_enabled: bool = True
start_mode: Literal["continue", "fresh"] = "continue"
class TurnRequest(BaseModel):
@ -916,6 +931,7 @@ async def _generate_and_save_session_evaluation(sess: InProcSession) -> None:
return
timeout_seconds = _session_evaluation_timeout_seconds()
transport_timeout_seconds = session_evaluation_transport_timeout_seconds()
enriched = enriched_masked_turns(
sess.masked_turns(),
counselor_identity=sess.learner_label,
@ -933,8 +949,12 @@ async def _generate_and_save_session_evaluation(sess: InProcSession) -> None:
theory_mode=sess.theory_mode,
scope="session_end",
audit_hook=session_persistence.record_llm_call_audit,
timeout=transport_timeout_seconds,
),
timeout=timeout_seconds,
# gateway의 생성 deadline과 HTTP deadline을 같게 두면 요청 초기화·응답 수신
# 비용만으로 app이 먼저 취소될 수 있다. transport grace와 durable audit 기록
# 예산 뒤에 outer grace를 두어 정상 결과를 timeout error로 바꾸지 않는다.
timeout=session_evaluation_outer_timeout_seconds(),
)
write = session_persistence.SessionEvaluationWrite.from_result(
session_id=sess.session_id,
@ -1050,9 +1070,7 @@ async def recover_missing_session_evaluations(*, limit: int | None = None) -> in
)
if recovery_limit <= 0:
return 0
stale_after_seconds = (
_session_evaluation_timeout_seconds() + MISSING_SESSION_EVALUATION_GRACE_SECONDS
)
stale_after_seconds = session_evaluation_stale_after_seconds()
(
candidates,
durable,
@ -1108,11 +1126,6 @@ def cancel_missing_session_evaluation_recovery() -> None:
task.cancel()
def _session_evaluation_timeout_seconds() -> float:
configured = float(settings.session_evaluation_timeout or settings.engine_timeout)
return max(configured, 1.0)
async def _enqueue_session_review_ready_notification(session_id: str) -> None:
try:
await notifications.enqueue_session_review_ready(session_id=session_id)
@ -1236,6 +1249,180 @@ async def list_learner_sessions(principal: CurrentPrincipal) -> LearnerSessionsR
)
def _preview_text(value: object, *, limit: int) -> str | None:
"""Keep the learner foldout bounded even when a legacy digest is verbose."""
text = str(value or "").strip()
if not text:
return None
if len(text) <= limit:
return text
return f"{text[: max(1, limit - 1)].rstrip()}…"
def _preview_items(value: object, *, limit: int, item_limit: int) -> list[str]:
if not isinstance(value, (list, tuple)):
return []
items: list[str] = []
for raw in value:
clipped = _preview_text(raw, limit=item_limit)
if clipped:
items.append(clipped)
if len(items) >= limit:
break
return items
def _db_datetime_iso(value: object) -> str | None:
return value.isoformat() if isinstance(value, datetime) else None
@router.get("/cases", response_model=LearnerCaseListResponse)
async def list_learner_cases(
persona_code: str,
principal: CurrentPrincipal,
) -> LearnerCaseListResponse:
"""Return complete case-local progress for one NPC, not a capped history slice."""
principal = _ensure_learner(principal)
try:
catalog_persona = await get_catalog_persona(persona_code)
except Exception as exc:
raise HTTPException(
status.HTTP_503_SERVICE_UNAVAILABLE,
detail="persona catalog database unavailable",
) from exc
if catalog_persona is None:
raise HTTPException(
status.HTTP_404_NOT_FOUND, detail=f"unknown persona {persona_code}"
)
try:
rows = await session_persistence.list_case_summaries(
learner_id=principal.user_id,
persona_id=catalog_persona.persona_id,
)
except session_persistence.CaseProgressUnavailableError as exc:
raise HTTPException(
status.HTTP_503_SERVICE_UNAVAILABLE,
detail="case_progress_unavailable",
) from exc
card = catalog_persona.card
return LearnerCaseListResponse(
cases=[
LearnerCaseSummary(
case_id=str(row["case_id"]),
persona_code=card.code,
persona_name=card.display_name,
last_session_no=int(row["last_session_no"] or 0),
progress=CaseProgressStats(
total_sessions=int(row["total_sessions"] or 0),
completed_sessions=int(row["completed_sessions"] or 0),
total_turns=int(row["total_turns"] or 0),
total_duration_seconds=int(row["total_duration_seconds"] or 0),
active_session_id=(
str(row["active_session_id"])
if row.get("active_session_id") is not None
else None
),
active_session_no=(
int(row["active_session_no"])
if row.get("active_session_no") is not None
else None
),
active_started_at=_db_datetime_iso(row.get("active_started_at")),
last_activity_at=_db_datetime_iso(row.get("last_activity_at")),
),
)
for row in rows
]
)
@router.get("/cases/{case_id}/memory", response_model=CaseMemoryPreview)
async def get_learner_case_memory_preview(
case_id: UUID,
principal: CurrentPrincipal,
) -> CaseMemoryPreview:
"""Load only the learner-safe compact memory when its foldout is opened."""
principal = _ensure_learner(principal)
case_key = str(case_id)
try:
async with db.acquire(role="learner", user_id=principal.user_id) as conn:
case_row = await conn.fetchrow(
"""
SELECT case_digest
FROM app.case_profile
WHERE case_id = $1::uuid
AND learner_id = $2::uuid
""",
case_key,
principal.user_id,
)
if case_row is None:
raise HTTPException(status.HTTP_404_NOT_FOUND, detail="case_not_found")
summary_row = await conn.fetchrow(
"""
SELECT ss.digest, ss.open_threads
FROM app.session_summary AS ss
JOIN app.sessions AS s ON s.id = ss.session_id
WHERE ss.case_id = $1::uuid
AND s.learner_id = $2::uuid
ORDER BY ss.session_no DESC, ss.created_at DESC
LIMIT 1
""",
case_key,
principal.user_id,
)
fact_rows = await conn.fetch(
"""
SELECT LEFT(pf.value, 160) AS value
FROM app.pinned_fact AS pf
JOIN app.case_profile AS cp ON cp.case_id = pf.case_id
WHERE pf.case_id = $1::uuid
AND cp.learner_id = $2::uuid
AND pf.status IN ('stable', 'evolving', 'locked')
AND 'client' = ANY(pf.visible_to)
ORDER BY pf.updated_at DESC
LIMIT 8
""",
case_key,
principal.user_id,
)
except HTTPException:
raise
except Exception as exc:
logger.exception("case memory preview read failed", extra={"case_id": case_key})
raise HTTPException(
status.HTTP_503_SERVICE_UNAVAILABLE,
detail="case_memory_unavailable",
) from exc
case_digest = _preview_text(case_row["case_digest"], limit=600)
latest_session_digest = _preview_text(
summary_row["digest"] if summary_row is not None else None,
limit=600,
)
open_threads = _preview_items(
summary_row["open_threads"] if summary_row is not None else [],
limit=6,
item_limit=160,
)
pinned_facts = _preview_items(
[row["value"] for row in fact_rows],
limit=8,
item_limit=160,
)
return CaseMemoryPreview(
case_id=case_key,
memory_available=bool(
case_digest or latest_session_digest or open_threads or pinned_facts
),
case_digest=case_digest,
latest_session_digest=latest_session_digest,
open_threads=open_threads,
pinned_facts=pinned_facts,
)
@router.get("/dashboard", response_model=LearnerDashboardResponse)
async def learner_dashboard(principal: CurrentPrincipal) -> LearnerDashboardResponse:
"""Return the current learner's real practice dashboard aggregates."""
@ -1391,15 +1578,16 @@ async def start_session(
status.HTTP_404_NOT_FOUND, detail=f"unknown persona {body.persona_code}"
)
card = catalog_persona.card
if body.start_mode == "fresh" and body.case_id is not None:
raise HTTPException(
status.HTTP_422_UNPROCESSABLE_ENTITY,
detail="fresh_start_must_not_select_case",
)
case_context = await session_persistence.get_case_context(
learner_id=principal.user_id,
persona_id=catalog_persona.persona_id,
)
recall = await _build_seed_recall(
case_id=case_context.case_id if case_context else None
)
session_no = (case_context.last_session_no + 1) if case_context else 1
# The durable transaction chooses or creates the case only after active-case
# validation. Start with an empty recall here so a fresh request cannot see
# any legacy case before its own empty case exists.
recall = memory.build_recall_context()
st = state_machine.init_state(
params=card.openness_params(),
carry=recall.carry,
@ -1408,20 +1596,51 @@ async def start_session(
carry_rapport = st.rapport_credit
goal_stages = [str(stage) for stage in body.goal_stages]
learner_feedback_enabled = principal.learner_feedback_enabled
async def build_locked_start_state(
stable_case_id: str,
_session_no: int,
) -> state_machine.SessionState:
nonlocal recall
recall = (
memory.build_recall_context()
if body.start_mode == "fresh"
else await _build_seed_recall(case_id=stable_case_id)
)
return state_machine.init_state(
params=card.openness_params(),
carry=recall.carry,
)
try:
sess = await session_persistence.create_session(
learner_id=principal.user_id,
card=card,
theory_mode=body.theory_mode,
state=st,
session_no=session_no,
session_no=1,
carry_rapport=carry_rapport,
persona_id=catalog_persona.persona_id,
persona_version=catalog_persona.version,
case_id=case_context.case_id if case_context else None,
case_id=str(body.case_id) if body.case_id is not None else None,
start_mode=body.start_mode,
goal_stages=goal_stages,
learner_feedback_enabled=learner_feedback_enabled,
locked_state_factory=build_locked_start_state,
)
except session_persistence.ActiveSessionExistsError as exc:
raise HTTPException(
status.HTTP_409_CONFLICT,
detail={
"code": "active_session_exists",
"session_id": exc.session_id,
},
) from exc
except session_persistence.CaseNotFoundError as exc:
raise HTTPException(
status.HTTP_404_NOT_FOUND,
detail="case_not_found",
) from exc
except session_persistence.SessionCreationPersistenceError as exc:
raise HTTPException(
status.HTTP_503_SERVICE_UNAVAILABLE,
@ -1430,6 +1649,64 @@ async def start_session(
degraded = catalog_persona.degraded or sess is None
if sess is None:
require_runtime_fallback_allowed("session creation")
# Runtime fallback cannot prove durable case memory. Keep it empty rather
# than leaking a guessed legacy recall, while preserving a selected
# in-process case ID when one is available.
recall = memory.build_recall_context()
st = state_machine.init_state(
params=card.openness_params(),
carry=recall.carry,
)
carry_rapport = st.rapport_credit
active_session = store.find_active(
learner_id=principal.user_id,
persona_id=catalog_persona.persona_id,
persona_code=card.code,
)
if active_session is not None:
raise HTTPException(
status.HTTP_409_CONFLICT,
detail={
"code": "active_session_exists",
"session_id": active_session.session_id,
},
)
runtime_case_id: str | None = None
runtime_session_no = 1
if body.start_mode == "continue":
related = [
candidate
for candidate in store.list()
if candidate.learner_id == principal.user_id
and (
candidate.persona_id == catalog_persona.persona_id
or candidate.persona_code == card.code
)
]
if body.case_id is not None:
runtime_case_id = str(body.case_id)
related = [
candidate
for candidate in related
if candidate.case_id == runtime_case_id
]
if not related:
raise HTTPException(
status.HTTP_404_NOT_FOUND,
detail="case_not_found",
)
elif related:
newest = max(related, key=lambda candidate: candidate.created_at)
runtime_case_id = newest.case_id
related = [
candidate
for candidate in related
if candidate.case_id == runtime_case_id
]
if related:
runtime_session_no = max(
candidate.session_no for candidate in related
) + 1
sess = store.create(
learner_id=principal.user_id,
persona=card,
@ -1437,12 +1714,14 @@ async def start_session(
state=st,
persona_id=catalog_persona.persona_id,
persona_version=catalog_persona.version,
session_no=session_no,
case_id=runtime_case_id,
session_no=runtime_session_no,
carry_rapport=carry_rapport,
goal_stages=goal_stages,
learner_feedback_enabled=learner_feedback_enabled,
)
else:
st = sess.state
store.put(sess)
# DB 재조회 전의 첫 턴과 runtime fallback에서도 인증된 학습자 표시명을
@ -1470,6 +1749,7 @@ async def start_session(
duration_limit_seconds=settings.session_duration_minutes * 60,
warning_before_end_seconds=settings.session_warning_minutes * 60,
learner_feedback_enabled=sess.learner_feedback_enabled,
start_mode=body.start_mode,
)

View file

@ -16,6 +16,8 @@ from ..session_read_model import (
learner_visible_turns,
missing_session_evaluation_record,
stage_label,
teacher_evaluation_failure,
teacher_evaluation_failure_message,
)
from ..services import session_metrics
from ..stage_contract import STAGE_LABEL_VALUES
@ -298,6 +300,7 @@ def _summary(
learner_turns = sum(1 for turn in visible_turns if turn.speaker == "counselor")
client_turns = sum(1 for turn in visible_turns if turn.speaker == "client")
evaluation_status = _evaluation_status_value(summary_evaluation_record)
evaluation_failure = teacher_evaluation_failure(summary_evaluation_record)
return TeacherSessionSummary(
session_id=sess.session_id,
learner_id=sess.learner_id,
@ -322,9 +325,7 @@ def _summary(
summary_evaluation_record,
has_visible_turns=bool(visible_turns),
),
evaluation_error=(
str(summary_evaluation_record.get("error") or "") if summary_evaluation_record else None
),
evaluation_error=teacher_evaluation_failure_message(evaluation_failure),
)

View file

@ -820,6 +820,7 @@ async def evaluate_session(
theory_mode: Optional[str] = None,
scope: str = "session_end",
audit_hook: Optional["LlmAuditHook"] = None,
timeout: float | None = None,
) -> SessionEvaluation:
"""deep-loop 정밀 평가 — 단계전환/회기말. 전체 축어록 + 코드 집계 분포 + LLM 정성 평가.
@ -859,7 +860,7 @@ async def evaluate_session(
cached = _evaluator_cache_get(cache_key)
if cached is not None:
return SessionEvaluation.model_validate(cached)
resp = await generate_with_audit(engine, req, audit_hook)
resp = await generate_with_audit(engine, req, audit_hook, timeout=timeout)
except EngineError as e:
base.error = f"engine_error: {e}"
return base

View file

@ -28,10 +28,18 @@ async def generate_with_audit(
engine: EngineClient,
request: GenerateRequest,
audit_hook: LlmAuditHook | None,
*,
timeout: float | None = None,
) -> GenerateResponse:
"""비스트리밍 LLM 호출의 지연·토큰·비용 기록을 한 계약으로 고정한다."""
started = time.perf_counter()
response = await engine.generate(request)
# deep-loop처럼 호출별 deadline이 필요한 경로가 audit 경계를 지나도 사라지지
# 않게 한다. 기본(None)은 기존 엔진 client deadline을 그대로 쓴다.
response = (
await engine.generate(request, timeout=timeout)
if timeout is not None
else await engine.generate(request)
)
latency_ms = int((time.perf_counter() - started) * 1000)
await record_llm_audit(
audit_hook,

View file

@ -0,0 +1,58 @@
"""deep-loop 평가의 실행 deadline과 HTTP transport deadline 계약."""
from __future__ import annotations
from .config import settings
# 게이트웨이의 모델 생성 deadline 뒤에도 세션 초기화·요청 직렬화·응답 수신이 남는다.
# 짧은 운영자 override는 빠르게 취소할 수 있도록 5초부터, 기본 300초에서는 30초까지만 준다.
SESSION_EVALUATION_TRANSPORT_GRACE_MIN_SECONDS = 5.0
SESSION_EVALUATION_TRANSPORT_GRACE_MAX_SECONDS = 30.0
SESSION_EVALUATION_TRANSPORT_GRACE_RATIO = 0.10
SESSION_EVALUATION_OUTER_GRACE_SECONDS = 5.0
SESSION_EVALUATION_STALE_STABILITY_SECONDS = 5.0
def session_evaluation_timeout_seconds() -> float:
"""평가 엔진이 생성에 쓸 수 있는 의미상 deadline."""
configured = float(settings.session_evaluation_timeout or settings.engine_timeout)
return max(configured, 1.0)
def session_evaluation_transport_timeout_seconds() -> float:
"""HTTP 호출이 gateway의 생성 deadline보다 먼저 취소되지 않는 경계."""
generation_timeout = session_evaluation_timeout_seconds()
grace = min(
SESSION_EVALUATION_TRANSPORT_GRACE_MAX_SECONDS,
max(
SESSION_EVALUATION_TRANSPORT_GRACE_MIN_SECONDS,
generation_timeout * SESSION_EVALUATION_TRANSPORT_GRACE_RATIO,
),
)
return generation_timeout + grace
def session_evaluation_outer_timeout_seconds() -> float:
"""background task가 생성 뒤 감사 원장 기록까지 기다리는 최종 deadline.
``evaluate_session()``은 engine transport가 끝난 뒤에도 audit hook을 await한다.
그 hook은 durable DB에서는 ``db_command_timeout``까지 걸릴 수 있으므로,
transport grace만 더한 outer deadline으로 감싸면 정상 모델 결과를 timeout error로
잘못 저장할 수 있다. 결과 평가 원장 저장은 이 await 바깥에서 한 번 더 일어나며,
stale deadline이 그 별도 예산을 보유한다.
"""
audit_persistence_timeout = max(float(settings.db_command_timeout), 1.0)
return (
session_evaluation_transport_timeout_seconds()
+ audit_persistence_timeout
+ SESSION_EVALUATION_OUTER_GRACE_SECONDS
)
def session_evaluation_stale_after_seconds() -> float:
"""실제 평가 task와 DB 저장이 모두 끝난 뒤에만 누락으로 판정하는 시점."""
return (
session_evaluation_outer_timeout_seconds()
+ max(float(settings.db_command_timeout), 1.0)
+ SESSION_EVALUATION_STALE_STABILITY_SECONDS
)

View file

@ -9,7 +9,7 @@ import time
import uuid
from dataclasses import dataclass
from datetime import datetime, timezone
from typing import Any, Iterable, Protocol
from typing import Any, Awaitable, Callable, Iterable, Literal, Protocol
from .db import acquire, get_pool
from .deps import Principal
@ -38,6 +38,22 @@ class SessionCreationPersistenceError(RuntimeError):
"""fail-closed 환경에서 영속 세션 생성이 실패했다."""
class ActiveSessionExistsError(RuntimeError):
"""같은 learner-persona 전체에 미종료 회기가 이미 존재한다."""
def __init__(self, session_id: str) -> None:
self.session_id = session_id
super().__init__("active_session_exists")
class CaseNotFoundError(RuntimeError):
"""선택한 연속 사례가 이 learner-persona에 존재하지 않는다."""
class CaseProgressUnavailableError(RuntimeError):
"""DB 전체 집계가 필요한 사례 진행 수치를 안전하게 읽지 못했다."""
_EVALUATION_CACHE: dict[str, dict[str, Any]] = {}
_CASE_WORKSHEET_CACHE: dict[str, dict[str, Any]] = {}
_SESSION_REVIEW_STATUS_CACHE: dict[str, dict[str, Any]] = {}
@ -1768,7 +1784,9 @@ async def save_session_evaluation(write: SessionEvaluationWrite) -> bool:
)
record = write.cache_record()
if runtime_fallback_allowed():
_EVALUATION_CACHE[write.session_id] = record
existing = _EVALUATION_CACHE.get(write.session_id)
if _should_replace_evaluation_record(existing, record):
_EVALUATION_CACHE[write.session_id] = record
try:
get_pool()
async with acquire(role="learner", user_id=write.learner_id) as conn:
@ -1787,6 +1805,8 @@ async def save_session_evaluation(write: SessionEvaluationWrite) -> bool:
payload = EXCLUDED.payload,
error = EXCLUDED.error,
updated_at = now()
WHERE app.session_evaluation.status <> 'ready'
OR EXCLUDED.status = 'ready'
""",
write.session_id,
write.status,
@ -2731,22 +2751,45 @@ async def get_case_context(
*,
learner_id: str,
persona_id: str,
case_id: str | None = None,
) -> CaseContext | None:
"""Return the stable learner-persona case row, creating it when possible."""
"""Return one owned continuation case without creating or mutating a row.
Legacy callers without ``case_id`` receive the most recently active case.
Fresh starts must never call this helper: their case row is created only after
the global active-session check inside ``create_session`` succeeds.
"""
try:
get_pool()
async with acquire(role="learner", user_id=learner_id) as conn:
row = await conn.fetchrow(
"""
INSERT INTO app.case_profile (persona_id, learner_id)
VALUES ($1::uuid, $2::uuid)
ON CONFLICT (persona_id, learner_id) DO UPDATE SET
updated_at = app.case_profile.updated_at
RETURNING case_id, last_session_no
""",
persona_id,
learner_id,
)
if case_id:
row = await conn.fetchrow(
"""
SELECT case_id, last_session_no
FROM app.case_profile
WHERE case_id = $1::uuid
AND persona_id = $2::uuid
AND learner_id = $3::uuid
""",
case_id,
persona_id,
learner_id,
)
else:
row = await conn.fetchrow(
"""
SELECT case_id, last_session_no
FROM app.case_profile
WHERE persona_id = $1::uuid
AND learner_id = $2::uuid
ORDER BY updated_at DESC, case_id DESC
LIMIT 1
""",
persona_id,
learner_id,
)
if row is None:
return None
return CaseContext(
case_id=str(row["case_id"]),
last_session_no=int(row["last_session_no"] or 0),
@ -2755,6 +2798,97 @@ async def get_case_context(
return None
async def list_case_summaries(
*,
learner_id: str,
persona_id: str,
) -> list[dict[str, Any]]:
"""Read complete case-scoped progress without the recent-session list cap.
Duration and turn counts deliberately use different CTEs so joining turns
cannot multiply the duration of a session. This is DB-only: returning a
runtime approximation would make the learner choose a continuation on false
progress data.
"""
try:
get_pool()
async with acquire(role="learner", user_id=learner_id) as conn:
rows = await conn.fetch(
"""
WITH scoped_cases AS (
SELECT cp.case_id, cp.last_session_no, cp.updated_at
FROM app.case_profile AS cp
WHERE cp.learner_id = $1::uuid
AND cp.persona_id = $2::uuid
),
session_stats AS (
SELECT
s.case_id,
count(*)::int AS total_sessions,
count(*) FILTER (WHERE s.ended_at IS NOT NULL)::int AS completed_sessions,
COALESCE(
sum(
GREATEST(
0,
EXTRACT(EPOCH FROM (COALESCE(s.ended_at, now()) - s.started_at))
)
),
0
)::bigint AS total_duration_seconds,
max(COALESCE(s.ended_at, s.started_at)) AS last_activity_at
FROM app.sessions AS s
JOIN scoped_cases AS c ON c.case_id = s.case_id
GROUP BY s.case_id
),
turn_stats AS (
SELECT s.case_id, count(t.id)::int AS total_turns
FROM app.sessions AS s
JOIN scoped_cases AS c ON c.case_id = s.case_id
LEFT JOIN app.turns AS t
ON t.session_id = s.id
AND 'counselor' = ANY(t.visible_to)
GROUP BY s.case_id
),
active_session AS (
SELECT DISTINCT ON (s.case_id)
s.case_id,
s.id AS active_session_id,
s.session_no AS active_session_no,
s.started_at AS active_started_at
FROM app.sessions AS s
JOIN scoped_cases AS c ON c.case_id = s.case_id
WHERE s.ended_at IS NULL
ORDER BY s.case_id, s.started_at DESC, s.id DESC
)
SELECT
c.case_id,
c.last_session_no,
COALESCE(ss.total_sessions, 0)::int AS total_sessions,
COALESCE(ss.completed_sessions, 0)::int AS completed_sessions,
COALESCE(ts.total_turns, 0)::int AS total_turns,
COALESCE(ss.total_duration_seconds, 0)::bigint AS total_duration_seconds,
active.active_session_id,
active.active_session_no,
active.active_started_at,
ss.last_activity_at
FROM scoped_cases AS c
LEFT JOIN session_stats AS ss USING (case_id)
LEFT JOIN turn_stats AS ts USING (case_id)
LEFT JOIN active_session AS active USING (case_id)
ORDER BY COALESCE(ss.last_activity_at, c.updated_at) DESC, c.case_id DESC
""",
learner_id,
persona_id,
)
return [dict(row) for row in rows]
except Exception as exc:
logger.exception(
"case progress read failed",
extra={"learner_id": learner_id, "persona_id": persona_id},
)
raise CaseProgressUnavailableError("case_progress_unavailable") from exc
async def create_session(
*,
learner_id: str,
@ -2766,10 +2900,25 @@ async def create_session(
persona_id: str | None = None,
persona_version: int | None = None,
case_id: str | None = None,
start_mode: Literal["continue", "fresh"] = "continue",
goal_stages: list[str] | None = None,
learner_feedback_enabled: bool = True,
locked_state_factory: (
Callable[[str, int], Awaitable[state_machine.SessionState]] | None
) = None,
) -> InProcSession | None:
"""Create a DB-backed session, returning None when DB persistence is unavailable."""
"""Create a DB-backed session, returning None when DB persistence is unavailable.
A fresh start creates a new case only after the global learner-persona active
session guard passes. A continuation selects the requested owned case (or the
most recent legacy case) in the same transaction. ``locked_state_factory``
therefore sees either the committed selected case or the empty new case, never
a cross-case or in-between memory state.
"""
if start_mode not in ("continue", "fresh"):
raise ValueError(f"unsupported session start mode: {start_mode}")
if start_mode == "fresh" and case_id is not None:
raise ValueError("fresh start must not select an existing case")
try:
get_pool()
runtime_case_id = str(uuid.uuid4())
@ -2777,21 +2926,86 @@ async def create_session(
pinned_persona_version = persona_version or SEED_VERSION
async with acquire(role="learner", user_id=learner_id) as conn:
async with conn.transaction():
stable_case_id = case_id
if stable_case_id is None:
# A case row cannot serialize two simultaneous first/fresh starts,
# so lock the learner-persona scope before inspecting active rows.
await conn.execute(
"SELECT pg_advisory_xact_lock(hashtextextended($1, 0))",
f"{learner_id}:{pinned_persona_id}",
)
active_row = await conn.fetchrow(
"""
SELECT id
FROM app.sessions
WHERE learner_id = $1::uuid
AND persona_id = $2::uuid
AND ended_at IS NULL
LIMIT 1
FOR UPDATE
""",
learner_id,
pinned_persona_id,
)
if active_row is not None:
raise ActiveSessionExistsError(str(active_row["id"]))
stable_case_id: str
if start_mode == "fresh":
case_row = await conn.fetchrow(
"""
INSERT INTO app.case_profile (persona_id, learner_id)
VALUES ($1::uuid, $2::uuid)
ON CONFLICT (persona_id, learner_id) DO UPDATE SET
updated_at = app.case_profile.updated_at
RETURNING case_id, last_session_no
""",
pinned_persona_id,
learner_id,
)
stable_case_id = str(case_row["case_id"])
session_no = 1
elif case_id is not None:
case_row = await conn.fetchrow(
"""
SELECT case_id, last_session_no
FROM app.case_profile
WHERE case_id = $1::uuid
AND learner_id = $2::uuid
AND persona_id = $3::uuid
FOR UPDATE
""",
case_id,
learner_id,
pinned_persona_id,
)
if case_row is None:
raise CaseNotFoundError("case_not_found")
stable_case_id = str(case_row["case_id"])
session_no = int(case_row["last_session_no"] or 0) + 1
else:
case_row = await conn.fetchrow(
"""
SELECT case_id, last_session_no
FROM app.case_profile
WHERE persona_id = $1::uuid
AND learner_id = $2::uuid
ORDER BY updated_at DESC, case_id DESC
LIMIT 1
FOR UPDATE
""",
pinned_persona_id,
learner_id,
)
if case_row is None:
case_row = await conn.fetchrow(
"""
INSERT INTO app.case_profile (persona_id, learner_id)
VALUES ($1::uuid, $2::uuid)
RETURNING case_id, last_session_no
""",
pinned_persona_id,
learner_id,
)
stable_case_id = str(case_row["case_id"])
session_no = int(case_row["last_session_no"] or 0) + 1
counter_row = await conn.fetchrow(
"""
UPDATE app.case_profile
@ -2805,8 +3019,16 @@ async def create_session(
session_no,
learner_id,
)
if counter_row is not None:
session_no = int(counter_row["last_session_no"] or session_no)
if counter_row is None:
raise CaseNotFoundError("case_not_found")
session_no = int(counter_row["last_session_no"] or session_no)
persisted_state = state
if locked_state_factory is not None:
persisted_state = await locked_state_factory(
stable_case_id,
session_no,
)
carry_rapport = persisted_state.rapport_credit
row = await conn.fetchrow(
"""
INSERT INTO app.sessions (
@ -2837,7 +3059,7 @@ async def create_session(
list(goal_stages or []),
learner_feedback_enabled,
)
await _upsert_state(conn, str(row["id"]), state)
await _upsert_state(conn, str(row["id"]), persisted_state)
return InProcSession(
session_id=str(row["id"]),
case_id=str(row["case_id"] or row["runtime_case_id"] or row["id"]),
@ -2845,7 +3067,7 @@ async def create_session(
persona_code=card.code,
theory_mode=theory_mode,
persona=card,
state=state,
state=persisted_state,
persona_id=pinned_persona_id,
persona_version=pinned_persona_version,
session_no=int(row["session_no"] or session_no),
@ -2857,6 +3079,8 @@ async def create_session(
goal_stages=list(goal_stages or []),
learner_feedback_enabled=learner_feedback_enabled,
)
except (ActiveSessionExistsError, CaseNotFoundError):
raise
except Exception as exc:
logger.exception(
"durable session creation failed",
@ -3218,6 +3442,21 @@ async def end_session(sess: InProcSession, carry: memory.CarryOver) -> bool:
get_pool()
summary_write = _build_session_summary_write(sess, carry)
async with acquire(role="learner", user_id=sess.learner_id) as conn:
# start_session/create_session also locks this stable case before it
# inspects active rows. Taking the case lock first gives end/start a
# single lock order: the next session either sees S1 still active or
# sees its committed summary and carry-over, never an in-between row.
await conn.fetchval(
"""
SELECT case_id
FROM app.case_profile
WHERE case_id = $1::uuid
AND learner_id = $2::uuid
FOR NO KEY UPDATE
""",
sess.case_id,
sess.learner_id,
)
await conn.execute(
"""
UPDATE app.sessions
@ -3463,3 +3702,12 @@ def _iso_dt(value: datetime | None) -> str:
if value is None:
return ""
return value.astimezone(timezone.utc).isoformat()
def _should_replace_evaluation_record(
existing: dict[str, Any] | None,
replacement: dict[str, Any],
) -> bool:
"""늦게 도착한 실패가 이미 확정된 ready 평가를 덮지 못하게 한다."""
return not (
str((existing or {}).get("status") or "") == "ready"
and str(replacement.get("status") or "") != "ready"
)

View file

@ -25,6 +25,7 @@ from .stage_contract import (
stage_label_or_none as stage_label_or_none,
)
from .store import InProcSession, TurnRecord
from .session_evaluation_timeout import session_evaluation_stale_after_seconds
WorksheetSpeaker = Literal["learner", "client"]
WorksheetItemSpec = tuple[str, str, list[str], WorksheetSpeaker | None]
@ -32,7 +33,6 @@ WorksheetSectionSpec = tuple[str, str, list[WorksheetItemSpec]]
LEARNER_VISIBLE_AI_ROLE = "counselor"
KOREA_STANDARD_TIME = timezone(timedelta(hours=9), name="KST")
MISSING_SESSION_EVALUATION_GRACE_SECONDS = 30.0
MISSING_SESSION_EVALUATION_ERROR = (
"회기말 평가가 제한 시간 이후에도 저장되지 않았습니다. AI 평가 재시도가 필요합니다."
)
@ -44,6 +44,8 @@ FIRST_SESSION_CHECKLIST_VERSION = "first-session-rapport-open-question.v1"
class LearnerSessionSummary(BaseModel):
session_id: str
# 같은 내담자도 새 사례에서 다시 S1이 될 수 있으므로, 이력 행의 연속체 경계를 함께 준다.
case_id: str = ""
persona_code: str
persona_name: str
session_no: int
@ -65,6 +67,44 @@ class LearnerSessionsResponse(BaseModel):
sessions: list[LearnerSessionSummary] = Field(default_factory=list)
class CaseProgressStats(BaseModel):
"""한 사례 안에서만 누적한 learner-visible 진행 수치."""
total_sessions: int = 0
completed_sessions: int = 0
total_turns: int = 0
total_duration_seconds: int = 0
active_session_id: str | None = None
active_session_no: int | None = None
active_started_at: str | None = None
last_activity_at: str | None = None
class LearnerCaseSummary(BaseModel):
case_id: str
persona_code: str
persona_name: str
last_session_no: int = 0
progress: CaseProgressStats = Field(default_factory=CaseProgressStats)
class LearnerCaseListResponse(BaseModel):
# case별 누적 수치는 DB 전체 집계여야 한다. runtime cache 추정값은 반환하지 않는다.
source: Literal["database"] = "database"
cases: list[LearnerCaseSummary] = Field(default_factory=list)
class CaseMemoryPreview(BaseModel):
"""접힌 learner UI에만 쓰는 최소·마스킹된 사례 기억 투영."""
case_id: str
memory_available: bool = False
case_digest: str | None = None
latest_session_digest: str | None = None
open_threads: list[str] = Field(default_factory=list)
pinned_facts: list[str] = Field(default_factory=list)
class LearnerDashboardOverview(BaseModel):
total_sessions: int = 0
completed_sessions: int = 0
@ -472,6 +512,21 @@ class SessionTeacherReviewStatus(BaseModel):
worksheetReviewedAt: str | None = None
class ReviewEvaluationFailure(BaseModel):
"""교수자용 deep-loop 실패 분류. 원문 예외·축어록은 절대 응답에 넣지 않는다."""
code: Literal[
"timeout",
"engine_unavailable",
"legacy_argv_limit",
"prompt_too_large",
"invalid_structured_output",
"missing_evaluation",
"unknown",
]
retryable: bool
class SessionReviewResponse(BaseModel):
session_id: str
sessionNo: int = Field(ge=1)
@ -501,6 +556,7 @@ class SessionReviewResponse(BaseModel):
pdfExportUrl: Optional[str] = None
degraded: bool = True
reviewReady: bool = False
evaluationFailure: ReviewEvaluationFailure | None = None
learnerFeedbackEnabled: bool = True
teacherReview: SessionTeacherReviewStatus | None = None
@ -561,6 +617,7 @@ def learner_summary(
client_turns = sum(1 for turn in turns if turn.speaker == "client")
return LearnerSessionSummary(
session_id=sess.session_id,
case_id=sess.case_id,
persona_code=sess.persona_code,
persona_name=sess.persona.display_name,
session_no=sess.session_no,
@ -1121,6 +1178,12 @@ def _review_summary_from_evaluation(
return fallback
status = str(evaluation_record.get("status") or "")
if status != "ready":
failure = teacher_evaluation_failure(evaluation_record)
if failure is not None and not failure.retryable:
return (
"저장된 축어록은 확인했지만 deep-loop 평가 AI 산출물을 표시하지 못했습니다. "
"평가 입력 경로를 조정한 뒤 다시 생성해야 합니다."
)
return (
"저장된 축어록은 확인했지만 deep-loop 평가 AI 산출물을 표시하지 못했습니다. "
"AI 평가 재시도가 필요합니다."
@ -1133,9 +1196,56 @@ def _review_summary_from_evaluation(
return prefix + (details if details else "아래 코칭 항목은 저장된 축어록과 평가 AI 결과를 기준으로 합니다.")
def _session_evaluation_timeout_seconds() -> float:
configured = float(settings.session_evaluation_timeout or settings.engine_timeout)
return max(1.0, configured)
def teacher_evaluation_failure(
evaluation_record: dict[str, object] | None,
) -> ReviewEvaluationFailure | None:
"""오류 원문을 노출하지 않고 교수자가 취할 다음 행동만 분류한다."""
if not evaluation_record or str(evaluation_record.get("status") or "") != "error":
return None
raw_error = str(evaluation_record.get("error") or "").strip().lower()
if raw_error == MISSING_SESSION_EVALUATION_ERROR.lower() or "저장되지 않았습니다" in raw_error:
return ReviewEvaluationFailure(code="missing_evaluation", retryable=True)
if (
("24,000" in raw_error or "명령줄 안전 한도" in raw_error)
and "agy" in raw_error
):
# 2026-08 이전 Windows Agy argv 경로의 durable 오류다. 현재 stdin 경로로는
# 재평가할 수 있으므로, 같은 오류처럼 보이더라도 복구 재시도를 열어 둔다.
return ReviewEvaluationFailure(code="legacy_argv_limit", retryable=True)
if "argv" in raw_error or "24000" in raw_error or "prompt too large" in raw_error:
return ReviewEvaluationFailure(code="prompt_too_large", retryable=False)
if "timeout" in raw_error or "timed out" in raw_error:
return ReviewEvaluationFailure(code="timeout", retryable=True)
if "no_structured_output" in raw_error or "parse_error" in raw_error:
return ReviewEvaluationFailure(code="invalid_structured_output", retryable=True)
if (
"engine_error" in raw_error
or "engine unavailable" in raw_error
or "transport error" in raw_error
):
return ReviewEvaluationFailure(code="engine_unavailable", retryable=True)
return ReviewEvaluationFailure(code="unknown", retryable=True)
def teacher_evaluation_failure_message(
failure: ReviewEvaluationFailure | None,
) -> str | None:
"""교수자 목록 API에서 provider 원문 대신 사용할 최소 행동 안내."""
if failure is None:
return None
if failure.code == "timeout":
return "AI 평가가 제한 시간 안에 끝나지 않았습니다. 다시 시도할 수 있습니다."
if failure.code == "engine_unavailable":
return "평가 엔진에 일시적으로 연결하지 못했습니다. 다시 시도할 수 있습니다."
if failure.code == "legacy_argv_limit":
return "이전 Windows 입력 한도에 걸린 평가입니다. 현재 입력 경로로 다시 시도할 수 있습니다."
if failure.code == "prompt_too_large":
return "평가 입력이 허용 크기를 넘어섰습니다. 입력 경로 조정이 필요합니다."
if failure.code == "invalid_structured_output":
return "평가 결과 형식이 검증되지 않았습니다. 다시 시도할 수 있습니다."
if failure.code == "missing_evaluation":
return "회기말 평가 기록이 아직 저장되지 않았습니다. 다시 시도할 수 있습니다."
return "AI 평가를 완료하지 못했습니다. 최신 상태를 확인해 주세요."
def _missing_session_evaluation_record(
@ -1146,7 +1256,7 @@ def _missing_session_evaluation_record(
) -> dict[str, object] | None:
if not sess.ended or not has_visible_turns or sess.ended_at is None:
return None
stale_after = _session_evaluation_timeout_seconds() + MISSING_SESSION_EVALUATION_GRACE_SECONDS
stale_after = session_evaluation_stale_after_seconds()
if now_ts - sess.ended_at < stale_after:
return None
return {
@ -1903,6 +2013,11 @@ def build_session_review(read_input: SessionReviewReadInput) -> SessionReviewRes
else ""
)
evaluation_ready = not feedback_hidden and evaluation_status == "ready"
evaluation_failure = (
teacher_evaluation_failure(evaluation_record)
if read_input.include_teacher_review and not feedback_hidden
else None
)
first_turn_ts = visible_turns[0].created_at if visible_turns else sess.created_at
turns: list[ReviewTurn] = []
@ -2083,6 +2198,7 @@ def build_session_review(read_input: SessionReviewReadInput) -> SessionReviewRes
pdfExportUrl=None,
degraded=review_degraded,
reviewReady=evaluation_ready,
evaluationFailure=evaluation_failure,
learnerFeedbackEnabled=read_input.learner_feedback_enabled,
teacherReview=teacher_review,
)

View file

@ -104,16 +104,17 @@ class SessionStore:
state: SessionState,
persona_id: str | None = None,
persona_version: int | None = None,
case_id: str | None = None,
session_no: int = 1,
carry_rapport: float = 0.0,
goal_stages: list[str] | None = None,
learner_feedback_enabled: bool = True,
) -> InProcSession:
session_id = uuid4().hex
case_id = uuid4().hex
stable_case_id = case_id or uuid4().hex
s = InProcSession(
session_id=session_id,
case_id=case_id,
case_id=stable_case_id,
learner_id=learner_id,
persona_code=persona.code,
theory_mode=theory_mode,
@ -138,6 +139,23 @@ class SessionStore:
def list(self) -> list[InProcSession]:
return list(self._sessions.values())
def find_active(
self,
*,
learner_id: str,
persona_id: str | None,
persona_code: str,
) -> Optional[InProcSession]:
"""Return the active session for one learner-persona continuity case."""
for session in self._sessions.values():
if session.ended or session.learner_id != learner_id:
continue
if persona_id is not None and session.persona_id == persona_id:
return session
if session.persona_id is None and session.persona_code == persona_code:
return session
return None
def append_turn(self, session_id: str, turn: TurnRecord) -> None:
s = self._sessions.get(session_id)
if s is not None:

View file

@ -9,6 +9,7 @@ from unittest.mock import AsyncMock, patch
from fastapi import HTTPException
from .config import settings
from .deps import Principal, Role
from .services import evaluator
@ -44,7 +45,11 @@ class ReevaluateSessionRouteTest(unittest.IsolatedAsyncioTestCase):
)
self.assertEqual(raised.exception.status_code, 502)
self.assertEqual(raised.exception.detail, "no_structured_output")
self.assertEqual(
raised.exception.detail,
"AI 평가를 완료하지 못했습니다. 최신 평가 상태를 확인해 주세요.",
)
self.assertNotIn("no_structured_output", raised.exception.detail)
saved_write = save_evaluation.await_args.args[0]
self.assertEqual(saved_write.status, "error")
self.assertEqual(saved_write.error, "no_structured_output")
@ -78,6 +83,39 @@ class ReevaluateSessionRouteTest(unittest.IsolatedAsyncioTestCase):
self.assertEqual(raised.exception.status_code, 503)
self.assertIn("could not be saved", raised.exception.detail)
async def test_reevaluate_session_redacts_engine_exception_from_http_response(self) -> None:
session_id = "00000000-0000-0000-0000-00000000e222"
sess = _session_stub()
with (
patch.object(eval_routes, "_load_session_or_404", AsyncMock(return_value=sess)),
patch.object(
eval_routes.evaluator,
"evaluate_session",
AsyncMock(side_effect=eval_routes.EngineError("provider body: [NAME]")),
),
patch.object(
eval_routes.session_persistence,
"save_session_evaluation",
AsyncMock(return_value=True),
) as save_evaluation,
):
with self.assertRaises(HTTPException) as raised:
await eval_routes.reevaluate_session(
session_id,
eval_routes.ReevaluateRequest(scope="session_end"),
_teacher_principal(),
)
self.assertEqual(raised.exception.status_code, 503)
self.assertEqual(
raised.exception.detail,
"AI 평가를 완료하지 못했습니다. 최신 평가 상태를 확인해 주세요.",
)
self.assertNotIn("[NAME]", raised.exception.detail)
saved_write = save_evaluation.await_args.args[0]
self.assertIn("provider body: [NAME]", saved_write.error)
async def test_reevaluate_session_prefers_session_theory_mode(self) -> None:
session_id = "00000000-0000-0000-0000-00000000e222"
sess = _session_stub(theory_mode="cbt", theory_target=["humanistic"])
@ -89,6 +127,7 @@ class ReevaluateSessionRouteTest(unittest.IsolatedAsyncioTestCase):
)
with (
patch.object(settings, "session_evaluation_timeout", 300.0),
patch.object(eval_routes, "_load_session_or_404", AsyncMock(return_value=sess)),
patch.object(
eval_routes.evaluator,
@ -108,6 +147,7 @@ class ReevaluateSessionRouteTest(unittest.IsolatedAsyncioTestCase):
)
self.assertEqual(evaluate_session.await_args.kwargs["theory_mode"], "cbt")
self.assertEqual(evaluate_session.await_args.kwargs["timeout"], 330.0)
async def test_reevaluate_session_uses_one_based_masked_turn_seq(self) -> None:
session_id = "00000000-0000-0000-0000-00000000e222"
@ -277,7 +317,10 @@ class ReevaluateSessionRouteTest(unittest.IsolatedAsyncioTestCase):
)
self.assertEqual(raised.exception.status_code, 503)
self.assertEqual(raised.exception.detail, "engine_error")
self.assertEqual(
raised.exception.detail,
"AI 평가를 완료하지 못했습니다. 최신 평가 상태를 확인해 주세요.",
)
saved_payload = replace_turn_evaluation.await_args.kwargs["evaluation"]
self.assertEqual(saved_payload["error"], "engine_error")
@ -289,7 +332,10 @@ class ReevaluateSessionRouteTest(unittest.IsolatedAsyncioTestCase):
"source": "engine",
"scope": "session_end",
"stage": "정리",
"payload": {},
"payload": {
"error": "session evaluation timeout after 45s",
"distribution": {"total": 0},
},
"error": "session evaluation timeout after 45s",
"updated_at": "2026-07-01T00:00:00Z",
}
@ -305,9 +351,16 @@ class ReevaluateSessionRouteTest(unittest.IsolatedAsyncioTestCase):
response = await eval_routes.get_session_evaluation(session_id, _teacher_principal())
self.assertEqual(response.status, "error")
self.assertEqual(response.error, "session evaluation timeout after 45s")
self.assertEqual(
response.error,
"AI 평가를 완료하지 못했습니다. 최신 평가 상태를 확인해 주세요.",
)
self.assertIsNotNone(response.failure)
assert response.failure is not None
self.assertEqual(response.failure.code, "timeout")
self.assertNotIn("session evaluation timeout after 45s", response.model_dump_json())
self.assertTrue(response.durable)
self.assertEqual(response.deep, {})
self.assertEqual(response.deep, {"distribution": {"total": 0}})
def _session_stub(

View file

@ -429,6 +429,46 @@ class EvaluationPersistenceMappingTest(unittest.IsolatedAsyncioTestCase):
self.assertNotIn("010-1234-5678", blob)
self.assertIn("[NAME]", blob)
self.assertIn("[PHONE]", blob)
self.assertIn(
"WHERE app.session_evaluation.status <> 'ready'",
conn.executed[0][0],
)
def test_late_error_never_replaces_ready_evaluation_record(self) -> None:
ready = {"status": "ready", "payload": {"strengths": ["완료"]}}
error = {"status": "error", "error": "late timeout"}
self.assertFalse(
session_persistence._should_replace_evaluation_record(ready, error)
)
self.assertTrue(
session_persistence._should_replace_evaluation_record(error, ready)
)
self.assertTrue(
session_persistence._should_replace_evaluation_record(ready, ready)
)
async def test_fallback_cache_keeps_ready_result_when_late_error_arrives(self) -> None:
session_id = "11111111-1111-1111-1111-111111111111"
session_persistence._EVALUATION_CACHE[session_id] = {"status": "ready"}
self.addCleanup(session_persistence._EVALUATION_CACHE.pop, session_id, None)
write = session_persistence.SessionEvaluationWrite.from_error(
session_id=session_id,
learner_id="22222222-2222-2222-2222-222222222222",
scope="session_end",
stage="정리",
error="late timeout",
)
with (
patch.object(session_persistence, "runtime_fallback_allowed", return_value=True),
patch.object(session_persistence, "get_pool", side_effect=RuntimeError("offline")),
patch.object(session_persistence, "require_runtime_fallback_allowed"),
):
saved = await session_persistence.save_session_evaluation(write)
self.assertFalse(saved)
self.assertEqual(session_persistence._EVALUATION_CACHE[session_id]["status"], "ready")
def test_rebuild_turn_evaluation_restores_review_shape(self) -> None:
rebuilt = session_persistence._rebuild_turn_evaluations(

View file

@ -30,9 +30,11 @@ def _turn_context() -> orchestrator.TurnContext:
class CaptureEvaluatorEngine:
def __init__(self) -> None:
self.requests: list[Any] = []
self.timeouts: list[float | None] = []
async def generate(self, req: Any) -> GenerateResponse:
async def generate(self, req: Any, *, timeout: float | None = None) -> GenerateResponse:
self.requests.append(req)
self.timeouts.append(timeout)
loop = req.metadata.get("loop")
if loop == "fast":
structured = {
@ -61,7 +63,7 @@ class FailingEvaluatorEngine:
def __init__(self) -> None:
self.requests: list[Any] = []
async def generate(self, req: Any) -> GenerateResponse:
async def generate(self, req: Any, *, timeout: float | None = None) -> GenerateResponse:
self.requests.append(req)
raise EngineError("synthetic evaluator failure")
@ -122,6 +124,23 @@ class EvaluatorModelRoutingTest(unittest.IsolatedAsyncioTestCase):
self.assertEqual(engine.requests[0].ai_role, "evaluator")
self.assertEqual(engine.requests[0].model, "cheap-deep")
async def test_deep_evaluator_forwards_explicit_timeout(self) -> None:
engine = CaptureEvaluatorEngine()
result = await evaluator.evaluate_session(
session_id="evaluator-model-session",
stage="라포",
masked_turns=[
{"speaker": "counselor", "text": "천천히 이야기해줘도 괜찮아요."},
{"speaker": "client", "text": "잘 모르겠어요."},
],
engine=engine, # type: ignore[arg-type]
timeout=300.0,
)
self.assertIsNone(result.error)
self.assertEqual(engine.timeouts, [300.0])
async def test_blank_model_settings_keep_gateway_default_routing(self) -> None:
settings.evaluator_fast_model = " "
settings.evaluator_deep_model = ""

View file

@ -9,6 +9,7 @@ from typing import Any
from unittest.mock import AsyncMock, patch
from .config import settings
from . import session_evaluation_timeout
from .routes import sessions
from .services import notifications, state_machine
from .services.persona import P1
@ -209,6 +210,39 @@ class NotificationTriggerTest(unittest.IsolatedAsyncioTestCase):
self.assertEqual(saved_write.status, "error")
self.assertEqual(saved_write.error, "session evaluation timeout after 1s")
async def test_session_evaluation_forwards_transport_and_audit_budget_after_deep_deadline(self) -> None:
sess = _ended_session()
result = sessions.evaluator.SessionEvaluation(
session_id=sess.session_id,
stage=sess.state.stage.value,
scope="session_end",
turns_evaluated=len(sess.turns),
)
with (
patched_settings(session_evaluation_timeout=300.0, db_command_timeout=30.0),
patch.object(
sessions.evaluator,
"evaluate_session",
AsyncMock(return_value=result),
) as evaluate_session,
patch.object(
sessions.session_persistence,
"save_session_evaluation",
AsyncMock(return_value=True),
),
patch.object(
sessions.notifications,
"enqueue_session_review_ready",
AsyncMock(),
),
patch.object(sessions.asyncio, "wait_for", wraps=asyncio.wait_for) as wait_for,
):
await sessions._generate_and_save_session_evaluation(sess)
self.assertEqual(evaluate_session.await_args.kwargs["timeout"], 330.0)
self.assertEqual(wait_for.await_args.kwargs["timeout"], 365.0)
async def test_scheduled_session_evaluation_task_crash_is_observed(self) -> None:
sess = _ended_session()
@ -245,11 +279,30 @@ class NotificationTriggerTest(unittest.IsolatedAsyncioTestCase):
) as schedule_evaluation,
):
scheduled = await sessions.recover_missing_session_evaluations(limit=2)
expected_stale_after = session_evaluation_timeout.session_evaluation_stale_after_seconds()
self.assertEqual(scheduled, 1)
list_missing.assert_awaited_once_with(older_than_seconds=40.0, limit=2)
list_missing.assert_awaited_once_with(
older_than_seconds=expected_stale_after,
limit=2,
)
schedule_evaluation.assert_called_once_with(sess)
def test_stale_deadline_follows_outer_completion_and_db_save_budget(self) -> None:
with patched_settings(session_evaluation_timeout=300.0, db_command_timeout=30.0):
self.assertEqual(
session_evaluation_timeout.session_evaluation_transport_timeout_seconds(),
330.0,
)
self.assertEqual(
session_evaluation_timeout.session_evaluation_outer_timeout_seconds(),
365.0,
)
self.assertEqual(
session_evaluation_timeout.session_evaluation_stale_after_seconds(),
400.0,
)
async def test_missing_session_evaluation_recovery_requires_durable_store(self) -> None:
sess = _ended_session()

View file

@ -119,10 +119,14 @@ class _ContractConnection:
]
matches.sort(key=lambda row: int(row["version"]), reverse=True)
return matches[0] if matches else None
if "FROM app.case_profile" in query and "FOR UPDATE" in query:
return None
if "INSERT INTO app.case_profile" in query:
return {"case_id": self.case_id, "last_session_no": 0}
if "UPDATE app.case_profile" in query:
return {"last_session_no": int(args[1])}
if "FROM app.sessions" in query and "ended_at IS NULL" in query:
return None
if "INSERT INTO app.sessions" in query:
self.session_insert_args = args
return {
@ -140,7 +144,11 @@ class _ContractConnection:
raise AssertionError(f"unexpected fetchrow: {query}")
async def execute(self, query: str, *args: Any) -> str:
if "audit.audit_log" in query or "app.session_state" in query:
if (
"audit.audit_log" in query
or "app.session_state" in query
or "pg_advisory_xact_lock" in query
):
return "INSERT 0 1"
raise AssertionError(f"unexpected execute: {query}")

View file

@ -0,0 +1,357 @@
"""새 사례/이어가기 API의 learner 경계 계약 테스트."""
from __future__ import annotations
import unittest
from datetime import datetime, timezone
from types import SimpleNamespace
from typing import Any
from unittest.mock import AsyncMock, patch
from uuid import UUID
from fastapi import HTTPException
from .deps import Principal, Role
from .routes import sessions
from .services import persona as persona_service
from .store import InProcSession, store
LEARNER_ID = "00000000-0000-0000-0000-000000000741"
PERSONA_ID = "00000000-0000-0000-0000-000000000742"
CASE_ID = "00000000-0000-0000-0000-00000000ca5e"
ACTIVE_SESSION_ID = "00000000-0000-0000-0000-000000000743"
def _principal() -> Principal:
return Principal(
user_id=LEARNER_ID,
role=Role.LEARNER,
cohort_ids=[],
email="case-api-test@hs.ac.kr",
display_name="Case API Test",
consent_at=1.0,
profile_completed_at=1.0,
)
def _catalog_persona() -> SimpleNamespace:
return SimpleNamespace(
card=persona_service.P1,
persona_id=PERSONA_ID,
version=3,
degraded=False,
)
class _Acquire:
def __init__(self, conn: "_MemoryConnection") -> None:
self.conn = conn
async def __aenter__(self) -> "_MemoryConnection":
return self.conn
async def __aexit__(
self,
exc_type: object,
exc: object,
tb: object,
) -> bool:
return False
class _MemoryConnection:
"""foldout이 필요한 최소 learner-safe 행만 내는 DB 대역."""
def __init__(
self,
*,
case_row: dict[str, Any] | None,
summary_row: dict[str, Any] | None = None,
fact_rows: list[dict[str, Any]] | None = None,
) -> None:
self.case_row = case_row
self.summary_row = summary_row
self.fact_rows = fact_rows or []
self.calls: list[tuple[str, tuple[Any, ...]]] = []
async def fetchrow(self, query: str, *args: Any) -> dict[str, Any] | None:
self.calls.append((query, args))
if "FROM app.case_profile" in query:
return self.case_row
if "FROM app.session_summary AS ss" in query:
return self.summary_row
raise AssertionError(f"unexpected fetchrow: {query}")
async def fetch(self, query: str, *args: Any) -> list[dict[str, Any]]:
self.calls.append((query, args))
if "FROM app.pinned_fact AS pf" not in query:
raise AssertionError(f"unexpected fetch: {query}")
return self.fact_rows
class LearnerCaseListApiTest(unittest.IsolatedAsyncioTestCase):
async def test_case_list_projects_one_case_with_complete_case_local_stats(self) -> None:
principal = _principal()
catalog_persona = _catalog_persona()
active_started_at = datetime(2026, 8, 31, 9, 15, tzinfo=timezone.utc)
last_activity_at = datetime(2026, 8, 31, 10, 45, tzinfo=timezone.utc)
rows = [
{
"case_id": CASE_ID,
"last_session_no": 4,
"total_sessions": 4,
"completed_sessions": 3,
"total_turns": 18,
"total_duration_seconds": 5_400,
"active_session_id": ACTIVE_SESSION_ID,
"active_session_no": 4,
"active_started_at": active_started_at,
"last_activity_at": last_activity_at,
}
]
list_summaries = AsyncMock(return_value=rows)
with (
patch.object(
sessions,
"get_catalog_persona",
AsyncMock(return_value=catalog_persona),
),
patch.object(
sessions.session_persistence,
"list_case_summaries",
list_summaries,
),
):
response = await sessions.list_learner_cases(
persona_code=persona_service.P1.code,
principal=principal,
)
list_summaries.assert_awaited_once_with(
learner_id=principal.user_id,
persona_id=PERSONA_ID,
)
self.assertEqual(response.source, "database")
self.assertEqual(len(response.cases), 1)
case = response.cases[0]
self.assertEqual(case.case_id, CASE_ID)
self.assertEqual(case.persona_code, persona_service.P1.code)
self.assertEqual(case.persona_name, persona_service.P1.display_name)
self.assertEqual(case.last_session_no, 4)
self.assertEqual(case.progress.total_sessions, 4)
self.assertEqual(case.progress.completed_sessions, 3)
self.assertEqual(case.progress.total_turns, 18)
self.assertEqual(case.progress.total_duration_seconds, 5_400)
self.assertEqual(case.progress.active_session_id, ACTIVE_SESSION_ID)
self.assertEqual(case.progress.active_session_no, 4)
self.assertEqual(case.progress.active_started_at, active_started_at.isoformat())
self.assertEqual(case.progress.last_activity_at, last_activity_at.isoformat())
async def test_case_list_fails_closed_when_database_progress_is_unavailable(self) -> None:
principal = _principal()
with (
patch.object(
sessions,
"get_catalog_persona",
AsyncMock(return_value=_catalog_persona()),
),
patch.object(
sessions.session_persistence,
"list_case_summaries",
AsyncMock(
side_effect=sessions.session_persistence.CaseProgressUnavailableError(
"database unavailable"
)
),
),
):
with self.assertRaises(HTTPException) as raised:
await sessions.list_learner_cases(
persona_code=persona_service.P1.code,
principal=principal,
)
self.assertEqual(raised.exception.status_code, 503)
self.assertEqual(raised.exception.detail, "case_progress_unavailable")
class LearnerCaseMemoryPreviewApiTest(unittest.IsolatedAsyncioTestCase):
async def test_memory_preview_is_owner_scoped_and_never_selects_raw_session_data(self) -> None:
principal = _principal()
conn = _MemoryConnection(
case_row={"case_digest": "사례 요약 " + "가" * 700},
summary_row={
"digest": "직전 회기 요약 " + "나" * 700,
"open_threads": ["남은 주제 " + "다" * 200, "다음 질문"],
},
fact_rows=[{"value": "기억 항목 " + "라" * 200}],
)
with patch.object(
sessions.db,
"acquire",
return_value=_Acquire(conn),
) as acquire:
response = await sessions.get_learner_case_memory_preview(
case_id=UUID(CASE_ID),
principal=principal,
)
acquire.assert_called_once_with(role="learner", user_id=principal.user_id)
self.assertEqual(response.case_id, CASE_ID)
self.assertTrue(response.memory_available)
self.assertEqual(len(response.case_digest or ""), 600)
self.assertEqual(len(response.latest_session_digest or ""), 600)
self.assertEqual(len(response.open_threads[0]), 160)
self.assertTrue(response.open_threads[0].endswith("…"))
self.assertEqual(response.open_threads[1], "다음 질문")
self.assertEqual(len(response.pinned_facts[0]), 160)
self.assertTrue(response.pinned_facts[0].endswith("…"))
queried_sql = "\n".join(query for query, _ in conn.calls).lower()
self.assertIn("and learner_id = $2::uuid", queried_sql)
self.assertIn("and s.learner_id = $2::uuid", queried_sql)
self.assertIn("and cp.learner_id = $2::uuid", queried_sql)
self.assertNotIn("app.turns", queried_sql)
self.assertNotIn("transcript", queried_sql)
self.assertNotIn("evaluator", queried_sql)
self.assertNotIn("end_state", queried_sql)
self.assertNotIn(" text", queried_sql)
self.assertEqual({args[1] for _, args in conn.calls}, {principal.user_id})
response_payload = response.model_dump()
self.assertNotIn("transcript", response_payload)
self.assertNotIn("evaluator", response_payload)
self.assertNotIn("end_state", response_payload)
self.assertEqual(
set(response_payload),
{
"case_id",
"memory_available",
"case_digest",
"latest_session_digest",
"open_threads",
"pinned_facts",
},
)
async def test_memory_preview_returns_404_before_loading_unowned_case_details(self) -> None:
principal = _principal()
conn = _MemoryConnection(case_row=None)
with patch.object(
sessions.db,
"acquire",
return_value=_Acquire(conn),
):
with self.assertRaises(HTTPException) as raised:
await sessions.get_learner_case_memory_preview(
case_id=UUID(CASE_ID),
principal=principal,
)
self.assertEqual(raised.exception.status_code, 404)
self.assertEqual(raised.exception.detail, "case_not_found")
self.assertEqual(len(conn.calls), 1)
self.assertIn("FROM app.case_profile", conn.calls[0][0])
self.assertEqual(conn.calls[0][1], (CASE_ID, principal.user_id))
class SessionStartCaseModeApiTest(unittest.IsolatedAsyncioTestCase):
async def asyncSetUp(self) -> None:
store._sessions.clear()
sessions._RECALL_CACHE.clear()
sessions._KB_CUES_CACHE.clear()
async def asyncTearDown(self) -> None:
store._sessions.clear()
sessions._RECALL_CACHE.clear()
sessions._KB_CUES_CACHE.clear()
async def test_fresh_start_rejects_selected_existing_case(self) -> None:
principal = _principal()
create_session = AsyncMock()
with (
patch.object(
sessions,
"get_catalog_persona",
AsyncMock(return_value=_catalog_persona()),
),
patch.object(
sessions.session_persistence,
"create_session",
create_session,
),
):
with self.assertRaises(HTTPException) as raised:
await sessions.start_session(
sessions.SessionStartRequest(
persona_code=persona_service.P1.code,
start_mode="fresh",
case_id=UUID(CASE_ID),
),
principal,
)
self.assertEqual(raised.exception.status_code, 422)
self.assertEqual(raised.exception.detail, "fresh_start_must_not_select_case")
create_session.assert_not_awaited()
async def test_continue_start_forwards_the_selected_case_to_durable_creation(self) -> None:
principal = _principal()
catalog_persona = _catalog_persona()
captured: dict[str, Any] = {}
async def fake_create_session(**kwargs: Any) -> InProcSession:
captured.update(kwargs)
return InProcSession(
session_id="selected-case-session",
case_id=str(kwargs["case_id"]),
learner_id=principal.user_id,
persona_code=persona_service.P1.code,
theory_mode=str(kwargs["theory_mode"]),
persona=persona_service.P1,
state=kwargs["state"],
persona_id=PERSONA_ID,
persona_version=3,
session_no=7,
prev_rapport_credit=float(kwargs["carry_rapport"]),
)
def close_background(coro: Any) -> SimpleNamespace:
coro.close()
return SimpleNamespace()
with (
patch.object(
sessions,
"get_catalog_persona",
AsyncMock(return_value=catalog_persona),
),
patch.object(
sessions.session_persistence,
"create_session",
AsyncMock(side_effect=fake_create_session),
),
patch.object(sessions.asyncio, "create_task", close_background),
):
response = await sessions.start_session(
sessions.SessionStartRequest(
persona_code=persona_service.P1.code,
start_mode="continue",
case_id=UUID(CASE_ID),
),
principal,
)
self.assertEqual(captured["case_id"], CASE_ID)
self.assertEqual(captured["start_mode"], "continue")
self.assertEqual(response.case_id, CASE_ID)
self.assertEqual(response.session_no, 7)
self.assertEqual(response.start_mode, "continue")
if __name__ == "__main__":
unittest.main()

View file

@ -0,0 +1,326 @@
"""같은 내담자 케이스의 회기 순차성 회귀 테스트."""
from __future__ import annotations
import unittest
from types import SimpleNamespace
from unittest.mock import AsyncMock, patch
from fastapi import HTTPException
from . import session_persistence
from .deps import Principal, Role
from .routes import sessions
from .services import memory, persona as persona_service, state_machine
from .store import store
class _Transaction:
async def __aenter__(self) -> None:
return None
async def __aexit__(self, exc_type, exc, tb) -> bool:
return False
class _Acquire:
def __init__(self, conn: "_ActiveSessionConnection") -> None:
self.conn = conn
async def __aenter__(self) -> "_ActiveSessionConnection":
return self.conn
async def __aexit__(self, exc_type, exc, tb) -> bool:
return False
class _ActiveSessionConnection:
"""새 row INSERT 전 active-case 확인 순서를 검증하는 최소 DB 대역."""
active_session_id = "00000000-0000-0000-0000-000000000777"
def __init__(self) -> None:
self.active_query = ""
self.insert_attempted = False
def transaction(self) -> _Transaction:
return _Transaction()
async def fetchrow(self, query: str, *args: object) -> dict[str, object] | None:
if "UPDATE app.case_profile" in query:
return {"last_session_no": 2}
if "FROM app.sessions" in query and "ended_at IS NULL" in query:
self.active_query = query
return {"id": self.active_session_id}
if "INSERT INTO app.sessions" in query:
self.insert_attempted = True
raise AssertionError("active session guard must run before INSERT")
raise AssertionError(f"unexpected query: {query}")
async def execute(self, query: str, *args: object) -> str:
if "pg_advisory_xact_lock" in query:
return "SELECT 1"
raise AssertionError(f"unexpected execute: {query}")
def _principal() -> Principal:
return Principal(
user_id="00000000-0000-0000-0000-000000000101",
role=Role.LEARNER,
cohort_ids=[],
email="continuity-guard@example.test",
display_name="연속성 검증 학습자",
consent_at=1.0,
profile_completed_at=1.0,
)
def _catalog_persona() -> SimpleNamespace:
return SimpleNamespace(
card=persona_service.P1,
persona_id="00000000-0000-0000-0000-0000000000a1",
version=1,
degraded=False,
)
class SessionContinuityGuardTest(unittest.IsolatedAsyncioTestCase):
async def asyncSetUp(self) -> None:
store._sessions.clear()
sessions._RECALL_CACHE.clear()
async def asyncTearDown(self) -> None:
store._sessions.clear()
sessions._RECALL_CACHE.clear()
async def test_persistence_rejects_a_second_active_session_before_insert(self) -> None:
conn = _ActiveSessionConnection()
principal = _principal()
with (
patch.object(session_persistence, "get_pool", return_value=object()),
patch.object(session_persistence, "acquire", return_value=_Acquire(conn)),
):
with self.assertRaises(session_persistence.ActiveSessionExistsError) as raised:
await session_persistence.create_session(
learner_id=principal.user_id,
card=persona_service.P1,
theory_mode="humanistic",
state=state_machine.SessionState(),
session_no=2,
persona_id="00000000-0000-0000-0000-0000000000a1",
persona_version=1,
case_id="00000000-0000-0000-0000-00000000ca5e",
)
self.assertEqual(raised.exception.session_id, conn.active_session_id)
self.assertIn("FOR UPDATE", conn.active_query)
self.assertIn("persona_id = $2::uuid", conn.active_query)
self.assertNotIn("case_id = $1::uuid", conn.active_query)
self.assertFalse(conn.insert_attempted)
async def test_persistence_builds_start_state_after_case_lock_and_active_check(
self,
) -> None:
class ReadyConnection:
def __init__(self) -> None:
self.events: list[str] = []
def transaction(self) -> _Transaction:
return _Transaction()
async def fetchrow(
self,
query: str,
*args: object,
) -> dict[str, object] | None:
if "FROM app.case_profile" in query and "FOR UPDATE" in query:
self.events.append("case_lock")
return {"case_id": args[0], "last_session_no": 1}
if "UPDATE app.case_profile" in query:
self.events.append("case_counter")
return {"last_session_no": 2}
if "FROM app.sessions" in query and "ended_at IS NULL" in query:
self.events.append("active_check")
return None
if "INSERT INTO app.sessions" in query:
self.events.append("session_insert")
return {
"id": "00000000-0000-0000-0000-000000000302",
"runtime_case_id": args[0],
"case_id": args[1],
"learner_id": args[2],
"persona_code": args[5],
"session_no": args[8],
"theory_mode": args[9],
"started_at": session_persistence.datetime.fromtimestamp(
1_000.0,
tz=session_persistence.timezone.utc,
),
"ended_at": None,
"prev_rapport_credit": args[10],
}
raise AssertionError(f"unexpected query: {query}")
async def execute(self, query: str, *args: object) -> str:
if "pg_advisory_xact_lock" in query:
self.events.append("scope_lock")
return "SELECT 1"
if "INSERT INTO app.session_state" not in query:
raise AssertionError(f"unexpected execute: {query}")
self.events.append("state_insert")
return "INSERT 0 1"
conn = ReadyConnection()
principal = _principal()
recalled_state = state_machine.SessionState(rapport_credit=0.37)
factory_calls: list[tuple[str, int]] = []
async def locked_state_factory(
case_id: str,
session_no: int,
) -> state_machine.SessionState:
self.assertEqual(
conn.events,
["scope_lock", "active_check", "case_lock", "case_counter"],
)
factory_calls.append((case_id, session_no))
return recalled_state
with (
patch.object(session_persistence, "get_pool", return_value=object()),
patch.object(session_persistence, "acquire", return_value=_Acquire(conn)),
):
created = await session_persistence.create_session(
learner_id=principal.user_id,
card=persona_service.P1,
theory_mode="humanistic",
state=state_machine.SessionState(),
session_no=2,
persona_id="00000000-0000-0000-0000-0000000000a1",
persona_version=1,
case_id="00000000-0000-0000-0000-00000000ca5e",
locked_state_factory=locked_state_factory,
)
self.assertEqual(
factory_calls,
[("00000000-0000-0000-0000-00000000ca5e", 2)],
)
self.assertEqual(
conn.events,
[
"scope_lock",
"active_check",
"case_lock",
"case_counter",
"session_insert",
"state_insert",
],
)
self.assertIsNotNone(created)
assert created is not None
self.assertIs(created.state, recalled_state)
self.assertEqual(created.prev_rapport_credit, 0.37)
async def test_start_returns_resumable_conflict_for_persisted_active_session(self) -> None:
principal = _principal()
catalog_persona = _catalog_persona()
active_session_id = "00000000-0000-0000-0000-000000000777"
with (
patch.object(
sessions,
"get_catalog_persona",
AsyncMock(return_value=catalog_persona),
),
patch.object(
sessions.session_persistence,
"get_case_context",
AsyncMock(
return_value=session_persistence.CaseContext(
case_id="00000000-0000-0000-0000-00000000ca5e",
last_session_no=1,
)
),
),
patch.object(
sessions,
"_build_seed_recall",
AsyncMock(return_value=memory.RecallContext()),
),
patch.object(
sessions.session_persistence,
"create_session",
AsyncMock(
side_effect=session_persistence.ActiveSessionExistsError(
active_session_id
)
),
),
):
with self.assertRaises(HTTPException) as raised:
await sessions.start_session(
sessions.SessionStartRequest(persona_code=persona_service.P1.code),
principal,
)
self.assertEqual(raised.exception.status_code, 409)
self.assertEqual(
raised.exception.detail,
{
"code": "active_session_exists",
"session_id": active_session_id,
},
)
async def test_runtime_fallback_rejects_a_second_active_session(self) -> None:
principal = _principal()
catalog_persona = _catalog_persona()
existing = store.create(
learner_id=principal.user_id,
persona=persona_service.P1,
theory_mode="humanistic",
state=state_machine.SessionState(),
persona_id=catalog_persona.persona_id,
persona_version=catalog_persona.version,
)
with (
patch.object(
sessions,
"get_catalog_persona",
AsyncMock(return_value=catalog_persona),
),
patch.object(
sessions.session_persistence,
"get_case_context",
AsyncMock(return_value=None),
),
patch.object(
sessions,
"_build_seed_recall",
AsyncMock(return_value=memory.RecallContext()),
),
patch.object(
sessions.session_persistence,
"create_session",
AsyncMock(return_value=None),
),
patch.object(sessions, "require_runtime_fallback_allowed"),
):
with self.assertRaises(HTTPException) as raised:
await sessions.start_session(
sessions.SessionStartRequest(persona_code=persona_service.P1.code),
principal,
)
self.assertEqual(raised.exception.status_code, 409)
self.assertEqual(
raised.exception.detail,
{
"code": "active_session_exists",
"session_id": existing.session_id,
},
)
self.assertEqual(len(store.list()), 1)

View file

@ -693,6 +693,12 @@ class SessionMemoryPersistenceTest(unittest.IsolatedAsyncioTestCase):
self.executed.append((query, args))
return "OK"
async def fetchval(self, query: str, *args: object) -> object:
self.executed.append((query, args))
test_case.assertIn("FROM app.case_profile", query)
test_case.assertIn("FOR NO KEY UPDATE", query)
return args[0]
async def fetchrow(self, query: str, *args: object):
self.executed.append((query, args))
if "INSERT INTO app.pinned_fact" in query:
@ -773,6 +779,17 @@ class SessionMemoryPersistenceTest(unittest.IsolatedAsyncioTestCase):
persisted = await session_persistence.end_session(sess, carry)
self.assertTrue(persisted)
case_lock_index = next(
index
for index, (query, _) in enumerate(conn.executed)
if "SELECT case_id" in query and "FOR NO KEY UPDATE" in query
)
session_end_index = next(
index
for index, (query, _) in enumerate(conn.executed)
if "UPDATE app.sessions" in query and "ended_at" in query
)
self.assertLess(case_lock_index, session_end_index)
summary_writes = [
args for query, args in conn.executed if "INSERT INTO app.session_summary" in query
]

View file

@ -249,15 +249,16 @@ class SessionTurnPersistenceTest(unittest.IsolatedAsyncioTestCase):
version=3,
degraded=False,
)
case_context = sessions.session_persistence.CaseContext(
case_id=case_id,
last_session_no=1,
)
next_session_id = "00000000-0000-0000-0000-000000000702"
async def create_next_session(**kwargs: object) -> InProcSession:
self.assertEqual(kwargs["case_id"], case_id)
self.assertEqual(kwargs["session_no"], 2)
self.assertEqual(kwargs["start_mode"], "continue")
# The route now delegates durable case selection to the locked
# persistence transaction. It only provides a provisional first
# session number; the selected case counter makes this session #2.
self.assertEqual(kwargs["session_no"], 1)
state = await kwargs["locked_state_factory"](case_id, 2)
created = InProcSession(
session_id=next_session_id,
case_id=case_id,
@ -265,9 +266,9 @@ class SessionTurnPersistenceTest(unittest.IsolatedAsyncioTestCase):
persona_code=card.code,
theory_mode=str(kwargs["theory_mode"]),
persona=card,
state=kwargs["state"],
session_no=int(kwargs["session_no"]),
prev_rapport_credit=float(kwargs["carry_rapport"]),
state=state,
session_no=2,
prev_rapport_credit=state.rapport_credit,
)
durable_sessions[created.session_id] = created
return created
@ -283,11 +284,6 @@ class SessionTurnPersistenceTest(unittest.IsolatedAsyncioTestCase):
"get_catalog_persona",
AsyncMock(return_value=catalog_persona),
),
patch.object(
sessions.session_persistence,
"get_case_context",
AsyncMock(return_value=case_context),
),
patch.object(
sessions,
"_build_seed_recall",
@ -301,7 +297,10 @@ class SessionTurnPersistenceTest(unittest.IsolatedAsyncioTestCase):
patch.object(sessions.asyncio, "create_task", close_background),
):
started = await sessions.start_session(
sessions.SessionStartRequest(persona_code=card.code),
sessions.SessionStartRequest(
persona_code=card.code,
case_id=case_id,
),
principal,
)
@ -511,8 +510,12 @@ class SessionTurnPersistenceTest(unittest.IsolatedAsyncioTestCase):
return FakeTransaction()
async def fetchrow(self, query: str, *args: object) -> dict[str, object]:
if "FROM app.case_profile" in query and "FOR UPDATE" in query:
return {"case_id": args[0], "last_session_no": 1}
if "UPDATE app.case_profile" in query:
return {"last_session_no": 2}
if "FROM app.sessions" in query and "ended_at IS NULL" in query:
return None
if "INSERT INTO app.sessions" in query:
self.session_insert_args = args
return {
@ -532,6 +535,8 @@ class SessionTurnPersistenceTest(unittest.IsolatedAsyncioTestCase):
raise AssertionError(f"unexpected query: {query}")
async def execute(self, query: str, *args: object) -> str:
if "pg_advisory_xact_lock" in query:
return "SELECT 1"
self.assert_jsonb_object(query, args)
return "INSERT 0 1"
@ -1811,8 +1816,13 @@ class SessionTurnPersistenceTest(unittest.IsolatedAsyncioTestCase):
async def fake_create_session(**kwargs):
self.assertEqual(kwargs["case_id"], case_context.case_id)
self.assertEqual(kwargs["session_no"], 2)
self.assertGreater(kwargs["state"].rapport_credit, 0)
self.assertEqual(kwargs["start_mode"], "continue")
self.assertEqual(kwargs["session_no"], 1)
state = await kwargs["locked_state_factory"](
case_context.case_id,
2,
)
self.assertGreater(state.rapport_credit, 0)
return InProcSession(
session_id="stable-case-session",
case_id=kwargs["case_id"],
@ -1820,9 +1830,9 @@ class SessionTurnPersistenceTest(unittest.IsolatedAsyncioTestCase):
persona_code=card.code,
theory_mode=kwargs["theory_mode"],
persona=card,
state=kwargs["state"],
session_no=kwargs["session_no"],
prev_rapport_credit=kwargs["carry_rapport"],
state=state,
session_no=2,
prev_rapport_credit=state.rapport_credit,
)
def close_background(coro):
@ -1833,11 +1843,6 @@ class SessionTurnPersistenceTest(unittest.IsolatedAsyncioTestCase):
patch.object(
sessions, "get_catalog_persona", AsyncMock(return_value=catalog_persona)
),
patch.object(
sessions.session_persistence,
"get_case_context",
AsyncMock(return_value=case_context),
),
patch.object(
sessions,
"_build_seed_recall",
@ -1851,7 +1856,10 @@ class SessionTurnPersistenceTest(unittest.IsolatedAsyncioTestCase):
patch.object(sessions.asyncio, "create_task", close_background),
):
response = await sessions.start_session(
sessions.SessionStartRequest(persona_code=card.code),
sessions.SessionStartRequest(
persona_code=card.code,
case_id=case_context.case_id,
),
principal,
)
@ -1911,16 +1919,23 @@ class SessionTurnPersistenceTest(unittest.IsolatedAsyncioTestCase):
return None
async def fake_create_session(**kwargs):
test_case.assertEqual(kwargs["case_id"], case_context.case_id)
test_case.assertEqual(kwargs["start_mode"], "continue")
test_case.assertEqual(kwargs["session_no"], 1)
state = await kwargs["locked_state_factory"](
case_context.case_id,
2,
)
return InProcSession(
session_id="db-seed-recall-session",
case_id=kwargs["case_id"],
case_id=case_context.case_id,
learner_id=principal.user_id,
persona_code=card.code,
theory_mode=kwargs["theory_mode"],
persona=card,
state=kwargs["state"],
session_no=kwargs["session_no"],
prev_rapport_credit=kwargs["carry_rapport"],
state=state,
session_no=2,
prev_rapport_credit=state.rapport_credit,
)
def close_background(coro):
@ -1931,11 +1946,6 @@ class SessionTurnPersistenceTest(unittest.IsolatedAsyncioTestCase):
patch.object(
sessions, "get_catalog_persona", AsyncMock(return_value=catalog_persona)
),
patch.object(
sessions.session_persistence,
"get_case_context",
AsyncMock(return_value=case_context),
),
patch.object(sessions.db, "get_pool", return_value=object()),
patch.object(
sessions.db,
@ -1950,7 +1960,10 @@ class SessionTurnPersistenceTest(unittest.IsolatedAsyncioTestCase):
patch.object(sessions.asyncio, "create_task", close_background),
):
response = await sessions.start_session(
sessions.SessionStartRequest(persona_code=card.code),
sessions.SessionStartRequest(
persona_code=card.code,
case_id=case_context.case_id,
),
principal,
)
started = store.get(response.session_id)
@ -2743,10 +2756,43 @@ class SessionTurnPersistenceTest(unittest.IsolatedAsyncioTestCase):
)
self.assertIn("AI 평가 재시도가 필요합니다", response.summary)
self.assertNotIn("session evaluation timeout after 45s", response.summary)
self.assertIsNone(response.evaluationFailure)
self.assertEqual(response.rubric, [])
self.assertEqual(response.goodMoments, [])
self.assertEqual(response.growthPoints, [])
teacher_response = sessions.build_session_review(
sessions.SessionReviewReadInput(
session=sess,
evaluation_record=error_record,
evaluation_durable=True,
include_teacher_review=True,
)
)
self.assertIsNotNone(teacher_response.evaluationFailure)
assert teacher_response.evaluationFailure is not None
self.assertEqual(teacher_response.evaluationFailure.code, "timeout")
self.assertTrue(teacher_response.evaluationFailure.retryable)
self.assertNotIn("session evaluation timeout after 45s", teacher_response.model_dump_json())
oversized_input_record = {
**error_record,
"error": "engine_error: Agy CLI 프롬프트가 Windows 명령줄 안전 한도(24,000자)를 초과했습니다.",
}
oversized_response = sessions.build_session_review(
sessions.SessionReviewReadInput(
session=sess,
evaluation_record=oversized_input_record,
evaluation_durable=True,
include_teacher_review=True,
)
)
self.assertIsNotNone(oversized_response.evaluationFailure)
assert oversized_response.evaluationFailure is not None
self.assertEqual(oversized_response.evaluationFailure.code, "legacy_argv_limit")
self.assertTrue(oversized_response.evaluationFailure.retryable)
self.assertNotIn("24,000", oversized_response.model_dump_json())
def test_review_marks_stale_missing_session_evaluation_as_failed(self) -> None:
principal = _principal()
sess = _session(principal)
@ -2780,7 +2826,10 @@ class SessionTurnPersistenceTest(unittest.IsolatedAsyncioTestCase):
session=sess,
evaluation_record=None,
evaluation_durable=True,
now_ts=(sess.ended_at or sess.created_at) + 41.0,
# 평가 생성·감사 원장·결과 저장의 전체 예산을 넘긴 뒤에만 누락을 실패로 본다.
now_ts=(sess.ended_at or sess.created_at)
+ sessions.session_evaluation_stale_after_seconds()
+ 1.0,
)
)
finally:

View file

@ -10,7 +10,6 @@ from fastapi import HTTPException
from .config import settings
from .deps import Principal, Role
from .routes import teacher
from .session_read_model import MISSING_SESSION_EVALUATION_ERROR
from .services import state_machine
from .services.persona import P1
from .store import InProcSession, TurnRecord
@ -424,7 +423,11 @@ class TeacherDashboardGrowthTest(unittest.IsolatedAsyncioTestCase):
self.assertEqual(failed.evaluation_status, "error")
self.assertFalse(failed.review_ready)
self.assertEqual(failed.supervisor_state, "평가 실패")
self.assertEqual(failed.evaluation_error, "session evaluation timeout after 45s")
self.assertEqual(
failed.evaluation_error,
"AI 평가가 제한 시간 안에 끝나지 않았습니다. 다시 시도할 수 있습니다.",
)
self.assertNotIn("session evaluation timeout after 45s", response.model_dump_json())
async def test_dashboard_marks_stale_missing_session_evaluation_as_failed(self) -> None:
principal = _principal()
@ -468,7 +471,10 @@ class TeacherDashboardGrowthTest(unittest.IsolatedAsyncioTestCase):
self.assertEqual(failed.evaluation_status, "error")
self.assertFalse(failed.review_ready)
self.assertEqual(failed.supervisor_state, "평가 실패")
self.assertEqual(failed.evaluation_error, MISSING_SESSION_EVALUATION_ERROR)
self.assertEqual(
failed.evaluation_error,
"회기말 평가 기록이 아직 저장되지 않았습니다. 다시 시도할 수 있습니다.",
)
async def test_dashboard_fails_closed_when_safety_alerts_are_not_durable_outside_dev(self) -> None:
principal = _principal()

View file

@ -698,28 +698,29 @@ async def _stream_agy(
raise ProviderError("Agy CLI를 찾을 수 없습니다.")
model, effort = await _resolve_selection(req, "agy_cli")
prompt = _cli_prompt(system_prompt, user_payload)
if os.name == "nt" and len(prompt) > 24_000:
raise ProviderError(
"Agy CLI 프롬프트가 Windows 명령줄 안전 한도(24,000자)를 초과했습니다."
)
args = [binary, "--model", model, "--sandbox"]
if effort:
args += ["--effort", effort]
args += [
"--print-timeout",
f"{int(CLI_TIMEOUT_SECONDS)}s",
# 긴 deep-loop 축어록을 Windows argv에 싣지 않는다. Agy의 공식 stream-json
# 입력 계약은 prompt를 stdin의 단일 user 이벤트로 받으므로 명령줄 길이 한계를
# 피하면서 전체 마스킹 근거를 그대로 보존한다.
"--input-format",
"stream-json",
"--output-format",
"stream-json",
"--print",
prompt,
]
proc = await asyncio.create_subprocess_exec(
*args,
cwd=str(_cli_runtime_cwd()),
stdin=asyncio.subprocess.PIPE,
stdout=asyncio.subprocess.PIPE,
stderr=asyncio.subprocess.PIPE,
env=_cli_subprocess_env(),
)
assert proc.stdin is not None
assert proc.stdout is not None
assert proc.stderr is not None
stderr_task = asyncio.create_task(proc.stderr.read())
@ -730,6 +731,30 @@ async def _stream_agy(
cached_input_tokens = 0
result_status = ""
try:
# 공식 protocol: 한 줄에 한 user event. 마지막 turn 뒤 stdin을 닫아도 CLI는
# terminal result를 내보낸 뒤 종료한다. stdin 거절은 child와 stderr를 정리한 뒤
# provider 오류로 승격해 프로세스를 남기지 않는다.
try:
proc.stdin.write(
(
json.dumps(
{"event": "user", "message": {"content": prompt}},
ensure_ascii=False,
)
+ "\n"
).encode("utf-8")
)
await proc.stdin.drain()
except (BrokenPipeError, ConnectionResetError) as exc:
raise ProviderError("Agy CLI가 stdin 평가 입력을 수락하지 않았습니다.") from exc
finally:
if not proc.stdin.is_closing():
proc.stdin.close()
try:
await proc.stdin.wait_closed()
except (BrokenPipeError, ConnectionResetError):
# 이미 종료된 CLI가 close 직후 EOF를 끊어도 finally가 child를 회수한다.
pass
async with asyncio.timeout(CLI_TIMEOUT_SECONDS):
while True:
raw = await proc.stdout.readline()

View file

@ -19,8 +19,30 @@ class _FakeStreamReader:
return self.body
class _FakeStreamWriter:
def __init__(self):
self.writes: list[bytes] = []
self.closed = False
def write(self, data: bytes) -> None:
self.writes.append(data)
async def drain(self) -> None:
return None
def is_closing(self) -> bool:
return self.closed
def close(self) -> None:
self.closed = True
async def wait_closed(self) -> None:
return None
class _FakeAgyProcess:
def __init__(self, events: list[dict]):
self.stdin = _FakeStreamWriter()
self.stdout = _FakeStreamReader(
[(json.dumps(event, ensure_ascii=False) + "\n").encode("utf-8") for event in events]
)
@ -102,6 +124,7 @@ class ProviderRegistryTest(unittest.IsolatedAsyncioTestCase):
},
]
}
long_payload = "x" * 24_001
with (
patch.object(provider_registry, "_binary", return_value="codex.exe"),
patch.object(
@ -321,6 +344,7 @@ class ProviderRegistryTest(unittest.IsolatedAsyncioTestCase):
captured.append(args)
return process
long_payload = "x" * 24_001
with (
patch.object(provider_registry, "_binary", return_value="agy"),
patch.object(
@ -342,7 +366,7 @@ class ProviderRegistryTest(unittest.IsolatedAsyncioTestCase):
result = await provider_registry.generate_with_provider(
request,
system_prompt="system",
user_payload="hello",
user_payload=long_payload,
)
self.assertEqual(result.text, "OK")
@ -350,10 +374,16 @@ class ProviderRegistryTest(unittest.IsolatedAsyncioTestCase):
self.assertEqual(result.tokens_out, 2)
self.assertEqual(result.cost_usd, 0.00001515)
args = captured[0]
print_index = args.index("--print")
self.assertEqual(print_index, len(args) - 2)
self.assertIn("[시스템 지침]", args[-1])
self.assertIn("--input-format", args)
self.assertEqual(args[args.index("--input-format") + 1], "stream-json")
self.assertEqual(args[args.index("--output-format") + 1], "stream-json")
self.assertNotIn("--print", args)
self.assertTrue(all(long_payload not in str(arg) for arg in args))
self.assertTrue(process.stdin.closed)
sent = json.loads(b"".join(process.stdin.writes).decode("utf-8"))
self.assertEqual(sent["event"], "user")
self.assertIn("[시스템 지침]", sent["message"]["content"])
self.assertIn(long_payload, sent["message"]["content"])
async def test_agy_stream_forwards_live_deltas_without_repeating_final_response(self):
capabilities = provider_registry.EngineCapabilitiesResponse(
@ -451,9 +481,52 @@ class ProviderRegistryTest(unittest.IsolatedAsyncioTestCase):
self.assertEqual(events[-1].result.tokens_out, 2)
self.assertEqual(events[-1].result.cost_usd, 0.00001515)
args = captured[0]
self.assertIn("--input-format", args)
self.assertEqual(args[args.index("--input-format") + 1], "stream-json")
self.assertIn("--output-format", args)
self.assertEqual(args[args.index("--output-format") + 1], "stream-json")
self.assertEqual(args.index("--print"), len(args) - 2)
self.assertNotIn("--print", args)
async def test_agy_stdin_rejection_reaps_child_process(self):
request = GenerateRequest(
provider="agy_cli",
model="gemini-3.6-flash-high",
reasoning_effort="high",
messages=[EngineMessage(role="user", content="hello")],
)
process = _FakeAgyProcess([])
async def broken_drain() -> None:
raise BrokenPipeError()
process.stdin.drain = broken_drain # type: ignore[method-assign]
async def fake_create_subprocess_exec(*args, **kwargs):
return process
with (
patch.object(provider_registry, "_binary", return_value="agy.exe"),
patch.object(
provider_registry,
"_resolve_selection",
AsyncMock(return_value=("gemini-3.6-flash-high", "high")),
),
patch.object(
provider_registry.asyncio,
"create_subprocess_exec",
fake_create_subprocess_exec,
),
):
with self.assertRaisesRegex(provider_registry.ProviderError, "stdin 평가 입력"):
async for _event in provider_registry._stream_agy(
request,
system_prompt="system",
user_payload="hello",
):
pass
self.assertTrue(process.stdin.closed)
self.assertEqual(process.returncode, -9)
async def test_generation_rejects_model_effort_not_returned_by_provider(self):
capabilities = provider_registry.EngineCapabilitiesResponse(

View file

@ -14,4 +14,13 @@
국소 구현 소유자는 `src/pages/Admin.tsx`, `src/pages/admin/admin-console.css`, `src/pages/SessionReview.tsx`, `src/pages/session-review/`다. 공통 토큰과 앱 셸은 각각 `src/styles/tokens.css`, `src/components/shell/`의 소유권을 유지한다.
- 2026-08-28 · `/learn` 성장 지표의 라포 헤더에서 중첩 inset surface를 제거해 같은 패널의 일반 헤더 위계와 정렬했다. 토큰 변경 없음.
- 2026-08-29 · 온보딩 최상단에 현재 Google 이메일과 기존 secondary 계정 전환 동선을 표시해 잘못 선택한 계정에서 즉시 로그아웃할 수 있게 했다. 토큰 변경 없음.
- 2026-08-29 · `/teach` 검토 큐와 교수자 요약 카드를 `--sp-3` 간격으로 분리해 두 표면의 위계를 복원했다. 토큰 변경 없음.
- 2026-08-29 · 페이지 탭과 연속 목록 행은 콘텐츠 `Surface`를 사용하지 않는다. 공통 `Tabs`가 ARIA 연결·roving focus·방향키를 소유하고, 페이지 CSS는 투명 배치와 도메인별 trigger 표현만 소유한다. 토큰 변경 없음.
- 2026-08-29 · 사용자 아바타는 안전한 웹 URL을 정상 디코딩한 뒤에만 이미지를 노출한다. 빈 값·금지 scheme·404·디코딩 실패는 모든 셸·설정·온보딩에서 동일한 이니셜 fallback으로 닫힌다. first-party 페르소나 아트는 이 계약의 대상이 아니다.
- 2026-08-30 · 활성 회기의 텍스트 컴포저는 입력창·AI 코칭·전송의 하단선을 공유한다. 반응형 높이 차이는 유지하고, 토큰 변경 없이 중첩 액션 행만 하단 정렬한다.
- 2026-08-31 · `/learn/practice`는 같은 NPC라도 `완전히 새로 시작`과 선택 사례 `이어서 진행`을 별도 native radio로 제공한다. 이어가기에는 사례별 누적 회기·대화 턴·시간을 보이고, 복수 사례는 select로 정확한 case를 고른다. 내담자 기억은 기본 닫힌 native foldout에서만 lazy 로드하며 기존 surface·spacing token을 재사용한다.
- 2026-08-30 · `/learn/session` 시작 화면은 사례 맥락 → 한 가지 첫 발화 초점 → 준비·대화·리뷰·재연습 흐름으로 읽힌다. 기존 1~4개 목표 선택, 처방 재연습, 동의·음성 URL 계약과 실패 폐쇄 동작은 유지하고 새 색·글꼴·장식 모션은 추가하지 않는다.
- 2026-08-30 · 목표 선택은 `핵심 1개 · 보조 0~3개`를 명시하고, 보조 목표를 제거하지 않고 핵심 순서만 바꿀 수 있게 한다. 짧은 데스크톱 높이에서는 같은 선택을 native select로 압축하고 시작 행동을 안전한 sticky bar에 둬 4개 목표와 CTA가 겹치지 않게 한다. 모든 조작은 44px 이상이며 토큰·기존 payload 계약은 유지한다.
- 2026-08-30 · 모바일은 DOM과 같은 사례 → 학습 → 재연습 순서로 읽고, 시작 CTA는 bottom bar와 safe area 위에 고정한다. 키보드 단축키 도움말과 코치 근거/이력은 열 때 포커스를 받고 Tab 순환·닫은 뒤 호출자 복원을 보장한다.
- 2026-08-30 · 공통 셸의 첫 키보드 정지는 `본문으로 건너뛰기`다. 링크는 포커스될 때만 보이고, 어느 역할·화면에서도 식별 가능한 main으로 포커스를 옮긴다.

View file

@ -0,0 +1,157 @@
import { expect, test, type Page } from "@playwright/test";
const PNG_1X1_BASE64 =
"iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mP8z8BQDwAFgwJ/lTQvYwAAAABJRU5ErkJggg==";
function jsonRoute(body: unknown, status = 200) {
return { status, contentType: "application/json", body: JSON.stringify(body) };
}
async function installOnboardingFixtures(page: Page, avatarUrl: string) {
await page.route("**/api/**", (route) =>
route.fulfill(jsonRoute({ detail: "not part of this focused fixture" }, 404)),
);
await page.route("**/api/auth/me", (route) =>
route.fulfill(
jsonRoute({
user_id: "e2e-image-resilience",
email: "avatar.fixture@hs.ac.kr",
role: "learner",
display_name: "온보딩 사용자",
admin_access: false,
super_admin: false,
account_status: "approved",
approval_required: false,
cohort_ids: [],
consent_at: null,
onboarding_completed_at: null,
nickname: "온보딩 사용자",
self_introduction: "",
avatar_url: avatarUrl,
}),
),
);
await page.route("**/api/users/me", (route) =>
route.fulfill(
jsonRoute({
user_id: "e2e-image-resilience",
email: "avatar.fixture@hs.ac.kr",
role: "learner",
display_name: "온보딩 사용자",
legal_name: "",
affiliation: "한신대학교",
department: "",
grade_level: "",
phone: "",
contact_address: "",
nickname: "온보딩 사용자",
self_introduction: "",
avatar_url: avatarUrl,
cohort_ids: [],
}),
),
);
await page.route("**/api/users/legal-docs", (route) =>
route.fulfill(
jsonRoute({
terms: {
kind: "terms",
status: "draft",
title: "서비스 이용약관",
version: "image-resilience-fixture",
body: "테스트 약관",
},
privacy: {
kind: "privacy",
status: "draft",
title: "개인정보 처리방침",
version: "image-resilience-fixture",
body: "테스트 개인정보 처리방침",
},
source_note: "이미지 회복성 전용 fixture",
}),
),
);
}
test.describe("사용자 이미지 회복성", () => {
test("대문자 외부 HTTPS URL도 안전하게 정규화해 실제 이미지로 전환한다", async ({
page,
}) => {
const externalAvatar = "HTTPS://images.example.test/profile/avatar.png";
await installOnboardingFixtures(page, externalAvatar);
await page.route("https://images.example.test/profile/avatar.png", (route) =>
route.fulfill({
status: 200,
contentType: "image/png",
body: Buffer.from(PNG_1X1_BASE64, "base64"),
}),
);
await page.goto("/onboarding");
const preview = page.locator(".ob-avatar__preview");
const image = preview.locator("img");
await expect(image).toBeVisible();
await expect(image).toHaveAttribute(
"src",
"https://images.example.test/profile/avatar.png",
);
await expect(preview.locator("[data-image-fallback]")).toHaveCount(0);
});
test("온보딩 아바타 파일이 404여도 깨진 아이콘 대신 닉네임 이니셜을 표시한다", async ({
page,
}) => {
const staleAvatar = "/uploads/profile-avatars/stale-onboarding-avatar.jpg";
await installOnboardingFixtures(page, staleAvatar);
await page.route("**/api/uploads/profile-avatars/stale-onboarding-avatar.jpg", (route) =>
route.fulfill(jsonRoute({ detail: "Not Found" }, 404)),
);
await page.goto("/onboarding");
await expect(page.getByRole("heading", { name: "가입 정보를 입력합니다." })).toBeVisible();
const preview = page.locator(".ob-avatar__preview");
await expect(preview.locator("[data-image-fallback='failed']")).toHaveText("온");
await expect(preview.locator("img")).toHaveCount(0);
});
test("지연된 이미지 응답 중에도 브라우저의 깨진 이미지 박스를 노출하지 않는다", async ({
page,
}) => {
const delayedAvatar = "/uploads/profile-avatars/delayed-onboarding-avatar.jpg";
let releaseImage: (() => void) | undefined;
const imageGate = new Promise<void>((resolve) => {
releaseImage = resolve;
});
await installOnboardingFixtures(page, delayedAvatar);
await page.route("**/api/uploads/profile-avatars/delayed-onboarding-avatar.jpg", async (route) => {
await imageGate;
await route.fulfill({
status: 200,
contentType: "image/png",
body: Buffer.from(PNG_1X1_BASE64, "base64"),
});
});
await page.goto("/onboarding", { waitUntil: "domcontentloaded" });
const preview = page.locator(".ob-avatar__preview");
await expect(preview.locator("[data-image-fallback='loading']")).toHaveText("온");
const pendingImage = preview.locator("img");
await expect(pendingImage).toHaveAttribute("data-image-state", "loading");
await expect(pendingImage).toBeHidden();
await expect(pendingImage).toHaveCSS("display", "none");
expect(await pendingImage.evaluate((image) => image.getBoundingClientRect().toJSON())).toMatchObject({
width: 0,
height: 0,
});
releaseImage?.();
await expect(pendingImage).toBeVisible();
await expect(pendingImage).toHaveAttribute("data-image-state", "ready");
await expect(preview.locator("[data-image-fallback]")).toHaveCount(0);
});
});

View file

@ -605,10 +605,10 @@ test.describe("layout visual gate @single-run", () => {
timeout: 15_000,
});
const plan = page.locator(".sx-prestart__plan");
await expect(plan).toContainText("시작 과업");
await expect(plan).toContainText("선택 접근");
await expect(plan).toContainText("이번 목표");
await expect(plan).toContainText("운영 기준");
await expect(plan).toContainText("준비");
await expect(plan).toContainText("대화");
await expect(plan).toContainText("리뷰·재연습");
await expect(plan).toContainText("위험 신호는 대화보다 안전 확인을 우선합니다.");
const widths = await page.evaluate(() => {
const head = document.querySelector<HTMLElement>(".sx-page--prestart .sx-head");

View file

@ -1053,8 +1053,9 @@ test.describe("학습자 자기주도 전체 루프 — 실제 src UI / route fi
);
await expect(goals.getByRole("button", { name: /탐색/ })).toHaveAttribute(
"aria-pressed",
"true",
"false",
);
await goals.getByRole("button", { name: /탐색/ }).click();
await goals.getByRole("button", { name: /개입/ }).click();
await expect(goals.getByRole("button", { name: /개입/ })).toHaveAttribute(
"aria-pressed",

View file

@ -279,6 +279,46 @@ async function expectMainControlsUnclipped(page: Page) {
expect(failures, `Main session controls are clipped: ${JSON.stringify(failures)}`).toEqual([]);
}
async function expectComposeControlsBottomAligned(page: Page) {
const result = await page.evaluate(() => {
const selectors = [
".sx-compose textarea",
".sx-coach-trigger-btn",
".sx-compose .vg-btn",
];
const controls = selectors.map((selector) => {
const element = document.querySelector<HTMLElement>(selector);
if (!element) return null;
const rect = element.getBoundingClientRect();
return {
selector,
top: rect.top,
bottom: rect.bottom,
height: rect.height,
};
});
if (controls.some((control) => control === null)) return null;
const resolvedControls = controls as Array<NonNullable<(typeof controls)[number]>>;
const bottoms = resolvedControls.map((control) => control.bottom);
return {
delta: Math.max(...bottoms) - Math.min(...bottoms),
controls: resolvedControls.map((control) => ({
selector: control.selector,
top: Math.round(control.top),
bottom: Math.round(control.bottom),
height: Math.round(control.height),
})),
};
});
expect(result, "Expected text composer controls to be present").not.toBeNull();
expect(
result!.delta,
`Expected text composer control bottoms to align: ${JSON.stringify(result!.controls)}`,
).toBeLessThanOrEqual(1);
}
async function expectRightPanelDoesNotIntersectSessionCore(page: Page) {
const result = await page.evaluate(() => {
const right = document.querySelector<HTMLElement>(".sx-page--active .sx-col-right");
@ -500,6 +540,7 @@ test.describe("learner session full-screen layout", () => {
await expectSessionControlsInsideViewport(page);
await expectNoVisibleSessionPanelOverlap(page);
await expectMainControlsUnclipped(page);
await expectComposeControlsBottomAligned(page);
await expectSessionPageHeightToMatchViewport(page);
await expectActiveSessionUsableLayout(page);
await expectRightPanelDoesNotIntersectSessionCore(page);

View file

@ -689,6 +689,7 @@ test.describe("session persistence", () => {
const persona = await fetchAvailablePersona(page, 1);
await page.goto(`/learn/session/${persona.code}`);
await page.locator("details.sx-prestart__settings > summary").click();
const cbtButton = page.locator(".sx-theory").getByRole("button", { name: /CBT/ });
await expect(cbtButton).toBeVisible();
await cbtButton.click();

View file

@ -394,6 +394,10 @@ test.describe("session review", () => {
growthPoints: [],
degraded: true,
reviewReady: false,
evaluationFailure: {
code: "timeout",
retryable: true,
},
teacherReview: {
status: "pending",
note: "",
@ -440,6 +444,9 @@ test.describe("session review", () => {
page.getByText("저장된 축어록은 확인했지만 deep-loop 평가 AI 산출물을 표시하지 못했습니다. AI 평가 재시도가 필요합니다."),
).toBeVisible();
await expect(page.getByText("engine_error: evaluator timeout")).toHaveCount(0);
await expect(
page.getByText("평가 생성이 제한 시간 안에 끝나지 않았습니다. 축어록은 보존됐으며 다시 시도할 수 있습니다."),
).toBeVisible();
await expect(page.getByRole("button", { name: "AI 평가 재시도" })).toBeVisible();
await expect(page.getByRole("button", { name: "검토 완료" })).toBeDisabled();
@ -474,6 +481,10 @@ test.describe("session review", () => {
growthPoints: [],
degraded: true,
reviewReady: false,
evaluationFailure: {
code: "timeout",
retryable: true,
},
teacherReview: {
status: "pending",
note: "",
@ -503,13 +514,110 @@ test.describe("session review", () => {
await page.getByRole("button", { name: "AI 평가 재시도" }).click();
await expect(
page.getByText("AI 평가 재시도를 완료하지 못했습니다. 잠시 뒤 다시 실행해 주세요."),
page.getByText("AI 평가가 제한 시간 안에 끝나지 않았습니다. 최신 상태를 다시 불러왔습니다."),
).toBeVisible();
await expect(page.getByText("engine_error: retry timeout")).toHaveCount(0);
await expect(page.getByText("평가 실패")).toBeVisible();
await expect(page.getByRole("button", { name: "AI 평가 재시도" })).toBeEnabled();
expect(reevaluateRequests).toBe(1);
expect(reviewRequests).toBe(reviewRequestsBeforeRetry);
await expect.poll(() => reviewRequests).toBeGreaterThan(reviewRequestsBeforeRetry);
});
test("does not offer a futile retry when the evaluation input is too large", async ({ page }) => {
await routeSupervisorCapableLearner(page);
await routePrepostMeasures(page);
const sessionId = "review-failed-input-too-large";
await page.route(`**/api/sessions/${sessionId}/review`, async (route) => {
const ready = filledReviewResponse(sessionId);
await route.fulfill({
status: 200,
contentType: "application/json",
body: JSON.stringify({
...ready,
supervisorState: "평가 실패",
summary:
"저장된 축어록은 확인했지만 deep-loop 평가 AI 산출물을 표시하지 못했습니다. 평가 입력 경로를 조정한 뒤 다시 생성해야 합니다.",
rubric: [],
goodMoments: [],
growthPoints: [],
degraded: true,
reviewReady: false,
evaluationFailure: {
code: "prompt_too_large",
retryable: false,
},
teacherReview: {
status: "pending",
note: "",
reviewedAt: null,
reviewerId: null,
updatedAt: null,
worksheetStatus: "pending",
worksheetNote: "",
worksheetReviewedAt: null,
},
}),
});
});
await page.goto(`/teach/session/${sessionId}/review`);
await openReviewTab(page, "피드백");
await expect(page.getByText("평가 실패")).toBeVisible();
await expect(
page.getByText("평가 입력이 허용 크기를 넘어섰습니다. 같은 재시도 대신 입력 경로를 조정해야 합니다."),
).toBeVisible();
await expect(page.getByRole("button", { name: "AI 평가 재시도" })).toHaveCount(0);
});
test("offers recovery retry for a legacy Windows argv-limit evaluation", async ({ page }) => {
await routeSupervisorCapableLearner(page);
await routePrepostMeasures(page);
const sessionId = "review-legacy-windows-argv-limit";
await page.route(`**/api/sessions/${sessionId}/review`, async (route) => {
const ready = filledReviewResponse(sessionId);
await route.fulfill({
status: 200,
contentType: "application/json",
body: JSON.stringify({
...ready,
supervisorState: "평가 실패",
summary:
"저장된 축어록은 확인했지만 deep-loop 평가 AI 산출물을 표시하지 못했습니다. AI 평가 재시도가 필요합니다.",
rubric: [],
goodMoments: [],
growthPoints: [],
degraded: true,
reviewReady: false,
evaluationFailure: {
code: "legacy_argv_limit",
retryable: true,
},
teacherReview: {
status: "pending",
note: "",
reviewedAt: null,
reviewerId: null,
updatedAt: null,
worksheetStatus: "pending",
worksheetNote: "",
worksheetReviewedAt: null,
},
}),
});
});
await page.goto(`/teach/session/${sessionId}/review`);
await openReviewTab(page, "피드백");
await expect(
page.getByText(
"이전 Windows 입력 한도에 걸린 평가입니다. 축어록은 보존됐으며 현재 입력 경로로 다시 시도할 수 있습니다.",
),
).toBeVisible();
await expect(page.getByRole("button", { name: "AI 평가 재시도" })).toBeVisible();
});
test("renders server review data without legacy transcript fixtures", async ({ page }) => {

View file

@ -0,0 +1,138 @@
import { expect, test, type Locator, type Page } from "@playwright/test";
import { signInAsAdmin, signInAsTeacher } from "./support";
async function expectConnectedTabPanel(tab: Locator, panel: Locator) {
const tabId = await tab.getAttribute("id");
const panelId = await panel.getAttribute("id");
expect(tabId).toBeTruthy();
expect(panelId).toBeTruthy();
await expect(tab).toHaveAttribute("aria-controls", panelId!);
await expect(panel).toHaveAttribute("aria-labelledby", tabId!);
}
async function expectKeyboardSelection(
page: Page,
tablistName: string,
startName: string,
key: "ArrowRight" | "ArrowLeft" | "Home" | "End",
expectedName: string,
) {
const tablist = page.getByRole("tablist", { name: tablistName });
const start = tablist.getByRole("tab", { name: startName });
const expected = tablist.getByRole("tab", { name: expectedName });
const panel = page.getByRole("tabpanel");
await start.focus();
await start.press(key);
await expect(expected).toBeFocused();
await expect(expected).toHaveAttribute("aria-selected", "true");
await expect(expected).toHaveAttribute("tabindex", "0");
await expect(start).toHaveAttribute("tabindex", startName === expectedName ? "0" : "-1");
await expectConnectedTabPanel(expected, panel);
}
test.describe("공통 Tabs behavior", () => {
test("관리자 사용자·접근 권한 탭이 패널 연결과 roving keyboard를 공유한다 @single-run", async ({
page,
}) => {
await signInAsAdmin(page);
await page.goto("/admin/users");
const userTabs = page.getByRole("tablist", { name: "사용자 관리 탭" });
const approval = userTabs.getByRole("tab", { name: /가입 승인/ });
const userPanel = page.getByRole("tabpanel");
await expect(userTabs).toBeVisible();
await expect(userTabs).toHaveAttribute("id", "admin-users-tabs");
await expect(userPanel).toHaveAttribute("id", "admin-users-tabs-panel");
await expect(userTabs).not.toHaveClass(/vg-surface/);
await expectConnectedTabPanel(approval, userPanel);
await expectKeyboardSelection(
page,
"사용자 관리 탭",
"가입 승인",
"ArrowRight",
"사용자 목록",
);
await expectKeyboardSelection(
page,
"사용자 관리 탭",
"사용자 목록",
"End",
"활동 요약",
);
await expectKeyboardSelection(
page,
"사용자 관리 탭",
"활동 요약",
"Home",
"가입 승인",
);
await page.goto("/admin/access");
const accessTabs = page.getByRole("tablist", { name: "접근 권한 탭" });
const roles = accessTabs.getByRole("tab", { name: "역할", exact: true });
const accessPanel = page.getByRole("tabpanel");
await expect(accessTabs).toBeVisible();
await expect(accessTabs).toHaveAttribute("id", "admin-access-tabs");
await expect(accessPanel).toHaveAttribute("id", "admin-access-tabs-panel");
await expect(accessTabs).not.toHaveClass(/vg-surface/);
await expectConnectedTabPanel(roles, accessPanel);
await expectKeyboardSelection(
page,
"접근 권한 탭",
"역할",
"End",
"상담 프로토콜",
);
await expectKeyboardSelection(
page,
"접근 권한 탭",
"상담 프로토콜",
"Home",
"역할",
);
});
test("페르소나 저작 탭이 같은 패널 연결과 방향키 계약을 사용한다 @single-run", async ({
page,
}) => {
await signInAsTeacher(page);
await page.route("**/api/personas", async (route) => {
if (route.request().method() !== "GET") return route.fallback();
await route.fulfill({
status: 200,
contentType: "application/json",
body: JSON.stringify([]),
});
});
await page.route("**/api/personas/review", async (route) => {
if (route.request().method() !== "GET") return route.fallback();
await route.fulfill({
status: 200,
contentType: "application/json",
body: JSON.stringify([]),
});
});
await page.goto("/teach/personas?view=personas&mode=create&step=edit");
const tablist = page.getByRole("tablist", { name: "저작 섹션" });
const overview = tablist.getByRole("tab", { name: "개요", exact: true });
const panel = page.getByRole("tabpanel");
await expect(tablist).toBeVisible();
await expect(tablist).toHaveAttribute("id", "persona-authoring-tabs");
await expect(panel).toHaveAttribute("id", "persona-authoring-tabs-panel");
await expect(tablist).not.toHaveClass(/vg-surface/);
await expectConnectedTabPanel(overview, panel);
await expectKeyboardSelection(
page,
"저작 섹션",
"개요",
"ArrowRight",
"임상",
);
await expectKeyboardSelection(page, "저작 섹션", "임상", "End", "프롬프트");
await expectKeyboardSelection(page, "저작 섹션", "프롬프트", "Home", "개요");
});
});

View file

@ -401,13 +401,23 @@ test.describe("uc learner practice/history", () => {
card.getByRole("button", { name: item.action, exact: true }),
).toBeVisible();
}
// 진행 중 카드에는 보관 버튼이 없고, 종료 카드에는 있다.
await expect(
cards.nth(0).getByRole("button", { name: "보관", exact: true }),
).toHaveCount(0);
await expect(
cards.nth(2).getByRole("button", { name: "보관", exact: true }),
).toBeVisible();
// 진행 중 카드에는 보관·다음 회기 버튼이 없고, 종료 카드에는 있다.
await expect(
cards.nth(0).getByRole("button", { name: "보관", exact: true }),
).toHaveCount(0);
await expect(
cards
.nth(0)
.getByRole("button", { name: "다음 회기 이어가기", exact: true }),
).toHaveCount(0);
await expect(
cards.nth(2).getByRole("button", { name: "보관", exact: true }),
).toBeVisible();
await expect(
cards
.nth(2)
.getByRole("button", { name: "다음 회기 이어가기", exact: true }),
).toBeVisible();
await expect(
cards.nth(3).getByRole("button", { name: "복원", exact: true }),
).toBeVisible();
@ -428,8 +438,8 @@ test.describe("uc learner practice/history", () => {
await expect(page).toHaveURL(new RegExp(`/learn/session/${REV_ID}/review$`));
});
// usecase: 종료된 기록 카드에서 '다시 연습'을 눌러 같은 내담자로 새 회기를 연다.
test("기록 카드의 다시 연습 버튼이 같은 내담자 새 회기로 이동한다", async ({
// usecase: 종료된 기록 카드에서 다음 회기를 열어 같은 내담자의 맥락을 이어간다.
test("종료 기록의 다음 회기 이어가기 버튼이 같은 내담자 새 회기로 이동한다", async ({
page,
}) => {
await installFixtures(page);
@ -438,7 +448,7 @@ test.describe("uc learner practice/history", () => {
const endCard = page.locator(".lh-session-card", { hasText: "김도윤" });
await expect(endCard).toHaveCount(1);
await endCard
.getByRole("button", { name: "다시 연습", exact: true })
.getByRole("button", { name: "다음 회기 이어가기", exact: true })
.click();
await expect(page).toHaveURL(/\/learn\/session\/P2$/);
});

View file

@ -0,0 +1,373 @@
/* =====================================================================
uc-session-case-launch.spec.ts — 새 사례 / 이어서 진행 시작 계약
목적: 같은 NPC라도 학습자가 완전히 새 사례를 시작할지, 기존 사례를
이어갈지 명시적으로 선택한다. 이어가기는 누적 회기·턴·시간을 먼저
보여 주고, 기억 요약은 접힌 상태에서 사용자가 열 때만 요청한다.
전부 route fixture 기반이다. 실제 DB·AI 엔진의 사례 기억 생성은
검증하지 않으며, Home의 URL launch intent와 Session의 POST 계약만
고정한다.
===================================================================== */
import { expect, test, type Page } from "@playwright/test";
const CONTINUE_CASE_ID = "11111111-1111-4111-8111-111111111111";
const PREVIOUS_CASE_ID = "55555555-5555-4555-8555-555555555555";
const FRESH_CASE_ID = "22222222-2222-4222-8222-222222222222";
const CONTINUE_SESSION_ID = "33333333-3333-4333-8333-333333333333";
const FRESH_SESSION_ID = "44444444-4444-4444-8444-444444444444";
function jsonRoute(body: unknown, status = 200) {
return {
status,
contentType: "application/json",
body: JSON.stringify(body),
};
}
const PERSONA = {
code: "P1",
display_name: "민서(청소년 우울)",
difficulty: "hard",
theory_target: ["humanistic"],
demographics: { age_band: "10대" },
presenting_summary: "자퇴와 무기력감을 둘러싼 상담 연습",
voice_preset: "soft-young-fem",
source: "database",
degraded: false,
};
function dashboardFixture() {
return {
message: "학습 현황 요약",
source: "runtime",
overview: {
total_sessions: 3,
active_sessions: 0,
review_ready_sessions: 0,
completed_sessions: 3,
archived_sessions: 0,
learner_turns: 9,
client_turns: 9,
last_practiced_at: "2026-08-31T09:00:00+09:00",
},
growth: {
trend: "insufficient",
avg_rapport: null,
avg_score: null,
evaluated_sessions: 0,
latest_score: null,
first_score: null,
score_delta: null,
top_techniques: [],
points: [],
},
recent_feedback: [],
persona_progress: [],
achievements: [],
};
}
function currentCaseFixture() {
return {
cases: [
{
case_id: CONTINUE_CASE_ID,
persona_code: "P1",
persona_name: "민서",
last_session_no: 3,
progress: {
total_sessions: 3,
completed_sessions: 3,
total_turns: 18,
total_duration_seconds: 5_400,
active_session_id: null,
active_session_no: null,
active_started_at: null,
last_activity_at: "2026-08-31T09:00:00+09:00",
},
},
{
case_id: PREVIOUS_CASE_ID,
persona_code: "P1",
persona_name: "민서",
last_session_no: 2,
progress: {
total_sessions: 2,
completed_sessions: 2,
total_turns: 10,
total_duration_seconds: 3_600,
active_session_id: null,
active_session_no: null,
active_started_at: null,
last_activity_at: "2026-08-20T09:00:00+09:00",
},
},
],
};
}
function memoryFixture() {
return {
case_id: CONTINUE_CASE_ID,
memory_available: true,
latest_session_digest: "지난 회기에서 수면 문제를 먼저 다뤘습니다.",
case_digest: "학업 부담과 무기력의 연결을 탐색 중입니다.",
open_threads: ["수면 리듬을 어떻게 조절할지"],
pinned_facts: ["기말고사 기간에는 불안이 커집니다."],
};
}
interface LaunchFixture {
memoryRequestCount: () => number;
startRequests: Array<Record<string, unknown>>;
}
/** catch-all을 먼저 등록하고, 실제 fixture endpoint를 뒤에 두어 LIFO 우선순위를 고정한다. */
async function installLaunchFixture(page: Page): Promise<LaunchFixture> {
let memoryRequests = 0;
const startRequests: Array<Record<string, unknown>> = [];
await page.route("**/api/**", (route) =>
route.fulfill(jsonRoute({ detail: "not part of this focused fixture" }, 404)),
);
await page.route("**/api/auth/me", (route) =>
route.fulfill(
jsonRoute({
user_id: "aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa",
email: "case.launch@hs.ac.kr",
display_name: "사례 시작 검증 학습자",
role: "learner",
admin_access: false,
super_admin: false,
account_status: "approved",
approval_required: false,
cohort_ids: [],
consent_at: "2026-08-01T00:00:00+09:00",
onboarding_completed_at: "2026-08-01T00:00:00+09:00",
nickname: "사례 시작 검증 학습자",
self_introduction: "",
avatar_url: "",
}),
),
);
await page.route("**/api/personas", (route) => route.fulfill(jsonRoute([PERSONA])));
await page.route("**/api/sessions", async (route) => {
if (route.request().method() !== "POST") {
await route.fallback();
return;
}
const request = (route.request().postDataJSON() ?? {}) as Record<string, unknown>;
startRequests.push(request);
const isFresh = request.start_mode === "fresh";
await route.fulfill(
jsonRoute(
{
session_id: isFresh ? FRESH_SESSION_ID : CONTINUE_SESSION_ID,
case_id: isFresh ? FRESH_CASE_ID : CONTINUE_CASE_ID,
persona_id: "persona-p1",
persona_version: 1,
session_no: isFresh ? 1 : 4,
stage: "라포",
effective_openness: 0.2,
recall_summary: isFresh ? null : "압축된 기존 사례 기억",
degraded: false,
started_at: "2026-08-31T10:00:00+09:00",
goal_stages: request.goal_stages ?? ["라포"],
duration_limit_seconds: 3_600,
warning_before_end_seconds: 600,
learner_feedback_enabled: true,
start_mode: isFresh ? "fresh" : "continue",
},
201,
),
);
});
await page.route("**/api/sessions/dashboard", (route) =>
route.fulfill(jsonRoute(dashboardFixture())),
);
await page.route("**/api/sessions/cases?persona_code=P1", (route) =>
route.fulfill(jsonRoute(currentCaseFixture())),
);
await page.route(`**/api/sessions/cases/${CONTINUE_CASE_ID}/memory`, (route) => {
memoryRequests += 1;
return route.fulfill(jsonRoute(memoryFixture()));
});
await page.route("**/api/users/me/prepost-measures**", (route) =>
route.fulfill(
jsonRoute({
pilot_id: "phase3-pilot-draft",
instrument_version: "fixture",
measures: [],
complete_pre_count: 0,
complete_post_count: 0,
updated_at: null,
}),
),
);
await page.route("**/api/voice/health", (route) =>
route.fulfill(jsonRoute({ available: true, reason: null })),
);
await page.route(`**/api/sessions/${CONTINUE_SESSION_ID}`, (route) =>
route.fulfill(sessionDetailFixture(CONTINUE_SESSION_ID, CONTINUE_CASE_ID, 4)),
);
await page.route(`**/api/sessions/${FRESH_SESSION_ID}`, (route) =>
route.fulfill(sessionDetailFixture(FRESH_SESSION_ID, FRESH_CASE_ID, 1)),
);
await page.route(`**/api/sessions/${CONTINUE_SESSION_ID}/alliance-pulses`, (route) =>
route.fulfill(jsonRoute({ items: [] })),
);
await page.route(`**/api/sessions/${FRESH_SESSION_ID}/alliance-pulses`, (route) =>
route.fulfill(jsonRoute({ items: [] })),
);
await page.route("**/api/sessions/*/live-coach", (route) =>
route.fulfill(
jsonRoute({
source: "database",
quota: { remaining: 3, max: 3 },
credit_events: [],
events: [],
}),
),
);
return { memoryRequestCount: () => memoryRequests, startRequests };
}
function sessionDetailFixture(sessionId: string, caseId: string, sessionNo: number) {
return jsonRoute({
session_id: sessionId,
case_id: caseId,
persona_id: "persona-p1",
persona_version: 1,
persona_code: "P1",
persona_name: "민서",
session_no: sessionNo,
status: "active",
stage: "라포",
theory_mode: "humanistic",
effective_openness: 0.2,
started_at: "2026-08-31T10:00:00+09:00",
ended_at: null,
review_ready: false,
turns: [],
goal_stages: ["라포"],
duration_limit_seconds: 3_600,
warning_before_end_seconds: 600,
progress: null,
});
}
function launchButton(page: Page, label: string) {
return page
.locator(".lh-actions")
.getByRole("button", { name: label, exact: true })
.last();
}
function launchModeLabel(page: Page, label: string) {
return page.locator(".lh-launch-mode label").filter({ hasText: label });
}
test.describe("uc session case launch", () => {
test("이어가기 통계와 접힌 기억을 확인하고 두 방식의 launch URL을 구분한다", async ({
page,
}) => {
const fixture = await installLaunchFixture(page);
await page.goto("/learn/practice");
const freshMode = page.getByRole("radio", { name: "완전히 새로 시작" });
const continueMode = page.getByRole("radio", { name: "이어서 진행" });
const continuity = page.locator(".lh-continuity");
// 기본은 새 사례다. 기존 기억 endpoint는 foldout을 열기 전까지 요청하지 않는다.
await expect(freshMode).toBeChecked();
await expect(continuity).toContainText("새 사례");
await expect(continuity.locator("details.lh-continuity__memory")).toHaveCount(0);
expect(fixture.memoryRequestCount()).toBe(0);
await expect(continueMode).toBeEnabled();
await launchModeLabel(page, "이어서 진행").click();
await expect(continueMode).toBeChecked();
await expect(continuity).toContainText("다음 4회기");
await expect(continuity).toContainText("3회기");
await expect(continuity).toContainText("18턴");
await expect(continuity).toContainText("1시간 30분");
const memory = continuity.locator("details.lh-continuity__memory");
await expect(memory).not.toHaveAttribute("open", "");
expect(fixture.memoryRequestCount()).toBe(0);
await memory.locator("summary").click();
await expect(memory).toHaveAttribute("open", "");
await expect(memory).toContainText("지난 회기에서 수면 문제를 먼저 다뤘습니다.");
await expect(memory).toContainText("수면 리듬을 어떻게 조절할지");
await expect.poll(fixture.memoryRequestCount).toBe(1);
await launchButton(page, "이어서 진행").click();
await expect(page).toHaveURL(
new RegExp(`/learn/session/P1\\?continuity=continue&case=${CONTINUE_CASE_ID}$`),
);
await page.goBack();
await expect(page.locator(".lh-continuity")).toBeVisible();
await launchModeLabel(page, "완전히 새로 시작").click();
await expect(freshMode).toBeChecked();
await expect(continuity.locator("details.lh-continuity__memory")).toHaveCount(0);
await launchButton(page, "완전히 새로 시작").click();
await expect(page).toHaveURL(/\/learn\/session\/P1\?continuity=fresh$/);
});
test("복수의 종료 사례에서는 고른 사례의 통계와 exact case URL을 사용한다", async ({
page,
}) => {
await installLaunchFixture(page);
await page.goto("/learn/practice");
await launchModeLabel(page, "이어서 진행").click();
const continuity = page.locator(".lh-continuity");
const caseSelect = continuity.getByRole("combobox", {
name: "이어서 진행할 사례",
});
await expect(caseSelect).toHaveValue(CONTINUE_CASE_ID);
await caseSelect.selectOption(PREVIOUS_CASE_ID);
await expect(caseSelect).toHaveValue(PREVIOUS_CASE_ID);
await expect(continuity).toContainText("다음 3회기");
await expect(continuity).toContainText("2회기");
await expect(continuity).toContainText("10턴");
await expect(continuity).toContainText("1시간");
await launchButton(page, "이어서 진행").click();
await expect(page).toHaveURL(
new RegExp(`/learn/session/P1\\?continuity=continue&case=${PREVIOUS_CASE_ID}$`),
);
});
for (const launch of [
{
label: "새 사례",
search: "?continuity=fresh",
expected: { start_mode: "fresh", case_id: null },
},
{
label: "이어서 진행",
search: `?continuity=continue&case=${CONTINUE_CASE_ID}`,
expected: { start_mode: "continue", case_id: CONTINUE_CASE_ID },
},
]) {
test(`${launch.label} 선택값을 회기 시작 POST 본문으로 전달한다`, async ({ page }) => {
const fixture = await installLaunchFixture(page);
await page.goto(`/learn/session/P1${launch.search}`);
await expect(page.locator(".sx-page--prestart")).toBeVisible();
await page.getByRole("button", { name: "회기 시작", exact: true }).click();
await expect.poll(() => fixture.startRequests.length).toBe(1);
expect(fixture.startRequests[0]).toMatchObject({
persona_code: "P1",
...launch.expected,
});
});
}
});

View file

@ -0,0 +1,135 @@
/* =====================================================================
uc-session-continuity-guard.spec.ts — 같은 내담자 활성 회기 보호
목적: 종료된 회기가 아닌 같은 내담자의 진행 중 회기가 있을 때 새 회기를
중복 생성하지 않고, 서버가 돌려준 기존 회기로 학습자를 이동시킨다.
모든 응답은 route fixture이며 실제 AI 엔진/DB를 쓰지 않는다.
===================================================================== */
import { expect, test, type Page } from "@playwright/test";
const ACTIVE_SESSION_ID = "77777777-7777-4777-8777-777777777777";
function jsonRoute(body: unknown, status = 200) {
return {
status,
contentType: "application/json",
body: JSON.stringify(body),
};
}
async function installFixture(page: Page) {
let startAttempts = 0;
await page.route("**/api/**", (route) =>
route.fulfill(jsonRoute({ detail: "not part of this focused fixture" }, 404)),
);
await page.route("**/api/auth/me", (route) =>
route.fulfill(
jsonRoute({
user_id: "00000000-0000-0000-0000-00000uccg301",
email: "continuity.guard@hs.ac.kr",
display_name: "연속성 검증 학습자",
role: "learner",
admin_access: false,
super_admin: false,
account_status: "approved",
approval_required: false,
cohort_ids: [],
consent_at: Math.floor(Date.now() / 1000),
onboarding_completed_at: Math.floor(Date.now() / 1000),
nickname: "연속성 검증 학습자",
self_introduction: "",
avatar_url: "",
}),
),
);
await page.route("**/api/personas", (route) =>
route.fulfill(
jsonRoute([
{
code: "P1",
display_name: "민서(청소년 우울)",
difficulty: "hard",
theory_target: ["humanistic"],
demographics: { age_band: "10대" },
presenting_summary: "자퇴와 무기력감을 둘러싼 상담 연습",
voice_preset: "soft-young-fem",
source: "database",
degraded: false,
},
]),
),
);
await page.route("**/api/users/me/prepost-measures**", (route) =>
route.fulfill(
jsonRoute({
pilot_id: "phase3-pilot-draft",
instrument_version: "test",
measures: [],
complete_pre_count: 0,
complete_post_count: 0,
updated_at: null,
}),
),
);
await page.route("**/api/sessions", async (route) => {
if (route.request().method() !== "POST") {
await route.fallback();
return;
}
startAttempts += 1;
await route.fulfill(
jsonRoute(
{
detail: {
code: "active_session_exists",
session_id: ACTIVE_SESSION_ID,
},
},
409,
),
);
});
await page.route(`**/api/sessions/${ACTIVE_SESSION_ID}`, (route) =>
route.fulfill(
jsonRoute({
session_id: ACTIVE_SESSION_ID,
case_id: "uc-continuity-case-001",
persona_code: "P1",
persona_name: "민서",
session_no: 1,
status: "active",
stage: "라포",
theory_mode: "humanistic",
effective_openness: 0.21,
started_at: new Date().toISOString(),
ended_at: null,
review_ready: false,
turns: [],
goal_stages: ["라포"],
progress: null,
duration_limit_seconds: 3600,
warning_before_end_seconds: 600,
}),
),
);
return { startAttempts: () => startAttempts };
}
test.describe("uc session continuity guard", () => {
test("같은 내담자의 활성 회기 충돌은 기존 회기로 이어간다", async ({ page }) => {
const fixture = await installFixture(page);
await page.goto("/learn/session/P1");
await expect(page.locator(".sx-page--prestart")).toBeVisible();
await page.getByRole("button", { name: "회기 시작" }).click();
await expect(page).toHaveURL(
new RegExp(`/learn/session/${ACTIVE_SESSION_ID}$`),
);
await expect(page.getByText("민서").first()).toBeVisible();
expect(fixture.startAttempts()).toBe(1);
});
});

View file

@ -471,6 +471,34 @@ test.describe("회기 대화 — 텍스트 턴과 SSE 스트림", () => {
).toBeVisible();
expect(stream.texts[0]).toHaveLength(2000);
expect(stream.texts[0]).toBe(longText);
const bubbleMetrics = await learnerUtterance(page)
.locator(".sx-utt__line")
.evaluate((element) => {
const bubble = element as HTMLElement;
const utterance = bubble.closest<HTMLElement>(".sx-utt");
const body = bubble.closest<HTMLElement>(".sx-utt__body");
if (!utterance || !body) return null;
const controls = Array.from(body.children).filter((child) => child !== bubble);
const controlWidth = controls.reduce(
(total, child) => total + (child as HTMLElement).getBoundingClientRect().width,
0,
);
const gap = Number.parseFloat(getComputedStyle(body).gap) || 0;
return {
availableWidth:
utterance.getBoundingClientRect().width - controlWidth - gap * controls.length,
bubbleWidth: bubble.getBoundingClientRect().width,
bubbleClientWidth: bubble.clientWidth,
bubbleScrollWidth: bubble.scrollWidth,
};
});
expect(bubbleMetrics).not.toBeNull();
expect(bubbleMetrics!.bubbleWidth).toBeGreaterThanOrEqual(bubbleMetrics!.availableWidth - 1);
expect(bubbleMetrics!.bubbleScrollWidth).toBeLessThanOrEqual(bubbleMetrics!.bubbleClientWidth + 1);
await expectNoHorizontalOverflow(page);
});

View file

@ -255,69 +255,75 @@ test.describe("usecase — 회기 사전 설정(목표 선택) 여정", () => {
}
});
// usecase: 학습자가 기본 선택된 회기 설정 요약(이론모드·목표)을 읽는다
test("기본 회기 설정 요약이 인간중심 이론과 라포·탐색 목표를 보여준다", async ({
// usecase: 학습자가 기본 회기 설정 요약과 첫 발화의 한 가지 초점을 읽는다
test("기본 회기 설정 요약이 인간중심 이론과 라포 핵심 초점을 보여준다", async ({
page,
}, testInfo) => {
}) => {
await routePrestartFixture(page);
await gotoPrestart(page);
const settingsSummary = page.locator("details.sx-prestart__settings > summary");
await expect(settingsSummary).toContainText("인간중심, 라포 · 탐색");
await expect(settingsSummary).toContainText("인간중심 · 라포");
await expect(page.locator("details.sx-prestart__settings")).not.toHaveAttribute("open", "");
const goals = goalsGroup(page);
await expect(goals.getByRole("button", { name: /라포/ })).toHaveAttribute(
"aria-pressed",
"true",
);
await expect(goals.getByRole("button", { name: /탐색/ })).toHaveAttribute(
"aria-pressed",
"true",
);
await expect(goals.getByRole("button", { name: /탐색/ })).toHaveAttribute("aria-pressed", "false");
await expect(goals.getByRole("button", { name: /개입/ })).toHaveAttribute(
"aria-pressed",
"false",
);
if (!testInfo.project.name.includes("mobile")) {
const plan = page.locator(".sx-prestart__plan");
await expect(plan).toContainText("2개 선택");
await expect(plan).toContainText("라포 · 탐색");
await expect(plan).toContainText("60분 회기");
await expect(plan).toContainText("종료 10분 전 알림");
}
const plan = page.locator(".sx-prestart__plan");
await expect(plan).toContainText("준비");
await expect(plan).toContainText("대화");
await expect(plan).toContainText("리뷰·재연습");
await expect(plan).toContainText("라포에 집중");
});
// usecase: 키보드 사용자는 전역 탐색을 지나 곧바로 회기 준비 본문으로 이동한다.
test("첫 Tab의 본문 건너뛰기가 회기 준비 본문에 포커스를 둔다", async ({ page }) => {
await routePrestartFixture(page);
await gotoPrestart(page);
const skipLink = page.getByRole("link", { name: "본문으로 건너뛰기" });
await page.keyboard.press("Tab");
await expect(skipLink).toBeFocused();
await expect(skipLink).toBeVisible();
await skipLink.press("Enter");
await expect(page.locator("main#vg-main-content")).toBeFocused();
});
// usecase: 학습자가 목표를 전부 해제해 보면 시작 버튼이 잠기고 안내를 받는다
test("목표를 모두 해제하면 회기 시작이 차단되고 선택 안내가 남는다", async ({
page,
}, testInfo) => {
}) => {
await routePrestartFixture(page);
await gotoPrestart(page);
const goals = goalsGroup(page);
await expect(startButton(page)).toBeEnabled();
await goals.getByRole("button", { name: /라포/ }).click();
await goals.getByRole("button", { name: /탐색/ }).click();
await expect(goals.getByRole("button", { name: /라포/ })).toHaveAttribute(
"aria-pressed",
"false",
);
await expect(goals.getByRole("button", { name: /탐색/ })).toHaveAttribute(
"aria-pressed",
"false",
);
await expect(startButton(page)).toBeDisabled();
await expect(
page.locator("details.sx-prestart__settings > summary"),
).toContainText("목표 선택 필요");
if (!testInfo.project.name.includes("mobile")) {
await expect(
page.getByText("이번 회기 목표를 1개 이상 선택하면 시작할 수 있어요."),
).toBeVisible();
await expect(page.locator(".sx-prestart__plan")).toContainText("선택 필요");
}
).toContainText("핵심 초점 선택 필요");
await expect(page.getByRole("heading", { name: "초점 선택 필요" })).toBeVisible();
await expect(page.locator(".sx-prestart__plan")).toContainText(
"목표 하나를 고르면 첫 발화의 기준이 여기에 표시됩니다.",
);
await expect(
page.getByText("오늘의 핵심 초점을 1개 이상 선택하면 시작할 수 있어요."),
).toBeVisible();
});
// usecase: 목표 0개 상태에서 학습자가 목표 하나를 고르면 다시 시작할 수 있다
@ -327,7 +333,6 @@ test.describe("usecase — 회기 사전 설정(목표 선택) 여정", () => {
const goals = goalsGroup(page);
await goals.getByRole("button", { name: /라포/ }).click();
await goals.getByRole("button", { name: /탐색/ }).click();
await expect(startButton(page)).toBeDisabled();
await goals.getByRole("button", { name: /개입/ }).click();
@ -338,11 +343,11 @@ test.describe("usecase — 회기 사전 설정(목표 선택) 여정", () => {
await expect(startButton(page)).toBeEnabled();
await expect(
page.locator("details.sx-prestart__settings > summary"),
).toContainText("인간중심, 개입");
).toContainText("인간중심 · 개입");
});
// usecase: 학습자가 네 단계 목표를 전부 선택한다 — 선택지는 4개가 전부라 초과 선택은 불가능하다
test("목표 4개를 모두 선택할 수 있고 선택지는 4개가 전부다", async ({ page }, testInfo) => {
test("목표 4개를 모두 선택할 수 있고 선택지는 4개가 전부다", async ({ page }) => {
await routePrestartFixture(page);
await gotoPrestart(page);
@ -351,6 +356,7 @@ test.describe("usecase — 회기 사전 설정(목표 선택) 여정", () => {
// 회기 단계는 라포·탐색·개입·정리 4개뿐 — 4개 초과 선택 자체가 불가능한 UI 계약.
await expect(goalButtons).toHaveCount(4);
await goals.getByRole("button", { name: /탐색/ }).click();
await goals.getByRole("button", { name: /개입/ }).click();
await goals.getByRole("button", { name: /정리/ }).click();
for (const name of [/라포/, /탐색/, /개입/, /정리/]) {
@ -363,9 +369,114 @@ test.describe("usecase — 회기 사전 설정(목표 선택) 여정", () => {
page.locator("details.sx-prestart__settings > summary"),
).toContainText("라포 · 탐색 · 개입 · 정리");
await expect(startButton(page)).toBeEnabled();
if (!testInfo.project.name.includes("mobile")) {
await expect(page.locator(".sx-prestart__plan")).toContainText("4개 선택");
}
});
// usecase: 보조 목표가 생겨도 '먼저 선택한 것'에 묶이지 않고, 학습자가 핵심 초점을 명시적으로 바꾼다.
test("보조 목표를 핵심 초점으로 바꾸면 저장 순서도 함께 바뀐다", async ({ page }) => {
const fixture = await routePrestartFixture(page);
await gotoPrestart(page);
const goals = goalsGroup(page);
await goals.getByRole("button", { name: /탐색/ }).click();
const primarySwitch = page.getByRole("group", { name: "핵심 초점 바꾸기" });
await expect(page.locator(".sx-prestart__primary-switch")).toContainText("보조 목표");
await primarySwitch.getByRole("button", { name: "탐색을 핵심 초점으로 설정" }).click();
await expect(page.locator(".sx-prestart__focus").getByRole("heading")).toHaveText("탐색");
await expect(
page.locator("details.sx-prestart__settings > summary"),
).toContainText("인간중심 · 탐색 · 라포");
await startButton(page).click();
expect(fixture.startRequests).toHaveLength(1);
expect(fixture.startRequests[0]).toMatchObject({ goal_stages: ["탐색", "라포"] });
});
// usecase: 높이가 짧은 데스크톱에서도 1~4개 목표의 핵심 전환과 시작 행동이 서로 가려지지 않는다.
test("짧은 데스크톱에서 4개 목표와 회기 시작 행동이 겹치지 않는다", async ({ page }, testInfo) => {
test.skip(testInfo.project.name.includes("mobile"), "데스크톱 중앙 열의 짧은 높이 회귀를 검증한다.");
await page.setViewportSize({ width: 1280, height: 720 });
const fixture = await routePrestartFixture(page);
await gotoPrestart(page);
const goals = goalsGroup(page);
await goals.getByRole("button", { name: /탐색/ }).click();
await goals.getByRole("button", { name: /개입/ }).click();
await goals.getByRole("button", { name: /정리/ }).click();
// 짧은 높이에서는 세 개의 큰 보조 버튼 대신 같은 선택지를 가진 native select를 쓴다.
const compactPrimarySelect = page.locator(".sx-prestart__primary-select select");
await expect(compactPrimarySelect).toBeVisible();
await compactPrimarySelect.selectOption("탐색");
await expect(page.locator(".sx-prestart__focus").getByRole("heading")).toHaveText("탐색");
const geometry = await page.evaluate(() => {
const main = document.querySelector<HTMLElement>(".vg-main");
const actions = document.querySelector<HTMLElement>(".sx-prestart__actions");
const cta = actions?.querySelector<HTMLElement>(".vg-btn");
const primaryControl = document.querySelector<HTMLElement>(".sx-prestart__primary-select select");
if (!main || !actions || !cta || !primaryControl) throw new Error("prestart geometry targets missing");
main.scrollTo({ top: 0 });
const rect = (element: HTMLElement) => {
const { top, bottom } = element.getBoundingClientRect();
return { top, bottom };
};
return {
main: rect(main),
actions: rect(actions),
cta: rect(cta),
primaryControl: rect(primaryControl),
hasHorizontalOverflow: document.documentElement.scrollWidth > window.innerWidth,
};
});
expect(geometry.cta.bottom).toBeLessThanOrEqual(geometry.main.bottom);
expect(geometry.primaryControl.bottom).toBeLessThanOrEqual(geometry.actions.top);
expect(geometry.hasHorizontalOverflow).toBe(false);
await startButton(page).click();
expect(fixture.startRequests).toHaveLength(1);
expect(fixture.startRequests[0]).toMatchObject({
goal_stages: ["탐색", "라포", "개입", "정리"],
});
});
// usecase: 모바일에서는 읽는 순서와 bottom bar 위의 시작 행동을 동시에 보장한다.
test("모바일에서 사례·학습·재연습 순서와 시작 CTA 안전 간격을 지킨다", async ({ page }, testInfo) => {
test.skip(!testInfo.project.name.includes("mobile"), "모바일 문서 순서와 bottom bar 관계를 검증한다.");
await routePrestartFixture(page);
await gotoPrestart(page);
const geometry = await page.evaluate(() => {
const main = document.querySelector<HTMLElement>(".vg-main");
const caseCard = document.querySelector<HTMLElement>(".sx-prestart__visual");
const learning = document.querySelector<HTMLElement>(".sx-prestart__learning");
const map = document.querySelector<HTMLElement>(".sx-prestart__plan");
const actions = document.querySelector<HTMLElement>(".sx-prestart__actions");
const cta = actions?.querySelector<HTMLElement>(".vg-btn");
const bottomNav = document.querySelector<HTMLElement>('nav[aria-label="주 메뉴"]');
if (!main || !caseCard || !learning || !map || !actions || !cta || !bottomNav) {
throw new Error("mobile prestart geometry targets missing");
}
main.scrollTo({ top: 0 });
const rect = (element: HTMLElement) => {
const { top, bottom } = element.getBoundingClientRect();
return { top, bottom };
};
return {
caseCard: rect(caseCard),
learning: rect(learning),
map: rect(map),
actions: rect(actions),
cta: rect(cta),
bottomNav: rect(bottomNav),
hasHorizontalOverflow: document.documentElement.scrollWidth > window.innerWidth,
};
});
expect(geometry.caseCard.top).toBeLessThan(geometry.learning.top);
expect(geometry.learning.top).toBeLessThan(geometry.map.top);
expect(geometry.cta.bottom).toBeLessThanOrEqual(geometry.bottomNav.top - 8);
expect(geometry.hasHorizontalOverflow).toBe(false);
});
// usecase: 학습자가 선택돼 있던 목표 하나를 다시 눌러 해제한다
@ -375,13 +486,16 @@ test.describe("usecase — 회기 사전 설정(목표 선택) 여정", () => {
const goals = goalsGroup(page);
const exploreGoal = goals.getByRole("button", { name: /탐색/ });
await expect(exploreGoal).toHaveAttribute("aria-pressed", "false");
await exploreGoal.click();
await expect(exploreGoal).toHaveAttribute("aria-pressed", "true");
await exploreGoal.click();
await expect(exploreGoal).toHaveAttribute("aria-pressed", "false");
await expect(
page.locator("details.sx-prestart__settings > summary"),
).toContainText("인간중심, 라포");
).toContainText("인간중심 · 라포");
// 나머지 기본 목표는 그대로 유지된다.
await expect(goals.getByRole("button", { name: /라포/ })).toHaveAttribute(
"aria-pressed",
@ -393,10 +507,11 @@ test.describe("usecase — 회기 사전 설정(목표 선택) 여정", () => {
// usecase: 학습자가 이론모드를 CBT로 바꿔 회기 접근을 조정한다
test("이론모드를 CBT로 바꾸면 선택 상태와 진행 초점이 갱신된다", async ({
page,
}, testInfo) => {
}) => {
await routePrestartFixture(page);
await gotoPrestart(page);
await page.locator("details.sx-prestart__settings > summary").click();
const theory = page.getByRole("group", { name: "이론모드 선택" });
await expect(theory.getByRole("button", { name: /인간중심/ })).toHaveAttribute(
"aria-pressed",
@ -414,12 +529,10 @@ test.describe("usecase — 회기 사전 설정(목표 선택) 여정", () => {
);
await expect(
page.locator("details.sx-prestart__settings > summary"),
).toContainText("CBT, 라포 · 탐색");
if (!testInfo.project.name.includes("mobile")) {
await expect(page.locator(".sx-prestart__plan")).toContainText(
"상황·생각·감정·행동의 연결을 한 단계씩 확인합니다.",
);
}
).toContainText("CBT · 라포");
await expect(page.locator(".sx-prestart__settings-note")).toContainText(
"상황·생각·감정·행동의 연결을 한 단계씩 확인합니다.",
);
});
// usecase: 학습자가 회기 시작을 눌러 active 회기로 넘어간다 — 고른 목표·이론이 요청에 실린다
@ -429,8 +542,7 @@ test.describe("usecase — 회기 사전 설정(목표 선택) 여정", () => {
const fixture = await routePrestartFixture(page);
await gotoPrestart(page);
// 기본 선택에서 탐색을 해제해 라포 1개만 목표로 남긴다(자유 선택 검증).
await goalsGroup(page).getByRole("button", { name: /탐색/ }).click();
// 기본 선택인 라포 한 가지 초점으로 시작한다.
await startButton(page).click();
await expect(page.locator(".sx-page.sx-page--active")).toBeVisible();
@ -465,6 +577,29 @@ test.describe("usecase — 회기 사전 설정(목표 선택) 여정", () => {
await expect(startButton(page)).toBeEnabled();
});
// usecase: 단축키 도움말은 모달 선언과 같은 포커스 규칙을 지키며, 닫으면 호출자로 돌아간다.
test("단축키 도움말은 포커스를 가두고 닫으면 시작 행동으로 돌려준다", async ({ page }) => {
await routePrestartFixture(page);
await gotoPrestart(page);
const start = startButton(page);
await start.focus();
await expect(start).toBeFocused();
// Playwright에서는 punctuation chord보다 명시한 Ctrl+/ 계약이 키보드 레이아웃에 독립적이다.
await start.press("Control+/");
const dialog = page.getByRole("dialog", { name: "키보드 단축키 안내" });
const confirm = dialog.getByRole("button", { name: "확인 (Esc)" });
await expect(dialog).toBeVisible();
await expect(confirm).toBeFocused();
await page.keyboard.press("Tab");
await expect(confirm).toBeFocused();
await page.keyboard.press("Escape");
await expect(dialog).toHaveCount(0);
await expect(start).toBeFocused();
});
// usecase: 리뷰 처방(G4 deliberate)에서 넘어온 학습자가 처방 맥락을 프리스타트에서 확인한다
test("G4 처방 연습 launch intent가 프리스타트에 난도 사다리 맥락으로 표시된다", async ({
page,

View file

@ -141,6 +141,14 @@ async function mountSettingsFixtures(
await routeUnmockedApi(page);
await page.route("**/api/static/avatars/*.png", (route) =>
route.fulfill({
status: 200,
contentType: "image/png",
body: Buffer.from(PNG_1X1_BASE64, "base64"),
}),
);
await page.route("**/api/auth/me", (route) =>
route.fulfill(
jsonRoute({
@ -471,6 +479,44 @@ test.describe("설정·동의 관리 유스케이스", () => {
await expect(account.locator(".vg-set__saved")).toHaveCount(0);
});
// usecase: DB에 남은 아바타 경로의 실제 파일이 사라져 404여도 깨진 이미지 아이콘 대신 이니셜을 유지한다
test("아바타 파일 404 시 톱바와 설정 미리보기 모두 이니셜 폴백을 유지한다", async ({ page }) => {
const staleAvatar = "/uploads/profile-avatars/stale-avatar.jpg";
await mountSettingsFixtures(page, { avatarUrl: staleAvatar });
await page.route("**/api/uploads/profile-avatars/stale-avatar.jpg", (route) =>
route.fulfill(jsonRoute({ detail: "Not Found" }, 404)),
);
await openLoadedSettings(page);
const avatarFrames = page.locator(
".vg-topbar__avatar, .vg-set__rail-avatar, .vg-set__avatar",
);
await expect(avatarFrames).toHaveCount(3);
for (const frame of await avatarFrames.all()) {
await expect(frame.locator("[data-image-fallback='failed']")).toHaveText("설");
await expect(frame.locator("img")).toHaveCount(0);
}
});
// usecase: 저장값이 웹 이미지가 아닌 scheme이면 요청하지 않고 즉시 안전한 이니셜 상태로 닫힌다
test("빈 URL과 비웹 scheme은 네트워크 요청 없이 이니셜 폴백으로 정규화한다", async ({ page }) => {
let unsafeRequestCount = 0;
page.on("request", (request) => {
if (/javascript:|data:|file:/i.test(request.url())) unsafeRequestCount += 1;
});
await mountSettingsFixtures(page, { avatarUrl: " javascript:alert(1) " });
await openLoadedSettings(page);
const avatarFrames = page.locator(
".vg-topbar__avatar, .vg-set__rail-avatar, .vg-set__avatar",
);
for (const frame of await avatarFrames.all()) {
await expect(frame.locator("[data-image-fallback='empty']")).toHaveText("설");
await expect(frame.locator("img")).toHaveCount(0);
}
expect(unsafeRequestCount).toBe(0);
});
// usecase: 학습자가 표시 이름을 빈값으로 저장 시도했다가 서버 거절을 받는다
test("표시 이름을 빈값으로 저장하면 거짓 저장됨 표시 없이 입력 상태가 유지된다", async ({
page,

View file

@ -20,17 +20,23 @@ function countRawColors(source) {
const shellPath = "src/components/shell/shell.css";
const surfacePath = "src/components/ui/ui.css";
const tabsPath = "src/components/ui/Tabs.tsx";
const settingsPath = "src/pages/settings/settings.css";
const sessionPath = "src/pages/Session.tsx";
const learnerHomePath = "src/pages/LearnerHome.tsx";
const adminPath = "src/pages/Admin.tsx";
const personaStudioPath = "src/pages/PersonaStudio.tsx";
const personaViewModelPath = "src/lib/personaViewModel.ts";
const appPath = "src/App.tsx";
const designDocPath = "../../docs/DESIGN_CONCEPT.md";
const shell = await read(shellPath);
const surface = await read(surfacePath);
const tabs = await read(tabsPath);
const settings = await read(settingsPath);
const session = await read(sessionPath);
const learnerHome = await read(learnerHomePath);
const admin = await read(adminPath);
const personaStudio = await read(personaStudioPath);
const personaViewModel = await read(personaViewModelPath);
const app = await read(appPath);
const designDoc = await read(designDocPath);
@ -95,6 +101,26 @@ forbid(
/#[0-9a-f]{3,8}|rgba?\(/i,
"공통 UI 색은 tokens.css 의미 토큰으로만 표현해야 합니다",
);
forbid(
tabsPath,
tabs,
/surfaceClassName|vg-surface/,
"Tabs behavior primitive는 콘텐츠 Surface를 만들면 안 됩니다",
);
for (const required of [
'role="tablist"',
'role="tab"',
"aria-controls",
"aria-labelledby",
"tabIndex",
'"ArrowRight"',
'"Home"',
'"End"',
]) {
if (!tabs.includes(required)) {
failures.push(`${tabsPath}: Tabs 접근성 계약 누락 (${required})`);
}
}
forbid(
shellPath,
shell,
@ -113,6 +139,21 @@ forbid(
/#[0-9a-f]{3,8}|rgba?\(/i,
"학습자 화면의 아바타 팔레트는 personaViewModel SSOT를 우회하면 안 됩니다",
);
for (const [relativePath, source, className, owner] of [
[adminPath, admin, "vgops-tabs", "관리자 탭 목록"],
[personaStudioPath, personaStudio, "ps-tabs", "페르소나 제작 탭 목록"],
[adminPath, admin, "vgops-approval", "가입 승인 연속 목록 행"],
[adminPath, admin, "vgops-ticket", "지원 티켓 연속 목록 행"],
]) {
forbid(
relativePath,
source,
new RegExp(
`surfaceClassName\\(["'](?:[^"']*\\s)?${className}(?:\\s[^"']*)?["']`,
),
`${owner}은 콘텐츠 Surface가 아니라 공통 컨트롤 또는 외곽 목록 프레임이 소유해야 합니다`,
);
}
forbid(
settingsPath,
settings,

View file

@ -0,0 +1,106 @@
import { useEffect, useState, type ImgHTMLAttributes, type ReactNode } from "react";
import { apiUrl } from "../../lib/api";
const CONTROL_CHARACTER = /[\u0000-\u001F\u007F]/;
const EXPLICIT_SCHEME = /^([a-z][a-z\d+.-]*):/i;
const SAFE_IMAGE_PROTOCOLS = new Set(["http:", "https:"]);
/**
* API 상대경로와 외부 http(s) 이미지만 브라우저가 읽을 수 있는 절대 URL로 정규화한다.
* 빈 값, 제어문자, 자격 증명 내장 URL, data/javascript/file 등 비웹 scheme은 실패 폐쇄한다.
*/
export function normalizeImageSource(source?: string | null): string {
const value = (source ?? "").trim();
if (!value || CONTROL_CHARACTER.test(value)) return "";
const scheme = EXPLICIT_SCHEME.exec(value)?.[1]?.toLowerCase();
if (scheme && scheme !== "http" && scheme !== "https") return "";
try {
const browserOrigin =
typeof window === "undefined" ? "http://localhost" : window.location.origin;
const candidate = scheme
? value
: value.startsWith("//")
? `${typeof window === "undefined" ? "https:" : window.location.protocol}${value}`
: apiUrl(value);
const parsed = new URL(candidate, browserOrigin);
if (!SAFE_IMAGE_PROTOCOLS.has(parsed.protocol)) return "";
if (parsed.username || parsed.password) return "";
return parsed.href;
} catch {
return "";
}
}
export interface ResilientImageProps
extends Omit<
ImgHTMLAttributes<HTMLImageElement>,
"alt" | "onError" | "onLoad" | "src"
> {
src?: string | null;
/** 장식 이미지면 빈 문자열. 의미가 있으면 구체적인 대체 텍스트. */
alt: string;
fallback: ReactNode;
}
/**
* 성공적으로 디코딩되기 전까지 fallback을 유지해 깨진 이미지 아이콘을 노출하지 않는다.
* src가 바뀌면 새 URL을 다시 시도하고, 같은 실패 URL은 재렌더링마다 재요청하지 않는다.
*/
export function ResilientImage({
src,
alt,
fallback,
decoding = "async",
style,
...imageProps
}: ResilientImageProps) {
const normalizedSrc = normalizeImageSource(src);
const [loadedSrc, setLoadedSrc] = useState("");
const [failedSrc, setFailedSrc] = useState("");
useEffect(() => {
setLoadedSrc("");
setFailedSrc("");
}, [normalizedSrc]);
const failed = Boolean(normalizedSrc) && failedSrc === normalizedSrc;
const loaded = Boolean(normalizedSrc) && loadedSrc === normalizedSrc && !failed;
const fallbackState = !normalizedSrc ? "empty" : failed ? "failed" : "loading";
return (
<>
{!loaded ? (
<span
data-image-fallback={fallbackState}
role={alt ? "img" : undefined}
aria-label={alt || undefined}
aria-hidden={alt ? undefined : true}
>
{fallback}
</span>
) : null}
{normalizedSrc && !failed ? (
<img
{...imageProps}
src={normalizedSrc}
alt={alt}
decoding={decoding}
hidden={!loaded}
style={loaded ? style : { ...style, display: "none" }}
data-image-state={loaded ? "ready" : "loading"}
onLoad={() => {
setFailedSrc("");
setLoadedSrc(normalizedSrc);
}}
onError={() => {
setLoadedSrc("");
setFailedSrc(normalizedSrc);
}}
/>
) : null}
</>
);
}

View file

@ -162,6 +162,13 @@ export function AppShell({ children, className, contextLabel, hideNav, bleed, wi
.filter(Boolean)
.join(" ")}
>
<a
className="vg-skip-link"
href="#vg-main-content"
onClick={() => window.requestAnimationFrame(() => mainRef.current?.focus())}
>
본문으로 건너뛰기
</a>
{hideTopbar ? null : <Topbar contextLabel={contextLabel} />}
<div className={"vg-shell__body" + (showNav ? "" : " vg-shell__body--bare")}>
{showNav ? (
@ -170,7 +177,7 @@ export function AppShell({ children, className, contextLabel, hideNav, bleed, wi
showAdminEntry={canAccessRole(user, "admin")}
/>
) : null}
<main ref={mainRef} className={mainClassName}>
<main id="vg-main-content" ref={mainRef} className={mainClassName} tabIndex={-1}>
<div className="vg-main__inner">{children}</div>
</main>
</div>

View file

@ -1,5 +1,6 @@
import { Link, useLocation, useNavigate } from "react-router-dom";
import { Icon } from "../ui/Icon";
import { ResilientImage } from "../avatar/ResilientImage";
import { accessibleRolesFor, canAccessRole, roleHomePath, roleLabel, useAuth, type Role } from "../../lib/auth";
import { useTheme } from "../../lib/useTheme";
@ -101,7 +102,11 @@ export function Topbar({ contextLabel }: TopbarProps) {
<>
<span className="vg-topbar__user">
<span className="vg-topbar__avatar" aria-hidden="true">
{user.avatarUrl ? <img src={user.avatarUrl} alt="" /> : initials(user.name)}
<ResilientImage
src={user.avatarUrl}
alt=""
fallback={initials(user.name)}
/>
</span>
<span className="vg-topbar__uname">{user.name}</span>
</span>

View file

@ -17,6 +17,29 @@
.vg-shell--fullscreen {
height: 100dvh;
}
.vg-skip-link {
position: fixed;
z-index: 100;
top: var(--sp-2);
left: var(--sp-2);
min-height: 44px;
display: inline-flex;
align-items: center;
padding: 0 var(--sp-3);
border-radius: var(--radius-sm);
background: var(--accent-deep);
color: var(--text-on-accent);
font-size: var(--fs-sm);
font-weight: 700;
text-decoration: none;
transform: translateY(calc(-100% - var(--sp-3)));
transition: transform var(--dur-fast) var(--ease-out);
}
.vg-skip-link:focus {
transform: translateY(0);
outline: 2px solid var(--focus-ring);
outline-offset: 2px;
}
/* ── 톱바 ── */
.vg-topbar {

View file

@ -0,0 +1,125 @@
import {
useRef,
type KeyboardEvent,
type ReactNode,
} from "react";
export interface TabItem<T extends string> {
value: T;
label: ReactNode;
disabled?: boolean;
}
export interface TabsProps<T extends string> {
id: string;
ariaLabel: string;
items: readonly TabItem<T>[];
value: T;
onValueChange: (value: T) => void;
listClassName?: string;
panelClassName?: string;
children: ReactNode;
}
function tabToken(value: string) {
return encodeURIComponent(value).replaceAll("%", "-");
}
/**
* Tabs — 탭과 현재 패널의 ARIA 연결·roving focus·키보드 이동 단일 소유자.
* 시각적 표면을 만들지 않으며, 도메인별 배치는 listClassName/panelClassName이 맡는다.
*/
export function Tabs<T extends string>({
id,
ariaLabel,
items,
value,
onValueChange,
listClassName,
panelClassName,
children,
}: TabsProps<T>) {
const triggerRefs = useRef<Array<HTMLButtonElement | null>>([]);
const activeIndex = items.findIndex((item) => item.value === value);
const activeItem = items[activeIndex];
if (!activeItem) {
throw new Error(`Tabs(${id})에 등록되지 않은 값입니다: ${value}`);
}
const panelId = `${id}-panel`;
const triggerId = (itemValue: T) => `${id}-tab-${tabToken(itemValue)}`;
const moveFocus = (
event: KeyboardEvent<HTMLButtonElement>,
currentIndex: number,
) => {
const enabledIndices = items
.map((item, index) => (item.disabled ? -1 : index))
.filter((index) => index >= 0);
if (enabledIndices.length === 0) return;
const position = enabledIndices.indexOf(currentIndex);
let nextIndex: number | undefined;
if (event.key === "ArrowRight" || event.key === "ArrowDown") {
nextIndex = enabledIndices[(position + 1) % enabledIndices.length];
} else if (event.key === "ArrowLeft" || event.key === "ArrowUp") {
nextIndex =
enabledIndices[(position - 1 + enabledIndices.length) % enabledIndices.length];
} else if (event.key === "Home") {
nextIndex = enabledIndices[0];
} else if (event.key === "End") {
nextIndex = enabledIndices[enabledIndices.length - 1];
}
if (nextIndex === undefined) return;
event.preventDefault();
const nextItem = items[nextIndex];
onValueChange(nextItem.value);
triggerRefs.current[nextIndex]?.focus();
};
return (
<>
<div
id={id}
className={["vg-tabs", listClassName ?? ""].filter(Boolean).join(" ")}
role="tablist"
aria-label={ariaLabel}
>
{items.map((item, index) => {
const selected = value === item.value;
return (
<button
ref={(element) => {
triggerRefs.current[index] = element;
}}
id={triggerId(item.value)}
type="button"
key={item.value}
role="tab"
aria-controls={panelId}
aria-selected={selected}
tabIndex={selected ? 0 : -1}
disabled={item.disabled}
className={`vg-tabs__trigger${selected ? " is-active" : ""}`}
onClick={() => onValueChange(item.value)}
onKeyDown={(event) => moveFocus(event, index)}
>
{item.label}
</button>
);
})}
</div>
<div
id={panelId}
className={["vg-tabs__panel", panelClassName ?? ""].filter(Boolean).join(" ")}
role="tabpanel"
aria-labelledby={triggerId(activeItem.value)}
tabIndex={0}
>
{children}
</div>
</>
);
}

View file

@ -16,6 +16,9 @@ export type { PanelProps } from "./Panel";
export { Surface, surfaceClassName } from "./Surface";
export type { SurfaceProps, SurfaceOptions, SurfaceVariant } from "./Surface";
export { Tabs } from "./Tabs";
export type { TabsProps, TabItem } from "./Tabs";
export { Kicker } from "./Kicker";
export type { KickerProps } from "./Kicker";

View file

@ -160,6 +160,16 @@
box-shadow: none;
}
/* ── Tabs behavior primitive. 시각 표면은 만들지 않는다. ── */
.vg-tabs,
.vg-tabs__panel {
min-width: 0;
}
.vg-tabs__trigger:focus-visible {
outline: 2px solid var(--focus-ring);
outline-offset: 2px;
}
/* ── Card / Panel 크기 계약. 표면은 위 Surface만 소유한다. ── */
.vg-card {
padding: var(--sp-5);

View file

@ -728,7 +728,8 @@ export interface paths {
* @description 회기 전체 deep-loop 재평가(슈퍼바이저 rationale/critique + 개선점 + 대안발화).
*
* 저장된 마스킹 축어록을 evaluator.evaluate_session 으로 평가한다.
* 엔진 장애는 503 으로 변환(평가는 비치명적이지만 트리거는 사용자 명시 요청이라 에러 노출).
* 엔진 장애는 503으로 변환한다. provider 예외 원문은 durable 기록에만 남기고 HTTP에는
* 안전한 안내만 반환한다.
*/
post: operations["reevaluate_session_eval_sessions__session_id__reevaluate_post"];
delete?: never;
@ -1667,6 +1668,46 @@ export interface paths {
patch?: never;
trace?: never;
};
"/sessions/cases": {
parameters: {
query?: never;
header?: never;
path?: never;
cookie?: never;
};
/**
* List Learner Cases
* @description Return complete case-local progress for one NPC, not a capped history slice.
*/
get: operations["list_learner_cases_sessions_cases_get"];
put?: never;
post?: never;
delete?: never;
options?: never;
head?: never;
patch?: never;
trace?: never;
};
"/sessions/cases/{case_id}/memory": {
parameters: {
query?: never;
header?: never;
path?: never;
cookie?: never;
};
/**
* Get Learner Case Memory Preview
* @description Load only the learner-safe compact memory when its foldout is opened.
*/
get: operations["get_learner_case_memory_preview_sessions_cases__case_id__memory_get"];
put?: never;
post?: never;
delete?: never;
options?: never;
head?: never;
patch?: never;
trace?: never;
};
"/sessions/dashboard": {
parameters: {
query?: never;
@ -4083,6 +4124,61 @@ export interface components {
/** Transfer Suites */
transfer_suites: components["schemas"]["TransferSuiteItem"][];
};
/**
* CaseMemoryPreview
* @description 접힌 learner UI에만 쓰는 최소·마스킹된 사례 기억 투영.
*/
CaseMemoryPreview: {
/** Case Digest */
case_digest?: string | null;
/** Case Id */
case_id: string;
/** Latest Session Digest */
latest_session_digest?: string | null;
/**
* Memory Available
* @default false
*/
memory_available: boolean;
/** Open Threads */
open_threads?: string[];
/** Pinned Facts */
pinned_facts?: string[];
};
/**
* CaseProgressStats
* @description 한 사례 안에서만 누적한 learner-visible 진행 수치.
*/
CaseProgressStats: {
/** Active Session Id */
active_session_id?: string | null;
/** Active Session No */
active_session_no?: number | null;
/** Active Started At */
active_started_at?: string | null;
/**
* Completed Sessions
* @default 0
*/
completed_sessions: number;
/** Last Activity At */
last_activity_at?: string | null;
/**
* Total Duration Seconds
* @default 0
*/
total_duration_seconds: number;
/**
* Total Sessions
* @default 0
*/
total_sessions: number;
/**
* Total Turns
* @default 0
*/
total_turns: number;
};
/** CatalogEntryView */
CatalogEntryView: {
/** Catalog Entry Id */
@ -5106,7 +5202,7 @@ export interface components {
};
/**
* EvaluationSummary
* @description 회기 평가 조회 응답(분포 + deep 결과 합본).
* @description 회기 평가 조회 응답(분포 + deep 결과 합본, provider 오류 원문 제외).
*/
EvaluationSummary: {
/** Deep */
@ -5120,6 +5216,7 @@ export interface components {
durable: boolean;
/** Error */
error?: string | null;
failure?: components["schemas"]["ReviewEvaluationFailure"] | null;
/** Session Id */
session_id: string;
/** Stage */
@ -5843,6 +5940,33 @@ export interface components {
/** Uncertainty */
uncertainty: number;
};
/** LearnerCaseListResponse */
LearnerCaseListResponse: {
/** Cases */
cases?: components["schemas"]["LearnerCaseSummary"][];
/**
* Source
* @default database
* @constant
* @enum {string}
*/
source: "database";
};
/** LearnerCaseSummary */
LearnerCaseSummary: {
/** Case Id */
case_id: string;
/**
* Last Session No
* @default 0
*/
last_session_no: number;
/** Persona Code */
persona_code: string;
/** Persona Name */
persona_name: string;
progress?: components["schemas"]["CaseProgressStats"];
};
/** LearnerDashboardAchievement */
LearnerDashboardAchievement: {
/** Detail */
@ -6117,6 +6241,11 @@ export interface components {
archived: boolean;
/** Archived At */
archived_at?: string | null;
/**
* Case Id
* @default
*/
case_id: string;
/** Client Turn Count */
client_turn_count: number;
/** Ended At */
@ -8899,6 +9028,19 @@ export interface components {
/** Persona */
persona: string;
};
/**
* ReviewEvaluationFailure
* @description 교수자용 deep-loop 실패 분류. 원문 예외·축어록은 절대 응답에 넣지 않는다.
*/
ReviewEvaluationFailure: {
/**
* Code
* @enum {string}
*/
code: "timeout" | "engine_unavailable" | "legacy_argv_limit" | "prompt_too_large" | "invalid_structured_output" | "missing_evaluation" | "unknown";
/** Retryable */
retryable: boolean;
};
/** ReviewFirstSessionChecklist */
ReviewFirstSessionChecklist: {
/**
@ -9546,6 +9688,7 @@ export interface components {
durationLabel: string;
/** Durationseconds */
durationSeconds: number;
evaluationFailure?: components["schemas"]["ReviewEvaluationFailure"] | null;
firstSessionChecklist?: components["schemas"]["ReviewFirstSessionChecklist"] | null;
/** Goodmoments */
goodMoments?: components["schemas"]["ReviewPoint"][];
@ -9640,6 +9783,8 @@ export interface components {
};
/** SessionStartRequest */
SessionStartRequest: {
/** Case Id */
case_id?: string | null;
/** Goal Stages */
goal_stages?: ("라포" | "탐색" | "개입" | "정리")[];
/**
@ -9647,6 +9792,12 @@ export interface components {
* @example P1
*/
persona_code: string;
/**
* Start Mode
* @default continue
* @enum {string}
*/
start_mode: "continue" | "fresh";
/**
* Theory Mode
* @default humanistic
@ -9692,6 +9843,12 @@ export interface components {
* @enum {string}
*/
stage: "라포" | "탐색" | "개입" | "정리";
/**
* Start Mode
* @default continue
* @enum {string}
*/
start_mode: "continue" | "fresh";
/**
* Started At
* @default
@ -14486,6 +14643,74 @@ export interface operations {
};
};
};
list_learner_cases_sessions_cases_get: {
parameters: {
query: {
persona_code: string;
};
header?: never;
path?: never;
cookie?: {
"__Host-vignette_sid"?: string | null;
vignette_sid?: string | null;
};
};
requestBody?: never;
responses: {
/** @description Successful Response */
200: {
headers: {
[name: string]: unknown;
};
content: {
"application/json": components["schemas"]["LearnerCaseListResponse"];
};
};
/** @description Validation Error */
422: {
headers: {
[name: string]: unknown;
};
content: {
"application/json": components["schemas"]["HTTPValidationError"];
};
};
};
};
get_learner_case_memory_preview_sessions_cases__case_id__memory_get: {
parameters: {
query?: never;
header?: never;
path: {
case_id: string;
};
cookie?: {
"__Host-vignette_sid"?: string | null;
vignette_sid?: string | null;
};
};
requestBody?: never;
responses: {
/** @description Successful Response */
200: {
headers: {
[name: string]: unknown;
};
content: {
"application/json": components["schemas"]["CaseMemoryPreview"];
};
};
/** @description Validation Error */
422: {
headers: {
[name: string]: unknown;
};
content: {
"application/json": components["schemas"]["HTTPValidationError"];
};
};
};
};
learner_dashboard_sessions_dashboard_get: {
parameters: {
query?: never;

View file

@ -224,6 +224,7 @@ export type PersonaDraftGenerateResponse = ApiSchema<"PersonaDraftGenerateRespon
/** POST /sessions — sessions.py SessionStartResponse */
export type SessionStartResponse = ApiSchema<"SessionStartResponse">;
export type SessionStartMode = ApiSchema<"SessionStartRequest">["start_mode"];
/** P2 단계 누적 게이지·상세 수치 — session_read_model.SessionProgress */
export type SessionProgress = ApiSchema<"SessionProgress">;
export type SessionStageProgress = ApiSchema<"SessionStageProgress">;
@ -248,6 +249,10 @@ export type LearnerSessionSummary = ApiSchema<"LearnerSessionSummary">;
export type SessionArchiveResponse = ApiSchema<"SessionArchiveResponse">;
export type LearnerSessionsResponse = ApiSchema<"LearnerSessionsResponse">;
export type CaseProgressStats = ApiSchema<"CaseProgressStats">;
export type LearnerCaseSummary = ApiSchema<"LearnerCaseSummary">;
export type LearnerCaseListResponse = ApiSchema<"LearnerCaseListResponse">;
export type CaseMemoryPreview = ApiSchema<"CaseMemoryPreview">;
export type LearnerDashboardResponse = ApiSchema<"LearnerDashboardResponse">;
export type LearnerDashboardPersonaProgress = ApiSchema<"LearnerDashboardPersonaProgress">;
export type LearnerDashboardAchievement = ApiSchema<"LearnerDashboardAchievement">;
@ -269,6 +274,7 @@ export type ReviewPhaseSegment = ApiSchema<"ReviewPhaseSegment">;
export type ReviewValencePoint = ApiSchema<"ReviewValencePoint">;
export type ReviewRubricRow = ApiSchema<"ReviewRubricRow">;
export type ReviewPoint = ApiSchema<"ReviewPoint">;
export type ReviewEvaluationFailure = ApiSchema<"ReviewEvaluationFailure">;
export type ReviewWorksheetEvidence = ApiSchema<"ReviewWorksheetEvidence">;
export type ReviewWorksheetItem = ApiSchema<"ReviewWorksheetItem">;
@ -537,12 +543,27 @@ export const sessionApi = {
},
get: (sessionId: string) =>
api.get<SessionDetailResponse>(`/sessions/${encodeURIComponent(sessionId)}`),
cases: (personaCode: string) =>
api.get<LearnerCaseListResponse>(
`/sessions/cases?persona_code=${encodeURIComponent(personaCode)}`,
),
caseMemory: (caseId: string) =>
api.get<CaseMemoryPreview>(
`/sessions/cases/${encodeURIComponent(caseId)}/memory`,
),
start: (
persona_code: string,
theory_mode: "humanistic" | "cbt" | "integrative" = "humanistic",
goal_stages: SessionStage[] = [],
options: { startMode?: SessionStartMode; caseId?: string } = {},
) =>
api.post<SessionStartResponse>("/sessions", { persona_code, theory_mode, goal_stages }),
api.post<SessionStartResponse>("/sessions", {
persona_code,
theory_mode,
goal_stages,
start_mode: options.startMode ?? "continue",
case_id: options.caseId ?? null,
}),
turn: (sessionId: string, text: string) =>
api.post<TurnResponse>(`/sessions/${encodeURIComponent(sessionId)}/turn`, { text }),
liveCoach: (sessionId: string, payload: LiveCoachRequest) =>

View file

@ -12,7 +12,6 @@ import {
AUTH_EXPIRED_EVENT,
ApiError,
api,
apiUrl,
authApi,
type MeResponse,
} from "./api";
@ -172,7 +171,8 @@ function userFromMe(me: MeResponse): AuthUser {
onboardingCompletedAt: onboarding.onboarding_completed_at ?? null,
nickname,
selfIntroduction: (me.self_introduction ?? "").trim(),
avatarUrl: avatarUrl ? apiUrl(avatarUrl) : "",
// 이미지 URL의 scheme·상대경로 검증은 실제 렌더 경계(ResilientImage)가 소유한다.
avatarUrl,
};
}

View file

@ -26,6 +26,7 @@ import {
Kicker,
ProgressBar,
surfaceClassName,
Tabs,
} from "../components/ui";
import {
adminApi,
@ -2076,25 +2077,28 @@ export default function Admin({ section = "overview" }: AdminProps) {
{usersError ? <InlineError message={usersError} /> : null}
<TabBar
<Tabs<UserTab>
id="admin-users-tabs"
ariaLabel="사용자 관리 탭"
items={[
[
"approval",
`가입 승인${accountCounts.pending ? ` ${accountCounts.pending}` : ""}`,
],
["manage", "사용자 목록"],
["register", "외부 연구참여자 사전등록"],
["activity", "활동 요약"],
{
value: "approval",
label: `가입 승인${accountCounts.pending ? ` ${accountCounts.pending}` : ""}`,
},
{ value: "manage", label: "사용자 목록" },
{ value: "register", label: "외부 연구참여자 사전등록" },
{ value: "activity", label: "활동 요약" },
]}
value={userTab}
onChange={setUserTab}
/>
{userTab === "approval" ? renderApprovalQueue() : null}
{userTab === "manage" ? renderUserList() : null}
{userTab === "register" ? renderUserCreate() : null}
{userTab === "activity" ? renderUserActivity() : null}
onValueChange={setUserTab}
listClassName="vgops-tabs"
panelClassName="vgops-tabs__panel"
>
{userTab === "approval" ? renderApprovalQueue() : null}
{userTab === "manage" ? renderUserList() : null}
{userTab === "register" ? renderUserCreate() : null}
{userTab === "activity" ? renderUserActivity() : null}
</Tabs>
</>
);
@ -2171,10 +2175,7 @@ export default function Admin({ section = "overview" }: AdminProps) {
{pendingUsers.length > 0 ? (
<div className={surfaceClassName("vgops-approval-list")}>
{pendingUsers.map((user) => (
<article
className={surfaceClassName("vgops-approval", { variant: "inset" })}
key={user.user_id}
>
<article className="vgops-approval" key={user.user_id}>
<div className="vgops-user__id">
<span aria-hidden="true">{initialOf(user)}</span>
<div>
@ -2869,91 +2870,94 @@ export default function Admin({ section = "overview" }: AdminProps) {
기준을 먼저 고정합니다.
</div>
) : null}
<TabBar
<Tabs<AccessTab>
id="admin-access-tabs"
ariaLabel="접근 권한 탭"
items={[
["roles", "역할"],
["groups", "그룹"],
["matrix", "권한 매트릭스"],
["protocols", "상담 프로토콜"],
{ value: "roles", label: "역할" },
{ value: "groups", label: "그룹" },
{ value: "matrix", label: "권한 매트릭스" },
{ value: "protocols", label: "상담 프로토콜" },
]}
value={accessTab}
onChange={setAccessTab}
/>
{accessTab === "roles" ? (
<section className="vgops-policy-grid">
{ROLE_POLICIES.map((policy) => (
<article
className={surfaceClassName("vgops-policy", { variant: "inset" })}
key={policy.role}
>
<div className="vgops-section__head">
<h2>{policy.role}</h2>
<Badge tone={policy.role === "관리자" ? "warn" : "neutral"}>
{policy.permissions.length}개 권한
</Badge>
</div>
<p>{policy.scope}</p>
<div className="vgops-chip-row">
{policy.permissions.map((permission) => (
<span key={permission}>{permission}</span>
))}
</div>
<small>{policy.risk}</small>
</article>
))}
</section>
) : null}
{accessTab === "groups" ? (
<section className="vgops-policy-grid">
{GROUP_POLICIES.map((group) => (
<article
className={surfaceClassName("vgops-policy", { variant: "inset" })}
key={group.name}
>
<div className="vgops-section__head">
<h2>{group.name}</h2>
<Badge tone="neutral">정책 초안</Badge>
</div>
<p>{group.scope}</p>
<div className="vgops-chip-row">
{group.access.map((item) => (
<span key={item}>{item}</span>
))}
</div>
</article>
))}
</section>
) : null}
{accessTab === "matrix" ? (
<section className={surfaceClassName("vgops-panel")}>
<div
className={surfaceClassName("vgops-access-table", {
variant: "inset",
})}
>
<div className="vgops-access-table__head">
<span>리소스</span>
<span>관리자</span>
<span>교수자</span>
<span>학습자</span>
</div>
{PERMISSION_MATRIX.map((row) => (
<div className="vgops-access-row" key={row.resource}>
<b>{row.resource}</b>
<span>{row.admin}</span>
<span>{row.teacher}</span>
<span>{row.learner}</span>
</div>
onValueChange={setAccessTab}
listClassName="vgops-tabs"
panelClassName="vgops-tabs__panel"
>
{accessTab === "roles" ? (
<section className="vgops-policy-grid">
{ROLE_POLICIES.map((policy) => (
<article
className={surfaceClassName("vgops-policy", { variant: "inset" })}
key={policy.role}
>
<div className="vgops-section__head">
<h2>{policy.role}</h2>
<Badge tone={policy.role === "관리자" ? "warn" : "neutral"}>
{policy.permissions.length}개 권한
</Badge>
</div>
<p>{policy.scope}</p>
<div className="vgops-chip-row">
{policy.permissions.map((permission) => (
<span key={permission}>{permission}</span>
))}
</div>
<small>{policy.risk}</small>
</article>
))}
</div>
</section>
) : null}
</section>
) : null}
{accessTab === "protocols" ? renderProtocols() : null}
{accessTab === "groups" ? (
<section className="vgops-policy-grid">
{GROUP_POLICIES.map((group) => (
<article
className={surfaceClassName("vgops-policy", { variant: "inset" })}
key={group.name}
>
<div className="vgops-section__head">
<h2>{group.name}</h2>
<Badge tone="neutral">정책 초안</Badge>
</div>
<p>{group.scope}</p>
<div className="vgops-chip-row">
{group.access.map((item) => (
<span key={item}>{item}</span>
))}
</div>
</article>
))}
</section>
) : null}
{accessTab === "matrix" ? (
<section className={surfaceClassName("vgops-panel")}>
<div
className={surfaceClassName("vgops-access-table", {
variant: "inset",
})}
>
<div className="vgops-access-table__head">
<span>리소스</span>
<span>관리자</span>
<span>교수자</span>
<span>학습자</span>
</div>
{PERMISSION_MATRIX.map((row) => (
<div className="vgops-access-row" key={row.resource}>
<b>{row.resource}</b>
<span>{row.admin}</span>
<span>{row.teacher}</span>
<span>{row.learner}</span>
</div>
))}
</div>
</section>
) : null}
{accessTab === "protocols" ? renderProtocols() : null}
</Tabs>
</>
);
@ -3125,12 +3129,7 @@ export default function Admin({ section = "overview" }: AdminProps) {
duplicateParentId !== ticket.ticket_id &&
duplicateParentId !== ticket.parent_ticket_id;
return (
<article
className={surfaceClassName("vgops-ticket", {
variant: "inset",
})}
key={ticket.ticket_id}
>
<article className="vgops-ticket" key={ticket.ticket_id}>
<div>
{/* 담당 그룹·처리 이력은 아래 <small> 에서 가운뎃점으로 이어 붙었었다.
칸 구분이 있는 meta 행으로 옮겨 <small> 은 가운뎃점 1개만 남긴다. */}
@ -3212,9 +3211,7 @@ export default function Admin({ section = "overview" }: AdminProps) {
>
{recentResolvedTickets.map((ticket) => (
<article
className={surfaceClassName("vgops-ticket vgops-ticket--history", {
variant: "inset",
})}
className="vgops-ticket vgops-ticket--history"
key={ticket.ticket_id}
>
<div>
@ -3291,39 +3288,6 @@ function EmptyState({ title, body }: { title: string; body: string }) {
);
}
function TabBar<T extends string>({
ariaLabel,
items,
value,
onChange,
}: {
ariaLabel: string;
items: Array<[T, string]>;
value: T;
onChange: (value: T) => void;
}) {
return (
<div
className={surfaceClassName("vgops-tabs", { variant: "inset", flat: true })}
role="tablist"
aria-label={ariaLabel}
>
{items.map(([id, label]) => (
<button
type="button"
key={id}
role="tab"
aria-selected={value === id}
className={value === id ? "is-active" : ""}
onClick={() => onChange(id)}
>
{label}
</button>
))}
</div>
);
}
function RoleMeter({
label,
value,

View file

@ -16,11 +16,14 @@ import { Button, Icon, Kicker, surfaceClassName } from "../components/ui";
import {
personaApi,
sessionApi,
type CaseMemoryPreview,
type LearnerDashboardPersonaProgress,
type LearnerDashboardResponse,
type LearnerCaseSummary,
type LearnerSessionSummary,
type PersonaSummary,
type SessionDetailResponse,
type SessionStartMode,
} from "../lib/api";
import { displayPiiSafeText } from "../lib/piiDisplay";
import {
@ -71,6 +74,7 @@ import {
import "./learner-home.css";
type LoadState = "loading" | "ready" | "error";
type MemoryLoadState = "idle" | LoadState;
export type LearnerHomeView = "dashboard" | "practice" | "history";
const DASHBOARD_TABS = [
@ -110,6 +114,14 @@ function oneMiddot(text: string): string {
return `${parts[0]} · ${parts.slice(1).join(", ")}`;
}
function formatCaseDuration(totalSeconds: number): string {
const safeSeconds = Math.max(0, Math.floor(totalSeconds));
const hours = Math.floor(safeSeconds / 3600);
const minutes = Math.floor((safeSeconds % 3600) / 60);
if (hours > 0) return `${hours}시간 ${minutes}분`;
return `${minutes}분`;
}
interface LearnerHomeProps {
view?: LearnerHomeView;
}
@ -142,6 +154,20 @@ export default function LearnerHome({ view = "dashboard" }: LearnerHomeProps) {
null,
);
const [recapLoadState, setRecapLoadState] = useState<LoadState>("loading");
// 새 사례와 이어지는 사례는 같은 NPC라도 case_id가 다르다. Home은 시작 전
// 선택만 담당하고, 기억 본문은 사용자가 foldout을 열 때까지 요청하지 않는다.
const [launchMode, setLaunchMode] = useState<SessionStartMode>("fresh");
const [continuityCases, setContinuityCases] = useState<LearnerCaseSummary[]>([]);
const [selectedContinuityCaseId, setSelectedContinuityCaseId] = useState<
string | null
>(null);
const [continuityLoadState, setContinuityLoadState] =
useState<LoadState>("loading");
const [memoryPreview, setMemoryPreview] = useState<CaseMemoryPreview | null>(
null,
);
const [memoryLoadState, setMemoryLoadState] =
useState<MemoryLoadState>("idle");
const [historyFilter, setHistoryFilter] = useState<HistoryFilter>("all");
const [historyQuery, setHistoryQuery] = useState("");
const [archiveBusyId, setArchiveBusyId] = useState<string | null>(null);
@ -270,6 +296,101 @@ export default function LearnerHome({ view = "dashboard" }: LearnerHomeProps) {
null,
[selectedCode, usablePersonas],
);
const caseModeAvailable =
view === "practice" && !voicePracticeRequested && !practiceLaunchRequested;
useEffect(() => {
setLaunchMode("fresh");
setSelectedContinuityCaseId(null);
setMemoryPreview(null);
setMemoryLoadState("idle");
}, [selected?.code]);
useEffect(() => {
let alive = true;
if (!caseModeAvailable || !selected || !isUsablePersona(selected)) {
setContinuityCases([]);
setContinuityLoadState("ready");
return () => {
alive = false;
};
}
setContinuityLoadState("loading");
setMemoryPreview(null);
setMemoryLoadState("idle");
sessionApi
.cases(selected.code)
.then((response) => {
if (!alive) return;
const nextCases = response.cases ?? [];
setContinuityCases(nextCases);
setSelectedContinuityCaseId((current) =>
current && nextCases.some((item) => item.case_id === current)
? current
: (nextCases[0]?.case_id ?? null),
);
setContinuityLoadState("ready");
})
.catch((error) => {
if (!alive) return;
console.warn("[learner-home] failed to load case continuity", error);
setContinuityCases([]);
setSelectedContinuityCaseId(null);
setContinuityLoadState("error");
});
return () => {
alive = false;
};
}, [caseModeAvailable, selected]);
const activeContinuityCase =
continuityCases.find((item) => item.progress?.active_session_id != null) ??
null;
const selectedContinuityCase =
activeContinuityCase ??
continuityCases.find((item) => item.case_id === selectedContinuityCaseId) ??
continuityCases[0] ??
null;
const selectedContinuityProgress = selectedContinuityCase?.progress ?? {
total_sessions: 0,
completed_sessions: 0,
total_turns: 0,
total_duration_seconds: 0,
active_session_id: null,
active_session_no: null,
active_started_at: null,
last_activity_at: null,
};
const activeCaseSessionId =
activeContinuityCase?.progress?.active_session_id ?? null;
const continuationAvailable =
continuityLoadState === "ready" &&
selectedContinuityCase != null &&
activeCaseSessionId == null;
const loadContinuityMemory = () => {
if (!selectedContinuityCase || memoryLoadState === "loading") return;
if (memoryPreview?.case_id === selectedContinuityCase.case_id) return;
setMemoryLoadState("loading");
sessionApi
.caseMemory(selectedContinuityCase.case_id)
.then((response) => {
setMemoryPreview(response);
setMemoryLoadState("ready");
})
.catch((error) => {
console.warn("[learner-home] failed to load case memory preview", error);
setMemoryPreview(null);
setMemoryLoadState("error");
});
};
const selectContinuityCase = (caseId: string) => {
setSelectedContinuityCaseId(caseId);
setMemoryPreview(null);
setMemoryLoadState("idle");
};
const sortedSessions = useMemo(
() => [...sessions].sort((a, b) => sessionSortTime(b) - sessionSortTime(a)),
[sessions],
@ -477,12 +598,23 @@ export default function LearnerHome({ view = "dashboard" }: LearnerHomeProps) {
if (selected && isUsablePersona(selected)) {
if (voicePracticeRequested && !voicePracticeContext) return;
if (practiceLaunchRequested && !practiceLaunchIntent) return;
const suffix = practiceLaunchIntent
? `?${practiceLaunchSearch(practiceLaunchIntent)}`
if (caseModeAvailable && activeCaseSessionId) {
navigate(`/learn/session/${encodeURIComponent(activeCaseSessionId)}`);
return;
}
const params = practiceLaunchIntent
? new URLSearchParams(practiceLaunchSearch(practiceLaunchIntent))
: voicePracticeContext
? `?${voicePracticeSearch(voicePracticeContext)}`
: "";
navigate(`/learn/session/${selected.code}${suffix}`);
? new URLSearchParams(voicePracticeSearch(voicePracticeContext))
: new URLSearchParams();
if (caseModeAvailable) {
params.set("continuity", launchMode);
if (launchMode === "continue" && selectedContinuityCase) {
params.set("case", selectedContinuityCase.case_id);
}
}
const suffix = params.toString();
navigate(`/learn/session/${selected.code}${suffix ? `?${suffix}` : ""}`);
}
};
@ -847,15 +979,22 @@ export default function LearnerHome({ view = "dashboard" }: LearnerHomeProps) {
: "기록"}
</button>
)}
<button
type="button"
className="lh-review-link lh-review-link--ghost"
onClick={() =>
navigate(`/learn/session/${session.persona_code}`)
}
>
다시 연습
</button>
{session.status === "ended" ? (
<button
type="button"
className="lh-review-link lh-review-link--ghost"
title="새 회기를 만들고 이전 회기의 맥락을 이어갑니다."
onClick={() => {
const params = new URLSearchParams({ continuity: "continue" });
if (session.case_id) params.set("case", session.case_id);
navigate(
`/learn/session/${session.persona_code}?${params.toString()}`,
);
}}
>
다음 회기 이어가기
</button>
) : null}
{session.status === "ended" ? (
<button
type="button"
@ -1258,7 +1397,7 @@ export default function LearnerHome({ view = "dashboard" }: LearnerHomeProps) {
} as CSSProperties
}
>
<div>
<div role="radiogroup" aria-label="회기 방식">
<span>상담 진행</span>
<b>
{spotlightSession ? `${recapProgress}%` : "0%"}
@ -1823,9 +1962,47 @@ export default function LearnerHome({ view = "dashboard" }: LearnerHomeProps) {
</div>
<div className="lh-actions">
{caseModeAvailable ? (
<fieldset className="lh-launch-mode">
<legend>회기 방식</legend>
<div>
<label>
<input
type="radio"
name="session-launch-mode"
checked={launchMode === "fresh"}
disabled={activeCaseSessionId != null}
onChange={() => setLaunchMode("fresh")}
/>
<span>완전히 새로 시작</span>
</label>
<label>
<input
type="radio"
name="session-launch-mode"
checked={launchMode === "continue"}
disabled={
activeCaseSessionId != null || !continuationAvailable
}
onChange={() => setLaunchMode("continue")}
/>
<span>
{continuityLoadState === "loading"
? "기록 확인 중"
: "이어서 진행"}
</span>
</label>
</div>
</fieldset>
) : null}
<span className="lh-actions__note">
회기 종료 후 저장된 대화 기록으로 리뷰와 코칭이
생성됩니다.
{activeCaseSessionId
? "진행 중인 회기가 있습니다. 같은 내담자의 새 사례는 이 회기를 마친 뒤 시작할 수 있습니다."
: caseModeAvailable && launchMode === "fresh"
? "새 사례는 이전 회기의 기억과 누적 기록을 가져오지 않습니다."
: caseModeAvailable
? "선택한 사례의 압축 기억과 누적 기록을 이어받습니다."
: "회기 종료 후 저장된 대화 기록으로 리뷰와 코칭이 생성됩니다."}
</span>
<Button
size="lg"
@ -1833,15 +2010,189 @@ export default function LearnerHome({ view = "dashboard" }: LearnerHomeProps) {
disabled={
!selected ||
(voicePracticeRequested && !voicePracticeContext) ||
(practiceLaunchRequested && !practiceLaunchIntent)
(practiceLaunchRequested && !practiceLaunchIntent) ||
(caseModeAvailable &&
activeCaseSessionId == null &&
launchMode === "continue" &&
!continuationAvailable)
}
trailing={<Icon name="chevron-right" size={18} />}
>
새 회기 시작
{activeCaseSessionId
? "진행 중인 회기 이어가기"
: caseModeAvailable && launchMode === "continue"
? "이어서 진행"
: "완전히 새로 시작"}
</Button>
</div>
</div>
{caseModeAvailable ? (
<section
className="lh-continuity"
aria-label="회기 연속성"
aria-live="polite"
>
{activeCaseSessionId ? (
<div className="lh-continuity__notice">
<Kicker>진행 중인 사례</Kicker>
<p>
현재 {selected?.code} 회기가 열려 있습니다. 위 버튼으로
그 회기를 이어가면 됩니다.
</p>
</div>
) : null}
{!activeCaseSessionId && launchMode === "fresh" ? (
<div className="lh-continuity__notice">
<Kicker>새 사례</Kicker>
<p>
이전 회기의 요약, 미해결 주제, 고정 기억을 가져오지 않고
1회기부터 시작합니다. 기존 사례 기록은 보존됩니다.
</p>
</div>
) : null}
{(activeCaseSessionId || launchMode === "continue") &&
continuityLoadState === "loading" ? (
<p className="lh-continuity__status">
이 내담자의 이어지는 사례를 확인하고 있습니다.
</p>
) : null}
{(activeCaseSessionId || launchMode === "continue") &&
continuityLoadState === "error" ? (
<p className="lh-continuity__status is-error" role="status">
연속 사례 통계를 확인하지 못했습니다. 이어가기는 열지 않았고,
완전히 새로 시작은 계속할 수 있습니다.
</p>
) : null}
{(activeCaseSessionId || launchMode === "continue") &&
continuityLoadState === "ready" &&
selectedContinuityCase ? (
<>
{continuityCases.length > 1 ? (
<label className="lh-continuity__case-select">
<span>이어서 진행할 사례</span>
<select
aria-label="이어서 진행할 사례"
value={selectedContinuityCase.case_id}
disabled={activeCaseSessionId != null}
onChange={(event) =>
selectContinuityCase(event.target.value)
}
>
{continuityCases.map((item, index) => {
const progress = item.progress ?? selectedContinuityProgress;
return (
<option key={item.case_id} value={item.case_id}>
{index === 0 ? "가장 최근 사례" : `이전 사례 ${index}`} · {progress.total_sessions}회기 · {progress.total_turns}턴
</option>
);
})}
</select>
</label>
) : null}
<div className="lh-continuity__head">
<div>
<Kicker>이어서 진행할 사례</Kicker>
<p>
이 사례에서 쌓인 기록만 다음 회기에 이어집니다.
</p>
</div>
<span>다음 {selectedContinuityCase.last_session_no + 1}회기</span>
</div>
<div className="lh-continuity__stats">
<span>
<b>{selectedContinuityProgress.total_sessions}회기</b>
<small>총 회기</small>
</span>
<span>
<b>{selectedContinuityProgress.total_turns}턴</b>
<small>대화 턴</small>
</span>
<span>
<b>
{formatCaseDuration(
selectedContinuityProgress.total_duration_seconds,
)}
</b>
<small>누적 회기 시간</small>
</span>
</div>
<details
className="lh-continuity__memory"
onToggle={(event) => {
if (event.currentTarget.open) loadContinuityMemory();
}}
>
<summary>
<span>내담자 기억</span>
<b>필요할 때만 펼쳐 보기</b>
<Icon name="chevron-right" size={16} />
</summary>
<div className="lh-continuity__memory-body">
{memoryLoadState === "loading" ||
memoryPreview?.case_id !== selectedContinuityCase.case_id ? (
<p>기억 요약을 불러오고 있습니다.</p>
) : memoryLoadState === "error" ? (
<p role="status">
기억 요약을 불러오지 못했습니다. 원문 대화는 표시하지
않습니다.
</p>
) : memoryPreview?.memory_available ? (
<dl>
{memoryPreview.latest_session_digest ? (
<div>
<dt>지난 회기 요약</dt>
<dd>{memoryPreview.latest_session_digest}</dd>
</div>
) : null}
{memoryPreview.case_digest ? (
<div>
<dt>사례의 큰 흐름</dt>
<dd>{memoryPreview.case_digest}</dd>
</div>
) : null}
{(memoryPreview.open_threads ?? []).length > 0 ? (
<div>
<dt>이어 볼 주제</dt>
<dd>
<ul>
{(memoryPreview.open_threads ?? []).map((thread) => (
<li key={thread}>{thread}</li>
))}
</ul>
</dd>
</div>
) : null}
{(memoryPreview.pinned_facts ?? []).length > 0 ? (
<div>
<dt>계속 기억하는 내용</dt>
<dd>
<ul>
{(memoryPreview.pinned_facts ?? []).map((fact) => (
<li key={fact}>{fact}</li>
))}
</ul>
</dd>
</div>
) : null}
</dl>
) : (
<p>
이 사례에는 다음 회기에 넘길 압축 기억이 아직 없습니다.
</p>
)}
</div>
</details>
</>
) : (activeCaseSessionId || launchMode === "continue") &&
continuityLoadState === "ready" ? (
<p className="lh-continuity__status">
이어갈 사례가 없습니다. 완전히 새로 시작할 수 있습니다.
</p>
) : null}
</section>
) : null}
<div
className={surfaceClassName("lh-summary", {
variant: "inset",

View file

@ -1,10 +1,11 @@
import { useEffect, useMemo, useState } from "react";
import { useNavigate } from "react-router-dom";
import { Button } from "../components/ui";
import { Button, Icon } from "../components/ui";
import { surfaceClassName } from "../components/ui/Surface";
import { AuthShell } from "../components/auth/AuthShell";
import { ResilientImage } from "../components/avatar/ResilientImage";
import { roleHomePath, useAuth } from "../lib/auth";
import { apiUrl, userApi, type LegalDocumentsResponse, type UserProfileResponse } from "../lib/api";
import { userApi, type LegalDocumentsResponse, type UserProfileResponse } from "../lib/api";
import "./onboarding.css";
interface OnboardingForm {
@ -59,7 +60,7 @@ function profileToForm(profile: UserProfileResponse | null): OnboardingForm {
export default function Onboarding() {
const navigate = useNavigate();
const { user, refresh } = useAuth();
const { user, logout, refresh } = useAuth();
const [docs, setDocs] = useState<LegalDocumentsResponse | null>(null);
const [form, setForm] = useState<OnboardingForm>(EMPTY_FORM);
const [loading, setLoading] = useState(true);
@ -105,12 +106,17 @@ export default function Onboarding() {
[form],
);
const avatarSrc = form.avatar_url ? apiUrl(form.avatar_url) : "";
const avatarSrc = form.avatar_url;
const update = <K extends keyof OnboardingForm>(key: K, value: OnboardingForm[K]) => {
setForm((current) => ({ ...current, [key]: value }));
};
const signOut = async () => {
await logout();
navigate("/login", { replace: true });
};
const uploadAvatar = async (file: File | null) => {
if (!file || uploadingAvatar) return;
setUploadingAvatar(true);
@ -162,6 +168,21 @@ export default function Onboarding() {
<>
<AuthShell className="ob-page">
<section className={surfaceClassName("ob-shell")} aria-label="가입 정보 입력">
<div className="ob-account" aria-label="현재 로그인 계정">
<div className="ob-account__identity">
<span>현재 Google 계정</span>
<strong>{user?.email ?? "계정 확인 중"}</strong>
</div>
<Button
type="button"
variant="secondary"
leading={<Icon name="logout" size={16} />}
onClick={() => void signOut()}
>
다른 계정으로 로그인
</Button>
</div>
<header className="ob-head">
<p>Vignette 가입 설정</p>
<h1>가입 정보를 입력합니다.</h1>
@ -180,7 +201,11 @@ export default function Onboarding() {
</div>
<div className="ob-avatar">
<div className="ob-avatar__preview" aria-hidden="true">
{avatarSrc ? <img src={avatarSrc} alt="" /> : <span>{form.nickname.trim().slice(0, 1) || "V"}</span>}
<ResilientImage
src={avatarSrc}
alt=""
fallback={form.nickname.trim().slice(0, 1) || "V"}
/>
</div>
<div className="ob-avatar__body">
<span>상징 아바타</span>

View file

@ -10,6 +10,7 @@ import {
Icon,
Kicker,
surfaceClassName,
Tabs,
} from "../components/ui";
import {
ApiError,
@ -2758,32 +2759,23 @@ export default function PersonaStudio() {
</div>
</Card>
<div
className={surfaceClassName("ps-tabs", {
variant: "inset",
flat: true,
})}
role="tablist"
aria-label="저작 섹션"
<Tabs<StudioTab>
id="persona-authoring-tabs"
ariaLabel="저작 섹션"
items={STUDIO_TABS.map((tab) => ({
value: tab.key,
label: tab.label,
}))}
value={activeTab}
onValueChange={setActiveTab}
listClassName="ps-tabs"
panelClassName="ps-tabs__panel"
>
{STUDIO_TABS.map((tab) => (
<button
type="button"
key={tab.key}
className={activeTab === tab.key ? "is-active" : ""}
onClick={() => setActiveTab(tab.key)}
role="tab"
aria-selected={activeTab === tab.key}
>
{tab.label}
</button>
))}
</div>
<Card className="ps-edit-panel">
<GuidancePanel tab={activeTab} />
{renderTab()}
</Card>
<Card className="ps-edit-panel">
<GuidancePanel tab={activeTab} />
{renderTab()}
</Card>
</Tabs>
{formError ? (
<p className="ps-status is-error" role="alert">

View file

@ -40,6 +40,7 @@ import {
type SessionDetailResponse,
type SessionProgress,
type SessionStage,
type SessionStartMode,
} from "../lib/api";
import { useAuth } from "../lib/auth";
import { formatElapsed, formatTimecode, clamp01 } from "../lib/format";
@ -135,6 +136,13 @@ const SESSION_PHASES: PhaseInfo[] = [
{ key: "정리", desc: "오늘의 대화 정리와 다음 약속" },
];
function primaryGoalActionLabel(goal: SessionStage): string {
const lastCode = goal.charCodeAt(goal.length - 1);
const hasFinalConsonant =
lastCode >= 0xac00 && lastCode <= 0xd7a3 && (lastCode - 0xac00) % 28 !== 0;
return `${goal}${hasFinalConsonant ? "을" : "를"} 핵심 초점으로 설정`;
}
const THEORY_MODE_OPTIONS: {
value: TheoryMode;
label: string;
@ -366,6 +374,22 @@ export default function Session() {
() => parsePracticeLaunchIntent(searchParams),
[searchParams],
);
// Home에서 고른 사례 방식만 REST 시작 요청으로 전달한다. 음성 재연습/처방은
// 출처 URL 계약을 우선하므로 이 선택기를 덮어쓰지 않는다.
const startMode = useMemo<SessionStartMode>(
() =>
!voicePracticeRequested &&
!practiceLaunchRequested &&
searchParams.get("continuity") === "fresh"
? "fresh"
: "continue",
[practiceLaunchRequested, searchParams, voicePracticeRequested],
);
const selectedCaseId = useMemo(() => {
if (startMode !== "continue") return undefined;
const candidate = searchParams.get("case")?.trim();
return candidate || undefined;
}, [searchParams, startMode]);
const practiceContextSearch = useMemo(
() =>
practiceLaunchIntent
@ -416,8 +440,10 @@ export default function Session() {
const [consentChecked, setConsentChecked] = useState(false);
const [consentBusy, setConsentBusy] = useState(false);
const [selectedTheoryMode, setSelectedTheoryMode] = useState<TheoryMode>("humanistic");
// 이번 회기 목표(2026-07-13 회의 P1): 4단계 전부가 아니라 1~2개를 고르고 시작한다.
const [selectedGoals, setSelectedGoals] = useState<SessionStage[]>(["라포", "탐색"]);
// 새 회기는 한 가지 수행 초점에서 시작한다. 처방 재연습은 검증된 라포·탐색 과업을 유지한다.
const [selectedGoals, setSelectedGoals] = useState<SessionStage[]>(
practiceLaunchIntent ? ["라포", "탐색"] : ["라포"],
);
// ── 회기/대화 상태 ──
const [stage, setStage] = useState<SessionStage>("라포");
@ -504,6 +530,9 @@ export default function Session() {
const [leftPanelCollapsed, setLeftPanelCollapsed] = useState(false);
const [rightPanelCollapsed, setRightPanelCollapsed] = useState(false);
const [shortcutHelpOpen, setShortcutHelpOpen] = useState(false);
const shortcutHelpPanelRef = useRef<HTMLElement>(null);
const shortcutHelpConfirmRef = useRef<HTMLButtonElement>(null);
const shortcutHelpPreviousFocusRef = useRef<HTMLElement | null>(null);
const [ctxCollapsed, setCtxCollapsed] = useState(true);
const [metersCollapsed, setMetersCollapsed] = useState(false);
const [safetyCollapsed, setSafetyCollapsed] = useState(true);
@ -533,6 +562,10 @@ export default function Session() {
const pendingVoiceLearnerTextRef = useRef<string>("");
const coachEvidenceCloseRef = useRef<HTMLButtonElement>(null);
const coachHistoryCloseRef = useRef<HTMLButtonElement>(null);
const coachEvidencePanelRef = useRef<HTMLElement>(null);
const coachHistoryPanelRef = useRef<HTMLElement>(null);
const coachEvidencePreviousFocusRef = useRef<HTMLElement | null>(null);
const coachHistoryPreviousFocusRef = useRef<HTMLElement | null>(null);
const coachCreditSeenRef = useRef<Set<string>>(new Set());
const coachCreditPulseTimerRef = useRef<number | null>(null);
@ -929,15 +962,27 @@ export default function Session() {
[applyCoachCreditEvents, liveSessionId],
);
const openCoachEvidence = useCallback(() => {
if (!coachEvidenceOpen) {
coachEvidencePreviousFocusRef.current =
document.activeElement instanceof HTMLElement ? document.activeElement : null;
}
setCoachEvidenceOpen(true);
}, [coachEvidenceOpen]);
const openCoachHistory = useCallback(
(turnSeq: number | null = null) => {
if (!coachHistoryOpen) {
coachHistoryPreviousFocusRef.current =
document.activeElement instanceof HTMLElement ? document.activeElement : null;
}
setCoachHistoryTurnSeq(turnSeq);
setCoachHistoryError(null);
setCoachEvidenceOpen(false);
setCoachHistoryOpen(true);
void refreshCoachHistory(liveSessionId, { surfaceErrors: true });
},
[liveSessionId, refreshCoachHistory],
[coachHistoryOpen, liveSessionId, refreshCoachHistory],
);
const requestLiveCoach = useCallback(
@ -1294,13 +1339,17 @@ export default function Session() {
};
}, [navigate, pushSignal, routeIsSessionId, routeParam, voicePracticeContext]);
// 이번 회기 목표 토글 — 1~4개 자유 선택(소유자 지시 2026-07-15).
// 이번 회기 목표 — 핵심 1개 + 보조 0~3개를 유지한다(소유자 지시 2026-07-15).
const toggleGoal = useCallback((goal: SessionStage) => {
setSelectedGoals((prev) =>
prev.includes(goal) ? prev.filter((g) => g !== goal) : [...prev, goal],
);
}, []);
const makePrimaryGoal = useCallback((goal: SessionStage) => {
setSelectedGoals((prev) => [goal, ...prev.filter((selected) => selected !== goal)]);
}, []);
/* ── 세션 시작 ───────────────────────────────────────────────────── */
const handleStart = useCallback(async () => {
if (voicePracticeRequested && !voicePracticeContext) {
@ -1320,7 +1369,10 @@ export default function Session() {
setResumedSessionLoaded(false);
setClientReplyPending(false);
try {
const res = await sessionApi.start(personaCode, selectedTheoryMode, selectedGoals);
const res = await sessionApi.start(personaCode, selectedTheoryMode, selectedGoals, {
startMode,
caseId: selectedCaseId,
});
setLiveSessionId(res.session_id); // ★ 진짜 세션 id 저장 — turn 이 이걸 써야 라이브
setSessionEnded(false);
setReviewReady(false);
@ -1385,6 +1437,25 @@ export default function Session() {
setStartError(
"이 페르소나는 아직 승인되지 않았거나 공개 목록에서 제외됐습니다. 승인 상태를 확인한 뒤 목록에서 다시 선택해 주세요.",
);
} else if (err instanceof ApiError && err.status === 409) {
const detail = (
err.body as {
detail?: { code?: unknown; session_id?: unknown };
}
)?.detail;
if (
detail?.code === "active_session_exists" &&
typeof detail.session_id === "string"
) {
pushSignal("neutral", "진행 중인 회기 이어가기");
navigate(`/learn/session/${encodeURIComponent(detail.session_id)}`, {
replace: true,
});
return;
}
setStartError(
"같은 내담자의 진행 중인 회기가 있습니다. 그 회기를 이어서 마무리한 뒤 다음 회기를 시작해 주세요.",
);
} else if (
err instanceof ApiError &&
err.detail === "session_persistence_unavailable"
@ -1398,7 +1469,7 @@ export default function Session() {
} finally {
setStarting(false);
}
}, [navigate, personaCode, personaSummary, practiceContextSearch, practiceLaunchIntent, practiceLaunchRequested, pushSignal, selectedGoals, selectedTheoryMode, voicePracticeContext, voicePracticeRequested]);
}, [navigate, personaCode, personaSummary, practiceContextSearch, practiceLaunchIntent, practiceLaunchRequested, pushSignal, selectedCaseId, selectedGoals, selectedTheoryMode, startMode, voicePracticeContext, voicePracticeRequested]);
const handleAlliancePreGateChange = useCallback((blocked: boolean) => {
setAlliancePreGateBlocked(blocked);
@ -2373,9 +2444,13 @@ export default function Session() {
}
// 2. 단축키 도움말: ? (입력창 밖) 또는 Ctrl+/ or Alt+/
// 브라우저·키보드 레이아웃에 따라 Shift+/가 key="?" 대신 key="/"+shiftKey로
// 들어올 수 있으므로 두 형태를 모두 같은 단축키로 취급한다.
const isQuestionMarkShortcut = e.key === "?" || (e.shiftKey && e.key === "/");
if (
((e.ctrlKey || e.metaKey || e.altKey) && e.key === "/") ||
(e.key === "?" && !(e.target instanceof HTMLInputElement || e.target instanceof HTMLTextAreaElement))
(isQuestionMarkShortcut &&
!(e.target instanceof HTMLInputElement || e.target instanceof HTMLTextAreaElement))
) {
e.preventDefault();
setShortcutHelpOpen((prev) => !prev);
@ -2471,7 +2546,7 @@ export default function Session() {
// Alt+E: AI 코칭 근거
if (isAlt && e.key.toLowerCase() === "e") {
e.preventDefault();
setCoachEvidenceOpen(true);
openCoachEvidence();
return;
}
@ -2504,6 +2579,7 @@ export default function Session() {
rightPanelCollapsed,
sessionEnded,
jumpToLatest,
openCoachEvidence,
openCoachHistory,
shortcutHelpOpen,
coachEvidenceOpen,
@ -2554,12 +2630,63 @@ export default function Session() {
voiceConsentPreviousFocusRef.current = null;
}, [voiceConsentDialogOpen]);
useEffect(() => {
if (!shortcutHelpOpen) return;
shortcutHelpPreviousFocusRef.current =
document.activeElement instanceof HTMLElement ? document.activeElement : null;
window.setTimeout(() => shortcutHelpConfirmRef.current?.focus(), 0);
const onKey = (event: KeyboardEvent) => {
if (event.key !== "Tab") return;
const controls = Array.from(
shortcutHelpPanelRef.current?.querySelectorAll<HTMLElement>(
"a[href], button:not([disabled]), input:not([disabled]), select:not([disabled]), textarea:not([disabled]), [tabindex]:not([tabindex='-1'])",
) ?? [],
).filter((control) => control.getClientRects().length > 0);
if (controls.length === 0) return;
const first = controls[0];
const last = controls[controls.length - 1];
if (event.shiftKey && document.activeElement === first) {
event.preventDefault();
last.focus();
} else if (!event.shiftKey && document.activeElement === last) {
event.preventDefault();
first.focus();
}
};
window.addEventListener("keydown", onKey);
return () => window.removeEventListener("keydown", onKey);
}, [shortcutHelpOpen]);
useEffect(() => {
if (shortcutHelpOpen) return;
const previous = shortcutHelpPreviousFocusRef.current;
if (previous?.isConnected) previous.focus();
shortcutHelpPreviousFocusRef.current = null;
}, [shortcutHelpOpen]);
useEffect(() => {
if (!coachEvidenceOpen) return;
window.setTimeout(() => coachEvidenceCloseRef.current?.focus(), 0);
const onKey = (event: KeyboardEvent) => {
if (event.key === "Escape") {
setCoachEvidenceOpen(false);
return;
}
if (event.key !== "Tab") return;
const controls = Array.from(
coachEvidencePanelRef.current?.querySelectorAll<HTMLElement>(
"a[href], button:not([disabled]), input:not([disabled]), select:not([disabled]), textarea:not([disabled]), [tabindex]:not([tabindex='-1'])",
) ?? [],
).filter((control) => control.getClientRects().length > 0);
if (controls.length === 0) return;
const first = controls[0];
const last = controls[controls.length - 1];
if (event.shiftKey && document.activeElement === first) {
event.preventDefault();
last.focus();
} else if (!event.shiftKey && document.activeElement === last) {
event.preventDefault();
first.focus();
}
};
window.addEventListener("keydown", onKey);
@ -2572,12 +2699,43 @@ export default function Session() {
const onKey = (event: KeyboardEvent) => {
if (event.key === "Escape") {
setCoachHistoryOpen(false);
return;
}
if (event.key !== "Tab") return;
const controls = Array.from(
coachHistoryPanelRef.current?.querySelectorAll<HTMLElement>(
"a[href], button:not([disabled]), input:not([disabled]), select:not([disabled]), textarea:not([disabled]), [tabindex]:not([tabindex='-1'])",
) ?? [],
).filter((control) => control.getClientRects().length > 0);
if (controls.length === 0) return;
const first = controls[0];
const last = controls[controls.length - 1];
if (event.shiftKey && document.activeElement === first) {
event.preventDefault();
last.focus();
} else if (!event.shiftKey && document.activeElement === last) {
event.preventDefault();
first.focus();
}
};
window.addEventListener("keydown", onKey);
return () => window.removeEventListener("keydown", onKey);
}, [coachHistoryOpen]);
useEffect(() => {
if (coachEvidenceOpen || coachHistoryOpen) return;
const previous = coachEvidencePreviousFocusRef.current;
if (previous?.isConnected) previous.focus();
coachEvidencePreviousFocusRef.current = null;
}, [coachEvidenceOpen, coachHistoryOpen]);
useEffect(() => {
if (coachHistoryOpen) return;
const previous = coachHistoryPreviousFocusRef.current;
if (previous?.isConnected) previous.focus();
coachHistoryPreviousFocusRef.current = null;
}, [coachHistoryOpen]);
useEffect(() => {
if (!endDialogOpen) return;
endPreviousFocusRef.current =
@ -2705,16 +2863,14 @@ export default function Session() {
!sessionEnded;
const elapsedLabel = timeUp && !sessionEnded ? "시간 만료" : formatTimecode(elapsed);
const remainingLabel = formatTimecode(remainingSeconds);
const limitMinutesLabel = Math.round(sessionLimitSeconds / 60);
const warningMinutesLabel = Math.max(1, Math.round(sessionWarningSeconds / 60));
const selectedTheoryOption =
THEORY_MODE_OPTIONS.find((option) => option.value === selectedTheoryMode) ??
THEORY_MODE_OPTIONS[0];
const selectedGoalSummary = SESSION_PHASES.filter((phase) =>
selectedGoals.includes(phase.key),
)
.map((phase) => phase.key)
.join(" · ");
const selectedGoalPhases = selectedGoals
.map((goal) => SESSION_PHASES.find((phase) => phase.key === goal))
.filter((phase): phase is PhaseInfo => phase != null);
const primaryGoal = selectedGoalPhases[0];
const selectedGoalSummary = selectedGoalPhases.map((phase) => phase.key).join(" · ");
const turnCount = utterances.filter((utterance) => !utterance.partial && !utterance.failed).length;
const latestClientUtterance = [...utterances]
.reverse()
@ -2839,42 +2995,54 @@ export default function Session() {
<Kicker>상담 연습 · {personaCode}</Kicker>
</div>
<h1 className="sx-head__title">
지금은 <em>{stage} 단계</em>입니다.
{started ? (
<>
지금은 <em>{stage} 단계</em>입니다.
</>
) : (
<>
첫 발화의 <em>기준</em>을 정합니다.
</>
)}
</h1>
<div className="sx-head__sub">
{clientName}의 말에 귀를 기울이세요. 정밀 평가는 회기가 끝난 뒤 리뷰에서 함께 봅니다.
{started
? `${clientName}의 말에 귀를 기울이세요. 정밀 평가는 회기가 끝난 뒤 리뷰에서 함께 봅니다.`
: `${clientName}의 사례를 읽고, 첫 반응에서 해볼 한 가지를 정한 뒤 시작하세요.`}
</div>
</div>
<div className="sx-phases" aria-label="회기 진행 단계">
{SESSION_PHASES.map((p, i) => {
const state = i < stageIdx ? "is-done" : i === stageIdx ? "is-cur" : "";
const isGoal = started && goalStages.includes(p.key);
return (
<div key={p.key} style={{ display: "flex", alignItems: "center" }}>
{i > 0 ? (
<span className={"sx-ph__link" + (i <= stageIdx ? " is-fill" : "")} />
) : null}
<div className={"sx-ph " + state + (isGoal ? " is-goal" : "")}>
<span className="sx-ph__dot" />
<span className="sx-ph__meta">
<span className="sx-ph__name">
{p.key}
{isGoal ? (
<em className="sx-ph__goal" title="이번 회기 목표">
목표
</em>
) : null}
{started ? (
<div className="sx-phases" aria-label="회기 진행 단계">
{SESSION_PHASES.map((p, i) => {
const state = i < stageIdx ? "is-done" : i === stageIdx ? "is-cur" : "";
const isGoal = goalStages.includes(p.key);
return (
<div key={p.key} style={{ display: "flex", alignItems: "center" }}>
{i > 0 ? (
<span className={"sx-ph__link" + (i <= stageIdx ? " is-fill" : "")} />
) : null}
<div className={"sx-ph " + state + (isGoal ? " is-goal" : "")}>
<span className="sx-ph__dot" />
<span className="sx-ph__meta">
<span className="sx-ph__name">
{p.key}
{isGoal ? (
<em className="sx-ph__goal" title="이번 회기 목표">
목표
</em>
) : null}
</span>
<span className="sx-ph__t">
{i < stageIdx ? "완료" : i === stageIdx ? "진행 중" : "예정"}
</span>
</span>
<span className="sx-ph__t">
{i < stageIdx ? "완료" : i === stageIdx ? "진행 중" : "예정"}
</span>
</span>
</div>
</div>
</div>
);
})}
</div>
);
})}
</div>
) : null}
</header>
{started ? (
@ -2949,13 +3117,18 @@ export default function Session() {
) : null}
{!started ? (
/* ── 시작 전: 준비 화면(한 화면 한 의도 = 세션 시작) ── */
<div
<>
{/* ── 시작 전: 사례 맥락 → 한 가지 수행 초점 → 근거 기반 복기 ── */}
<section
className={surfaceClassName(
`sx-prestart${practiceLaunchIntent ? " sx-prestart--prescribed" : ""}`,
)}
aria-label="회기 시작 전 준비"
>
<div className={surfaceClassName("sx-prestart__visual", { variant: "inset" })}>
<aside
className={surfaceClassName("sx-prestart__visual", { variant: "inset" })}
aria-labelledby="sx-prestart-case-title"
>
<ClientAvatar
persona={personaUi.avatar}
state="idle"
@ -2966,29 +3139,41 @@ export default function Session() {
showCaption={false}
showMeta={false}
/>
{/* 아바타 카드는 인물 그림 + 이름 + 한 줄 소개만 맡는다.
호소·대상·난도 목록은 본문 .sx-prestart__facts 와 똑같은 내용이라
(3열·2열 모두에서 두 번 노출) 여기서는 제거했다. 이름 이니셜 원도
바로 위 초상과 이름을 중복하는 장식이라 함께 걷어냈다. */}
<div className="sx-prestart__case" aria-label="내담자 요약">
<b>{personaUi.context.name}</b>
{/* D3 — 한 줄에 · 가 3개 몰리던 소개를 줄당 1개로 나눠 표시 */}
<div className="sx-prestart__case">
<Kicker>오늘 만날 내담자</Kicker>
<b id="sx-prestart-case-title">{personaUi.context.name}</b>
<p>
{clientMetaLines.map((line, i) => (
<span key={`${i}-${line}`}>{line}</span>
))}
</p>
</div>
</div>
<dl className="sx-prestart__facts">
{personaUi.context.rows.map((row) => (
<div key={row.l}>
<dt>{row.l}</dt>
<dd>{row.v}</dd>
</div>
))}
</dl>
<div className="sx-prestart__chips" aria-label="내담자 태그">
{personaUi.context.chips.map((chip) => (
<span className={chip.clay ? "is-clay" : ""} key={chip.t}>
{chip.t}
</span>
))}
</div>
</aside>
<div className="sx-prestart__main">
{/* D4 — eyebrow "○○ 단계 준비" 는 바로 위 페이지 제목 "지금은 ○○ 단계입니다."
와 같은 말이라 제거했다(단계 정보는 상단 제목·단계 레일·진행 초점에 이미 있다). */}
<h2 className="sx-prestart__title">{prestartTitle}</h2>
<p className="sx-prestart__desc">
짧은 첫 인사로 안전감을 만들고, 정밀 평가는 회기가 끝난 뒤 리뷰에서 함께
확인합니다.
</p>
<div className="sx-prestart__main sx-prestart__learning">
<header className="sx-prestart__intro">
<Kicker>시작 전 1분</Kicker>
<h2 className="sx-prestart__title">{prestartTitle}</h2>
<p className="sx-prestart__desc">
사례를 모두 해결하려고 하기보다, 첫 반응에서 해볼 한 가지를 정하세요. 대화가
끝나면 리뷰의 근거 턴을 보고 같은 장면을 다시 연습합니다.
</p>
</header>
{voicePracticeRequested ? (
voicePracticeContext ? (
<section className="sx-voice-practice-context" aria-labelledby="sx-voice-practice-title">
@ -3041,33 +3226,97 @@ export default function Session() {
</p>
)
) : null}
<details
className={`sx-prestart__settings${practiceLaunchIntent ? " is-prescribed" : ""}`}
open={practiceLaunchIntent ? undefined : true}
>
<section className="sx-prestart__focus" aria-labelledby="sx-prestart-focus-title">
<div className="sx-prestart__focus-head">
<div>
<Kicker>오늘의 핵심 초점</Kicker>
<h3 id="sx-prestart-focus-title">{primaryGoal?.key ?? "초점 선택 필요"}</h3>
</div>
<p>
{primaryGoal?.desc ?? "목표 하나를 고르면 첫 발화에서 해볼 반응을 안내합니다."}
</p>
</div>
<fieldset className="sx-goals" aria-label="이번 회기 목표 선택">
<legend>
이번 회기 목표 <small>핵심 1개 · 보조 0~3개</small>
</legend>
<div className="sx-goals__grid">
{SESSION_PHASES.map((phase) => {
const selected = selectedGoals.includes(phase.key);
const isPrimary = selected && primaryGoal?.key === phase.key;
return (
<button
type="button"
key={phase.key}
className={
(selected ? "is-selected" : "") + (isPrimary ? " is-primary" : "")
}
aria-pressed={selected}
aria-label={
isPrimary
? `${phase.key} 핵심 초점, ${phase.desc}`
: `${phase.key}, ${phase.desc}`
}
onClick={() => toggleGoal(phase.key)}
>
<span>{phase.key}</span>
<small>{phase.desc}</small>
</button>
);
})}
</div>
<p className="sx-goals__hint">
{primaryGoal ? (
<>
첫 발화의 기준은 <b>{primaryGoal.key}</b>입니다. 보조 목표는 회기 전체에
남고, 회기는 {Math.round((durationLimitSeconds > 0 ? durationLimitSeconds : 3600) / 60)}분 기준으로 이어집니다.
</>
) : (
"목표 하나를 고르면 첫 발화의 기준이 표시되고 회기를 시작할 수 있습니다."
)}
</p>
</fieldset>
{selectedGoalPhases.length > 1 ? (
<div className="sx-prestart__primary-switch">
<p>
<b>보조 목표</b>는 유지한 채 첫 발화의 기준만 바꿀 수 있습니다.
</p>
<div role="group" aria-label="핵심 초점 바꾸기">
{selectedGoalPhases.slice(1).map((phase) => (
<button
key={phase.key}
type="button"
onClick={() => makePrimaryGoal(phase.key)}
>
{primaryGoalActionLabel(phase.key)}
</button>
))}
</div>
<label className="sx-prestart__primary-select">
<span>첫 발화 핵심</span>
<select
value={primaryGoal?.key ?? ""}
onChange={(event) => makePrimaryGoal(event.target.value as SessionStage)}
>
{selectedGoalPhases.map((phase) => (
<option key={phase.key} value={phase.key}>
{primaryGoalActionLabel(phase.key)}
</option>
))}
</select>
</label>
</div>
) : null}
</section>
<details className={`sx-prestart__settings${practiceLaunchIntent ? " is-prescribed" : ""}`}>
<summary>
<span>선택한 회기 설정</span>
<span>연습 방식과 추가 설정</span>
<b>
{selectedTheoryOption.label}, {selectedGoalSummary || "목표 선택 필요"}
{selectedTheoryOption.label} · {selectedGoalSummary || "핵심 초점 선택 필요"}
</b>
<Icon name="chevron-right" size={16} />
</summary>
<div className="sx-prestart__settings-body">
<dl className="sx-prestart__facts">
{personaUi.context.rows.map((row) => (
<div key={row.l}>
<dt>{row.l}</dt>
<dd>{row.v}</dd>
</div>
))}
</dl>
<div className="sx-prestart__chips" aria-label="내담자 태그">
{personaUi.context.chips.map((chip) => (
<span className={chip.clay ? "is-clay" : ""} key={chip.t}>
{chip.t}
</span>
))}
</div>
<fieldset className="sx-theory" aria-label="이론모드 선택">
<legend>이론모드</legend>
<div className="sx-theory__seg">
@ -3085,33 +3334,9 @@ export default function Session() {
))}
</div>
</fieldset>
<fieldset className="sx-goals" aria-label="이번 회기 목표 선택">
<legend>
이번 회기 목표 <small>1~4개 선택</small>
</legend>
<div className="sx-goals__grid">
{SESSION_PHASES.map((phase) => {
const selected = selectedGoals.includes(phase.key);
return (
<button
type="button"
key={phase.key}
className={selected ? "is-selected" : ""}
aria-pressed={selected}
onClick={() => toggleGoal(phase.key)}
>
<span>{phase.key}</span>
<small>{phase.desc}</small>
</button>
);
})}
</div>
<p className="sx-goals__hint">
실제 상담처럼 한 회기에 모든 단계를 이루지 않아도 됩니다. 회기는{" "}
{Math.round((durationLimitSeconds > 0 ? durationLimitSeconds : 3600) / 60)}분
기준으로 진행되고, 목표를 이뤄도 시간이 남으면 계속 이어갈 수 있어요.
</p>
</fieldset>
<p className="sx-prestart__settings-note">
{selectedTheoryOption.focus}
</p>
</div>
</details>
{personaStatusMessage ? (
@ -3156,52 +3381,114 @@ export default function Session() {
</Button>
<span>
{selectedGoals.length === 0
? "이번 회기 목표를 1개 이상 선택하면 시작할 수 있어요."
: "실시간에는 대화 흐름만 낮은 강도로 표시됩니다."}
? "오늘의 핵심 초점을 1개 이상 선택하면 시작할 수 있어요."
: "실시간에는 대화 흐름만 낮은 강도로 표시되고, 상세 피드백은 리뷰에서 확인합니다."}
</span>
</div>
</div>
<div
className={surfaceClassName("sx-prestart__plan", { variant: "inset" })}
aria-label="시작 전 초점"
<aside
className={surfaceClassName("sx-prestart__plan sx-prestart__learning-map", { variant: "inset" })}
aria-labelledby="sx-prestart-learning-map-title"
>
<Kicker>진행 초점</Kicker>
<p className="sx-prestart__plan-summary">
선택한 회기 설정을 첫 발화에서 바로 쓸 수 있는 기준으로 정리했습니다.
<Kicker>학습 흐름</Kicker>
<h3 id="sx-prestart-learning-map-title">시도한 장면을 다시 씁니다.</h3>
<ol className="sx-prestart__learning-loop">
<li>
<span>준비</span>
<div>
<b>한 가지 반응을 정합니다.</b>
<p>
{primaryGoal
? `첫 발화의 기준으로 ${primaryGoal.key}에 집중하고 시작합니다.`
: "목표 하나를 고르면 첫 발화의 기준이 여기에 표시됩니다."}
</p>
</div>
</li>
<li>
<span>대화</span>
<div>
<b>먼저 말해 본 뒤 신호를 봅니다.</b>
<p>실시간에는 대화 흐름만 낮은 강도로 표시합니다.</p>
</div>
</li>
<li>
<span>리뷰·재연습</span>
<div>
<b>근거 턴으로 다음 시도를 고릅니다.</b>
<p>첫 회기라면 라포 반영과 한 초점 개방질문을 근거와 함께 확인합니다.</p>
</div>
</li>
</ol>
<p className="sx-prestart__boundary">
위험 신호는 대화보다 안전 확인을 우선합니다.
</p>
<dl className="sx-prestart__plan-list">
<div>
<dt>시작 과업</dt>
<dd>
<b>{currentPhase.key}</b>
{currentPhase.desc}
</dd>
</aside>
</section>
{shortcutHelpOpen ? (
<div
className="sx-coach-modal-backdrop"
role="presentation"
onMouseDown={(event) => {
if (event.target === event.currentTarget) setShortcutHelpOpen(false);
}}
>
<section
ref={shortcutHelpPanelRef}
className="sx-coach-modal sx-shortcut-modal"
role="dialog"
aria-modal="true"
aria-labelledby="sx-shortcut-modal-title"
onMouseDown={(event) => event.stopPropagation()}
>
<div className="sx-coach-modal__head">
<span className="sx-coach-modal__avatar" aria-hidden="true">
<Icon name="spark" size={20} />
</span>
<div>
<h2 id="sx-shortcut-modal-title">키보드 단축키 안내</h2>
<p>시작 전에는 목표를 고르고 회기를 여는 데만 집중하세요.</p>
</div>
</div>
<div>
<dt>선택 접근</dt>
<dd>
<b>{selectedTheoryOption.label}</b>
{selectedTheoryOption.focus}
</dd>
<div className="sx-coach-modal__body sx-shortcut-modal__body">
<div className="sx-shortcut-group">
<h3>시작 전 조작</h3>
<dl className="sx-shortcut-list">
<div>
<dt><kbd>Space</kbd> 또는 <kbd>Enter</kbd></dt>
<dd>포커스한 회기 목표 선택/해제</dd>
</div>
<div>
<dt><kbd>Ctrl</kbd>+<kbd>Enter</kbd></dt>
<dd>선택한 목표로 회기 시작</dd>
</div>
<div>
<dt><kbd>?</kbd> 또는 <kbd>Ctrl</kbd>+<kbd>/</kbd></dt>
<dd>단축키 도움말 열기/닫기</dd>
</div>
<div>
<dt><kbd>Escape</kbd></dt>
<dd>이 도움말 닫기</dd>
</div>
</dl>
</div>
</div>
<div>
<dt>이번 목표</dt>
<dd>
<b>{selectedGoals.length > 0 ? `${selectedGoals.length}개 선택` : "선택 필요"}</b>
{selectedGoalSummary || "목표를 1개 이상 선택하면 시작할 수 있습니다."}
</dd>
<div className="sx-coach-modal__actions">
<button
type="button"
ref={shortcutHelpConfirmRef}
onClick={() => setShortcutHelpOpen(false)}
>
확인 (Esc)
</button>
</div>
<div>
<dt>운영 기준</dt>
<dd>
<b>{limitMinutesLabel}분 회기</b>
종료 {warningMinutesLabel}분 전 알림 · 위험 신호 시 안전 확인 우선
</dd>
</div>
</dl>
</section>
</div>
</div>
) : null}
</>
) : (
<>
{/* ── 시간 알람 바(회의 P1): 10분 전 경고 + 시간 만료 정리 유도 — 강제 노출 ── */}
@ -4109,7 +4396,7 @@ export default function Session() {
<blockquote>{coachSuggestion.next_utterance}</blockquote>
) : null}
<div className="sx-coach-bubble__actions">
<button type="button" onClick={() => setCoachEvidenceOpen(true)}>
<button type="button" onClick={openCoachEvidence}>
근거 보기
</button>
<button type="button" onClick={() => openCoachHistory(null)}>
@ -4432,6 +4719,7 @@ export default function Session() {
}}
>
<section
ref={coachHistoryPanelRef}
className="sx-coach-history__panel"
role="dialog"
aria-modal="true"
@ -4558,6 +4846,7 @@ export default function Session() {
}}
>
<section
ref={coachEvidencePanelRef}
className="sx-coach-modal__panel"
role="dialog"
aria-modal="true"
@ -4775,6 +5064,7 @@ export default function Session() {
}}
>
<section
ref={shortcutHelpPanelRef}
className="sx-coach-modal sx-shortcut-modal"
role="dialog"
aria-modal="true"
@ -4876,6 +5166,7 @@ export default function Session() {
<div className="sx-coach-modal__actions">
<button
type="button"
ref={shortcutHelpConfirmRef}
onClick={() => setShortcutHelpOpen(false)}
>
확인 (Esc)

View file

@ -68,6 +68,7 @@ import {
REVIEW_READY_POLL_INTERVAL_MS,
REVIEW_READY_POLL_LIMIT,
displayEvaluationRetryError,
evaluationFailureMessage,
displayGeneratedReviewText,
displayReviewSummary,
displayTranscriptText,
@ -1108,7 +1109,6 @@ export default function SessionReview() {
if (resultError) {
throw new Error(resultError);
}
setReviewReloadSeq((seq) => seq + 1);
} catch (err) {
const message =
err instanceof ApiError
@ -1119,6 +1119,9 @@ export default function SessionReview() {
setEvaluationRetryError(displayEvaluationRetryError(message));
} finally {
setEvaluationRetrying(false);
// 재시도 결과가 error여도 서버가 최신 durable 상태를 저장할 수 있다. 성공/실패
// 어느 쪽이든 다시 읽어야 교수자가 오래된 실패 원인을 보지 않는다.
setReviewReloadSeq((seq) => seq + 1);
}
}
@ -1253,7 +1256,9 @@ export default function SessionReview() {
canReviewEndedSession &&
hasTranscript &&
!data.reviewReady &&
data.supervisorState === "평가 실패";
data.supervisorState === "평가 실패" &&
(data.evaluationFailure?.retryable ?? true);
const evaluationFailure = isSupervisorView ? data.evaluationFailure : null;
const reviewReadiness = hasTranscript
? `${turns.length}개 발화 기반`
: "축어록 저장 후 생성";
@ -1447,6 +1452,17 @@ export default function SessionReview() {
{evaluationRetrying ? "AI 평가 실행 중" : "AI 평가 재시도"}
</Button>
) : null}
{evaluationFailure ? (
<p
className={surfaceClassName(
`sr-share-note sr-evaluation-failure${evaluationFailure.retryable ? "" : " sr-share-note--error"}`,
{ variant: "inset", flat: true },
)}
role="status"
>
{evaluationFailureMessage(evaluationFailure)}
</p>
) : null}
<Button
variant="primary"
size="sm"

View file

@ -1,5 +1,6 @@
import { useCallback, useEffect, useMemo, useRef, useState } from "react";
import { AppShell } from "../components/shell/AppShell";
import { ResilientImage } from "../components/avatar/ResilientImage";
import {
Badge,
Button,
@ -15,7 +16,6 @@ import { roleLabel, useAuth } from "../lib/auth";
import {
adminApi,
adminEngineApi,
apiUrl,
userApi,
type AdminHealthResponse,
type AdminEngineConfigResponse,
@ -653,8 +653,8 @@ export default function Settings() {
const accountName = displayName || profile?.email || user?.name || user?.email || "사용자";
const accountEmail = profile?.email ?? user?.email ?? "";
const initials = accountName.trim().slice(0, 1).toUpperCase();
// 프로필이 먼저 도착하면 프로필 값을, 아니면 auth 스토어의 절대화된 URL을 쓴다.
const avatarSrc = profile?.avatar_url ? apiUrl(profile.avatar_url) : user?.avatarUrl ?? "";
// 프로필이 먼저 도착하면 원본 값을 쓰고, 공통 이미지 경계에서 URL을 검증·절대화한다.
const avatarSrc = profile?.avatar_url || user?.avatarUrl || "";
const isLearner = role === "learner";
const consentAt = user?.consentAt ?? null;
const engineModels = engineCapabilities?.models ?? [];
@ -702,7 +702,7 @@ export default function Settings() {
<div className={surfaceClassName("vg-set__rail-card", { variant: "inset" })} aria-label="계정 요약">
<div className="vg-set__rail-avatar" aria-hidden="true">
{avatarSrc ? <img src={avatarSrc} alt="" /> : initials}
<ResilientImage src={avatarSrc} alt="" fallback={initials} />
</div>
<div className="vg-set__rail-copy">
<div className="vg-set__rail-name">{accountName}</div>
@ -753,7 +753,7 @@ export default function Settings() {
<div className={surfaceClassName("vg-set__profile", { variant: "inset", flat: true })}>
<div className="vg-set__avatar" aria-hidden="true">
{avatarSrc ? <img src={avatarSrc} alt="" /> : initials}
<ResilientImage src={avatarSrc} alt="" fallback={initials} />
</div>
<div className="vg-set__profile-meta">
<div className="n">{accountName}</div>

View file

@ -606,6 +606,12 @@
padding-bottom: 2px;
}
.vgops-tabs__panel {
display: flex;
flex-direction: column;
gap: var(--sp-4);
}
.vgops-tabs button {
flex: 0 0 auto;
min-height: 44px;

View file

@ -94,27 +94,32 @@
padding:8px 12px;
border:1px solid transparent;
border-radius:var(--radius-pill);
background:transparent;
background-color:transparent;
color:var(--text-body);
font-size:var(--fs-sm);
font-weight:650;
cursor:pointer;
min-height:42px;
transition:all var(--dur-fast) var(--ease-spring);
min-height:44px;
transition:
background-color var(--dur-fast) var(--ease-spring),
border-color var(--dur-fast) var(--ease-spring),
box-shadow var(--dur-fast) var(--ease-spring),
color var(--dur-fast) var(--ease-spring),
transform var(--dur-fast) var(--ease-spring);
}
.lh-tabs button:active{
transform:scale(0.96);
}
.lh-tabs button:hover{
color:var(--text-strong);
background:color-mix(in srgb,var(--text-strong) 5%,transparent);
background-color:color-mix(in srgb,var(--text-strong) 5%,transparent);
}
.lh-tabs button:focus-visible{
outline:2px solid var(--focus-ring);
outline-offset:1px;
}
.lh-tabs button.is-active{
background:var(--bg-surface);
background-color:var(--bg-surface);
border-color:var(--border-strong);
color:var(--text-strong);
box-shadow:var(--shadow-sm);
@ -1019,10 +1024,12 @@
.lh-practice-launch-intent dl{
grid-template-columns:repeat(auto-fit,minmax(128px,1fr));
}
.lh-practice-launch-intent__details{
.lh-practice-launch-intent__details,
.lh-continuity__memory{
min-width:0;
}
.lh-practice-launch-intent__details summary{
.lh-practice-launch-intent__details summary,
.lh-continuity__memory summary{
min-width:0;
min-height:44px;
display:grid;
@ -1037,15 +1044,18 @@
cursor:pointer;
list-style:none;
}
.lh-practice-launch-intent__details summary::-webkit-details-marker{
.lh-practice-launch-intent__details summary::-webkit-details-marker,
.lh-continuity__memory summary::-webkit-details-marker{
display:none;
}
.lh-practice-launch-intent__details summary span{
.lh-practice-launch-intent__details summary span,
.lh-continuity__memory summary span{
color:var(--accent-deep);
font-size:var(--fs-xs);
font-weight:760;
}
.lh-practice-launch-intent__details summary b{
.lh-practice-launch-intent__details summary b,
.lh-continuity__memory summary b{
min-width:0;
overflow:hidden;
color:var(--text-strong);
@ -1054,19 +1064,62 @@
text-overflow:ellipsis;
white-space:nowrap;
}
.lh-practice-launch-intent__details summary svg{
.lh-practice-launch-intent__details summary svg,
.lh-continuity__memory summary svg{
transition:transform var(--dur-base) var(--ease-out);
}
.lh-practice-launch-intent__details[open] summary svg{
.lh-practice-launch-intent__details[open] summary svg,
.lh-continuity__memory[open] summary svg{
transform:rotate(90deg);
}
.lh-practice-launch-intent__details summary:focus-visible{
.lh-practice-launch-intent__details summary:focus-visible,
.lh-continuity__memory summary:focus-visible{
outline:2px solid var(--border-focus);
outline-offset:2px;
}
.lh-practice-launch-intent__details dl{
margin-top:var(--sp-2);
}
.lh-continuity__memory-body{
margin-top:var(--sp-2);
}
.lh-continuity__memory-body > p{
margin:0;
color:var(--text-body);
font-size:var(--fs-sm);
line-height:1.55;
word-break:keep-all;
}
.lh-continuity__memory-body dl{
display:grid;
gap:var(--sp-2);
margin:0;
}
.lh-continuity__memory-body dl > div{
min-width:0;
padding-top:var(--sp-2);
border-top:1px solid var(--border-subtle);
}
.lh-continuity__memory-body dt{
color:var(--text-muted);
font-size:var(--fs-xs);
font-weight:760;
}
.lh-continuity__memory-body dd{
margin:5px 0 0;
color:var(--text-body);
font-size:var(--fs-sm);
line-height:1.55;
white-space:pre-wrap;
word-break:keep-all;
overflow-wrap:anywhere;
}
.lh-continuity__memory-body ul{
display:grid;
gap:4px;
margin:0;
padding-left:18px;
}
.lh-practice-layout{
min-width:0;
display:grid;
@ -1357,6 +1410,139 @@
text-align:right;
word-break:keep-all;
}
.lh-launch-mode{
width:min(100%,340px);
margin:0;
padding:0;
border:0;
}
.lh-launch-mode legend{
margin:0 0 6px;
color:var(--text-muted);
font-size:var(--fs-xs);
font-weight:760;
}
.lh-launch-mode > div{
display:grid;
grid-template-columns:repeat(2,minmax(0,1fr));
gap:8px;
}
.lh-launch-mode label{
position:relative;
min-width:0;
display:block;
}
.lh-launch-mode input{
position:absolute;
width:1px;
height:1px;
margin:-1px;
overflow:hidden;
clip:rect(0 0 0 0);
white-space:nowrap;
}
.lh-launch-mode label > span{
min-width:0;
min-height:44px;
display:grid;
place-items:center;
padding:8px 10px;
border:1px solid var(--border-subtle);
border-radius:var(--radius-sm);
background:var(--bg-surface-2);
color:var(--text-body);
font-size:var(--fs-sm);
font-weight:740;
line-height:1.25;
word-break:keep-all;
cursor:pointer;
}
.lh-launch-mode label:hover input:not(:disabled) + span{
border-color:var(--border-strong);
background:var(--bg-surface);
color:var(--text-strong);
}
.lh-launch-mode input:checked + span{
border-color:var(--accent);
background:var(--accent-tint);
color:var(--accent-deep);
box-shadow:inset 0 0 0 1px color-mix(in srgb,var(--accent) 12%,transparent);
}
.lh-launch-mode input:focus-visible + span{
outline:2px solid var(--focus-ring);
outline-offset:2px;
}
.lh-launch-mode input:disabled + span{
cursor:not-allowed;
opacity:.58;
}
.lh-continuity{
min-width:0;
display:grid;
gap:var(--sp-3);
padding:var(--sp-4);
border:1px solid var(--border-subtle);
border-radius:var(--radius);
background:var(--bg-surface-2);
}
.lh-continuity__notice,
.lh-continuity__head{
min-width:0;
}
.lh-continuity__notice p,
.lh-continuity__head p,
.lh-continuity__status{
margin:7px 0 0;
color:var(--text-body);
font-size:var(--fs-sm);
line-height:1.55;
word-break:keep-all;
}
.lh-continuity__status.is-error{
color:var(--warn-text);
}
.lh-continuity__head{
display:flex;
align-items:start;
justify-content:space-between;
gap:var(--sp-3);
}
.lh-continuity__head > span{
flex:none;
color:var(--accent-deep);
font-family:var(--font-num);
font-size:var(--fs-xs);
font-weight:800;
white-space:nowrap;
}
.lh-continuity__case-select{
min-width:0;
display:grid;
gap:6px;
}
.lh-continuity__case-select > span{
color:var(--text-muted);
font-size:var(--fs-xs);
font-weight:760;
}
.lh-continuity__case-select select{
width:100%;
min-height:44px;
padding:8px 10px;
border:1px solid var(--border-subtle);
border-radius:var(--radius-sm);
background:var(--bg-surface);
color:var(--text-strong);
font:inherit;
}
.lh-continuity__case-select select:focus-visible{
outline:2px solid var(--focus-ring);
outline-offset:2px;
}
.lh-continuity__case-select select:disabled{
cursor:not-allowed;
opacity:.72;
}
.lh-summary{
min-width:0;
padding:var(--sp-4);
@ -1406,13 +1592,15 @@
gap:var(--sp-4);
padding:var(--sp-5);
}
.lh-activity__stats{
.lh-activity__stats,
.lh-continuity__stats{
min-width:0;
display:grid;
grid-template-columns:repeat(3,minmax(0,1fr));
gap:8px;
}
.lh-activity__stats span{
.lh-activity__stats span,
.lh-continuity__stats span{
min-width:0;
min-height:58px;
display:grid;
@ -1423,13 +1611,15 @@
border-radius:var(--radius);
background:var(--bg-surface-2);
}
.lh-activity__stats b{
.lh-activity__stats b,
.lh-continuity__stats b{
color:var(--text-strong);
font-family:var(--font-num);
font-size:22px;
line-height:1;
}
.lh-activity__stats small{
.lh-activity__stats small,
.lh-continuity__stats small{
color:var(--text-muted);
font-size:12px;
font-weight:720;
@ -1912,6 +2102,7 @@
.lh-list-pane,
.lh-preview__main,
.lh-activity,
.lh-continuity,
.lh-persona-progress,
.lh-history-main,
.lh-archive-note{
@ -1975,16 +2166,27 @@
margin:0;
max-width:70%;
}
.lh-activity__stats{
.lh-activity__stats,
.lh-continuity__stats{
gap:6px;
}
.lh-activity__stats span{
.lh-activity__stats span,
.lh-continuity__stats span{
min-height:46px;
padding:8px 4px;
text-align:center;
}
.lh-activity__stats b{font-size:17px;}
.lh-activity__stats small{font-size:11px;}
.lh-activity__stats b,
.lh-continuity__stats b{font-size:17px;}
.lh-activity__stats small,
.lh-continuity__stats small{font-size:11px;}
.lh-launch-mode{
width:100%;
}
.lh-continuity__head{
display:grid;
gap:6px;
}
.lh-session-list li{
grid-template-columns:1fr;
gap:10px;

View file

@ -919,8 +919,10 @@
.ps-stepper button.is-current > span:first-child,.ps-stepper button.is-done > span:first-child{border-color:var(--accent);background:var(--accent);color:var(--text-on-accent);}
.ps-authoring-layout{grid-template-columns:minmax(0,1fr) minmax(260px,320px);}
.ps-authoring-layout[data-authoring-step="source"] .ps-tabs,
.ps-authoring-layout[data-authoring-step="source"] .ps-tabs__panel,
.ps-authoring-layout[data-authoring-step="source"] .ps-edit-panel,
.ps-authoring-layout[data-authoring-step="generate"] .ps-tabs,
.ps-authoring-layout[data-authoring-step="generate"] .ps-tabs__panel,
.ps-authoring-layout[data-authoring-step="generate"] .ps-edit-panel,
.ps-authoring-layout[data-authoring-step="edit"] .ps-source-panel,
.ps-authoring-layout[data-authoring-step="review"] .ps-source-panel{display:none;}

View file

@ -1,4 +1,5 @@
import type {
ReviewEvaluationFailure,
SessionReviewResponse,
TeacherSessionReviewStatusResponse,
UserPrepostMeasureItem,
@ -134,9 +135,36 @@ export function displayGeneratedReviewText(text: string) {
export function displayEvaluationRetryError(message: string) {
if (!message.trim()) return "AI 평가를 다시 실행하지 못했습니다.";
if (/timeout|timed out/i.test(message)) {
return "AI 평가가 제한 시간 안에 끝나지 않았습니다. 최신 상태를 다시 불러왔습니다.";
}
if (/engine_error|engine unavailable|transport error/i.test(message)) {
return "평가 엔진에 일시적으로 연결하지 못했습니다. 최신 상태를 다시 불러왔습니다.";
}
return "AI 평가 재시도를 완료하지 못했습니다. 잠시 뒤 다시 실행해 주세요.";
}
export function evaluationFailureMessage(
failure: ReviewEvaluationFailure | null | undefined,
) {
switch (failure?.code) {
case "timeout":
return "평가 생성이 제한 시간 안에 끝나지 않았습니다. 축어록은 보존됐으며 다시 시도할 수 있습니다.";
case "engine_unavailable":
return "평가 엔진에 일시적으로 연결하지 못했습니다. 축어록은 보존됐으며 다시 시도할 수 있습니다.";
case "legacy_argv_limit":
return "이전 Windows 입력 한도에 걸린 평가입니다. 축어록은 보존됐으며 현재 입력 경로로 다시 시도할 수 있습니다.";
case "prompt_too_large":
return "평가 입력이 허용 크기를 넘어섰습니다. 같은 재시도 대신 입력 경로를 조정해야 합니다.";
case "invalid_structured_output":
return "평가 결과 형식이 검증되지 않았습니다. 축어록은 보존됐으며 다시 시도할 수 있습니다.";
case "missing_evaluation":
return "회기말 평가 기록이 아직 저장되지 않았습니다. 축어록은 보존됐으며 다시 시도할 수 있습니다.";
default:
return "평가 AI가 완료되지 않았습니다. 축어록은 보존됐으며 다시 시도할 수 있습니다.";
}
}
export function displayTranscriptText(text: string) {
return displayPiiSafeText(text);
}

View file

@ -314,27 +314,32 @@
padding: 8px 14px;
border: 1px solid transparent;
border-radius: var(--radius-pill);
background: transparent;
background-color: transparent;
color: var(--text-body);
font-size: var(--fs-sm);
font-weight: 650;
cursor: pointer;
min-height: 42px;
transition: all var(--dur-fast) var(--ease-spring);
min-height: 44px;
transition:
background-color var(--dur-fast) var(--ease-spring),
border-color var(--dur-fast) var(--ease-spring),
box-shadow var(--dur-fast) var(--ease-spring),
color var(--dur-fast) var(--ease-spring),
transform var(--dur-fast) var(--ease-spring);
}
.sr-tabs button:active {
transform: scale(0.96);
}
.sr-tabs button:hover {
color: var(--text-strong);
background: color-mix(in srgb, var(--text-strong) 5%, transparent);
background-color: color-mix(in srgb, var(--text-strong) 5%, transparent);
}
.sr-tabs button:focus-visible {
outline: 2px solid var(--focus-ring);
outline-offset: 1px;
}
.sr-tabs button.is-active {
background: var(--bg-surface);
background-color: var(--bg-surface);
border-color: var(--border-strong);
color: var(--text-strong);
box-shadow: var(--shadow-sm);
@ -1452,11 +1457,6 @@
color: var(--text-body);
background: color-mix(in srgb, var(--bg-surface) 82%, var(--bg-surface-2));
}
.sr-ws-input.is-readonly:focus-visible {
outline: none;
border-color: var(--border-subtle);
box-shadow: none;
}
.sr-ws-input::placeholder {
color: var(--text-muted);
}

View file

@ -158,7 +158,11 @@
font: 650 12px/1 var(--font-sans);
white-space: nowrap;
cursor: pointer;
transition: all var(--dur-fast) var(--ease-out);
transition:
background var(--dur-fast) var(--ease-out),
border-color var(--dur-fast) var(--ease-out),
color var(--dur-fast) var(--ease-out),
opacity var(--dur-fast) var(--ease-out);
}
.sx-sessionbar__toggle-btn:hover {
background: var(--accent-tint);
@ -183,7 +187,11 @@
font: 700 12.5px/1 var(--font-sans);
white-space: nowrap;
cursor: pointer;
transition: all var(--dur-fast) var(--ease-out);
transition:
background var(--dur-fast) var(--ease-out),
border-color var(--dur-fast) var(--ease-out),
color var(--dur-fast) var(--ease-out),
transform var(--dur-fast) var(--ease-out);
}
.sx-sessionbar button:hover {
background: var(--accent-tint);
@ -411,7 +419,10 @@
color: var(--text-muted);
font: 600 11.5px/1 var(--font-sans);
cursor: pointer;
transition: all var(--dur-fast) var(--ease-out);
transition:
background var(--dur-fast) var(--ease-out),
border-color var(--dur-fast) var(--ease-out),
color var(--dur-fast) var(--ease-out);
}
.sx-panel-close-btn:hover {
@ -448,7 +459,12 @@
gap: 14px;
padding: 18px 4px;
cursor: pointer;
transition: all var(--dur-fast) var(--ease-spring);
transition:
background var(--dur-fast) var(--ease-spring),
border-color var(--dur-fast) var(--ease-spring),
box-shadow var(--dur-fast) var(--ease-spring),
color var(--dur-fast) var(--ease-spring),
transform var(--dur-fast) var(--ease-spring);
}
.sx-mini-rail-btn:hover {
@ -1169,6 +1185,7 @@
display: flex;
align-items: flex-end;
gap: 7px;
min-width: 0;
max-width: 100%;
}
.sx-utt__line {
@ -1176,7 +1193,8 @@
line-height: 1.58;
padding: 9px 13px;
border-radius: var(--radius);
max-width: min(88%, 68ch);
min-width: 0;
max-width: 100%;
overflow-wrap: anywhere;
}
/* 내담자 = clay-tint 틴트 블록 (외곽선·꼬리·border-left 없음) */
@ -1351,6 +1369,7 @@
min-width: 0;
}
.sx-compose textarea {
display: block;
width: 100%;
resize: none;
background: var(--bg-surface-2);
@ -1404,7 +1423,7 @@
.sx-compose__actions {
display: flex;
align-items: center;
align-items: flex-end;
gap: 8px;
flex: 0 0 auto;
}
@ -1428,7 +1447,13 @@
font: 700 13px/1 var(--font-sans);
white-space: nowrap;
cursor: pointer;
transition: all var(--dur-fast) var(--ease-out);
transition:
background var(--dur-fast) var(--ease-out),
border-color var(--dur-fast) var(--ease-out),
box-shadow var(--dur-fast) var(--ease-out),
color var(--dur-fast) var(--ease-out),
opacity var(--dur-fast) var(--ease-out),
transform var(--dur-fast) var(--ease-out);
}
.sx-coach-trigger-btn:hover:not(:disabled) {
background: color-mix(in srgb, var(--accent) 22%, var(--bg-surface-2));
@ -1582,7 +1607,9 @@
background: transparent;
color: var(--text-muted);
cursor: pointer;
transition: all var(--dur-fast) var(--ease-out);
transition:
background var(--dur-fast) var(--ease-out),
color var(--dur-fast) var(--ease-out);
}
.sx-coach-bubble-popup__close:hover {
background: color-mix(in srgb, var(--accent) 15%, transparent);
@ -1677,7 +1704,11 @@
font-size: 12px;
font-weight: 650;
cursor: pointer;
transition: all var(--dur-fast) var(--ease-out);
transition:
background var(--dur-fast) var(--ease-out),
border-color var(--dur-fast) var(--ease-out),
color var(--dur-fast) var(--ease-out),
transform var(--dur-fast) var(--ease-out);
text-align: left;
}
.sx-coach-chip:hover:not(:disabled) {
@ -1741,7 +1772,9 @@
font-size: 11.5px;
font-weight: 700;
cursor: pointer;
transition: all var(--dur-fast) var(--ease-out);
transition:
background var(--dur-fast) var(--ease-out),
transform var(--dur-fast) var(--ease-out);
}
.sx-coach-msg__apply-btn:hover {
background: var(--accent);
@ -1808,7 +1841,9 @@
background: var(--bg-surface-2);
color: var(--text-strong);
font-size: 12.5px;
transition: all var(--dur-fast) var(--ease-out);
transition:
border-color var(--dur-fast) var(--ease-out),
box-shadow var(--dur-fast) var(--ease-out);
}
.sx-coach-bubble-popup__composer input:focus {
border-color: var(--accent);
@ -1827,7 +1862,9 @@
justify-content: center;
cursor: pointer;
flex-shrink: 0;
transition: all var(--dur-fast) var(--ease-out);
transition:
background var(--dur-fast) var(--ease-out),
color var(--dur-fast) var(--ease-out);
}
.sx-coach-bubble-popup__composer button:hover:not(:disabled) {
background: var(--accent);
@ -5760,3 +5797,467 @@
gap: 14px;
}
}
/* ── 2026-08-30 · 회기 프리브리프: 사례 → 한 가지 수행 초점 → 근거 기반 재연습 ──
시작 전 화면은 설정을 한꺼번에 읽는 대시보드가 아니라, 첫 발화에 필요한 판단만
앞에 두는 학습 준비면이다. 기존 API payload·동의·처방/음성 URL 문맥은 바꾸지 않는다. */
.sx-page--prestart .sx-head {
align-items: flex-start;
}
.sx-page--prestart .sx-head__lt {
max-width: 46rem;
}
.sx-page--prestart .sx-prestart {
grid-template-areas: "case learning map";
grid-template-columns: minmax(210px, 0.78fr) minmax(0, 1.5fr) minmax(220px, 0.84fr);
align-items: start;
gap: var(--sp-5);
padding: var(--sp-5);
overflow: visible;
}
.sx-page--prestart .sx-prestart__visual {
grid-area: case;
align-self: stretch;
align-content: start;
justify-items: start;
gap: var(--sp-3);
padding: var(--sp-4);
}
.sx-page--prestart .sx-prestart__visual .vg-avatar {
justify-self: center;
}
.sx-page--prestart .sx-prestart__case {
justify-items: start;
text-align: left;
}
.sx-page--prestart .sx-prestart__case b {
margin-top: var(--sp-1);
}
.sx-page--prestart .sx-prestart__case p {
max-width: 28ch;
}
.sx-page--prestart .sx-prestart__facts {
width: 100%;
grid-template-columns: repeat(auto-fit, minmax(min(100%, 10rem), 1fr));
gap: var(--sp-3);
margin: 0;
padding: var(--sp-3) 0;
max-height: none;
overflow: visible;
}
.sx-page--prestart .sx-prestart__chips {
margin-top: 0;
}
.sx-page--prestart .sx-prestart__learning {
grid-area: learning;
display: grid;
align-content: start;
gap: var(--sp-4);
}
.sx-page--prestart .sx-prestart__intro {
display: grid;
gap: var(--sp-2);
}
.sx-page--prestart .sx-prestart__intro .vg-kicker {
margin: 0;
}
.sx-page--prestart .sx-prestart__title,
.sx-page--prestart .sx-prestart__desc {
margin: 0;
}
.sx-page--prestart .sx-prestart__title {
max-width: 20ch;
}
.sx-page--prestart .sx-prestart__desc {
max-width: 38ch;
}
.sx-page--prestart .sx-prestart__learning .sx-voice-practice-context {
margin-top: 0;
}
.sx-page--prestart .sx-prestart__focus {
display: grid;
gap: var(--sp-3);
padding-top: var(--sp-4);
border-top: 1px solid var(--glass-inset-border);
}
.sx-page--prestart .sx-prestart__focus-head {
display: grid;
grid-template-columns: minmax(0, 0.84fr) minmax(0, 1.16fr);
align-items: end;
gap: var(--sp-4);
}
.sx-page--prestart .sx-prestart__focus-head h3 {
margin: var(--sp-1) 0 0;
color: var(--text-strong);
font-size: var(--fs-h3);
font-weight: 700;
line-height: 1.35;
}
.sx-page--prestart .sx-prestart__focus-head p {
margin: 0;
color: var(--text-body);
font-size: var(--fs-sm);
line-height: 1.65;
}
.sx-page--prestart .sx-goals {
width: 100%;
margin: 0;
}
.sx-page--prestart .sx-goals__grid {
padding: var(--sp-2);
gap: var(--sp-2);
}
.sx-page--prestart .sx-goals__grid button {
min-height: 68px;
text-align: left;
}
.sx-page--prestart .sx-goals__grid button.is-primary {
border-color: var(--accent-deep);
box-shadow: inset 0 0 0 1px var(--accent-deep);
}
.sx-page--prestart .sx-goals__grid button.is-primary span::after {
content: " · 핵심";
color: var(--accent-deep);
font-size: var(--fs-xs);
font-weight: 700;
}
.sx-page--prestart .sx-goals__hint {
margin: 0;
max-width: 54ch;
}
.sx-page--prestart .sx-goals__hint b {
color: var(--accent-deep);
font-weight: 700;
}
.sx-page--prestart .sx-prestart__primary-switch {
display: grid;
gap: var(--sp-2);
padding-top: var(--sp-3);
border-top: 1px solid var(--glass-inset-border);
}
.sx-page--prestart .sx-prestart__primary-switch p {
margin: 0;
color: var(--text-muted);
font-size: var(--fs-xs);
line-height: 1.55;
}
.sx-page--prestart .sx-prestart__primary-switch p b {
color: var(--text-body);
font-weight: 700;
}
.sx-page--prestart .sx-prestart__primary-switch [role="group"] {
display: flex;
flex-wrap: wrap;
gap: var(--sp-2);
}
.sx-page--prestart .sx-prestart__primary-switch button {
min-height: 44px;
padding: 0 var(--sp-3);
border: 1px solid var(--glass-inset-border);
border-radius: var(--radius-sm);
background: transparent;
color: var(--text-body);
font-size: var(--fs-xs);
font-weight: 700;
cursor: pointer;
}
.sx-page--prestart .sx-prestart__primary-switch button:hover {
border-color: color-mix(in srgb, var(--accent) 48%, var(--glass-inset-border));
color: var(--text-strong);
}
.sx-page--prestart .sx-prestart__primary-switch button:focus-visible {
outline: 2px solid var(--focus-ring);
outline-offset: 2px;
}
.sx-page--prestart .sx-prestart__primary-select {
display: none;
}
.sx-page--prestart .sx-prestart__settings {
margin-top: 0;
padding-top: var(--sp-3);
border-top: 1px solid var(--glass-inset-border);
}
.sx-page--prestart .sx-prestart__settings:not(.is-prescribed) > summary {
display: grid;
}
.sx-page--prestart .sx-prestart__settings-body {
padding-top: var(--sp-3);
}
.sx-page--prestart .sx-theory {
width: 100%;
margin: 0;
}
.sx-page--prestart .sx-prestart__settings-note {
margin: var(--sp-3) 0 0;
color: var(--text-muted);
font-size: var(--fs-sm);
line-height: 1.6;
}
.sx-page--prestart .sx-prestart__voice-disclosure,
.sx-page--prestart .sx-consent {
width: 100%;
margin: 0;
}
.sx-page--prestart .sx-prestart__actions {
margin-top: 0;
}
.sx-page--prestart .sx-prestart__plan {
grid-area: map;
align-self: stretch;
display: grid;
align-content: start;
gap: var(--sp-3);
padding: var(--sp-4);
}
.sx-page--prestart .sx-prestart__learning-map h3 {
margin: 0;
color: var(--text-strong);
font-size: var(--fs-h3);
font-weight: 700;
line-height: 1.4;
}
.sx-page--prestart .sx-prestart__learning-loop {
display: grid;
gap: 0;
margin: 0;
padding: 0;
list-style: none;
}
.sx-page--prestart .sx-prestart__learning-loop li {
display: grid;
grid-template-columns: minmax(3.5rem, auto) minmax(0, 1fr);
gap: var(--sp-2);
padding: var(--sp-3) 0;
border-top: 1px solid var(--border-subtle);
}
.sx-page--prestart .sx-prestart__learning-loop li > span {
color: var(--accent-deep);
font-size: var(--fs-xs);
font-weight: 700;
}
.sx-page--prestart .sx-prestart__learning-loop li > div {
min-width: 0;
}
.sx-page--prestart .sx-prestart__learning-loop b {
display: block;
color: var(--text-strong);
font-size: var(--fs-sm);
font-weight: 700;
line-height: 1.45;
}
.sx-page--prestart .sx-prestart__learning-loop p,
.sx-page--prestart .sx-prestart__boundary {
margin: var(--sp-1) 0 0;
color: var(--text-muted);
font-size: var(--fs-xs);
line-height: 1.6;
}
.sx-page--prestart .sx-prestart__boundary {
padding-top: var(--sp-3);
border-top: 1px solid var(--border-subtle);
}
@media (max-width: 1260px) {
.sx-page--prestart .sx-prestart {
grid-template-areas:
"case learning"
"map map";
grid-template-columns: minmax(190px, 0.7fr) minmax(0, 1.3fr);
}
.sx-page--prestart .sx-prestart__plan {
border-top: 1px solid var(--glass-inset-border);
}
.sx-page--prestart .sx-prestart__learning-loop {
grid-template-columns: repeat(3, minmax(0, 1fr));
gap: var(--sp-3);
}
.sx-page--prestart .sx-prestart__learning-loop li {
grid-template-columns: 1fr;
gap: var(--sp-1);
}
}
/* 짧은 데스크톱(1280×720 등)에서는 첫 발화 준비의 정보는 모두 유지하되 중앙 학습 열의
여백만 조밀하게 만든다. 이전에는 상태 설명이 줄바꿈되면서 핵심 CTA가 접혔다. */
@media (min-width: 1261px) and (max-height: 800px) {
.sx-page--prestart .sx-prestart__learning {
gap: var(--sp-2);
}
.sx-page--prestart .sx-prestart__focus {
gap: var(--sp-1);
padding-top: var(--sp-2);
}
.sx-page--prestart .sx-goals__grid {
padding: 2px;
}
.sx-page--prestart .sx-goals__grid button {
min-height: 52px;
}
.sx-page--prestart .sx-prestart__settings {
padding-top: var(--sp-2);
}
.sx-page--prestart .sx-prestart__primary-switch {
gap: var(--sp-1);
padding-top: var(--sp-2);
}
.sx-page--prestart .sx-prestart__primary-switch > p,
.sx-page--prestart .sx-prestart__primary-switch > [role="group"] {
display: none;
}
.sx-page--prestart .sx-prestart__primary-select {
min-width: 0;
display: grid;
grid-template-columns: minmax(0, 1fr) minmax(10.5rem, 1.25fr);
align-items: center;
gap: var(--sp-2);
}
.sx-page--prestart .sx-prestart__primary-select span {
color: var(--text-body);
font-size: var(--fs-xs);
font-weight: 700;
}
.sx-page--prestart .sx-prestart__primary-select select {
min-width: 0;
min-height: 44px;
padding: 0 var(--sp-2);
border: 1px solid var(--glass-inset-border);
border-radius: var(--radius-sm);
background: var(--glass-surface-inset);
color: var(--text-strong);
font: inherit;
}
.sx-page--prestart .sx-prestart__actions {
position: sticky;
z-index: 3;
bottom: var(--sp-1);
flex-wrap: nowrap;
align-items: center;
gap: var(--sp-3);
padding: var(--sp-2);
border: 1px solid var(--glass-inset-border);
border-radius: var(--radius);
background: var(--glass-surface);
box-shadow: var(--glass-shadow);
}
.sx-page--prestart .sx-prestart__actions span {
min-width: 0;
flex: 1;
}
}
@media (max-width: 720px) {
.vg-main:has(.sx-page--prestart),
.vg-main:has(.sx-page--prestart .sx-prestart--prescribed) {
padding-bottom: calc(var(--bottom-bar-h) + env(safe-area-inset-bottom) + var(--sp-6));
}
.sx-page--prestart .sx-prestart {
grid-template-areas:
"case"
"learning"
"map";
grid-template-columns: minmax(0, 1fr);
gap: var(--sp-4);
padding: var(--sp-3);
}
.sx-page--prestart .sx-prestart__visual {
grid-template-columns: 108px minmax(0, 1fr);
grid-template-rows: auto auto;
column-gap: var(--sp-3);
align-items: center;
}
.sx-page--prestart .sx-prestart__visual .vg-avatar,
.sx-page--prestart .sx-prestart__visual .vg-avatar__svg {
width: 108px !important;
height: 108px !important;
}
.sx-page--prestart .sx-prestart__visual .vg-avatar__stage {
height: 108px !important;
}
.sx-page--prestart .sx-prestart__case {
display: grid;
grid-column: 2;
grid-row: 1;
}
.sx-page--prestart .sx-prestart__facts,
.sx-page--prestart .sx-prestart__chips {
grid-column: 1 / -1;
}
.sx-page--prestart .sx-prestart__facts {
grid-template-columns: repeat(auto-fit, minmax(min(100%, 8rem), 1fr));
}
.sx-page--prestart .sx-prestart__focus-head {
grid-template-columns: minmax(0, 1fr);
align-items: start;
gap: var(--sp-2);
}
.sx-page--prestart .sx-goals__grid {
grid-template-columns: repeat(2, minmax(0, 1fr));
}
.sx-page--prestart .sx-prestart__plan {
display: grid;
}
/* 처방 재연습은 과제·성공 기준이 이미 위에 고정되어 있다. 작은 화면에서 이를
다시 설명하거나 목표 선택을 노출하면 주 행동(회기 시작)이 첫 화면 밖으로 밀린다. */
.sx-page--prestart .sx-prestart--prescribed {
grid-template-areas:
"learning"
"case";
}
.sx-page--prestart .sx-prestart--prescribed > .sx-prestart__plan,
.sx-page--prestart .sx-prestart--prescribed .sx-prestart__focus {
display: none;
}
.sx-page--prestart .sx-prestart--prescribed .sx-prestart__actions span {
display: none;
}
.sx-page--prestart .sx-prestart__learning-loop {
grid-template-columns: minmax(0, 1fr);
}
.sx-page--prestart .sx-prestart__learning-loop li {
grid-template-columns: minmax(3.5rem, auto) minmax(0, 1fr);
}
.sx-page--prestart .sx-prestart__actions,
.sx-page--prestart .sx-prestart--prescribed .sx-prestart__actions {
position: sticky;
z-index: 3;
bottom: calc(var(--bottom-bar-h) + env(safe-area-inset-bottom) + var(--sp-2));
padding: var(--sp-2);
border: 1px solid var(--glass-inset-border);
border-radius: var(--radius);
background: var(--glass-surface);
box-shadow: var(--glass-shadow);
}
.sx-page--prestart .sx-prestart__actions .vg-btn {
width: 100%;
}
.sx-page--prestart .sx-prestart__actions span {
display: block;
}
}
@media (max-width: 460px) {
.sx-page--prestart .sx-prestart__visual {
display: grid;
}
.sx-page--prestart .sx-prestart--prescribed {
grid-template-areas: "learning";
}
.sx-page--prestart .sx-prestart--prescribed .sx-prestart__visual {
display: none;
}
.sx-page--prestart .sx-prestart__visual {
grid-template-columns: 88px minmax(0, 1fr);
}
.sx-page--prestart .sx-prestart__visual .vg-avatar,
.sx-page--prestart .sx-prestart__visual .vg-avatar__svg {
width: 88px !important;
height: 88px !important;
}
.sx-page--prestart .sx-prestart__visual .vg-avatar__stage {
height: 88px !important;
}
.sx-page--prestart .sx-goals__grid button {
min-height: 64px;
padding: var(--sp-2);
}
}

View file

@ -30,13 +30,22 @@
| REQ-004 | **DONE · 내부 기술** | learner 현재 설정 AND 세션 snapshot. OFF는 AI 파생 API 403/UI 무요청·혼합 결과 redaction, 사용자 입력·privacy 보존; teacher/admin 유지 |
| REQ-005 | **DONE · 내부 기술·운영 실증** | 새 회기는 승인 페르소나 `persona_id/version` 고정. P20의 `suicide_ideation_stage=0.9 → int(0) → DB 1..5` 장애를 clamp로 제거했고, 공개 P20 회기 생성·실제 AI 응답·종료·평가를 확인 |
| REQ-006 | **DONE · 내부 기술** | prompt와 구조화 결과의 상담자/내담자 identity를 `[COUNSELOR]`/`[CLIENT]`로 역할 마스킹 |
| REQ-007 | **DONE · 내부 기술** | 회기 종료를 평가보다 먼저 영속화해 옛 평가 실패 뒤에도 새 회기 생성·턴 진행 가능 |
| REQ-007 | **DONE · 내부 기술** | 회기 종료를 평가보다 먼저 영속화해 평가 실패 뒤에도 같은 learner-persona case의 다음 회기 생성·턴 진행 가능. 종료·시작은 같은 case row lock 순서를 써 S2가 S1 summary/carry를 빠뜨리지 않고, 진행 중인 같은 case는 409 `active_session_exists`로 기존 회기만 이어간다. migration 21의 online partial unique index와 invalid-index pre/postcondition이 병렬 생성을 fail-closed로 차단 |
| REQ-008 | **READY · 실제 재부팅 GATE** | 원본 응답 생성 실패는 기본 엔진+live-client readiness, 구조화 done 없는 SSE EOF의 `client_stream_incomplete` 복원과 공개 P20 실제 응답으로 닫았다. 후속 재부팅 복구는 전역 mutex·단계별 상한·프로세스 트리 종료·전체 다운 즉시복구와 PowerShell 5.1 timed `WaitForExit`의 process handle 선확보를 적용했다. 실제 PS5.1 계약 32 passed, detached-clean `44b7835c…`·tree `06133249…`, 5174 자동복구·HTTP 200, watchdog result 0/failcount 0까지 확인했지만 실제 Windows 재부팅 smoke 전에는 개선관리 상태를 `검토`로 유지한다. PC 비종속 상시 호스트 이전도 별도 운영 게이트다. |
2026-08-29 최신 read-only 상태에서 정적 public Web과 Pages `0c60261e…`(source `5bf89ff…`)는 유지되지만,
local API 8001은 연결 거부, public API는 530이며 Docker daemon이 없어 DB/API는 **OUTAGE**다. task는 old
detached `dba9b75a…` runtime을 계속 가리킨다. 과거 `status=ok·db=true·engine=true`와 watchdog result 0은 이전 성공
증거이지 현재 GREEN이 아니다. avatar fail-closed 코드와 upload receipt는 아직 후보이고 배포하지 않았다.
2026-08-29 read-only 상태(<b>이 PC 로컬 기준</b>): 정적 public Web과 Pages `0c60261e…`(source `5bf89ff…`)는 유지됐지만,
이 PC 로컬 API 8001은 연결 거부였고 이 PC의 Docker daemon 부재로 이 PC 기준 DB/API는 복구 불가였다. task는 old
detached `dba9b75a…` runtime을 계속 가리켰다. <b>2026-08-31 재실측(정식 분리 확인):</b> `https://api-vignette.chanpaca.net/health`는
별도 호스트(Cloudflare 뒤)에서 200·`environment=prod`·`db=true`·`engine=true`·`engine_mode=openai`로 정상 서빙 중이며,
이 PC에는 cloudflared 프로세스가 없어 public 도메인은 이 PC가 아니다. 즉 이 PC 로컬 8001/task 상태는 개발 워크스테이션의
잔여 스냅샷이고 public 도메인 장애를 뜻하지 않는다. avatar fail-closed 코드와 upload receipt는 아직 후보이고 배포하지 않았다.
2026-08-30 NAS production 재확인에서는 `vignette-prod` DB·API·engine이 healthy였고, restart loop이던 web/proxy는
필요 최소 capability만 추가해 두 서비스만 재생성했다. 내부 Caddy→web과 `/api/health`는 200이지만, compose의
Tailnet bind 주소가 NAS 인터페이스에 없어 외부 private/public GREEN은 아직 주장하지 않는다. LAN/0.0.0.0으로
노출을 넓히지 않았다. 회기 연속성 migration 21은 중복 활성 learner-persona case 14개(초과 row 28개)를 발견해
보존·종료 기준을 owner가 결정할 때까지 적용하지 않는다. 기존 20번 transactional migration과 새 21번 online index,
연속성 hunk만 포함한 production 전용 clean candidate가 필요하며 preview 전용 release agent와 8/7 manifest는 사용하지 않는다.
---

View file

@ -291,7 +291,7 @@
<div class="brand"><span class="mark" aria-hidden="true"></span><span>Vignette 커맨드센터<small>팀장 리뷰 · dev status</small></span></div>
<div class="head-right">
<a class="owner-pill" href="#owner"><span class="d" aria-hidden="true"></span>내 차례 <b id="pill-owner">0</b></a>
<span class="stamp">2026-08-29 KST</span>
<span class="stamp">2026-08-31 KST</span>
</div>
</header>
@ -300,10 +300,13 @@
<section class="pulse">
<div class="pulse-main">
<span class="eyebrow">project pulse</span>
<h1>지금 위치: <em>공개 정적 Web은 유지</em>, <em>Public API·DB는 OUTAGE</em>. 이미지 fail-closed 후보·E2E와 C-001·REQ-008 사람 게이트가 남았다.</h1>
<p class="pulse-state"><b>현재:</b> 배포된 API/task 기준선은 <code>dba9b75a…</code>, Pages는 <code>0c60261e…</code>(source <code>5bf89ff…</code>)지만 Docker daemon 부재로 local 8001은 연결 거부, public API는 530이다. 아바타 decode fail-closed 변경은 후보 코드일 뿐 미배포라 운영 GREEN이 아니다. G8 차단·보류·반려·승인의 격리 local 내장 브라우저 proof는 GREEN이다. <b>다음:</b> 전체 통합 GREEN과 G8 실DB/public proof를 확인한 뒤 push/Pages/runtime/task 전환 승인을 받고, 실제 재부팅은 별도 승인으로 실행한다.</p>
<h1>지금 위치: <em>public 도메인은 별도 호스트(Cloudflare)에서 정상 서빙 중</em>(이 PC와 분리 운영), NAS preview는 degraded. 이미지 fail-closed 후보·E2E와 C-001·REQ-008 사람 게이트가 남았다.</h1>
<p class="pulse-state"><b>2026-08-31 배포 파이프라인 재정립(소유자 지시):</b> git 관리·배포는 <code>git.chanpaca.net</code>(Forgejo 11.0.16) 중심으로 이관 완료 — <code>yunchan/vignette</code> 레포 생성, <code>master</code>=<code>be08c0b5</code> push, 소스 SSOT 지정. <code>github.com</code>(origin)은 <b>private 백업/미러</b>로 유지(제거 아님). 배포 대상은 <b>NAS Production</b>(<code>docker-compose.nas.yml</code>, <code>vignette-prod</code>)이며 이 PC는 단순 개발용. Cloudflare는 <b>서비스 공개 서빙용만 유지</b>, cloudflare tunnel은 제거 대상. 관리 도구 <code>scripts/vignette-pipeline.py --check</code>로 기준선 무결성 점검(ALL OK): 문서 <a href="./ops/deployment-pipeline.md">deployment-pipeline.md</a>.</p>
<p class="pulse-state"><b>현재:</b> 2026-08-30 NAS <code>vignette-prod</code>의 DB·API·engine은 healthy이고, restart loop이던 web/proxy는 필요한 최소 capability만 추가해 재생성했다. Caddy 내부 경유 web 및 <code>/api/health</code>는 200이지만, compose가 bind하는 Tailnet 주소가 NAS에 없어 외부 private/public GREEN은 주장하지 않는다. 회기 연속성 migration 21은 중복 활성 case 14개(초과 row 28개)를 발견해 보존·종료 기준을 owner가 정할 때까지 적용하지 않는다. 아바타 decode fail-closed 변경은 후보 코드일 뿐 미배포다. <b>다음:</b> 중복 회기 정리 기준·Tailnet 복구·production 전용 clean candidate를 확정한 뒤 DB 적용, 실제 브라우저 E2E, 외부 ingress를 순서대로 검증한다.</p>
<details class="pulse-details">
<summary>운영 복구·watchdog·배포 상세 보기</summary>
<p class="pulse-state"><b>2026-08-31 사례 연속성 후보:</b> source candidate에는 같은 NPC의 <code>완전히 새로 시작</code>(빈 새 case)과 <code>이어서 진행</code>(선택 case의 압축 기억)을 분리했고, 사례별 누적 회기·상담자 가시 턴·누적 시간을 시작 전 표시하며 기억은 lazy foldout으로 숨겼다. migration 22는 legacy case unique만 해제하고 migration 21의 단일 활성 회기 제약을 유지한다. 이는 source/test 후보 상태이며 NAS DB 적용·배포·실제 production 브라우저 GREEN은 아직 하지 않았다.</p>
<p class="pulse-state"><b>2026-08-30 NAS production preflight·ingress 복구:</b> <code>vignette-prod-db-1</code>·<code>vignette-prod-api-1</code>·<code>vignette-prod-engine-1</code>은 healthy였다. <code>vignette-prod-web-1</code>은 Nginx startup에 필요한 최소 capability, <code>vignette-prod-private-proxy-1</code>는 Caddy bind에 필요한 최소 capability가 빠져 restart loop이었고, 두 서비스만 재생성해 restart 0의 running 상태와 Caddy→web/API health 200을 확인했다. DB·upload volume·API·engine·tunnel은 건드리지 않았다. 다만 configured Tailnet bind <code>100.116.83.60</code>는 NAS 인터페이스에 없어 host port가 열리지 않는다. LAN/0.0.0.0 bind로 넓히지 않았으며, Tailnet 자체 복구 또는 owner가 정한 보안 경계를 먼저 적용해야 한다.</p>
<p class="pulse-state"><b>2026-08-29 최신 read-only 상태:</b> <code>VignettePublicRuntime</code>과 watchdog은 여전히 old <code>dba9b75a…</code> root를 가리키며, Docker Desktop Linux engine pipe가 없어 DB/API 복구에 실패한다. 정적 로그인 Web 200은 동적 API 정상 증거가 아니다. 운영 변경 승인 전에는 Docker 시작·API/tunnel 재시작·task 재등록·DB/avatar URL 수정·stable upload root cutover를 하지 않는다.</p>
<p class="pulse-state"><b>2026-08-29 아바타 무결성:</b> 허용 source union은 <code>93 objects · 52,973 bytes · SHA-256 9d703126…e6aa</code>다. 실제 decode는 정상 3·실패 90, 현 DB 참조는 정상 2·실패 6·missing 0이다. 후보는 손상 bytes와 참조를 private forensic으로 보존하되 public serve는 404/fallback으로 막고, decode-valid 객체만 immutable public cache에 싣는다. 이 후보는 전체 API/Web/E2E·내장 브라우저·운영 배포 검증 전까지 GREEN이 아니다.</p>
<p class="pulse-state"><b>2026-08-29 재부팅 복구 hardening의 이전 성공 증거:</b> Windows PowerShell 5.1의 timed <code>WaitForExit()</code>가 process handle 선확보 없이는 성공한 web build의 <code>ExitCode</code>를 null로 남겨 실패로 오판하는 경계를 수정했다. 실제 PS5.1 계약 <code>32 passed</code>, detached-clean <code>44b7835c…</code>·tree <code>06133249…</code>에 로그온·5분 watchdog을 같은 핀으로 재등록했다. 당시 watchdog 3회차 복구로 5174가 자동 기동해 HTTP 200을 반환했고 후속 실행은 <code>LastTaskResult=0</code>·failcount 0, local/public health <code>status=ok·db=true·engine=true</code>였다. 기존 <code>ExecutionTimeLimit=PT1H</code>·<code>MultipleInstances=IgnoreNew</code>·exclusive mutex·bounded wait·process-tree 종료·hard-down 즉시복구 계약도 유지한다. 이것은 로그인 뒤 과거 복구 증거이며 현재 장애나 실제 Windows 재부팅 smoke를 대신하지 않는다.</p>
@ -320,7 +323,7 @@
<span class="mchip good">Outcome clean E2E <b>126</b> · visual <b>15/15</b></span>
<span class="mchip good">Alliance G1 baseline 1.2 <b>9/9</b> · 내부 DONE</span>
<span class="mchip">Tailnet <b>이전 확인 OK</b></span>
<span class="mchip crit">Public API <b>OUTAGE · 530/local refused</b></span>
<span class="mchip good">Public API(정식) <b>200 · prod · db/engine true</b></span>
<span class="mchip">이전 OpenAPI 증거 · Public API <b>126 paths · G1~G8</b></span>
<span class="mchip good">Direct-runtime preflight <b>APP ROLE OK</b></span>
<span class="mchip crit">Avatar decode <b>3 valid · 90 invalid</b></span>
@ -709,6 +712,8 @@
<p class="dg-note">220차 개선관리 완료본 현행 증거 동기화(2026-08-29): <code>Vignette_개선관리_완료.xlsx</code>의 상태·수식·서식은 유지하고 <code>개발·기능 이슈!M5:M12</code>와 <code>임상·교육 이슈!M6:M7</code>의 오래된 API/Pages 배포 근거만 현재 <code>dba9b75a…</code>·tree <code>14cd4607…</code>·Pages <code>ef48c0ae…</code>로 갱신했다. artifact-tool import→values-only edit→export→reimport 뒤 6개 전 시트와 수정 집중 4개 렌더를 직접 확인했고 수식 오류 0, 완료 8·검토 3·총 11, 임상 checker <code>pending_external_review</code>·<code>review_complete=false</code>를 유지한다. 새 완료본 SHA는 <code>aab6ef52…e26a</code>다. 기존 C-001 사전검증 원장은 당시 14개 해시의 역사 증거로 보존하고, 현행 원장에서 기술 산출물 13/13 불변과 새 워크북 해시를 결합해 현재 패키지 14/14 연속성을 다시 확인했다. 실제 Gmail callback·Windows 재부팅 smoke·외부 임상 승인 없이 상태를 완료로 올리지 않았다. 기계 판독 증거는 <code>docs/ops/evidence/workbook-runtime-sync-2026-08-29.json</code>이다.</p>
<p class="dg-note">221차 교수자 콘솔 표면 간격 교정·공개 승격(2026-08-29): <code>/teach</code>의 검토 큐와 교수자 요약이 독립 Surface인데 부모 <code>.pf-signal-strip</code>의 <code>gap:0</code> 때문에 테두리·그림자가 맞붙던 원인을 <code>--sp-3</code>=12px로 교정했다. 수정 전 0px를 다시 주입해 새 회귀 검사가 RED가 되는 것을 확인하고 복원 뒤 focused <b>1 passed</b>, 390~1440 7폭 교수자 gate <b>1 passed</b>, 전체 layout visual <b>15 passed</b>, session 무회귀 <b>8 passed</b>, typecheck·design SSOT·lint·build를 통과했다. tracked-clean <code>5bf89ff4…</code>·tree <code>29f76aeb…</code>에서 599파일 build 2회 byte-identical, 이전 자산 172개 보존 후 Pages production <code>0c60261e-cb37-482d-ba42-d91586194c48</code>로 승격했다. 실서비스 1425×1272 DOM은 computed/실측 간격 12px·overflow 0·console warning/error 0이고 custom/preview의 <code>Professor-BfR874KA.css</code> SHA <code>63dbe2c7…7fff</code>가 clean build와 일치한다. 증거는 <code>docs/ops/evidence/professor-summary-gap-deploy-2026-08-29.json</code>이다.</p>
<p class="dg-note">222차 REQ-001 완료·개선관리 재생성(2026-08-29): 기존 실서비스 인증 세션은 <code>yunchan8804@gmail.com</code>으로 설정·관리자 콘솔에 접근하고 온보딩으로 되돌아가지 않으며, 학습 이력 20건·리뷰 필요 6건을 표시했다. 소유자가 복구 데이터 가시성을 수락했고 최신 Pages <code>0c60261e…</code>의 단일 Google CTA 1개·구 선택 버튼 0·dev login 0·무제한 도메인·공개 Playwright 2 passed를 함께 확인해 REQ-001을 완료로 승격했다. 개선관리 완료본은 artifact-tool 구조 추출로 <b>6시트·11개 고유 요구·38수식·오류 0·완료 9/검토 2</b>를 확인했다. C-001은 패키지 8/8·기술 사례 6/6·canonical checker 정상의 <code>pending-valid</code>이며 외부 입력 46칸은 공란으로 보존했다. 완료본 SHA는 <code>c832547f…d8bd</code>, sidecar SHA는 <code>8c9618f0…a610</code>이고 REQ-008 실제 Windows 재부팅 smoke와 C-001 외부 임상 승인만 검토로 남는다.</p>
<p class="dg-note">223차 REQ-007 회기 연속성 보강(2026-08-30, source-only): 종료 기록의 모호한 <code>다시 연습</code> 행동을 <code>다음 회기 이어가기</code>로 바꾸고, 같은 learner-persona case에 진행 중 회기가 있으면 API가 <code>409 active_session_exists</code>와 기존 session id를 돌려 브라우저가 그 회기로 이동하게 했다. 종료·시작은 동일 case row를 먼저 잠가 S2가 S1의 summary/carry를 빠뜨리지 않으며, migration 21의 online partial unique index와 invalid/wrong-index 전·후 condition이 병렬 active row를 fail-closed로 막는다. 종료 영속 뒤 다음 회기는 평가 완료를 기다리지 않는다. 연속성 대상 API <b>87 passed</b>(현 작업트리의 별도 stale-evaluation timeout 기대치 1건 제외), release agent <b>32 passed</b>, Playwright history <b>14 passed</b>·continuity guard <b>1 passed</b>, typecheck·API type check·production build를 확인했다. 기존 DB migration 21은 owner의 duplicate/target-index read-only audit 및 명시 적용이 필요하며, 공개/NAS/DB에는 적용·배포하지 않았다.</p>
<p class="dg-note">224차 NAS production preflight·ingress 복구(2026-08-30): 운영 DB에는 같은 learner-persona의 중복 활성 case <b>14개</b>(초과 active row <b>28개</b>)가 있어 migration 21의 partial unique index를 적용하지 않았다. 과거 회기 중 turn이 있는 row를 자동 종료하거나 삭제하지 않고 owner의 보존·종료 기준을 기다린다. 운영에는 이미 transactional <code>20_public_bootstrap_ticket_events.sql</code>이 있으므로 새 online index는 <code>21_single_active_session.sql</code>로 번호를 분리했다. NAS web/proxy restart loop은 최소 capability를 추가해 두 서비스만 재생성하고 내부 Caddy→web/API health 200으로 복구했지만, configured Tailnet bind 주소가 NAS에 존재하지 않아 외부 private/public GREEN은 아니다. preview 전용 release agent·기존 8/7 manifest를 production 경로로 재사용하지 않으며, 연속성 hunk와 migration 20/21을 명시한 clean production candidate가 별도로 필요하다.</p>
<div class="dg-principles" aria-label="디자인 생성 가드레일">
<div><b>래스터만 사용</b><span>이미지 생성 도구 산출물은 PNG 기반 시안이다. SVG·벡터·와이어프레임·로고 시트로 해석하지 않는다.</span></div>
<div><b>기능 우선</b><span>메인 라우트의 실제 액션과 정보 구조를 먼저 반영한다. 장식은 기능을 가리지 않는 수준에서만 쓴다.</span></div>
@ -1119,7 +1124,7 @@
<tbody>
<tr><td>Web typecheck</td><td><code>npm run typecheck</code></td><td>Passed</td></tr>
<tr><td>Design SSOT / auth visual</td><td><code>npm run check:design-ssot</code> / <code>npx playwright test e2e/auth-visual.spec.ts --project=chromium-single-run --reporter=line</code> / <code>npx playwright test e2e/layout-visual-gate.spec.ts --project=chromium-single-run --reporter=line</code></td><td>SSOT checker passed; login/onboarding light-dark desktop-mobile 1 passed; 14 core screens × 7 widths visual gate 14 passed.</td></tr>
<tr><td>Full Playwright E2E baseline</td><td><code>npm run e2e:parallel</code> / <code>npm run e2e:single-run</code> / <code>npm run e2e:list</code></td><td>2026-08-29 현재 수집은 <b>1158 tests / 64 files</b>다. 이 숫자는 수집량이며 현 작업트리 전체 GREEN과 동일하지 않다. G8 clean-head release gate는 candidate 112/112와 실제 NAS-origin 112/112를 통과했다. 이전 단일 120/120과 2026-07-15의 fixture desktop/mobile 166/166 + DB/engine/provider 직렬 49/49 = 215/215는 범위가 다른 역사 기준선으로 보존한다.</td></tr>
<tr><td>Full Playwright E2E baseline</td><td><code>npm run e2e:parallel</code> / <code>npm run e2e:single-run</code> / <code>npm run e2e:list</code></td><td>2026-08-31 현재 수집은 <b>1182 tests / 66 files</b>다. 이 숫자는 수집량이며 현 작업트리 전체 GREEN과 동일하지 않다. G8 clean-head release gate는 candidate 112/112와 실제 NAS-origin 112/112를 통과했다. 이전 단일 120/120과 2026-07-15의 fixture desktop/mobile 166/166 + DB/engine/provider 직렬 49/49 = 215/215는 범위가 다른 역사 기준선으로 보존한다.</td></tr>
<tr><td>Refactor governance P1~P8</td><td><code>ruff check app</code> / <code>pytest -q app</code> / <code>pytest -q engine_gateway</code> / <code>npm run typecheck</code> / <code>npm run check:api-types</code> / <code>npm run check:design-ssot</code> / <code>npm run check:dead-code</code> / <code>npm run check:duplication</code> / <code>npm run build</code> / <code>npm audit --audit-level=high</code> / full Playwright</td><td>Backend 400 passed, gateway 29 passed, web gates/build/audit passed, vulnerabilities 0, production duplication 1 clone/15 lines/0.03%, Playwright 215/215 passed. 상세 근거는 <code>ops/refactor-governance-2026-07-15.md</code>.</td></tr>
<tr><td>API typegen SSOT</td><td><code>npm run check:api-types</code></td><td>Passed; FastAPI OpenAPI → <code>src/lib/api.gen.ts</code> stale check</td></tr>
<tr><td>Outcome &amp; Alliance OS G0</td><td><code>py -3.11 -X utf8 -m pytest -p no:cacheprovider apps/api/app/test_measurement_contract.py apps/api/app/test_runtime_schema_ssot.py -q</code> / <code>scripts/check-measurement-ledger.sql</code> / measurement·API contract checks / web typecheck / DB-backed <code>session-persistence</code> focused E2E 3종</td><td>G0 contract/schema 11 passed, 기존 backend 100 passed, auth 39 passed. Python→JSON Schema→TypeScript→PostgreSQL enum·필수필드 계약이 일치하고 8개 deterministic benchmark가 검증됐다. Live PostgreSQL에서 learner/client/evaluator 가시 행 1/1/2, 교차 누수 0, append-only guard 2를 확인했다. 학습자 턴→교수자 대시보드, 워크시트 검수, 종료 deep 평가→durable 리뷰 E2E는 각각 1 passed. G0/AOS-001~004 완료.</td></tr>
@ -1216,10 +1221,10 @@
<tr><td>Public OAuth start</td><td><code>/auth/config</code> + <code>/auth/login?provider=google</code></td><td>2026-08-28 public auth config 200, Google configured true, <code>allowed_email_domains=[]</code>, redirect URI <code>https://api-vignette.chanpaca.net/auth/callback</code>, dev-login disabled. 로그인 DOM은 모든 Google 계정을 명시하고 실제 Google 선택기에 <code>yunchan@twentyoz.kr</code>와 <code>yunchan8804@gmail.com</code>이 함께 노출됐다. 기존 Google 계정 선택→callback→<code>/admin</code> 성공을 확인했다. 신규 Gmail 선택은 Vignette 계정 생성이므로 사용자 행동시점 확인 뒤 별도 실증한다.</td></tr>
<tr><td>Persona auth boundary</td><td><code>GET /personas</code></td><td>2026-06-30 복구 후 public unauth <code>/personas</code>는 401 <code>not authenticated</code>를 반환한다.</td></tr>
<tr><td>Public login</td><td><code>auth.spec.ts --grep public login</code></td><td>1 passed</td></tr>
<tr><td>Public runtime scripts · source pin</td><td><code>start/watch/boot-public-runtime*.ps1</code> · <code>install-public-runtime-task.ps1</code> · <code>register-boot-task.ps1</code></td><td>2026-08-29 최신 read-only 확인에서 두 task는 old detached <code>dba9b75a…</code> runtime을 계속 가리킨다. Docker daemon 부재로 runtime task는 실패했고 watchdog도 DB/API를 복구하지 못한다. 새 total-size/decode receipt 후보는 미배포이며, 후보 통합 GREEN·사용자 승인 전 task 재등록이나 runtime 재시작을 하지 않는다. 실제 Windows 재부팅 자동복구 smoke도 별도 운영 gate다.</td></tr>
<tr><td>Public API health</td><td><code>http://127.0.0.1:8001/health</code> / <code>https://api-vignette.chanpaca.net/health</code></td><td><b>2026-08-29 최신 상태는 OUTAGE다.</b> local 8001은 연결 거부, public API는 530이며 Docker Desktop Linux engine pipe가 없다. 정적 public Web 200은 API·DB GREEN을 뜻하지 않는다. 2026-08-28의 <code>status=ok·db=true·engine=true</code>와 voice exact 값은 과거 성공 증거로만 보존한다.</td></tr>
<tr><td>Public runtime current snapshot</td><td><code>health + provenance + Scheduled Tasks + Pages</code></td><td>배포된 동적 런타임/task 기준선은 clean commit <code>dba9b75a…</code>·tree <code>14cd4607…</code>, Cloudflare Pages production은 <code>0c60261e-cb37-482d-ba42-d91586194c48</code>(source <code>5bf89ff4…</code>)다. 현재 API/DB는 장애이고 fail-closed avatar 후보와 새 upload receipt는 아직 이 기준선에 승격되지 않았다. 후보와 deployed baseline을 분리하며, 승인 전 Docker/API/tunnel/task/DB/upload-root mutation을 하지 않는다.</td></tr>
<tr><td>Public/local/Tailnet login recovery</td><td><code>https://vignette.chanpaca.net/login</code> / <code>https://api-vignette.chanpaca.net/health</code> / <code>https://alpaca-home.taile93291.ts.net/login</code></td><td>2026-08-28 Google callback→관리자·P20 실제 회기 폐루프는 유효한 과거 증거다. 2026-08-29에는 public API 530으로 신규 callback·관리자·G8 실DB E2E를 재검증할 수 없으므로 현재 운영 GREEN으로 재사용하지 않는다. public Web은 정적 로그인 화면만 200이다.</td></tr>
<tr><td>Public runtime scripts · source pin</td><td><code>start/watch/boot-public-runtime*.ps1</code> · <code>install-public-runtime-task.ps1</code> · <code>register-boot-task.ps1</code></td><td>이 행은 <b>이 PC의 Windows 런타임/task 기준</b>이다. 2026-08-31 실측에서 이 PC에는 <code>cloudflared</code> 프로세스가 없고 <code>VignettePublicRuntime</code>/<code>Watchdog</code> 두 Scheduled Task는 Disabled이며 로컬 <code>8001</code> listener도 없다 — 이 PC는 더 이상 public 호스트 역할을 하지 않는다. public 도메인은 별도 호스트에서 정상 서빙 중(health 200). 새 avatar fail-closed receipt 후보는 여전히 미배포이며, 사용자 승인 전 이 PC의 task 재등록·runtime 재시작을 하지 않는다. 실제 Windows 재부팅 자동복구 smoke는 별도 운영 gate다.</td></tr>
<tr><td>Public API health</td><td><code>http://127.0.0.1:8001/health</code> / <code>https://api-vignette.chanpaca.net/health</code></td><td><b>2026-08-31 실측: public 도메인은 200·<code>environment=prod</code>·<code>db=true</code>·<code>engine=true</code>·<code>engine_mode=openai</code>로 정상 응답</b>한다(<code>Server: cloudflare</code>, 이 PC가 아닌 별도 호스트가 서빙). 이 PC 로컬 <code>127.0.0.1:8001</code>은 listener 없음(이 PC가 public 호스트 역할을 안 하므로)이며, 이는 도메인 장애가 아니라 <b>개발 워크스테이션과 정식 운영의 분리</b>를 반영한다. NAS preview 8088은 별개로 <code>degraded</code>다. 2026-08-29 OUTAGE 기록은 그 시점의 이 PC 기준 스냅샷으로, 오늘 실측이 이를 대체한다.</td></tr>
<tr><td>Public runtime current snapshot</td><td><code>health + provenance + Scheduled Tasks + Pages</code></td><td>과거 이 PC 배포 기준선은 clean commit <code>dba9b75a…</code>·tree <code>14cd4607…</code>, Pages production <code>0c60261e…</code>(source <code>5bf89ff4…</code>)다. 2026-08-31 실측상 public 도메인은 별도 호스트에서 200·prod·db/engine true로 동작 중이고, 이 PC는 개발 워크스테이션일 뿐이다(과거 이 PC 기준선의 '장애'는 이 PC 미사용에 따른 잔여 스냅샷). fail-closed avatar 후보와 새 upload receipt는 아직 승격되지 않았다. 후보와 deployed baseline을 분리하며, 승인 전 Docker/API/tunnel/task/DB/upload-root mutation을 하지 않는다.</td></tr>
<tr><td>Public/local/Tailnet login recovery</td><td><code>https://vignette.chanpaca.net/login</code> / <code>https://api-vignette.chanpaca.net/health</code> / <code>https://alpaca-home.taile93291.ts.net/login</code></td><td>2026-08-28 Google callback→관리자·P20 실제 회기 폐루프는 유효한 과거 증거다. <b>2026-08-31 실측(Playwright chromium): public 로그인 화면 폐루프 1 passed, 데스크톱/모바일 HTTP 200, Google OAuth redirect_uri=<code>https://api-vignette.chanpaca.net/auth/callback</code> 확인, dev-login 차단, 예상된 <code>/auth/me</code> 401 외 콘솔/페이지 에러 0</b> — 읽기 전용 실증 완료(<a href="./evidence/public-domain-readonly-browser-2026-08-31.json">증거</a>). 실제 Google 계정 로그인→callback→관리자·P20 실회기·턴 생성은 production DB mutation이라 소유자 승인·계정 세션(storageState)이 필요해 여전히 열린 게이트다.</td></tr>
<tr><td>Local 5175 login</td><td><code>PLAYWRIGHT_BASE_URL=http://127.0.0.1:5175 auth.spec.ts</code></td><td>desktop/mobile passed</td></tr>
<tr><td>Learner/readiness E2E</td><td><code>learner.spec.ts + readiness.spec.ts desktop/mobile</code></td><td>14 passed</td></tr>
<tr><td>Learner growth header</td><td><code>uc-learner-home-dashboard.spec.ts --grep "성장 지표 라포 헤더"</code></td><td>2026-08-28 chromium desktop/mobile 2 passed. 라포 문구 부모를 inset surface에서 plain div로 바꾸고 computed background transparent·border/radius/padding 0을 고정했다. typecheck·design SSOT·cosmetic filter safety도 통과했으며 Pages에는 아직 미배포다.</td></tr>

View file

@ -307,10 +307,12 @@ RBAC×AIView로 차단된다. 이 모듈은 평가 신호만 산출한다.
회기 라이프사이클 메모리(4계층 매핑: ① working / ② episodic / ③ summary / ④ semantic).
- 회기 시작: `(persona_id, learner_id)` 안정 `case_profile`을 확보한 뒤
`build_recall_context(...) -> RecallContext`를 조립한다. 동기 seed는
`case_profile.case_digest` + 직전 `session_summary` + client-visible `pinned_fact`
기반이고, episodic 단편/KB 단서는 백그라운드 warm cache로 붙는다.
- 회기 시작: `continue`는 선택한 owned `case_id`(구클라이언트는 가장 최근 사례)를 같은
생성 트랜잭션 안에서 잠그고 `build_recall_context(...) -> RecallContext`를 조립한다.
`fresh`는 활성 회기 검사를 먼저 통과한 뒤 빈 `case_profile`을 새로 만들어 항상 1회기·빈
recall로 시작한다. 동기 seed는 이어지는 사례의 `case_profile.case_digest` + 직전
`session_summary` + client-visible `pinned_fact` 기반이고, episodic 단편/KB 단서는
백그라운드 warm cache로 붙는다.
- 회기 종료: 마스킹된 client-visible 축어록으로 fallback `session_summary.digest`를 만들고,
같은 트랜잭션에서 `case_profile.case_digest`, `rapport_trajectory`, `alliance_level`을
갱신한다. 동시에 마스킹된 client-visible 발화에서 `[NAME]`/`[ORG]` identity와 명시적 상담 약속만
@ -391,9 +393,11 @@ session lifecycle을 유지하며, future Node read API는 이 read-model contra
핵심 엔드포인트:
- `POST /sessions` — `get_catalog_persona(code)`로 승인 카드 조회 → `case_profile` upsert →
case digest/직전 summary/pinned fact seed recall → `state_machine.init_state(...)` →
`session_persistence.create_session(...)`. 생성 시 승인 페르소나의 `persona_id`와 `persona_version`을
- `POST /sessions` — `get_catalog_persona(code)`로 승인 카드 조회 → `start_mode=fresh|continue`와
선택 `case_id`를 영속 생성 트랜잭션에 전달 → 사례별 digest/직전 summary/pinned fact seed recall →
`state_machine.init_state(...)` → `session_persistence.create_session(...)`. `fresh`는 기존 사례의
기억을 읽지 않는 별도 case를 만들고, `continue`는 소유한 해당 case만 이어간다. 생성 시 승인 페르소나의
`persona_id`와 `persona_version`을
세션에 고정하고 시작/상세 응답에도 두 값을 반환한다. 이후 더 높은 버전이 승인돼도 기존 회기는 고정된
역사 버전을 해석한다. DB 영속 생성 실패는 안전하지 않은 성공으로 흡수하지 않고 안정적인
`503 session_persistence_unavailable`로 반환한다. 프론트 세션 시작 전 화면은 `persona.theory_target`
@ -443,6 +447,11 @@ session lifecycle을 유지하며, future Node read API는 이 read-model contra
제외한다. `growth.training_exposure`는 종료 회기만 집계하고 4회 미만이면 `insufficient`, 4회 이상에서
최다 페르소나 비중이 0.75 이상이면 `훈련 집중 주의`, 그 밖에는 `balanced`로 표시한다. 투명한 노출 비중이지
공정성·임상 진단이 아니다. 성취는 공식 등급/수료가 아니라 실제 연습 milestone만 표시한다.
- `GET /sessions/cases?persona_code=...` — 같은 NPC의 사례별 누적 회기·상담자에게 보인 턴·누적
회기 시간과 진행 중 회기를 DB 전체에서 집계한다. 런타임 추정값은 반환하지 않으며 DB read가 실패하면
503으로 닫아 UI가 이어가기를 열지 않는다. `GET /sessions/cases/{case_id}/memory`는 foldout을 연
학습자에게만 소유 사례의 압축 digest·미해결 주제·client-visible 고정 기억을 제한 길이로 반환하며,
원문 축어록·evaluator·CCD·episodic 벡터는 반환하지 않는다.
- `GET /sessions/{id}/review` — 저장된 축어록 + 평가 AI 산출물을
`session_read_model.build_session_review(...)`가 학습자-안전 리뷰로 구성한다. 리뷰 조회 시 발화별 fast-loop 평가는
`app.feedback_scores`/라벨 조인 테이블에서 `TurnRecord.evaluation` 형태로 hydrate한다.
@ -775,7 +784,7 @@ React 19 + Vite. 라우팅은 `apps/web/src/App.tsx`(react-router-dom).
## 5. 데이터베이스 스키마 개요
DB는 PostgreSQL 16 + pgvector(단일 SoR). 초기화 SQL은 `infra/db/init/`에 번호순으로 적용되며,
개선관리 계약까지 필요한 현행 끝점은 `17_improvement_workbook_contracts.sql`이다.
개선관리·회기 순차성 계약까지 필요한 현행 끝점은 `21_single_active_session.sql`이다.
스키마는 **4분할**: `app` / `kb` / `audit` / `ds`.
### 5.1 app 스키마 (`infra/db/init/02_schema.sql`)
@ -791,7 +800,10 @@ DB는 PostgreSQL 16 + pgvector(단일 SoR). 초기화 SQL은 `infra/db/init/`에
`app.counselor_profile`(상담사 AI).
- **라벨 코드테이블**(taxonomy 3축) — `stage_def`, `technique_label_def`, `client_state_def`, `scale_def`.
- **세션** `app.sessions` — case_id/persona_id/persona_version 핀, stage_path. `case_id`는
(persona_id, learner_id) 복합 인스턴스 식별.
같은 `(persona_id, learner_id)` 안에서도 새 사례와 이어지는 사례를 구분하는 별도 사례 식별이다.
migration 21의 partial unique index는 같은 learner-persona의 미종료 회기를 하나로 제한한다.
종료가 durable하게 기록된 뒤에만 선택한 case의 다음 `session_no` 또는 빈 새 case의 1회기를
생성한다.
- **회기 보관 상태** `app.session_archive_state` — `session_id`/`learner_id` 단위의 학습자 보기 상태.
`archived_at`/`updated_at`만 저장하고 restore 시 row를 삭제한다. RLS는 학습자 본인의 보관/복원과
teacher/admin 조회만 허용하며, 원 세션·발화·리뷰·공유 링크는 보존한다.
@ -921,7 +933,7 @@ DB는 PostgreSQL 16 + pgvector(단일 SoR). 초기화 SQL은 `infra/db/init/`에
- ① WORKING `app.session_state` — 상태머신 수치 체크포인트(매 턴 UPSERT, openness/ideation CHECK 제약).
- ② EPISODIC 임베딩 `app.turn_embedding` — BGE-M3 dense `vector(1024)` + sparse, HNSW 인덱스.
- ③ SUMMARY `app.session_summary` — (A) end_state 무손실 carry-over + (B) digest narrative.
- ④ SEMANTIC `app.case_profile`(evolving, `UNIQUE(persona_id, learner_id)`) + `app.pinned_fact`
- ④ SEMANTIC `app.case_profile`(evolving, learner-persona당 여러 종료 사례 허용) + `app.pinned_fact`
(+`pinned_fact_history` append-only). 현재 자동 쓰기는 learner-owned case의 마스킹 identity/agreement
fact만 허용하고, 삽입/값 변경 history와 명시적 상담 약속 철회 contradiction까지 남긴다.
관계·임상 fact 승격과 광범위 자동 모순 판정은 후속이다.
@ -934,6 +946,26 @@ DB는 PostgreSQL 16 + pgvector(단일 SoR). 초기화 SQL은 `infra/db/init/`에
기존 DB는 owner가 단일 트랜잭션으로 실행한다. 애플리케이션 역할 startup은 readiness만 확인하며 runtime
DDL로 빠진 계약을 보충하지 않는다. 누락되면 migration 17 적용을 요구하며 fail-closed한다.
### 5.1.2 단일 활성 회기 migration 21
`infra/db/init/21_single_active_session.sql`은 `(learner_id, persona_id)`에 대해 `ended_at IS NULL`인
row를 하나만 허용하는 online partial unique index를 추가한다. API도 learner-persona advisory transaction
lock 안에서 active row를 확인해 409 `active_session_exists`와 기존 `session_id`를 돌려준다. 종료와 시작은
사례 선택/생성 및 state recall을 같은 durable 경계에서 처리하므로 새 회기가 S1의 미완료 summary를 읽는
중간 상태를 만들지 않는다. 따라서 종료 후 다음 회기는 평가 완료와
무관하게 허용하되, 진행 중인 회기를 자동 종료하거나 병렬로 새 회기를 만들지 않는다. migration은 중복 active
row와 invalid/wrong-named index를 전·후 condition으로 fail-closed한다. 기존 DB 적용 전 owner는 읽기 전용
점검 뒤 보존·정리 방식을 명시적으로 결정해야 한다.
### 5.1.3 복수 사례 migration 22
`infra/db/init/22_case_profile_multi_case.sql`은 legacy
`UNIQUE(persona_id, learner_id)` constraint만 정확히 찾아 제거해 같은 NPC에 새 사례를 만들 수 있게 한다.
기존 `case_profile`·세션·요약·고정 기억은 수정하거나 병합하지 않는다. activity read index는
`CREATE INDEX CONCURRENTLY`로 만들고, 다중 legacy constraint·invalid/wrong target index는 전·후 condition으로
fail-closed한다. migration 21의 learner-persona 단일 활성 회기 제약은 유지한다. 기존 production에는 migration
21 preflight에서 발견된 중복 활성 row 보존·종료 기준을 owner가 결정한 뒤에만 21→22 순서로 적용한다.
### 5.2 audit 스키마 + app 평가/종단 (`infra/db/init/04_audit_eval_rls.sql`)
- 평가: `app.feedback_scores`(발화별 점수·rationale, `visible_to='{evaluator}'`, loop fast/deep),

View file

@ -498,7 +498,7 @@ py -3.11 scripts\sync-persona-sources.py --help
### 3.6 개선관리 migration 17과 프로토콜 레지스트리
새 Postgres volume은 `infra/db/init/`의 번호순 init으로 migration 17까지 적용한다. 이미 존재하는 DB는
새 Postgres volume은 `infra/db/init/`의 번호순 init으로 migration 21까지 적용한다. 이미 존재하는 DB는
애플리케이션 역할이 startup에서 테이블을 만들지 않으므로 owner DSN으로 한 번 적용해야 한다.
```powershell
@ -514,6 +514,26 @@ psql.exe "$env:VIGNETTE_OWNER_DATABASE_URL" -v ON_ERROR_STOP=1 --single-transact
활성화는 라이선스·`external_llm_ok` 검증과 evaluator-only RAG 색인이 한 트랜잭션에서 성공해야 끝난다.
라이선스 C/D는 외부 LLM 사용을 허용할 수 없다.
### 3.7 단일 활성 회기 migration 21
같은 학습자·페르소나 케이스는 미종료 회기를 하나만 가질 수 있다. 기존 DB에 migration 21을 적용하기 전에는
owner DSN으로 아래 **읽기 전용** 점검을 먼저 실행한다. 중복 row 또는 실패 후 남은 invalid/wrong target index가
있으면 임의 종료·삭제·DROP 하지 말고 보존/복구 방식을 소유자가 결정한다.
```powershell
psql.exe "$env:VIGNETTE_OWNER_DATABASE_URL" -v ON_ERROR_STOP=1 -c "SELECT learner_id, persona_id, count(*) FROM app.sessions WHERE ended_at IS NULL AND persona_id IS NOT NULL GROUP BY learner_id, persona_id HAVING count(*) > 1;"
psql.exe "$env:VIGNETTE_OWNER_DATABASE_URL" -v ON_ERROR_STOP=1 -c "SELECT c.relname, i.indisvalid, i.indisready, i.indisunique, pg_get_indexdef(i.indexrelid) AS definition FROM pg_class c JOIN pg_namespace n ON n.oid = c.relnamespace JOIN pg_index i ON i.indexrelid = c.oid WHERE n.nspname = 'app' AND c.relname = 'uq_sessions_one_active_learner_persona';"
```
두 결과가 비어 있거나 target index가 valid/ready/unique이고 정의가 일치할 때만 owner가 online index를 적용한다.
본 migration은 pre/postcondition으로 같은 검사를 다시 하며, `CREATE INDEX CONCURRENTLY`를 쓰므로
`--single-transaction`을 붙이면 안 된다.
```powershell
psql.exe "$env:VIGNETTE_OWNER_DATABASE_URL" -v ON_ERROR_STOP=1 `
-f infra\db\init\21_single_active_session.sql
```
---
## 4. 웹(프런트엔드) 실행

View file

@ -20,7 +20,7 @@ Vignette 저장소의 모든 검증 수단(백엔드 단위 테스트, 웹 타
| API 타입 생성 체크 | `apps/web` | `npm run check:api-types` | 불필요 | 불필요 | 불필요 | 불필요 | 불필요 | pass |
| 웹 타입체크 | `apps/web` | `npm run typecheck` | 불필요 | 불필요 | 불필요 | 불필요 | 불필요 | pass |
| 웹 빌드 | `apps/web` | `npm run build` | 불필요 | 불필요 | 불필요 | 불필요 | 불필요 | pass |
| Playwright E2E(전체) | `apps/web` | `npm run e2e` | **필요(+시드)** | **필요** | 자동기동 | 일부만 | **필요** | 현재 수집 1158 tests / 64 files · 현 작업트리 전체 GREEN 미검증 |
| Playwright E2E(전체) | `apps/web` | `npm run e2e` | **필요(+시드)** | **필요** | 자동기동 | 일부만 | **필요** | 현재 수집 1182 tests / 66 files · 현 작업트리 전체 GREEN 미검증 |
핵심 원칙: **단위 테스트(pytest)와 타입체크/빌드는 외부 서비스 없이 단독 실행된다.**
**E2E만 풀스택(DB+API+웹+브라우저)을 요구한다.** 아래 각 절에서 근거와 절차를 설명한다.
@ -309,7 +309,7 @@ VITE_API_BASE=http://127.0.0.1:8000 npm run e2e # 프록시 대신 API
### 3.6 실측 테스트 개수 (현재)
2026-08-29 `npx playwright test --list` 기준 **현재 수집 1158 tests / 64 files**다
2026-08-31 `npx playwright test --list` 기준 **현재 수집 1182 tests / 66 files**다
(유스케이스 16테마 `uc-*.spec.ts` 239 시나리오 포함).
이 숫자는 수집량이지 통과량이 아니다. 현 작업트리 전체 1109개 완주는 아직 증거가 없으며,
과거 전체 GREEN 기록과 이번 focused/release gate 결과를 구분해 적는다.

View file

@ -20,8 +20,11 @@
> 승인 10필드와 서명 증거가 없어 B4 외부 GATE로 유지하며, `review_complete=true` 전에는 완료로 닫지 않는다.
> 현재 개선관리 집계는 **완료 9·검토 2·총 11**이다. C-001 외부 입력 46칸은 조작하지 않는다.
>
> **2026-08-29 최신 운영 상태** — 정적 public Web은 200이지만 local API 8001은 연결 거부, public API는 530이고
> Docker daemon 부재로 DB/API는 OUTAGE다. 배포된 동적 runtime/task 기준선은 old `dba9b75a…`, Pages는
> **2026-08-29 최신 운영 상태(이 PC 로컬 기준)·2026-08-31 재실측 정정** — 당시 이 PC 로컬 API 8001은 연결 거부였고 이 PC의
> Docker daemon 부재로 이 PC 기준 DB/API는 복구 불가였다(이 PC는 개발 워크스테이션). <b>2026-08-31 재실측:</b> public 도메인
> `https://api-vignette.chanpaca.net/health`는 별도 호스트(Cloudflare 뒤)에서 200·`environment=prod`·`db=true`·`engine=true`로
> 정상 서빙 중이며, 이 PC에는 cloudflared 프로세스가 없어 public 도메인은 이 PC가 아니다. 즉 2026-08-29의 OUTAGE 표현은
> 도메인 장애가 아니라 이 PC 로컬 상태였으며 오늘 실측이 이를 대체한다. 배포된 동적 runtime/task 기준선은 old `dba9b75a…`, Pages는
> `0c60261e…`(source `5bf89ff…`)다. avatar union은 93 objects·52,973 bytes·SHA-256 `9d703126…e6aa`, decode
> 정상 3/실패 90, 현 DB 참조 정상 2/실패 6/missing 0이다. fail-closed 후보와 deployed baseline을 분리하며,
> 전체 회귀·아바타 실브라우저 fallback·G8 실DB/public 증거·사용자 배포 승인 전에는 운영 전체를 GREEN으로 올리지 않는다.
@ -30,6 +33,10 @@
> 현재 소스·실행 증거 재감사에서는 G0~G6과 G8이 DONE이다. G1 승격 prompt 1.2+read-skew/JSON 복구는 24/24 ready·방향 9/9·오류 0을 재확인했고, G0 census 29/29·위반 0, G4/G5 실제 API/DB/브라우저 폐루프, G6 safety metadata-only 최우선 runtime을 disposable clone에서 확인했다. G8은 실제 receipt-bound image rollback 2회(`nas-g8-723eeef2…`/`nas-g8-2738846c…`)에 더해 source HEAD `61a41d1f…6af`·tree `87dec55d…3b77`·archive `4d15d055…119d4d`의 candidate 112/112와 실제 NAS 평문 origin 112/112를 통과했다. 과거 `6030a677…c611`의 UUID 24건 실패와 후속 SHA 결함 rollback은 이력으로 보존하며 현재 완료 증거로 재사용하지 않는다. G7 Multimodal Alliance는 내부 구현 DONE과 외부 proof GATE를 분리한다. detached-clean public `a73bcd24…`·OpenAPI 126·`local_whisper`/`melotts` ready·authenticated WSS 무마이크 rehearsal까지 완료했고, 명시 동의 물리 마이크 3,120초·독립 라벨 voice-gain benchmark·동시 topology high-water를 추적한다. 외부 Deepgram/OpenAI adapter는 fallback으로 보존한다. G0~G8과
> AOS-001~012는 `docs/TODO.md` I절에서 전건 추적하고, 상태는 SSOT 대시보드의 9개 계획 카드가 소유한다.
> 이 얇은 백로그에는 그중 외부·환경 증거가 필요한 항목만 기존 B2/B4/Phase 3 게이트와 합쳐 유지한다.
>
> **2026-08-31 재검증(목표 마무리 기록)** — 아래 열린 항목 전건을 SSOT 대시보드(2026-08-29/30)·최신 핸드오프(`ops/handoff-goal-production-2026-08-29.md` §0)·실제 환경과 교차 재확인했다. 실증 게이트가 남아 있어 **가짜 증거로 DONE 체크하지 않는다**(운영 원칙).
> **운영 인프라 정정(중요):** 정식(production)은 `infra/docker-compose.nas.yml`의 **NAS `vignette-prod` 스택**(`ssot-host: nas`·`runtime-class: production`)으로 분리 운영 중이다. 2026-08-31 실측으로 public 도메인 `https://api-vignette.chanpaca.net/health`가 200·`status=ok`·`db=true`·`engine=true`·`environment=prod`·`engine_mode=openai`로 응답하는 반면, **이 Windows PC에는 cloudflared 프로세스가 없고 로컬 API `8001` listener도 없다** — 즉 public 도메인은 이 PC를 지나지 않는다. 이 PC는 개발 워크스테이션(과거 자택 public 호스트였던 경로의 잔여 상태: Docker `vignette-dev-db:55432` Up·로컬 엔진 `9099` LISTENING·`VignettePublicRuntime`/`Watchdog` 2개 Scheduled Task Disabled)이다. 따라서 아래 항목 중 이 PC의 `8001`/task/재부팅 관련 게이트(B2)는 **정식(NAS)과 분리된 이 PC/개발 런타임 기준**으로 읽어야 하며, public 도메인 장애를 뜻하지 않는다. push·Pages 배포·public runtime/task 변경은 별도 승인 전 미실행.
> 실제 닫힘 판정은 이 PC 기준이 아니라 **정식 운영 주체(NAS `vignette-prod` ingress·DB·도메인) 기준**으로 해야 하며, 이 PC에서 NAS ingress를 직접 실측할 수 없어 별도 확인이 필요하다. 2026-08-31 추가로 **public 도메인 읽기 전용 실브라우저 폐루프**(Playwright chromium: 로그인 화면 1 passed·데스크톱/모바일 200·Google OAuth redirect_uri 확인·dev-login 차단·`/auth/me` 401 외 에러 0)를 실증했다(증거 <code>ops/evidence/public-domain-readonly-browser-2026-08-31.json</code>) — 이는 public 도메인 정상 서빙의 추가 증거이며, 실제 Google 계정 로그인→callback→관리자/P20 실회기·턴 생성(production DB mutation)은 소유자 승인·계정 세션이 필요해 여전히 열린 게이트다. `public API/DB·아바타 정식 승격`, `G8 실DB/public 사람 게이트`, `음성 캐스케이드 live`, `DB 백업 운영화`, `vnet.18ka.net live`, `claude_cli↔Anthropic API live`, `Compose infra/.env`, `B1 티켓 자동 분류`, `C-001`, `한신대 거버넌스`, `L1 등재`, `Phase 3`은 전부 열린 게이트로 유지한다. 참고: `공개 DB 계정·회기 복구 안정화`와 `stable-source 재부팅 후 watchdog smoke`는 사실상 **같은 잔여 게이트(실제 Windows 재부팅 후 자동복구 smoke)**를 추적 중이다 — 재부팅 smoke가 닫히면 두 항목과 REQ-008이 함께 닫힌다.
---
@ -197,6 +204,39 @@
## Phase 3 파일럿 게이트 (실참여자 필요)
---
## 배포 파이프라인 재정립 + A 경로 (NAS prod 실배포 → E2E 검증) — 2026-09-01 재부팅 후 실행
> **소유자 지시(2026-08-31)**: 배포는 Forgejo(git.chanpaca.net) 중심, NAS Production 대상, github은 private 백업/미러,
> 이 PC는 개발 전용, Cloudflare는 서빙용만·tunnel 제거. **A 경로로 진행**: 실제 prod 배포 준비 → 실배포 → 로그인·작동 E2E 확인까지.
> 2026-09-01 재부팅 후 아래를 순서대로 진행. 지침: `docs/ops/deployment-pipeline.md` · 핸드오프 `docs/ops/handoff-goal-production-2026-08-29.md`.
### 재부팅 직후 (truth 재확인)
- [ ] OS/셸/경로/도구 확정(AGENTS.md §0), git HEAD·worktree·status 확인 (재부팅 전 스냅샷: HEAD `be08c0b5`, Forgejo master == 로컬, 미커밋 98/untracked 27)
- [ ] live public API health·NAS prod(`vignette-prod`, `yunchan-nas`)·Forgejo(토큰) read-only 재확인 — `scripts/vignette-pipeline.py --check`
- [ ] NAS prod 배포 기계장치 확정: 현재 preview용 SSH target(`100.116.83.60:8088`)을 prod(192.168.0.38)용 경로로 분리/고정
### A-1. 배포 후보 GREEN 정리
- [ ] 이 PC 98미커밋/27untracked를 검토해 **기능 코드 diff만 좁게 stage**(dirty tree 전체 commit 금지 — 핸드오프 §11)
- [ ] `apps/web`: `npm run typecheck`·`npm run build` / `apps/api`: 관련 test suite / SSOT checker PASS
- [ ] Forgejo master로 배포 후보(hunk) 커밋을 좁게 push, 후보 SHA·tree 고정(레포: `yunchan/vignette`)
### A-2. NAS prod 실배포 (승인·백업 후)
- [ ] NAS prod 이미지 빌드·업로드→compose 교체 절차를 **prod 전용으로 설계**(영구 볼륨 `pgdata`/`apiuploads` 보존, 다운타임 허용 창, backup/rollback)
- [ ] 소유자 실배포 승인 문구 제시 → 승인 후 NAS prod `docker-compose.nas.yml` 기준 이미지 재빌드·교체
- [ ] 배포 후 readiness: public API `status=ok·db/engine true`, NAS 5개 컨테이너 healthy, OpenAPI/auth 계약 확인
### A-3. 로그인·작동 E2E 검증 (실브라우저)
- [ ] public 도메인 로그인 화면 렌더 + Google OAuth redirect_uri 검증 (`auth.spec.ts` public) — 읽기 전용
- [ ] 실제 Google 계정 로그인→callback→관리자/P20 실회기·턴 생성(production DB mutation) — 소유자 승인 + 계정 세션(storageState) 필요
- [ ] 배포된 WEB 200·새 asset hash·MIME, DB/이미지 fallback 확인 → **로그인·정상 작동까지 전건 GREEN일 때만 완료**
### 잔여(재부팅 외) — 그대로 유지
- [ ] 실배포 완료 전까지는 아래가 열린 게이트 유지: `public API/DB·아바타 정식 승격`, `G8 실DB/public 사람 게이트`,
`음성 캐스케이드 live`, `DB 백업 운영화`, `vnet.18ka.net live`, `claude_cli↔Anthropic API live`, `Compose infra/.env`,
`B1 티켓 자동 분류`, `C-001`, `한신대 거버넌스`, `L1 등재`, `Phase 3`, 재부팅 후 watchdog smoke/REQ-008
- [ ] **20명 교육용 파일럿 운영 / 효과성·KPI 측정(SUS·자기효능감·κ/ICC·환각률) / 재귀학습 데이터셋 approved 산출 /
개인정보·동의 감사.** 문서·checker·dry-run exporter는 준비됨(`docs/phase3/*`, `scripts/check-phase3-artifacts.py`,
`scripts/export-recursive-dataset.py`, `scripts/export-phase3-kpi.py`). 공식 문항 확정, 통계 검정, 실험/통제군 배정,

View file

@ -0,0 +1,70 @@
# 배포 파이프라인 (Deployment Pipeline)
> 작성: 2026-08-31 · 문서 소유: docs/ops (SSOT 방향)
> 상태: **초기 이관 완료 / NAS 자동배포 구성 잔여**
## 목표 아키텍처 (소유자 지시)
```
이 PC(개발 워크스테이션)
│ push (master)
▼
Forgejo git.chanpaca.net ────── 소스 SSOT (이관 완료 2026-08-31)
│ ├─ 미러(백업) ── github.com (private 유지) [현행 origin]
│ └─ 배포 ──▶ NAS Production (vignette-prod)
│ docker-compose.nas.yml (SSOT-host=nas, runtime-class=production)
│
Cloudflare = 서비스 공개 서빙용만 유지 (tunnel 제거 대상)
```
- 나는 이 PC를 **개발 전용**으로만 사용한다. 배포 대상은 반드시 **NAS Production**이다.
- github.com은 **private**로 백업/미러만 유지한다 (제거 아님).
- git 관리·배포 파이프라인은 **git.chanpaca.net (Forgejo)** 이 소유한다.
## 1. 저장소 (소스 SSOT)
| 원격 | URL | 역할 | 상태 |
|---|---|---|---|
| `origin` | https://github.com/yunchan8804-blip/vignette.git | private 백업/미러 | 유지 |
| `forgejo` | ssh://git@git.chanpaca.net:2222/yunchan/vignette.git | **소스 SSOT·배포** | ✅ 이관 완료 |
- Forgejo 레포: `yunchan/vignette` (id 14, public, default master)
- 이관 기준 커밋: `be08c0b5` (master 최신, 로컬 HEAD와 일치)
- Forgejo 접근: SSH 키(`~/.ssh/id_ed25519`, Host `git.chanpaca.net` → `192.168.0.38:2222`) · API 토큰(`infra/.env.deploy`의 `FORGEJO_API_TOKEN`, gitignore)
## 2. 로컬 브랜치 규칙
- `master` = Forgejo `master`와 동기화 (배포 기준선)
- 기능/scoped 브랜치 = 개발용, 검증 후 master로 합침
## 3. NAS Production 배포 흐름 (구성 예정)
```
[이 PC] git push forgejo master
▼
[Forgejo] master = be08c0b5 (SSOT)
▼
[NAS 192.168.0.38] git pull origin master (vignette-prod 소스)
▼ docker compose -f docker-compose.nas.yml up -d --build
vignette-prod (api/web/engine/db/proxy) 재기동
▼
[Cloudflare] 서빙 (api-vignette.chanpaca.net / vignette.chanpaca.net)
```
NAS 배포는 Forgejo에서 직접 pull하는 방식으로 전환하고, cloudflare tunnel에 의존하지 않는다.
## 4. 검증 게이트 (배포 전)
- `apps/web`: `npm run typecheck`, `npm run build`
- `apps/api`: 관련 test suite
- SSOT checker `scripts/test_dev_dashboard_ssot.py`
- Forgejo master == 로컬 master (배포 무결성)
- NAS: `docker compose ps` healthy, `/api/health` ok·db/engine true
## 5. 남은 구성 작업 (TODO)
- [ ] Forgejo master를 기준으로 NAS 자동배포 스크립트/후크 구성 (또는 NAS에서 git pull)
- [ ] `origin`(github) private 유지하나 Forgejo가 SSOT임을 문서·SSOT 대시보드에 반영
- [ ] cloudflare tunnel 제거 (서빙용만 유지)
- [ ] 배포 시 NAS 접근 자격(SSH 키/배포 계정)을 `.env.deploy`/시크릿으로 관리
```

View file

@ -0,0 +1,62 @@
{
"$schema": "evidence/v1",
"id": "public-domain-readonly-browser-2026-08-31",
"title": "public 도메인 읽기 전용 브라우저 폐루프 실측 (production, 이 PC와 분리 확인)",
"date": "2026-08-31",
"operator": "agent (read-only, production DB 미접촉)",
"scope": "읽기 전용. 사용자 계정 로그인/회기·턴 생성(production DB mutation) 없음. 배포·설정 변경 없음.",
"targets": {
"public_web": "https://vignette.chanpaca.net/login",
"public_api": "https://api-vignette.chanpaca.net"
},
"method": "Playwright 1.61.1 chromium (desktop 1440x900 / mobile 390x844) + curl/HTTP 실측",
"evidence": {
"playingwright_public_login_spec": {
"spec": "e2e/auth.spec.ts :: keeps the public login screen on real Google OAuth only",
"result": "1 passed (9.1s)",
"verified": [
"GET api-vignette.chanpaca.net/auth/config -> google_oauth_configured=true, dev_login_enabled=false, allowed_email_domains=[]",
"vignette.chanpaca.net/login -> Google 로그인 버튼(.lg-obtn) 1개, dev 로그인 요소 0, 'Google OAuth is not configured' 없음",
"Google 버튼 클릭 -> accounts.google.com 이동, client_id 포함",
"redirect_uri=https%3A%2F%2Fapi-vignette.chanpaca.net%2Fauth%2Fcallback"
]
},
"production_render_probe": {
"desktop_mobile_http": [200, 200],
"has_google_button": true,
"title": "Vignette · 상담 시뮬레이션",
"heading": "실제 계정으로 들어가고, 실제 회기만 남깁니다.",
"has_logo": true,
"has_error_text_fallback": false,
"console_page_errors_beyond_expected_auth": [],
"only_401": {
"request": "GET https://api-vignette.chanpaca.net/auth/me",
"reason": "비로그인 방문자 조회로 반환되는 정상 인증 경계 401 (로그인 페이지가 미인증 상태를 판별해 Google 버튼 표시)"
}
},
"public_api_health_x3": [
"200 status=ok environment=prod db=true engine=true engine_mode=openai"
],
"serving_identity": {
"dns": ["104.21.33.204", "172.67.149.131", "2606:4700:3030::6815:21cc", "2606:4700:3030::ac43:9583"],
"header_server": "cloudflare",
"cf_ray": "a33aa06b4c5ee9e1-LAX",
"conclusion": "이 PC가 아닌 별도 호스트(Cloudflare 뒤)가 서빙. 이 PC에는 cloudflared 프로세스 없음(확인) -> 이 PC와 정식 분리 운영"
},
"this_pc_state": {
"cloudflared_process": "absent",
"local_api_8001_listener": "absent",
"scheduledTasks": { "VignettePublicRuntime": "Disabled", "VignettePublicRuntimeWatchdog": "Disabled" },
"containers": "vignette-dev-db (up, 55432)",
"note": "개발 워크스테이션 (과거 자택 public 호스트 경로의 잔여 상태). 이 PC 로컬 상태는 public 도메인 장애가 아님."
}
},
"conclusion": {
"closed_readonly": "public 도메인(production)은 별도 호스트에서 정상 서빙 중. 실브라우저 로그인 화면·Google OAuth redirect_uri·개발 로그인 차단이 읽기 전용으로 실증됨. 이 PC와 정식 분리 운영이 실측으로 확인됨.",
"open_gate": "실제 Google 계정 로그인 -> 인증 callback -> 관리자/P20 실제 회기·턴 생성(production DB mutation)은 사용자(소유자) 승인과 계정 세션(storageState)이 필요해 여전히 열린 게이트. production DB mutation 없이는 read-only로는 증명 불가."
},
"screen_captures": [
"apps/web/node_modules/.tmp/public-login-desktop.png",
"apps/web/node_modules/.tmp/public-login-mobile.png"
]
}

Binary file not shown.

Before

Width:  |  Height:  |  Size: 709 KiB

After

Width:  |  Height:  |  Size: 403 KiB

Before After
Before After

Binary file not shown.

Before

Width:  |  Height:  |  Size: 391 KiB

After

Width:  |  Height:  |  Size: 655 KiB

Before After
Before After

Binary file not shown.

Before

Width:  |  Height:  |  Size: 1.3 MiB

After

Width:  |  Height:  |  Size: 760 KiB

Before After
Before After

Binary file not shown.

After

Width:  |  Height:  |  Size: 555 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 912 KiB

After

Width:  |  Height:  |  Size: 483 KiB

Before After
Before After

Binary file not shown.

Before

Width:  |  Height:  |  Size: 1 MiB

After

Width:  |  Height:  |  Size: 873 KiB

Before After
Before After

Binary file not shown.

After

Width:  |  Height:  |  Size: 374 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 442 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 527 KiB

After

Width:  |  Height:  |  Size: 362 KiB

Before After
Before After

Binary file not shown.

Before

Width:  |  Height:  |  Size: 810 KiB

After

Width:  |  Height:  |  Size: 696 KiB

Before After
Before After

Binary file not shown.

After

Width:  |  Height:  |  Size: 531 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 982 KiB

After

Width:  |  Height:  |  Size: 574 KiB

Before After
Before After

Binary file not shown.

Before

Width:  |  Height:  |  Size: 1.1 MiB

After

Width:  |  Height:  |  Size: 944 KiB

Before After
Before After

Binary file not shown.

After

Width:  |  Height:  |  Size: 297 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 374 KiB

After

Width:  |  Height:  |  Size: 286 KiB

Before After
Before After

Binary file not shown.

Before

Width:  |  Height:  |  Size: 631 KiB

After

Width:  |  Height:  |  Size: 396 KiB

Before After
Before After

22
infra/Caddyfile.nas Normal file
View file

@ -0,0 +1,22 @@
{
admin off
auto_https off
}
:80 {
@voice path /api/voice/ws*
reverse_proxy @voice api:8000
@sse path /api/*/stream*
reverse_proxy @sse api:8000 {
flush_interval -1
}
handle_path /api/* {
reverse_proxy api:8000
}
handle {
reverse_proxy web:80
}
}

View file

@ -347,7 +347,8 @@ CREATE INDEX IF NOT EXISTS idx_sess_sum_emb ON app.session_summary
-- =============================================================================
-- 8. 메모리 ④ SEMANTIC (설계서 §3.5) — case_profile(evolving) + pinned_fact
-- 케이스 = (persona_id 템플릿) × (learner_id 인스턴스). 학습자별 독립 연속체.
-- 케이스 = (persona_id 템플릿) × (learner_id 인스턴스) × 시작 시점.
-- 같은 내담자도 새 사례와 이어지는 사례를 분리해 학습자별 독립 연속체를 보존한다.
-- =============================================================================
CREATE TABLE IF NOT EXISTS app.case_profile (
case_id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
@ -360,9 +361,10 @@ CREATE TABLE IF NOT EXISTS app.case_profile (
alliance_level REAL DEFAULT 0.2, -- 치료동맹 누적(EWMA)
case_digest TEXT NOT NULL DEFAULT '', -- 전체 궤적 8~12문장(큰그림)
digest_embedding vector(1024),
updated_at TIMESTAMPTZ NOT NULL DEFAULT now(),
UNIQUE (persona_id, learner_id) -- 핵심 복합키(§3.5)
updated_at TIMESTAMPTZ NOT NULL DEFAULT now()
);
CREATE INDEX IF NOT EXISTS idx_case_profile_learner_persona_activity
ON app.case_profile (learner_id, persona_id, updated_at DESC, case_id);
CREATE INDEX IF NOT EXISTS idx_case_learner ON app.case_profile(learner_id);
CREATE INDEX IF NOT EXISTS idx_case_emb ON app.case_profile
USING hnsw (digest_embedding vector_cosine_ops) WITH (m = 16, ef_construction = 64);

View file

@ -0,0 +1,32 @@
-- 공개 부트스트랩 장애의 재시도 이력을 support_ticket 본문과 분리해 append-only로 보존한다.
-- 브라우저가 보낼 수 있는 값은 API의 폐쇄 enum으로 더 제한하므로 이 테이블에는
-- 응답 원문, URL, 쿠키, 계정 식별자 같은 고객 데이터가 들어가지 않는다.
CREATE TABLE IF NOT EXISTS app.support_ticket_event (
id BIGINT GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
ticket_id UUID NOT NULL
REFERENCES app.support_ticket(id) ON DELETE CASCADE,
observer_kind TEXT NOT NULL CHECK (observer_kind = 'public_browser'),
event_kind TEXT NOT NULL CHECK (
event_kind IN ('auth_restore_failure', 'boot_render_failure')
),
status_code SMALLINT NOT NULL CHECK (status_code IN (500, 502, 503, 504)),
attempt TEXT NOT NULL CHECK (attempt IN ('automatic', 'retry')),
source_path TEXT NOT NULL CHECK (source_path = '/ops/public-bootstrap'),
created_at TIMESTAMPTZ NOT NULL DEFAULT now()
);
CREATE INDEX IF NOT EXISTS idx_support_ticket_event_ticket_latest
ON app.support_ticket_event(ticket_id, created_at DESC);
ALTER TABLE app.support_ticket_event ENABLE ROW LEVEL SECURITY;
DROP POLICY IF EXISTS p_support_ticket_event_select ON app.support_ticket_event;
CREATE POLICY p_support_ticket_event_select
ON app.support_ticket_event FOR SELECT
USING (app.current_role_name() = 'admin');
DROP POLICY IF EXISTS p_support_ticket_event_insert ON app.support_ticket_event;
CREATE POLICY p_support_ticket_event_insert
ON app.support_ticket_event FOR INSERT
WITH CHECK (app.current_role_name() = 'admin');

View file

@ -0,0 +1,87 @@
-- =============================================================================
-- Vignette · migration 21 — learner-persona별 단일 활성 회기
-- =============================================================================
-- 기존 DB 적용 전 owner가 아래 읽기 전용 점검을 실행한다.
-- 중복 또는 실패 후 남은 invalid index가 있으면 임의 종료·DROP 하지 말고
-- 소유자가 보존·복구 방식을 결정해야 한다.
--
-- SELECT learner_id, persona_id, count(*)
-- FROM app.sessions
-- WHERE ended_at IS NULL AND persona_id IS NOT NULL
-- GROUP BY learner_id, persona_id
-- HAVING count(*) > 1;
--
-- CREATE INDEX CONCURRENTLY는 transaction block 안에서 실행할 수 없다.
-- release agent가 online migration으로 owner psql에 전달한다.
-- 이 파일의 전·후 condition은 IF NOT EXISTS가 invalid/wrong index를 조용히
-- 건너뛰는 경우를 fail-closed로 막는다.
DO $$
DECLARE
target_index oid := to_regclass('app.uq_sessions_one_active_learner_persona');
BEGIN
IF EXISTS (
SELECT 1
FROM app.sessions
WHERE ended_at IS NULL
AND persona_id IS NOT NULL
GROUP BY learner_id, persona_id
HAVING count(*) > 1
) THEN
RAISE EXCEPTION
'migration 21 blocked: duplicate active learner-persona sessions exist';
END IF;
IF target_index IS NOT NULL AND NOT EXISTS (
SELECT 1
FROM pg_index AS index_meta
WHERE index_meta.indexrelid = target_index
AND index_meta.indrelid = 'app.sessions'::regclass
AND index_meta.indisvalid
AND index_meta.indisready
AND index_meta.indisunique
AND index_meta.indnkeyatts = 2
AND pg_get_indexdef(index_meta.indexrelid, 1, true) = 'learner_id'
AND pg_get_indexdef(index_meta.indexrelid, 2, true) = 'persona_id'
AND regexp_replace(
pg_get_expr(index_meta.indpred, index_meta.indrelid),
'[[:space:]()]',
'',
'g'
) = 'ended_atISNULLANDpersona_idISNOTNULL'
) THEN
RAISE EXCEPTION
'migration 21 blocked: target index exists but is invalid or has a different definition';
END IF;
END
$$;
CREATE UNIQUE INDEX CONCURRENTLY IF NOT EXISTS uq_sessions_one_active_learner_persona
ON app.sessions (learner_id, persona_id)
WHERE ended_at IS NULL AND persona_id IS NOT NULL;
DO $$
BEGIN
IF NOT EXISTS (
SELECT 1
FROM pg_index AS index_meta
WHERE index_meta.indexrelid = 'app.uq_sessions_one_active_learner_persona'::regclass
AND index_meta.indrelid = 'app.sessions'::regclass
AND index_meta.indisvalid
AND index_meta.indisready
AND index_meta.indisunique
AND index_meta.indnkeyatts = 2
AND pg_get_indexdef(index_meta.indexrelid, 1, true) = 'learner_id'
AND pg_get_indexdef(index_meta.indexrelid, 2, true) = 'persona_id'
AND regexp_replace(
pg_get_expr(index_meta.indpred, index_meta.indrelid),
'[[:space:]()]',
'',
'g'
) = 'ended_atISNULLANDpersona_idISNOTNULL'
) THEN
RAISE EXCEPTION
'migration 21 failed: valid target unique index was not created';
END IF;
END
$$;

View file

@ -0,0 +1,129 @@
-- =============================================================================
-- Vignette · migration 22 — 동일 learner-persona의 새 사례 분리
-- =============================================================================
-- migration 21의 learner-persona 단일 활성 회기 제약은 그대로 유지한다.
-- 이 migration은 끝난 기존 사례를 보존한 채, 같은 내담자에 새 사례(case_profile)를
-- 만들 수 있도록 legacy pair unique만 제거한다. raw transcript·memory row는 수정하지 않는다.
--
-- CREATE INDEX CONCURRENTLY는 transaction block 안에서 실행할 수 없다.
-- release agent가 online migration으로 owner psql에 전달한다.
SET lock_timeout = '5s';
SET statement_timeout = '15min';
DO $$
DECLARE
legacy_constraints text[];
target_index oid := to_regclass('app.idx_case_profile_learner_persona_activity');
BEGIN
SELECT array_agg(candidate.conname ORDER BY candidate.conname)
INTO legacy_constraints
FROM (
SELECT constraint_meta.conname
FROM pg_constraint AS constraint_meta
WHERE constraint_meta.conrelid = 'app.case_profile'::regclass
AND constraint_meta.contype = 'u'
AND ARRAY(
SELECT attribute_meta.attname
FROM unnest(constraint_meta.conkey) WITH ORDINALITY AS key_column(attnum, ordinality)
JOIN pg_attribute AS attribute_meta
ON attribute_meta.attrelid = constraint_meta.conrelid
AND attribute_meta.attnum = key_column.attnum
ORDER BY key_column.ordinality
) = ARRAY['persona_id', 'learner_id']::text[]
) AS candidate;
IF COALESCE(array_length(legacy_constraints, 1), 0) > 1 THEN
RAISE EXCEPTION
'migration 22 blocked: multiple legacy case_profile persona-learner unique constraints exist';
END IF;
IF target_index IS NOT NULL AND NOT EXISTS (
SELECT 1
FROM pg_index AS index_meta
WHERE index_meta.indexrelid = target_index
AND index_meta.indrelid = 'app.case_profile'::regclass
AND index_meta.indisvalid
AND index_meta.indisready
AND NOT index_meta.indisunique
AND index_meta.indnkeyatts = 4
AND pg_get_indexdef(index_meta.indexrelid) LIKE
'%(learner_id, persona_id, updated_at DESC, case_id)%'
) THEN
RAISE EXCEPTION
'migration 22 blocked: target index exists but is invalid or has a different definition';
END IF;
END
$$;
CREATE INDEX CONCURRENTLY IF NOT EXISTS idx_case_profile_learner_persona_activity
ON app.case_profile (learner_id, persona_id, updated_at DESC, case_id);
DO $$
DECLARE
legacy_constraints text[];
BEGIN
IF NOT EXISTS (
SELECT 1
FROM pg_index AS index_meta
WHERE index_meta.indexrelid = 'app.idx_case_profile_learner_persona_activity'::regclass
AND index_meta.indrelid = 'app.case_profile'::regclass
AND index_meta.indisvalid
AND index_meta.indisready
AND NOT index_meta.indisunique
AND index_meta.indnkeyatts = 4
AND pg_get_indexdef(index_meta.indexrelid) LIKE
'%(learner_id, persona_id, updated_at DESC, case_id)%'
) THEN
RAISE EXCEPTION
'migration 22 failed: valid case activity index was not created';
END IF;
SELECT array_agg(candidate.conname ORDER BY candidate.conname)
INTO legacy_constraints
FROM (
SELECT constraint_meta.conname
FROM pg_constraint AS constraint_meta
WHERE constraint_meta.conrelid = 'app.case_profile'::regclass
AND constraint_meta.contype = 'u'
AND ARRAY(
SELECT attribute_meta.attname
FROM unnest(constraint_meta.conkey) WITH ORDINALITY AS key_column(attnum, ordinality)
JOIN pg_attribute AS attribute_meta
ON attribute_meta.attrelid = constraint_meta.conrelid
AND attribute_meta.attnum = key_column.attnum
ORDER BY key_column.ordinality
) = ARRAY['persona_id', 'learner_id']::text[]
) AS candidate;
IF COALESCE(array_length(legacy_constraints, 1), 0) > 1 THEN
RAISE EXCEPTION
'migration 22 blocked: multiple legacy case_profile persona-learner unique constraints exist';
END IF;
IF COALESCE(array_length(legacy_constraints, 1), 0) = 1 THEN
EXECUTE format(
'ALTER TABLE app.case_profile DROP CONSTRAINT %I',
legacy_constraints[1]
);
END IF;
IF EXISTS (
SELECT 1
FROM pg_constraint AS constraint_meta
WHERE constraint_meta.conrelid = 'app.case_profile'::regclass
AND constraint_meta.contype = 'u'
AND ARRAY(
SELECT attribute_meta.attname
FROM unnest(constraint_meta.conkey) WITH ORDINALITY AS key_column(attnum, ordinality)
JOIN pg_attribute AS attribute_meta
ON attribute_meta.attrelid = constraint_meta.conrelid
AND attribute_meta.attnum = key_column.attnum
ORDER BY key_column.ordinality
) = ARRAY['persona_id', 'learner_id']::text[]
) THEN
RAISE EXCEPTION
'migration 22 failed: legacy case_profile persona-learner unique constraint remains';
END IF;
END
$$;

View file

@ -0,0 +1,308 @@
name: vignette-prod
# NAS 운영 전용 완결 스택이다. infra/docker-compose.yml의 로컬 개발 스택과 합치지 않는다.
# 외부 볼륨은 백업/격리 복구/휴먼 게이트를 통과한 뒤 운영자가 미리 생성해야 한다.
x-api-image: &api-image
image: ${VIGNETTE_NAS_API_IMAGE:?Immutable NAS API image reference is required}
x-web-image: &web-image
image: ${VIGNETTE_NAS_WEB_IMAGE:?Immutable NAS web image reference is required}
x-production-labels: &production-labels
com.vignette.owner: vignette
com.vignette.runtime-class: production
com.vignette.ssot-host: nas
com.vignette.stack: vignette-prod
services:
db:
image: ${VIGNETTE_NAS_POSTGRES_IMAGE:?Immutable NAS PostgreSQL image ID is required}
restart: unless-stopped
stop_grace_period: 1m
environment:
POSTGRES_USER: ${POSTGRES_USER:-vignette_owner}
POSTGRES_PASSWORD: ${POSTGRES_PASSWORD:?NAS PostgreSQL owner password is required}
POSTGRES_DB: ${POSTGRES_DB:-vignette}
APP_DB_USER: ${APP_DB_USER:-vignette_app}
APP_DB_PASSWORD: ${APP_DB_PASSWORD:?NAS application DB password is required}
volumes:
- type: volume
source: pgdata
target: /var/lib/postgresql/data
- type: bind
source: ./db/init
target: /docker-entrypoint-initdb.d
read_only: true
healthcheck:
test:
- CMD-SHELL
- >-
PGPASSWORD=$${APP_DB_PASSWORD} psql -U $${APP_DB_USER} -d $${POSTGRES_DB}
-tAc "SELECT to_regclass('app.ci_regression_dag_node') IS NOT NULL"
| grep -qx t
interval: 10s
timeout: 5s
retries: 12
start_period: 5m
labels:
<<: *production-labels
com.vignette.data-role: database-ssot
networks: [backend]
engine:
<<: *api-image
command:
- python
- -m
- uvicorn
- engine_gateway.gateway:app
- --host
- 0.0.0.0
- --port
- "9099"
restart: unless-stopped
stop_grace_period: 30s
environment:
OPENAI_API_KEY: ${OPENAI_API_KEY:?OpenAI key is required for the NAS engine}
OPENAI_BASE_URL: ${OPENAI_BASE_URL:-https://api.openai.com/v1}
OPENAI_ENGINE_MODEL: ${OPENAI_ENGINE_MODEL:?An approved OpenAI engine model is required}
OPENAI_ENGINE_MODELS: ${OPENAI_ENGINE_MODELS:-gpt-5.6-terra,gpt-5.6-luna,gpt-4.1}
ENGINE_GATEWAY_SHARED_SECRET: ${ENGINE_GATEWAY_SHARED_SECRET:?Gateway shared secret is required}
ENGINE_CAPABILITY_CACHE_TTL_SECONDS: ${ENGINE_CAPABILITY_CACHE_TTL_SECONDS:-1800}
ENGINE_READY_TTL_SECONDS: ${ENGINE_READY_TTL_SECONDS:-1800}
ENGINE_READY_FAILURE_TTL_SECONDS: ${ENGINE_READY_FAILURE_TTL_SECONDS:-30}
ENGINE_READY_TIMEOUT_SECONDS: ${ENGINE_READY_TIMEOUT_SECONDS:-45}
ENGINE_GENERATE_TIMEOUT_SECONDS: ${ENGINE_GENERATE_TIMEOUT_SECONDS:-300}
expose:
- "9099"
read_only: true
tmpfs:
- /tmp:rw,noexec,nosuid,size=128m
cap_drop: [ALL]
security_opt:
- no-new-privileges:true
healthcheck:
test:
- CMD
- python
- -c
- >-
import json, urllib.request;
payload=json.load(urllib.request.urlopen('http://localhost:9099/health'));
assert payload.get('ok') is True
interval: 15s
timeout: 5s
retries: 8
start_period: 30s
labels:
<<: *production-labels
com.vignette.data-role: engine-ssot
networks: [backend, app-egress]
api:
<<: *api-image
restart: unless-stopped
stop_grace_period: 1m
# NAS 호스트 터널만 접근할 수 있도록 loopback에만 고정 바인딩한다.
ports:
- "127.0.0.1:18080:8000"
depends_on:
db: { condition: service_healthy }
engine: { condition: service_healthy }
environment:
ENVIRONMENT: prod
DATABASE_URL: postgresql://${APP_DB_USER:-vignette_app}:${APP_DB_PASSWORD:?NAS application DB password is required}@db:5432/${POSTGRES_DB:-vignette}
ENGINE_URL: http://engine:9099
ENGINE_MODE: openai
VIGNETTE_LIVE_CLIENT_PROVIDER: openai
ENGINE_GATEWAY_SHARED_SECRET: ${ENGINE_GATEWAY_SHARED_SECRET:?Gateway shared secret is required}
OPENAI_API_KEY: ${OPENAI_API_KEY:?OpenAI key is required for production voice and engine paths}
OPENAI_BASE_URL: ${OPENAI_BASE_URL:-https://api.openai.com/v1}
VIGNETTE_VOICE_STT_PROVIDER: openai
VIGNETTE_VOICE_TTS_PROVIDER: openai
SESSION_SECRET: ${SESSION_SECRET:?Production session secret is required}
VIGNETTE_RUPTURE_INTERNAL_TOKEN: ${VIGNETTE_RUPTURE_INTERNAL_TOKEN:?G3 token is required}
VIGNETTE_PRACTICE_INTERNAL_TOKEN: ${VIGNETTE_PRACTICE_INTERNAL_TOKEN:?G4 token is required}
VIGNETTE_CALIBRATION_TRANSFER_INTERNAL_TOKEN: ${VIGNETTE_CALIBRATION_TRANSFER_INTERNAL_TOKEN:?G5 token is required}
VIGNETTE_SUPERVISION_RESEARCH_INTERNAL_TOKEN: ${VIGNETTE_SUPERVISION_RESEARCH_INTERNAL_TOKEN:?G6 token is required}
VIGNETTE_MULTIMODAL_ALLIANCE_INTERNAL_TOKEN: ${VIGNETTE_MULTIMODAL_ALLIANCE_INTERNAL_TOKEN:?G7 token is required}
VIGNETTE_CONTINUOUS_IMPROVEMENT_INTERNAL_TOKEN: ${VIGNETTE_CONTINUOUS_IMPROVEMENT_INTERNAL_TOKEN:?G8 token is required}
VIGNETTE_CONTINUOUS_IMPROVEMENT_PRODUCER_ENABLED: ${VIGNETTE_CONTINUOUS_IMPROVEMENT_PRODUCER_ENABLED:-false}
VIGNETTE_CONTINUOUS_IMPROVEMENT_PRODUCER_INTERVAL_SECONDS: ${VIGNETTE_CONTINUOUS_IMPROVEMENT_PRODUCER_INTERVAL_SECONDS:-3600}
VIGNETTE_CONTINUOUS_IMPROVEMENT_PRODUCER_STARTUP_DELAY_SECONDS: ${VIGNETTE_CONTINUOUS_IMPROVEMENT_PRODUCER_STARTUP_DELAY_SECONDS:-30}
VIGNETTE_CONTINUOUS_IMPROVEMENT_PRODUCER_RETRY_DELAY_SECONDS: ${VIGNETTE_CONTINUOUS_IMPROVEMENT_PRODUCER_RETRY_DELAY_SECONDS:-300}
VIGNETTE_CONTINUOUS_IMPROVEMENT_PRODUCER_LEASE_TIMEOUT_SECONDS: ${VIGNETTE_CONTINUOUS_IMPROVEMENT_PRODUCER_LEASE_TIMEOUT_SECONDS:-1800}
VIGNETTE_CONTINUOUS_IMPROVEMENT_PRODUCER_ENGINE_TIMEOUT_SECONDS: ${VIGNETTE_CONTINUOUS_IMPROVEMENT_PRODUCER_ENGINE_TIMEOUT_SECONDS:-300}
VIGNETTE_CONTINUOUS_IMPROVEMENT_PRODUCER_BATCH_SIZE: ${VIGNETTE_CONTINUOUS_IMPROVEMENT_PRODUCER_BATCH_SIZE:-1}
VIGNETTE_CONTINUOUS_IMPROVEMENT_DRIFT_TRIGGER_ENABLED: ${VIGNETTE_CONTINUOUS_IMPROVEMENT_DRIFT_TRIGGER_ENABLED:-false}
VIGNETTE_CONTINUOUS_IMPROVEMENT_ROLLBACK_EXECUTOR_ENABLED: "false"
OAUTH_GOOGLE_CLIENT_ID: ${OAUTH_GOOGLE_CLIENT_ID:?Google OAuth client id is required}
OAUTH_GOOGLE_CLIENT_SECRET: ${OAUTH_GOOGLE_CLIENT_SECRET:?Google OAuth client secret is required}
OAUTH_REDIRECT_URI: ${OAUTH_REDIRECT_URI:-https://api-vignette.chanpaca.net/auth/callback}
AUTH_ALLOWED_EMAIL_DOMAINS: '${AUTH_ALLOWED_EMAIL_DOMAINS:-["hs.ac.kr","twentyoz.kr"]}'
AUTH_TEACHER_EMAILS: '${AUTH_TEACHER_EMAILS:-[]}'
AUTH_ADMIN_EMAILS: '${AUTH_ADMIN_EMAILS:-[]}'
AUTH_SUPER_ADMIN_EMAILS: '${AUTH_SUPER_ADMIN_EMAILS:?Super admin allowlist is required}'
AUTH_APPROVED_EMAILS: '${AUTH_APPROVED_EMAILS:-[]}'
AUTH_NEW_USER_DEFAULT_STATUS: pending
AUTH_DEV_LOGIN_ENABLED: "false"
AUTH_DEV_LOGIN_EXTRA_ORIGINS: '[]'
DEFAULT_AFFILIATION: ${DEFAULT_AFFILIATION:-}
AUTO_SEED_PERSONAS: "false"
ALLOW_SEED_PERSONA_FALLBACK: "false"
EVALUATOR_GOLDEN_FEWSHOT_ENABLED: ${EVALUATOR_GOLDEN_FEWSHOT_ENABLED:-false}
FRONTEND_BASE_URL: https://vignette.chanpaca.net
FRONTEND_ORIGIN_MAP: '${FRONTEND_ORIGIN_MAP:?Set FRONTEND_ORIGIN_MAP in the NAS secret environment}'
CORS_ORIGINS: '${CORS_ORIGINS:-["https://vignette.chanpaca.net","https://vignette-b1q.pages.dev"]}'
USER_UPLOAD_DIR: /app/uploads
NOTIFICATION_EMAIL_PROVIDER: ${NOTIFICATION_EMAIL_PROVIDER:-disabled}
NOTIFICATION_EMAIL_MAX_ATTEMPTS: ${NOTIFICATION_EMAIL_MAX_ATTEMPTS:-3}
NOTIFICATION_EMAIL_RETRY_SECONDS: ${NOTIFICATION_EMAIL_RETRY_SECONDS:-900}
SMTP_HOST: ${SMTP_HOST:-}
SMTP_PORT: ${SMTP_PORT:-587}
SMTP_USERNAME: ${SMTP_USERNAME:-}
SMTP_PASSWORD: ${SMTP_PASSWORD:-}
SMTP_FROM_EMAIL: ${SMTP_FROM_EMAIL:-}
SMTP_FROM_NAME: ${SMTP_FROM_NAME:-Vignette}
SMTP_STARTTLS: ${SMTP_STARTTLS:-true}
SMTP_SSL: ${SMTP_SSL:-false}
VIGNETTE_RUNTIME_CLASS: production
VIGNETTE_SSOT_HOST: nas
VIGNETTE_NAS_PGDATA_VOLUME: ${VIGNETTE_NAS_PGDATA_VOLUME:?Explicit NAS PostgreSQL volume name is required}
VIGNETTE_NAS_APIUPLOADS_VOLUME: ${VIGNETTE_NAS_APIUPLOADS_VOLUME:?Explicit NAS uploads volume name is required}
volumes:
- type: volume
source: apiuploads
target: /app/uploads
volume:
nocopy: true
read_only: true
tmpfs:
- /tmp:rw,noexec,nosuid,size=128m
cap_drop: [ALL]
security_opt:
- no-new-privileges:true
healthcheck:
test:
- CMD
- python
- -c
- >-
import json, urllib.request;
payload=json.load(urllib.request.urlopen('http://localhost:8000/health'));
assert payload.get('status') == 'ok' and payload.get('db') is True and payload.get('engine') is True
interval: 30s
timeout: 10s
retries: 8
start_period: 2m
labels:
<<: *production-labels
com.vignette.data-role: api-ssot
networks: [backend, app-egress]
web:
<<: *web-image
restart: unless-stopped
depends_on:
api: { condition: service_healthy }
read_only: true
tmpfs:
- /tmp:rw,noexec,nosuid,size=16m
# nginx가 client/proxy/fastcgi 임시 파일과 PID를 기록해야 한다.
# 루트 FS는 계속 read-only로 유지한다.
- /var/cache/nginx:rw,noexec,nosuid,size=16m
- /var/run:rw,noexec,nosuid,size=1m
cap_drop: [ALL]
security_opt:
- no-new-privileges:true
labels:
<<: *production-labels
com.vignette.data-role: static-web-replica
networks: [backend]
private-proxy:
image: caddy@sha256:5f5c8640aae01df9654968d946d8f1a56c497f1dd5c5cda4cf95ab7c14d58648
restart: unless-stopped
depends_on:
web: { condition: service_started }
api: { condition: service_healthy }
ports:
- "${VIGNETTE_NAS_PRIVATE_BIND_ADDRESS:?Explicit NAS Tailnet or private bind address is required}:${VIGNETTE_NAS_PRIVATE_HTTP_PORT:-18088}:80"
volumes:
- type: bind
source: ./Caddyfile.nas
target: /etc/caddy/Caddyfile
read_only: true
read_only: true
tmpfs:
- /data:rw,noexec,nosuid,size=16m
- /config:rw,noexec,nosuid,size=16m
- /tmp:rw,noexec,nosuid,size=16m
cap_drop: [ALL]
security_opt:
- no-new-privileges:true
labels:
<<: *production-labels
com.vignette.data-role: tailnet-private-validation
networks: [backend]
cloudflared:
image: cloudflare/cloudflared@sha256:d9ff527dc19799e24d3689058161fb01e752a24be1823577bae54c9c2489275f
profiles: [public-cutover-gate]
command:
- tunnel
- --no-autoupdate
- --config
- /etc/cloudflared/config.yml
- run
restart: unless-stopped
depends_on:
api: { condition: service_healthy }
volumes:
- type: bind
source: ${VIGNETTE_TUNNEL_CONFIG_PATH:?Rendered cloudflared config path is required}
target: /etc/cloudflared/config.yml
read_only: true
- type: bind
source: ${VIGNETTE_TUNNEL_CREDENTIAL_PATH:?Tunnel credential JSON path is required}
target: /run/secrets/vignette-tunnel.json
read_only: true
read_only: true
tmpfs:
- /tmp:rw,noexec,nosuid,size=32m
cap_drop: [ALL]
security_opt:
- no-new-privileges:true
labels:
<<: *production-labels
com.vignette.data-role: gated-public-edge
# API는 NAS loopback에만 열리고, 터널은 호스트 네트워크로 이를 호출한다.
# Docker 재시작 뒤에도 restart 정책으로 공개 연결을 자동 복구한다.
network_mode: host
volumes:
pgdata:
external: true
name: ${VIGNETTE_NAS_PGDATA_VOLUME:?Explicit NAS PostgreSQL volume name is required}
apiuploads:
external: true
name: ${VIGNETTE_NAS_APIUPLOADS_VOLUME:?Explicit NAS uploads volume name is required}
networks:
backend:
name: vignette-prod-backend
driver: bridge
internal: true
labels:
<<: *production-labels
app-egress:
name: vignette-prod-app-egress
driver: bridge
labels:
<<: *production-labels
tunnel-egress:
name: vignette-prod-tunnel-egress
driver: bridge
labels:
<<: *production-labels

39
scripts/dist-snap.py Normal file
View file

@ -0,0 +1,39 @@
"""dist 결정성 스냅샷 — sha256 파일 지도를 만들고 두 빌드를 비교한다.
사용: python -X utf8 dist-snap.py snap1 | python -X utf8 dist-snap.py compare dist-snap1.json
"""
import hashlib
import json
import os
import sys
def snap(root: str) -> dict:
out = {}
for dp, _, fns in os.walk(root):
for fn in fns:
p = os.path.join(dp, fn)
rel = os.path.relpath(p, root).replace(os.sep, "/")
with open(p, "rb") as fh:
out[rel] = hashlib.sha256(fh.read()).hexdigest()
return out
if sys.argv[1] == "snap":
s = snap("dist")
name = sys.argv[2]
with open(name, "w", encoding="utf-8") as fh:
json.dump(s, fh)
print("files:", len(s))
elif sys.argv[1] == "compare":
with open(sys.argv[2], encoding="utf-8") as fh:
s1 = json.load(fh)
s2 = snap("dist")
only1 = sorted(set(s1) - set(s2))
only2 = sorted(set(s2) - set(s1))
diff = sorted(k for k in set(s1) & set(s2) if s1[k] != s2[k])
print("build1 files:", len(s1), "build2 files:", len(s2))
print("only_in_build1:", only1[:10])
print("only_in_build2:", only2[:10])
print("content_diff:", diff[:10])
print("DETERMINISTIC" if not (only1 or only2 or diff) else "NON_DETERMINISTIC")

View file

@ -0,0 +1,90 @@
/**
* 이전 Pages 배포 세대의 자산 보존 — immutable preview URL(들)의 HTML/JS/CSS 의존
* 그래프를 따라 내려받아, 새 빌드 dist 에 없는 파일만 추가한다(기존 파일은 덮어쓰지 않는다).
* 사용: node preserve-assets.mjs
*/
import { mkdir, writeFile, readFile } from "node:fs/promises";
import { createHash } from "node:crypto";
import path from "node:path";
const ORIGINS = [
"https://vignette.chanpaca.net",
"https://5a525329.vignette-b1q.pages.dev",
"https://e1c73735.vignette-b1q.pages.dev",
"https://bbebb2d3.vignette-b1q.pages.dev",
"https://44edecc8.vignette-b1q.pages.dev",
"https://0ffdc694.vignette-b1q.pages.dev",
"https://7bd59055.vignette-b1q.pages.dev",
];
const DIST = "dist";
async function exists(p) {
try {
await readFile(p);
return true;
} catch {
return false;
}
}
async function collect(origin) {
const seen = new Map(); // path -> sha256 hex
const html = await (await fetch(origin + "/")).text();
// index.html 이 참조하는 엔트리 자산
const refs = new Set();
for (const m of html.matchAll(/(?:src|href)="(\/[^"]+\.(?:js|css))"/g)) refs.add(m[1]);
for (const m of html.matchAll(/(?:src|href)="(\/[^"]+\.(?:png|svg|ico|webmanifest|json|woff2?))"/g))
refs.add(m[1]);
// JS 청크 의존 그래프 폐쇄
const queue = [...refs];
while (queue.length) {
const ref = queue.pop();
if (seen.has(ref)) continue;
const res = await fetch(origin + ref);
if (!res.ok) {
seen.set(ref, "FETCH_FAILED_" + res.status);
continue;
}
const buf = Buffer.from(await res.arrayBuffer());
seen.set(ref, createHash("sha256").update(buf).digest("hex"));
if (ref.endsWith(".js")) {
const text = buf.toString("utf8");
for (const m of text.matchAll(/["'`](\.\/[A-Za-z0-9_.-]+\.(?:js|css))["'`]/g)) {
const p = path.posix.normalize(path.posix.join(path.posix.dirname(ref), m[1]));
if (!seen.has(p)) queue.push(p);
}
}
}
return seen;
}
const perOrigin = [];
let added = 0;
const addedList = [];
for (const origin of ORIGINS) {
const map = await collect(origin);
let ok = 0;
for (const [p, sha] of map) {
if (sha.startsWith("FETCH_FAILED")) continue;
const rel = p.replace(/^\//, "");
const target = path.join(DIST, rel);
if (await exists(target)) {
ok += 1;
continue;
}
await mkdir(path.dirname(target), { recursive: true });
const res = await fetch(origin + p);
await writeFile(target, Buffer.from(await res.arrayBuffer()));
added += 1;
addedList.push(rel);
}
perOrigin.push({ origin, assets: map.size, reused_in_new_build: ok });
console.log(`origin ${origin}: ${map.size} assets, ${ok} already in new build`);
}
console.log(`assets_added: ${added}`);
await writeFile(
"preserve-report.json",
JSON.stringify({ origins: perOrigin, assets_added: added, added: addedList }, null, 1),
"utf8",
);

View file

@ -124,8 +124,17 @@ RELEASE_DB_MIGRATIONS = (
"17_improvement_workbook_contracts.sql",
"18_admin_usage_ledger_index.sql",
"19_auth_identity_alias.sql",
"20_public_bootstrap_ticket_events.sql",
"21_single_active_session.sql",
"22_case_profile_multi_case.sql",
)
RELEASE_DB_ONLINE_MIGRATIONS = frozenset(
{
"18_admin_usage_ledger_index.sql",
"21_single_active_session.sql",
"22_case_profile_multi_case.sql",
}
)
RELEASE_DB_ONLINE_MIGRATIONS = frozenset({"18_admin_usage_ledger_index.sql"})
# These files are runtime-critical but were added after the first manifest
# snapshot. A release must classify them as whole-file payloads; otherwise a
@ -138,6 +147,9 @@ REQUIRED_RELEASE_PAYLOAD_PATHS = (
"infra/db/init/17_improvement_workbook_contracts.sql",
"infra/db/init/18_admin_usage_ledger_index.sql",
"infra/db/init/19_auth_identity_alias.sql",
"infra/db/init/20_public_bootstrap_ticket_events.sql",
"infra/db/init/21_single_active_session.sql",
"infra/db/init/22_case_profile_multi_case.sql",
)
REQUIRED_OPENAPI_PATHS = {

View file

@ -419,6 +419,122 @@ class OutcomeReleaseAgentTests(unittest.TestCase):
self.agent_module.REQUIRED_RELEASE_PAYLOAD_PATHS,
)
def test_single_active_session_index_is_online_and_release_required(self) -> None:
migration_path = (
SCRIPT_PATH.parent.parent
/ "infra"
/ "db"
/ "init"
/ "21_single_active_session.sql"
)
migration = migration_path.read_text(encoding="utf-8")
self.assertNotIn("BEGIN;", migration)
self.assertIn(
"CREATE UNIQUE INDEX CONCURRENTLY IF NOT EXISTS uq_sessions_one_active_learner_persona",
migration,
)
self.assertIn("ON app.sessions (learner_id, persona_id)", migration)
self.assertIn("WHERE ended_at IS NULL AND persona_id IS NOT NULL;", migration)
self.assertIn(
"duplicate active learner-persona sessions exist",
migration,
)
self.assertIn(
"target index exists but is invalid or has a different definition",
migration,
)
self.assertIn("index_meta.indisvalid", migration)
self.assertIn("index_meta.indisready", migration)
self.assertIn("valid target unique index was not created", migration)
self.assertNotIn("COMMIT;", migration)
self.assertIn(
"21_single_active_session.sql",
self.agent_module.RELEASE_DB_MIGRATIONS,
)
self.assertIn(
"21_single_active_session.sql",
self.agent_module.RELEASE_DB_ONLINE_MIGRATIONS,
)
self.assertIn(
"infra/db/init/21_single_active_session.sql",
self.agent_module.REQUIRED_RELEASE_PAYLOAD_PATHS,
)
self.assertIn(
"20_public_bootstrap_ticket_events.sql",
self.agent_module.RELEASE_DB_MIGRATIONS,
)
self.assertNotIn(
"20_public_bootstrap_ticket_events.sql",
self.agent_module.RELEASE_DB_ONLINE_MIGRATIONS,
)
self.assertIn(
"infra/db/init/20_public_bootstrap_ticket_events.sql",
self.agent_module.REQUIRED_RELEASE_PAYLOAD_PATHS,
)
def test_case_profile_multi_case_migration_is_online_safe_and_release_required(
self,
) -> None:
migration_path = (
SCRIPT_PATH.parent.parent
/ "infra"
/ "db"
/ "init"
/ "22_case_profile_multi_case.sql"
)
migration = migration_path.read_text(encoding="utf-8")
self.assertNotIn("BEGIN;", migration)
self.assertNotIn("COMMIT;", migration)
self.assertIn("legacy_constraints text[];", migration)
self.assertIn("constraint_meta.contype = 'u'", migration)
self.assertIn(
"ARRAY['persona_id', 'learner_id']::text[]",
migration,
)
self.assertIn(
"multiple legacy case_profile persona-learner unique constraints exist",
migration,
)
self.assertIn(
"ALTER TABLE app.case_profile DROP CONSTRAINT %I",
migration,
)
self.assertIn(
"legacy case_profile persona-learner unique constraint remains",
migration,
)
self.assertIn(
"CREATE INDEX CONCURRENTLY IF NOT EXISTS idx_case_profile_learner_persona_activity",
migration,
)
self.assertIn(
"ON app.case_profile (learner_id, persona_id, updated_at DESC, case_id);",
migration,
)
self.assertIn("index_meta.indisvalid", migration)
self.assertIn("index_meta.indisready", migration)
self.assertIn("NOT index_meta.indisunique", migration)
self.assertIn("index_meta.indnkeyatts = 4", migration)
self.assertIn(
"target index exists but is invalid or has a different definition",
migration,
)
self.assertIn("valid case activity index was not created", migration)
self.assertIn(
"22_case_profile_multi_case.sql",
self.agent_module.RELEASE_DB_MIGRATIONS,
)
self.assertIn(
"22_case_profile_multi_case.sql",
self.agent_module.RELEASE_DB_ONLINE_MIGRATIONS,
)
self.assertIn(
"infra/db/init/22_case_profile_multi_case.sql",
self.agent_module.REQUIRED_RELEASE_PAYLOAD_PATHS,
)
def test_two_patch_runs_must_be_byte_identical_before_any_deploy(self) -> None:
agent, runner, deployment, _, _ = self.make_agent(
active_sha=None,
@ -773,6 +889,9 @@ class OutcomeReleaseAgentTests(unittest.TestCase):
"17_improvement_workbook_contracts.sql",
"18_admin_usage_ledger_index.sql",
"19_auth_identity_alias.sql",
"20_public_bootstrap_ticket_events.sql",
"21_single_active_session.sql",
"22_case_profile_multi_case.sql",
),
self.agent_module.RELEASE_DB_MIGRATIONS,
)
@ -968,8 +1087,26 @@ class OutcomeReleaseAgentTests(unittest.TestCase):
if "18_admin_usage_ledger_index.sql" in line
and "psql -v ON_ERROR_STOP=1" in line
)
active_session_online_migration_command = next(
line
for line in promote_command.splitlines()
if "21_single_active_session.sql" in line
and "psql -v ON_ERROR_STOP=1" in line
)
case_profile_online_migration_command = next(
line
for line in promote_command.splitlines()
if "22_case_profile_multi_case.sql" in line
and "psql -v ON_ERROR_STOP=1" in line
)
self.assertIn("--single-transaction", transactional_migration_command)
self.assertNotIn("--single-transaction", online_migration_command)
self.assertNotIn(
"--single-transaction", active_session_online_migration_command
)
self.assertNotIn(
"--single-transaction", case_profile_online_migration_command
)
self.assertEqual(f"{root}/release/infra/.env", state["env_file"])
def test_adopted_legacy_state_infers_compose_adjacent_env_file(self) -> None:

View file

@ -0,0 +1,133 @@
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""Vignette 배포 파이프라인 관리 도구.
소스 SSOT = Forgejo git.chanpaca.net (master)
배포 대상 = NAS Production /volume1/docker/vignette-prod (docker-compose.nas.yml)
이 PC = 개발 전용
역할:
- Forgejo master == 로컬 master == 배포 기준선 무결성 확인
- github(origin, private 백업 미러) 존재 확인
- NAS production 컨테이너/이미지 compose ref 조회 (read-only)
- 배포 전 검증 게이트(SSOT checker) 존재 확인
※ 실제 NAS 이미지 빌드·주입·compose up은 소유자 승인 후 별도 실행.
이 도구는 배포 파이프라인의 관리/점검(read-only)을 담당한다.
사용법:
python -X utf8 scripts/vignette-pipeline.py --check
python -X utf8 scripts/vignette-pipeline.py --config
"""
from __future__ import annotations
import argparse
import os
import shutil
import subprocess
import sys
from pathlib import Path
REPO_ROOT = Path(__file__).resolve().parent.parent
SSOT_DASHBOARD = REPO_ROOT / "docs" / "dev_dashboard.html"
FORGEJO_SSOT_BRANCH = "master"
FORGEJO_REMOTE = "forgejo"
GITHUB_REMOTE = "origin"
NAS_COMPOSE_HOST = "yunchan-nas" # ssh config Host (192.168.0.38, user yunchan)
NAS_COMPOSE_PATH = "/volume1/docker/vignette-prod/docker-compose.nas.yml"
NAS_COMPOSE_FILE = "docker-compose.nas.yml"
NAS_PROJECT = "vignette-prod"
def _run(cmd: list[str], cwd: Path | None = None, ok_codes=(0,)) -> str:
r = subprocess.run(cmd, cwd=cwd or REPO_ROOT, capture_output=True, text=True)
if r.returncode not in ok_codes:
raise RuntimeError(f"cmd failed ({r.returncode}): {' '.join(cmd)}\n{r.stderr[-800:]}")
return r.stdout
def _git(*args: str) -> str:
return _run(["git", *args]).strip()
def check(forgejo_available: bool = True) -> int:
problems = 0
def ok(msg: str) -> None:
print(f" [PASS] {msg}")
def warn(msg: str) -> None:
nonlocal problems
problems += 1
print(f" [FAIL] {msg}")
print("== 배포 파이프라인 점검 ==")
# 1) Forgejo SSOT == 로컬 master
local_master = _git("rev-parse", FORGEJO_SSOT_BRANCH)
ok(f"로컬 {FORGEJO_SSOT_BRANCH} = {local_master[:12]}")
if forgejo_available:
remote_master = _git("ls-remote", f"{FORGEJO_REMOTE}", "refs/heads/master").split("\t")[0]
if remote_master and remote_master == local_master:
ok(f"Forgejo master = {remote_master[:12]} == 로컬 (배포 기준선 일치)")
else:
warn(f"Forgejo master {remote_master[:12] if remote_master else 'MISSING'} != 로컬 {local_master[:12]}. push 필요.")
else:
warn("Forgejo 원격/접근 없음 — 이관 미완료")
# 2) remote 목록
remotes = _git("remote", "-v")
if github := [f.split()[1] for f in remotes.splitlines() if f.startswith("origin\t")]:
ok(f"github origin(private 백업) = {github[0]}")
else:
warn("github origin 없음")
if f"{FORGEJO_REMOTE}\t" in remotes:
ok(f"Forgejo {FORGEJO_REMOTE} 원격 존재 (SSOT)")
else:
warn(f"Forgejo {FORGEJO_REMOTE} 원격 없음")
# 3) SSOT checker 존재
checker = REPO_ROOT / "scripts" / "test_dev_dashboard_ssot.py"
if checker.exists():
ok(f"SSOT checker 존재: {checker.name}")
else:
warn("SSOT checker 없음")
# 4) 배포 파이프라인 문서
pipe_doc = REPO_ROOT / "docs" / "ops" / "deployment-pipeline.md"
if pipe_doc.exists():
ok(f"배포 파이프라인 문서 존재")
else:
warn("deployment-pipeline.md 없음")
return problems
def config() -> None:
env = REPO_ROOT / "infra" / ".env.deploy"
print(f"== 배포 파이프라인 구성 ==")
print(f" Forgejo SSOT : {FORGEJO_REMOTE} (ssh://git@git.chanpaca.net:2222/yunchan/vignette.git)")
print(f" github 백업 : {GITHUB_REMOTE} (https://github.com/yunchan8804-blip/vignette.git, private)")
print(f" NAS 대상 : {NAS_COMPOSE_HOST}:{NAS_COMPOSE_PATH} ({NAS_PROJECT})")
print(f" 로컬 마스터 : {_git('rev-parse', FORGEJO_SSOT_BRANCH)[:12]}")
print(f" .env.deploy : {env} (토큰 gitignore, 채움 필요)")
def main() -> int:
ap = argparse.ArgumentParser(description="Vignette 배포 파이프라인 관리")
ap.add_argument("--check", action="store_true", help="배포 기준선 무결성 점검")
ap.add_argument("--config", action="store_true", help="파이프라인 구성 요약")
ap.add_argument("--skip-forgejo", action="store_true", help="Forgejo 원격 접근 생략(오프라인 점검)")
args = ap.parse_args()
if args.config:
config()
return 0
problems = check(forgejo_available=not args.skip_forgejo)
print(f"\n결과: {'ALL OK' if problems == 0 else f'{problems} 개 문제'}")
return 0 if problems == 0 else 1
if __name__ == "__main__":
sys.exit(main())