# 전체 문제점 목록

> 원본 코드/프롬프트/기존 문서를 수정하지 않고 생성한 read-only 감사 문서입니다.

이 파일은 전체 감사에서 확인한 문제를 별도로 모은 것이다. Severity는 운영 영향과 재발 가능성을 기준으로 임시 분류했다.

## P0 / P1 즉시 설계 정리가 필요한 문제

### 1. 이미지 생성 실행 경로가 이중화되어 있음

| 항목 | 내용 |
|---|---|
| 위치 | `backend/app/api/v1/steps.py`, `backend/app/api/v1/images.py`, frontend `EpisodeDetail`, `EpisodeActionBar`, `Entities` |
| 현상 | StepRunner 기반 `/steps/*`와 legacy/direct `/generate-reference-images`, `/generate-images`가 동시에 활성 |
| 영향 | checkpoint, `step_run`, DB registration, progress, verify, concurrency lock이 다르게 동작 |
| 사고 패턴 | 한 경로는 completed로 보이지만 다른 consumer는 asset/reference를 찾지 못함 |
| 방향 | image generation을 StepRunner/하나의 orchestrator로 단일화하고 legacy endpoint는 wrapper/deprecated 처리 |

### 2. DB schema source가 분산되어 있고 startup migration이 실패를 숨길 수 있음

| 항목 | 내용 |
|---|---|
| 위치 | `backend/app/core/database.py`, `backend/alembic`, `backend/migrations` |
| 현상 | `create_all()` + startup raw SQL + Alembic + standalone SQL이 혼재 |
| 영향 | 실제 DB와 코드/마이그레이션이 drift해도 앱이 뜰 수 있음 |
| 사고 패턴 | 컬럼 길이/type/index 누락, DB insert 실패, silent failure |
| 방향 | Alembic baseline을 source of truth로 만들고 startup DDL은 제거 또는 fail-fast |

### 3. Asset step completed 검증이 충분히 강제되지 않음

| 항목 | 내용 |
|---|---|
| 위치 | image asset steps, StepRunner verify, direct image APIs |
| 현상 | 파일 생성, DB row 등록, checkpoint manifest가 서로 다른 성공 상태를 가질 수 있음 |
| 영향 | PNG는 있는데 DB row 0, DB row는 있는데 file path unresolved, completed인데 consumer fail 가능 |
| 방향 | asset step 공통 exit verify: expected count, DB count, file count, path resolvability, selected filter 일치 |

### 4. Background job이 process-local/in-memory에 의존

| 항목 | 내용 |
|---|---|
| 위치 | `job_manager.py`, `task_registry.py`, `images.py` raw/background thread |
| 현상 | daemon thread와 in-memory dict 기반 |
| 영향 | reload/crash/multi-worker에서 task state 손실, 중복 실행, running stuck |
| 방향 | DB-backed lock/queue 또는 external worker queue 도입 |

### 5. Step/model source of truth가 중복

| 항목 | 내용 |
|---|---|
| 위치 | `STEP_MANIFEST`, `STEP_CATALOG`, `STEP_CLASSES`, `llm_client.PIPELINE_STEPS`, README |
| 현상 | manifest는 single source라고 하지만 runtime model routing은 별도 map을 봄 |
| 영향 | UI에 보이는 모델과 실제 호출 모델이 달라질 수 있음 |
| 방향 | manifest/catalog에 model/provider를 통합하고 `_resolve_model()`이 catalog를 사용하도록 정리 |

### 6. Prompt loading이 version pack atomic이 아님

| 항목 | 내용 |
|---|---|
| 위치 | `backend/app/modules/prompt_loader.py` |
| 현상 | 같은 module 안에서 stem별 최신 파일을 찾아 서로 다른 version prompt/schema가 섞일 수 있음 |
| 영향 | prompt/schema contract drift, provenance 오판 |
| 확인 예 | `shot_extract`, `shot_director`, `entity_extractor_v2` |
| 방향 | module/version pack을 먼저 고정하고 같은 version 안에서 stem을 로드 |

### 7. DB prompt version ordering이 문자열 기준

| 항목 | 내용 |
|---|---|
| 위치 | `prompt_loader.py`, `api/v1/prompts.py` |
| 현상 | `ORDER BY version DESC`, `MAX(version)`이 lexical |
| 영향 | `9.*`가 `10.*`보다 최신처럼 선택될 수 있음 |
| 방향 | numeric-aware version sort 또는 explicit created_at/version_rank 컬럼 도입 |

