00edd6bff8819ade2115db7b6c96ff4aea0ce884
PR-3 of DS AI routing policy (2026-05-23, see plan
~/.claude/plans/document-server-ai-cheeky-reddy.md +
memory project_document_server_ai_routing_policy).
기존 BackendSelector (PR-DocSrv-Web-Ask-Selector-1, 2 옵션 default
qwen-macbook) 확장 — 4 옵션 + DeviceToggle inline.
UI 변경 (frontend/src/routes/ask/+page.svelte):
- BackendChoice = auto | mac-mini-default | qwen-macbook | claude-cloud
(기존 default 는 legacy alias, auto 또는 mac-mini-default 로 자동 매핑).
- select 4 옵션 (Auto router / Mac mini default / This device /
Claude Cloud) + tooltip.
- DeviceToggle (checkbox 'This is M5 Max') inline — localStorage
ds_device_self_label = macbook-m5-max | null. mount 시 복원.
- This device 옵션 disabled state = !isMacBookM5Max (토글 off 시
grey-out). 토글 off 시 qwen-macbook 선택돼 있었으면 auto 복귀.
- Claude Cloud 옵션 disabled state = !CLOUD_DEV_ENABLED (build-time
flag VITE_ENABLE_CLOUD_BACKEND_DEV, default false). 운영 토글
불가 — 후속 PR DS runtime feature flag API 로 migrate 예정.
- friendlyErrorMessage(reason) — 503 error_reason 매핑
(macbook_unavailable / provider_not_configured / router_* / upstream_*).
- retryWithDefault → retryWithMacMiniDefault 명명 정정.
- parseBackend backward-compat: default / gemma-macmini →
mac-mini-default.
source IP 의존 0 (PR-0 round 2 발견: caddy 2-hop + X-Forwarded-For
미설정 → DS 가 보는 source IP = LAN gateway, 신뢰 불가).
사용자 명시 토글 + localStorage 방식 채택 (Q3=C).
Closure (build + bundle string + lint):
- frontend build PASS (SvelteKit/TS syntax + svelte compile 모두 OK).
- 컴파일된 bundle 에 9 핵심 string 박혀있음 (mac-mini-default /
qwen-macbook / claude-cloud / Auto router / This is M5 Max /
ds_device_self_label / provider_not_configured / This device /
Cloud backend not configured).
- lint:tokens 본 PR 변경 위반 0 (기존 62 stale debt 는 별 chore
PR-DocSrv-Frontend-Token-Cleanup-1).
Backup: ~/.local/share/ds-routing-pr2-backups/20260523/
ask-page.svelte.pre-pr3.
선행: PR-1 (llm-router alias scaffold) + PR-2 (RouterBackend
dispatcher, refactor commit bcf644f) closed.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
hyungi_Document_Server
Self-hosted 개인 지식관리(PKM) + 다국 뉴스 비교 분석 웹 애플리케이션.
모델 이름·엔드포인트·머신 정보는 운영 상태에 따라 변하므로 README 에 박지 않습니다. 운영 단일 진실 소스(SSOT):
~/.claude/projects/-Users-hyungiahn/memory/infra_inventory.md. 모델/엔드포인트/포트/SSH 어디서든 README 와 inventory 가 충돌하면 inventory 가 정답입니다.
기술 스택
- 백엔드: FastAPI + SQLAlchemy 2.0 async, APScheduler cron
- DB: PostgreSQL 16 + pgvector + pg_trgm (단일
pkmDB) - 프론트엔드: SvelteKit 5 (runes mode) + Tailwind CSS 4
- 문서 파싱: kordoc 마이크로서비스 (HWP/HWPX/PDF → Markdown), LibreOffice headless (오피스), marker (PDF → markdown Phase 1B)
- AI 파이프라인 (역할별, 자세한 모델 매핑은 inventory):
- 분류/요약 본체: Mac mini MLX 26B (primary)
- Triage / fallback / chat: GPU Ollama 4B
- Embedding: GPU Ollama
bge-m3(1024d) - Reranker: GPU TEI 컨테이너
bge-reranker-v2-m3 - OCR: docker compose
ocr-service(Surya OCR GPU) - STT: Mac mini MLX Whisper large-v3
- Premium (수동 trigger): Anthropic Claude (
require_explicit_trigger)
- 인증: JWT (access) + HttpOnly cookie (refresh) + TOTP 2FA
- 인프라: Docker Compose, Caddy (HTTP only, 앞단 home-caddy 가 HTTPS 종료), Synology NAS NFS
주요 기능
- 문서 자동 분류/태그/요약 — Triage(4B) → Deep summary(26B) tier 분리, 백로그 guard / 텍스트 슬라이스 / inconsistency 감지
- 하이브리드 검색 — pgvector 벡터 + pg_trgm 전문검색 + reranker (bge-reranker-v2-m3) + Ask pipeline (HyDE / evidence_service)
- 다국어 OCR — Surya OCR GPU (한/영/일/중/독/불 등), NFC/NFD 경로 정규화
- 음성/영상 전사 — MLX Whisper large-v3,
/audio/video라우트 + direct play - 법령 변경 모니터링 —
law_monitorcron, freshness decay (365일 반감기) - 이메일 자동 수집 — MailPlus IMAP, NFS 저장
- Phase 4 Global Digest — 매일 04:00 KST 7일 rolling 뉴스 country×topic 2-level 비교 (
/digest) - 야간 뉴스 브리핑 — 매일 05:10 KST KST 자정~05:00 5시간 윈도우, topic×country 비교 분석 1페이지 카드 (
/news) - 자료실 (Library) — 카테고리 facet 분류 + AI 제안 1-click 승인
- 메모/이벤트/공부 — 5초 행동 기록 메모, 일정/할 일/회고 events 도메인, 가스기사 학습 워크스페이스 (274 개념 + 2,100 기출)
- 마크다운 canonical layer — extracted_images NAS 저장 +
document_images메타 + 단기 토큰 인증 (?token=)
Quick Start
git clone https://git.hyungi.net/hyungi/hyungi_document_server.git
cd hyungi_document_server
# 인증 정보 (DB 비밀번호, JWT secret, Claude API key 등)
cp credentials.env.example credentials.env
$EDITOR credentials.env
# AI 모델 / 엔드포인트 / 경로
$EDITOR config.yaml # inventory 참조하면서 채움
$EDITOR .env # POSTGRES_PASSWORD, MAC_MINI_HOST, NAS_NFS_PATH 등
docker compose up -d --build
운영 도메인 (GPU 서버 배포 기준): https://document.hyungi.net
API 문서: https://document.hyungi.net/docs
디렉토리 구조
├── app/ FastAPI 백엔드
│ ├── api/ 라우터 (documents, search, briefing, digest, memos, events, study, …)
│ ├── workers/ APScheduler / queue (briefing_worker, digest_worker, classify_worker, …)
│ ├── services/ 도메인 로직 (briefing/, digest/, search/, clustering_common, …)
│ ├── ai/client.py AIClient (call_triage / call_primary / call_fallback, parse_json_response)
│ ├── prompts/ *.txt 프롬프트 (분류, 요약, briefing_comparative, digest_topic, …)
│ ├── policy/ AI envelope + prompt_render
│ └── models/ SQLAlchemy ORM
├── frontend/ SvelteKit 5 (runes mode) + Tailwind
│ └── src/routes/ /news (아침 브리핑) /library /memos /audio /video /study /digest /ask …
├── services/
│ ├── kordoc/ HWP/HWPX/PDF 파싱 (Node.js)
│ ├── ocr/ Surya OCR GPU 서비스 (FastAPI)
│ └── marker/ PDF → markdown Phase 1B
├── migrations/ 255+ SQL migrations (schema_migrations 추적)
├── docs/ 설계 문서
└── tests/ pytest
gpu-server/ 폴더는 v1 잔재로 deprecated (현재 AI Gateway 는 ~/home-gateway/ 별 repo).
인프라 구성 (운영 기준)
| 머신 | 역할 |
|---|---|
| GPU 서버 (메인) | Docker Compose (fastapi, frontend, postgres pkm, kordoc, ocr-service, marker-service, reranker(TEI), caddy), Ollama (bge-m3, 4B chat), home-gateway 별 compose |
| Mac mini | MLX 26B primary 추론 + MLX Whisper STT (HTTP 추론 endpoint only, ingress 역할 0) |
| Synology NAS | 파일 원본 (/volume4/Document_Server/PKM/), Synology Office/Drive/Calendar/MailPlus, NFS export → GPU |
| VPS-2 (OVH) | 메일 relay (relay.hyungi.net:587 SASL+TLS+DKIM+LE), Gitea bare mirror, Secondary MX |
상세 IP / 모델 / 컨테이너 / drift / verify 명령은 infra_inventory.md 참조.
운영 변경 정책
- inventory 먼저 갱신
config.yaml/credentials.env갱신- deploy (commit → push Gitea → GPU
git pull && docker compose up -d --build) - verify (smoke endpoints, postgres count, 모니터링)
순서를 어기면 drift. drift 발견 시 infra_inventory.md 의 Drift Log 에 등록 후 정정.
문서
Description
Languages
Python
67%
Svelte
23.1%
Swift
5.3%
TypeScript
3.2%
Shell
0.5%
Other
0.9%