### 8. Prompt admin UI가 실제 runtime file fallback을 보여주지 못함

| 항목 | 내용 |
|---|---|
| 위치 | `PromptManager`, `/api/v1/prompts`, `prompt_loader` |
| 현상 | UI는 DB `prompt_template`만 보고, runtime은 file fallback도 사용 |
| 영향 | 운영자가 현재 active prompt를 잘못 판단 |
| 방향 | prompt effective view API 추가: DB/file/provenance/version/stem별 source 표시 |

### 9. File path invariant가 `ImageAsset.file_path`에만 강하게 적용됨

| 항목 | 내용 |
|---|---|
| 위치 | `file_paths.py`, checkpoint JSON, source_path, manifest |
| 현상 | DB image path는 normalize되지만 checkpoint/manifest/source path는 제각각 |
| 영향 | cwd 의존, absolute/relative 혼합, consumer path failure |
| 방향 | 모든 persisted path에 공통 path schema/helper 적용 |

### 10. Run-all과 single-step concurrency 경계가 완전하지 않음

| 항목 | 내용 |
|---|---|
| 위치 | `analysis_dispatch_service.py`, `step_execution_service.py` |
| 현상 | 서로 다른 task key/check로 완전 상호 배제가 아님 |
| 영향 | 같은 episode에서 batch와 single step 또는 legacy image generation이 겹칠 수 있음 |
| 방향 | episode-level execution lock 도입 |

## P1 / P2 중기 개선 필요

### 11. `partial` 결과가 downstream으로 소비될 수 있음

| 항목 | 내용 |
|---|---|
| 위치 | `StepRunner.check_gate`, `analysis_dispatch_service.run_steps_batch` |
| 현상 | partial은 failed처럼 cascade stop되지 않음 |
| 영향 | incomplete prompt/entity/asset이 후속 step으로 전달 |
| 방향 | step별 `allow_partial_downstream` contract 추가 |

### 12. `Episode.status`가 pipeline truth보다 넓게 설정될 수 있음

| 항목 | 내용 |
|---|---|
| 위치 | `checkpoint_sync/episode_projection_service.py`, `pipeline_gate.py` |
| 현상 | projection sync 후 analyzed 상태가 실제 전체 분석 완료와 어긋날 수 있음 |
| 영향 | gate/status UI가 잘못 열림 |
| 방향 | episode status와 step_run completion summary 분리 |

### 13. Prompt/schema local validation 부족

| 항목 | 내용 |
|---|---|
| 위치 | `llm_client.py` |
| 현상 | provider strict mode 이후 local jsonschema validation이 약함 |
| 영향 | shape drift가 downstream에서 late failure로 터짐 |
| 방향 | 모든 structured call에서 local schema validation과 error classification 수행 |

### 14. Direct file prompt readers가 DB prompt system을 우회

| 항목 | 내용 |
|---|---|
| 위치 | `prompt_service.py`, `prompt_sanitizer.py`, `image_validator.py`, `pdf_validator.py` |
| 현상 | hard-coded version/newest dir 직접 read |
| 영향 | prompt activation/audit/provenance가 적용되지 않음 |
| 방향 | `prompt_loader` 계약으로 흡수하거나 intentional exception으로 문서화 |

### 15. Frontend API client가 모든 success response를 JSON으로 가정

| 항목 | 내용 |
|---|---|
| 위치 | `frontend/src/api/client.ts` |
| 현상 | `res.json()` unconditional |
| 영향 | 204/empty success에서 client failure |
| 방향 | content-type/content-length 기반 parsing |

### 16. 일부 frontend upload/direct fetch가 error를 제대로 확인하지 않음

| 항목 | 내용 |
|---|---|
| 위치 | `Entities.tsx`, upload hooks |
| 현상 | shared API client 우회, `res.ok` 확인 누락 가능 |
| 영향 | failed upload를 success처럼 처리 |
| 방향 | 모든 fetch를 shared helper 또는 동일 error contract로 통합 |

### 17. Project/Episode filesystem 작업과 DB transaction이 분리

| 항목 | 내용 |
|---|---|
| 위치 | `project_service.py`, `episode_service.py` |
| 현상 | directory/PDF를 먼저 쓰고 DB commit은 나중 |
| 영향 | commit/validation 실패 시 orphan file/dir |
| 방향 | 실패 cleanup, staging temp path, transaction compensation |

### 18. Episode delete가 generated assets/checkpoints를 완전히 정리하지 않음

| 항목 | 내용 |
|---|---|
| 위치 | `episode_service.py` |
| 현상 | source file/일부 DB row는 지우지만 checkpoint/assets/log/step_run orphan 가능 |
| 영향 | storage 증가, old asset이 status/query에 섞일 수 있음 |
| 방향 | soft delete와 physical cleanup policy 분리 |

### 19. Import/export schema가 최신 필드와 drift 가능

| 항목 | 내용 |
|---|---|
| 위치 | `project_export_service.py` |
| 현상 | newer fields 일부 누락 가능 |
| 영향 | round-trip import/export 시 data loss |
| 방향 | schema versioned export contract와 regression test |

### 20. Read endpoint가 file side effect를 가짐

| 항목 | 내용 |
|---|---|
| 위치 | `images.py` file route |
| 현상 | GET image file 요청 중 thumbnail 생성 가능 |
| 영향 | read traffic이 storage mutation을 일으킴 |
| 방향 | explicit thumbnail generation 또는 lazy cache policy 명시 |

## P2 / P3 정리 필요

### 21. README/docs drift

| 항목 | 내용 |
|---|---|
| 예 | README model sample, deployment Docker Compose claim, frontend README stock template, manifest count comment |
| 영향 | 새 환경/운영자가 잘못 설정 |
| 방향 | docs generated section과 manual section 분리 |

### 22. Test DB config drift

| 항목 | 내용 |
|---|---|
| 위치 | `backend/tests/conftest.py`, `conftest_pg.py`, `docker-compose.test.yml` |
| 현상 | default host/port/user/password가 다름 |
| 영향 | 테스트가 실행 환경마다 다른 DB를 봄 |
| 방향 | `.env.test` 또는 single source fixture |

### 23. Requirements 누락 가능성

| 항목 | 내용 |
|---|---|
| 예 | `litellm`, `opik`, script imports |
| 영향 | fresh install에서 import failure |
| 방향 | import audit + lockfile/requirements regeneration |

### 24. Legacy/orphan 코드가 active 분석을 오염

| 항목 | 내용 |
|---|---|
| 위치 | `Old`, `_backup_*`, `prototype*`, `screenplay`, experiment scripts |
| 영향 | 코드 검색 결과가 active path인지 판단하기 어려움 |
| 방향 | active/legacy/orphan registry 작성, search exclude profile |

### 25. Mutation script safety가 일관되지 않음

| 항목 | 내용 |
|---|---|
| 위치 | `backend/scripts`, `scripts` |
| 현상 | DB/file mutation script와 experiment script 혼재 |
| 영향 | 실수로 runtime data 변경 가능 |
| 방향 | dry-run default, explicit `--apply`, target DB/project 표시, safety guard 공유 |

## 이미지 생성 사고와 연결되는 root cause 묶음

이미지 생성 사고는 단일 코드 한 줄보다 아래 조합으로 재발한다.

```mermaid
flowchart TB
    DualPath[dual image execution path] --> Drift[status/checkpoint/DB drift]
    WeakVerify[weak asset exit verify] --> Drift
    PathMixed[mixed persisted paths] --> ConsumerFail[consumer cannot open refs]
    SilentDB[silent DB/migration/insert failures] --> FakeComplete[false completed]
    PromptModelDrift[prompt/model source drift] --> BadPrompt[wrong or missing refs]
    Drift --> UserFailure[scene/reference images missing]
    ConsumerFail --> UserFailure
    FakeComplete --> UserFailure
    BadPrompt --> UserFailure
```

따라서 수정 우선순위는 다음이 합리적이다.

1. 이미지 실행 경로 단일화
2. asset step exit verify 공통화
3. DB schema/migration fail-fast
4. persisted path invariant 확대
5. prompt/model effective source 표시
6. frontend button/API 경로 정리

## 권장 작업 순서

| 순서 | 작업 | 이유 |
|---:|---|---|
| 1 | `/generate-*` legacy endpoint를 StepRunner wrapper로 만들거나 UI에서 제거 | 사용자 사고 경로 즉시 감소 |
| 2 | asset step verify base class 도입 | completed false positive 차단 |
| 3 | startup migration exception fail-fast | schema drift 은폐 차단 |
| 4 | prompt/model source 통합 설계 | LLM/image 설정 혼동 감소 |
| 5 | path schema를 checkpoint까지 확대 | cwd/relative/absolute 문제 제거 |
| 6 | test DB/devops 정리 | 재발 방지 |
| 7 | legacy/orphan registry | 장기 유지보수성 개선 |
