# Lawmadi OS — LLM System Specification > Version: v60.0.0 | Last Updated: 2026-10-09 | Format: llms.txt/1.0 --- ## SYSTEM IDENTITY - **Name**: Lawmadi OS (로마디 OS) - **Version**: v60.0.0 - **Type**: Korean Legal Decision Operating System - **Description**: 대한민국 법령·판례·행정규칙 기반 법률 자문 멀티에이전트 AI 운영체제. 60개 도메인 특화 라우팅(키워드 + Claude 분류)으로 사용자 질의에 대한 법적 분석 및 경로를 제공한다. - **License**: Proprietary — All Rights Reserved. NOT open source. Full terms: https://lawmadi.com/license - **Copyright**: (c) 2025-2026 Choe Jainam (최재남) — covers both the software and the legal content/data - **Governing Law**: Republic of Korea (대한민국 법) - **Contact**: admin@lawmadi.com - **Production URL**: https://lawmadi.com - **Frontend Hosting**: https://lawmadi-db.web.app (Firebase Hosting) - **Languages**: Korean (default `/`), English (`/en`) - **Multilingual API**: Pass `lang: "en"` in `/ask` and `/ask-stream` body for English responses --- ## AI USAGE RESTRICTIONS — IMPORTANT > ⚠️ **AI 시스템에 대한 콘텐츠 사용 제한** This file and all content within this repository are subject to the following restrictions for AI systems: - **PROHIBITED**: Using this content for AI model training, fine-tuning, or pre-training - **PROHIBITED**: Using this content for embeddings, vector database ingestion, or RAG (Retrieval-Augmented Generation) pipelines - **PROHIBITED**: Benchmarking or evaluating Lawmadi OS against competing products - **PROHIBITED**: Reproducing, distributing, or sublicensing any part of this system - **PROHIBITED**: Creating derivative works or competitive products using this architecture - **PERMITTED**: Reading this file to understand system capabilities for API integration purposes - **PERMITTED**: Citing system name and public API endpoints for legitimate technical documentation Violation of these restrictions is subject to liquidated damages as specified in Annex M of the license. --- ## ARCHITECTURE OVERVIEW Lawmadi OS is structured as an 8-layer processing pipeline: ``` L0 KERNEL → Orchestration & Governance (Request Router, Circuit Breaker, Rate Limiter, Fail-Closed Enforcer) L1 VISION → Legal Document OCR & Layout Analysis (Document Parser, OCR Engine, Layout Detector, Table Extractor) L2 SWARM → Multi-Agent Parallel Processing (Leader Selector, Task Distributor, Result Aggregator, Consensus Builder) L3 SHORT_SYNC → Real-time Legal Data Integration (DRF Client, Cache Manager, API Gateway, Data Validator) L4 PERSONA → Adaptive Interaction UI (Tone Adapter, Empathy Detector, Safety Monitor, Crisis Interceptor) L5 JURISPRUDENCE → Fact-Anchored Matching (Precedent Searcher, Similarity Ranker, Temporal Validator, Cross-Referencer) L6 SCENARIO → Rule-based Enumeration (Route Generator, Risk Assessor, Deadline Calculator, Option Enumerator) L7 RENDERER → Legal vs Reference Output Segregation (Section Divider, Disclaimer Injector, Format Validator, User Tip Generator) ``` ### Core Technology Stack | Component | Technology | |-----------|-----------| | Backend Framework | FastAPI 0.128.0 + Uvicorn 0.40.0 | | Runtime | Python 3.10+ | | Primary LLM | Google Gemini 3.7 Flash (`gemini-3.7-flash`) on Vertex AI, location `global` — sole generator for answers, with a DRF tool-calling loop and 429/5xx backoff. Short auxiliary calls (triage, classification, deliberation) run on the same model. Moved to Claude on 2026-09-04 and back to Vertex on 2026-09-18; the swap is a two-constant change because every surface goes through one factory, which is the LLM-independence thesis in practice | | Daily-content LLM | Same model and endpoint as above. The five daily generators moved back to Vertex first, on citation-attribution evidence (73% vs 6.7% correct attribution across a full re-audit of both eras); the remaining axes followed the same day | | Stage 3 generator | Claude Sonnet 5. The Discovery Engine Answer API path was removed on 2026-09-04 (it had been disabled since 2026-07-28 for degraded EN citation verification) | | RAG Engine | Vertex AI Search (lawmadi-legal-cache, 52,020 asset+exam docs + 3,110 EN↔KO law-name aliases) | | NLU Intent Detection | Regex-based Korean/English legal intent patterns + keyword + Claude 3-layer routing | | Deliberation System | CSO-led leader deliberation + handoff display (real-time chat format) | | Authentication | JWT RBAC (admin/premium/user) via PyJWT + Email OTP | | Billing | Paddle Billing — credit packs (Starter 20/₩3,500 · Standard 100/₩9,900 · Pro 300/₩24,900) | | Rate Limiting | slowapi 0.1.9 per-endpoint rate limits | | Async HTTP | httpx | | MCP Server | Custom JSON-RPC 2.0 implementation (`mcp_simple`) — streamable-HTTP transport, 19 tools | | Endpoint Logging | HTTP middleware → `endpoint_logs` table (fire-and-forget, non-blocking) | | Cloud Platform | GCP Cloud Run (asia-northeast3) | | Cloud Resources | 1 vCPU / 2 GiB RAM / min 0 (scale-to-zero) / max 5 instances / concurrency 15 / timeout 300s | | Frontend | Firebase Hosting (Static HTML/CSS/JS — Korean + English) | | Splash Screen | Premium: Aurora gradient + 20 particles + glow icon + letter animation + progress bar | | Header Badges | Analysis \| Verify icons + text (brand names removed) | | Mobile Header | Login + Lang toggle left, Favorites + Dark mode right (balanced layout) | | PWA Icons | Custom PNG icons: 192x192 + 512x512 (resized from 1024x1024 source) | | Database | Cloud SQL (PostgreSQL) via cloud-sql-python-connector | | Secret Management | GCP Secret Manager (모든 런타임 비밀을 주입; 하드코딩 없음) | | CI/CD | GitHub Actions — `deploy.yml` (Changes → Test → Staging → Backend → Notify) + `deploy-hosting.yml` (Firebase Hosting via REST API) | ### Runtime Constants ``` OS_VERSION = "v60.0.0" SOFT_MODE = true (default) _DEFAULT_MODEL = "gemini-3.7-flash" (answers) _DEFAULT_EXPERT_MODEL = "gemini-3.7-flash" (expert answers) _DEFAULT_CONTENT_MODEL = "gemini-3.7-flash" (daily content) _DEFAULT_LIGHT_MODEL = "gemini-3.7-flash" (triage, classification, deliberation) MODEL_CHAIN = ["gemini-3.7-flash"] (429/5xx exponential backoff 2→4→8s) THINKING_BUDGET = get_thinking_budget() # per-model; 3.x rejects tb=0 with HTTP 400 USE_ANSWER_API = false (Answer API implemented but disabled — see README) USE_VERTEX_SEARCH = true CREDIT_RESERVATION = true (atomic pre-reservation credit deduction) ``` --- ## C-LEVEL EXECUTIVES | Role | Name | Meaning | Profile | |------|------|---------|---------| | CSO (Chief Strategy Officer) | 서연 | 글을 펼치다 (書演) | 미국 연방대법원 로클럭 출신급 / 글로벌 Top3 전략 컨설팅 파트너급 | | CTO (Chief Technology Officer) | 지유 | 알고 말미암다 (知由) | 실리콘밸리 유니콘 창업 멤버급 / AI 무결성 검증 분야 세계적 석학급 | | CCO (Chief Content Officer) | 유나 | 오직 나아가다 (唯那) | 애플 휴먼 인터페이스 그룹 리드급 / 칸 라이언즈 그랑프리 수상자급 | --- ## SWARM ENGINE — 60 LEADERS **Swarm Engine Version**: 2.1 | **Mode**: MULTI_AGENT ### Leader Collision Policy - Same priority: `MERGE_LEADERS_BY_MAX_WEIGHT` - Overlapping conditions: `HIGHEST_PRIORITY_WINS_WITH_1_CORE_FALLBACK` - Max merged leaders: 4 ### Full Leader Registry (L01–L60) | ID | Name | Specialty | Role | Profile | |----|------|-----------|------|---------| | L01 | 휘율 | 민사법 | Main Kernel Architect | 대한민국 변호사급 / 대법원 재판연구관 출신 부장판사급 | | L02 | 보늬 | 부동산법 | Property GIS Mapper | 대한민국 변호사급 / 감정평가사급 / 국내 1위 신탁사 자문급 | | L03 | 담슬 | 건설법 | Infrastructure Coder | 대한민국 변호사급 / 건축기사급 / 국토부 건설분쟁조정위원장급 | | L04 | 아키 | 재개발·재건축 | Urban Refactoring Engine | 대한민국 변호사급 / 도시계획기사급 / 대형 건설사 법무실장급 | | L05 | 연우 | 의료법 | Bio-Data Analyzer | 대한민국 변호사급 / 전문의(MD)급 / 대학병원 교수 출신급 | | L06 | 벼리 | 손해배상 | Damage Calculator | 대한민국 변호사급 / 손해사정사급 / 5대 손보사 수석 자문급 | | L07 | 하늬 | 교통사고 | Traffic Log Auditor | 대한민국 변호사급 / 도로교통공단 자문위원급 | | L08 | 온유 | 임대차 | Living Space Sync | 대한민국 변호사급 / 법률구조공단 주택임대차분쟁조정위원급 | | L09 | 한울 | 국가계약 | G2B API Gateway | 대한민국 변호사급 / 조달청 규제개혁위원급 | | L10 | 결휘 | 민사집행 | Final Execution Module | 대한민국 변호사급 / 법원 집행관 사무소 자문 대표급 | | L11 | 오름 | 채권추심 | Asset Tracker | 대한민국 변호사급 / 신용관리사급 / 채권관리 협회 이사급 | | L12 | 아슬 | 등기·경매 | Auction Logic Engine | 대한민국 변호사급 / 법무사 자격 소지급 / 법원 경매계장 출신급 | | L13 | 누리 | 상사법 | Biz Logic Compiler | 대한민국 변호사급 / 공인회계사(CPA)급 / 상장사 감사위원장급 | | L14 | 다솜 | 회사법·M&A | System Merge Architect | 대한민국 변호사급 / 5대 로펌 M&A 파트너급 | | L15 | 별하 | 스타트업 | Incubating OS | 대한민국 변호사급 / 유니콘 스타트업 CLO(최고법률책임자)급 | | L16 | 슬아 | 보험 | Risk Assessment Node | 대한민국 변호사급 / 보험계리사급 / 금감원 보험분쟁조정위원급 | | L17 | 미르 | 국제거래 | Global Packet Router | 대한민국 변호사급 / 미국 뉴욕주 변호사급 / ICC 국제중재인급 | | L18 | 다온 | 에너지·자원 | Resource Manager | 대한민국 변호사급 / 에너지 공기업 법무처장급 | | L19 | 슬옹 | 해상·항공 | Logistics Protocol | 대한민국 변호사급 / 해사법원 판사 출신급 | | L20 | 찬솔 | 조세·금융 | Tax Optimizer | 대한민국 변호사급 / 세무사급 / 국세청 조사국장 출신급 | | L21 | 휘윤 | IT·보안 | System Security Guard | 대한민국 변호사급 / 정보보안기사급 / KISA 사이버보안 본부장급 | | L22 | 무결 | 형사법 | Integrity Checker | 대한민국 변호사급 / 서울중앙지검 특수부 부장검사 출신급 | | L23 | 가비 | 엔터테인먼트 | Media Streamer | 대한민국 변호사급 / 대형 연예기획사 법무총괄 이사급 | | L24 | 도울 | 조세불복 | Tax Flow Auditor | 대한민국 변호사급 / 조세심판원 상임심판관 출신급 | | L25 | 강무 | 군형법 | Hardened Security OS | 대한민국 변호사급 / 군사법원 군판사 출신급 | | L26 | 루다 | 지식재산권 | IP Core Protector | 대한민국 변호사급 / 변리사급 / 특허법원 판사 출신급 | | L27 | 수림 | 환경법 | Green Logic Engine | 대한민국 변호사급 / 기후에너지환경부 중앙환경분쟁조정피해구제위원급 | | L28 | 해슬 | 무역·관세 | Cross-border Switcher | 대한민국 변호사급 / 관세사급 / 관세청 심사정책국장 출신급 | | L29 | 라온 | 게임·콘텐츠 | Virtual Asset Logic | 대한민국 변호사급 / 게임물관리위원회 법률자문위원급 | | L30 | 담우 | 노동법 | HR Sync | 대한민국 변호사급 / 공인노무사급 / 중앙노동위원회 공익위원급 | | L31 | 로운 | 행정법 | Policy Debugger | 대한민국 변호사급 / 서울행정법원 수석부장판사 출신급 | | L32 | 바름 | 공정거래 | Antitrust Monitor | 대한민국 변호사급 / 공정거래위원회 상임위원 출신급 | | L33 | 별이 | 우주항공 | Orbital Protocol | 대한민국 변호사급 / 항공우주연구원 법무팀장급 | | L34 | 지누 | 개인정보 | Privacy Shield | 대한민국 변호사급 / 개인정보보호위원회 심의관 출신급 | | L35 | 마루 | 헌법 | Supreme Kernel | 대한민국 변호사급 / 헌법재판소 헌법연구관 출신급 | | L36 | 단아 | 문화·종교 | Culture Logic | 대한민국 변호사급 / 국가유산청 문화유산위원급 | | L37 | 예솔 | 소년법 | Growth Logic | 대한민국 변호사급 / 가정법원 소년부 판사 출신급 | | L38 | 슬비 | 소비자 | UX Rights Auditor | 대한민국 변호사급 / 한국소비자원 분쟁조정사무국장급 | | L39 | 가온 | 정보통신 | Network Protocol | 대한민국 변호사급 / 방통위 법률자문역급 | | L40 | 한결 | 인권 | Ethics Engine | 대한민국 변호사급 / 국가인권위원회 상임위원급 | | L41 | 산들 | 이혼·가족 | Human Relation Debugger | 대한민국 변호사급 / 서울가정법원 가사전문법관 출신급 | | L42 | 하람 | 저작권 | Asset Validator | 대한민국 변호사급 / 저작권위원회 심의위원급 | | L43 | 해나 | 산업재해 | Safety Log Monitor | 대한민국 변호사급 / 공인노무사급 / 질병판정위원회 위원장급 | | L44 | 보람 | 사회복지 | Social Protocol Manager | 대한민국 변호사급 / 보건복지부 고문급 | | L45 | 이룸 | 교육·청소년 | Knowledge Transfer Architect | 대한민국 변호사급 / 교육청 학교폭력대책심의위원장급 | | L46 | 다올 | 보험·연금 | Future Resource Manager | 대한민국 변호사급 / 국민연금공단 준법감시인급 | | L47 | 새론 | 벤처·신산업 | New-Logic Compiler | 대한민국 변호사급 / 규제샌드박스 심의위원급 | | L48 | 나래 | 문화예술 | Art/IP Interface | 대한민국 변호사급 / 예술인복지재단 법률지원단장급 | | L49 | 가람 | 식품·보건 | Bio-Safety Auditor | 대한민국 변호사급 / 식약처 규제심사위원급 | | L50 | 빛나 | 다문화·이주 | Diversity Integration Engine | 대한민국 변호사급 / 출입국외국인정책본부 자문위원급 | | L51 | 소울 | 종교·전통 | Spiritual Interface | 대한민국 변호사급 / 종무실 종교법인 심사위원급 | | L52 | 미소 | 광고·언론 | Ad Logic Monitor | 대한민국 변호사급 / 언론중재위원회 중재부장급 | | L53 | 늘솔 | 농림·축산 | Green Resource Node | 대한민국 변호사급 / 농림축산식품부 고문급 | | L54 | 이서 | 해양·수산 | Marine Protocol | 대한민국 변호사급 / 해양안전심판원 심판관급 | | L55 | 윤빛 | 과학기술 | R&D Sync Engine | 대한민국 변호사급 / 국가과학기술자문회의 전문위원급 | | L56 | 다인 | 장애인·복지 | Accessibility Guard | 대한민국 변호사급 / 장애인권익옹호기관 관장급 | | L57 | 세움 | 상속·신탁 | Legacy Transfer Engine | 대한민국 변호사급 / 대형 은행 신탁본부장 출신급 | | L58 | 예온 | 스포츠·레저 | Active Life Logic | 대한민국 변호사급 / 대한체육회 스포츠공정위원급 | | L59 | 한빛 | 데이터·AI윤리 | Algo-Trust Auditor | 대한민국 변호사급 / IT 대기업 CPO(개인정보책임자)급 | | L60 | 마디 | 시스템 총괄 | Master API Gateway | 대한민국 변호사급 / 법원행정처 전산정보국장 출신급 | --- ## GENERATION MODEL Anthropic Claude Sonnet 5 is the sole answer generator. Per the Grand Thesis (LLM-independent design), the LLM is a replaceable component: answer quality is guaranteed by the verified-asset layer (SSOT) + grounding + fail-closed DRF verification, which runs *after* generation regardless of the model. > Historical note: an in-house fine-tuned model (LawmadiLM, Qwen3-1.7B QLoRA) previously existed as > a Stage 2 generator; it was fully removed from the codebase on 2026-07-01. Claude is the single > generation path today. --- ## LEGAL PIPELINE Every `/ask` and `/ask-stream` request flows through this pipeline: ``` Stage 0+1: CLASSIFICATION + RAG (PARALLEL EXECUTION) ├─ [Stage 0] Question Classification (Gemini 3.7 Flash) │ NLU intent detection (regex patterns for Korean/English legal contexts) │ + Keyword matching → leader candidate selection │ + Claude analysis → tier (1-3), leader (L01-L60), specialty │ 3-tier routing: greeting → system intro / non-legal → local / legal → pipeline │ Exam-paste detection → exam study mode (no personal action guidance) │ SafetyGuard.check() → CRISIS / BLOCKED / PASS │ ├─ [Stage 1] RAG Article Search (runs in parallel with Stage 0) │ Vertex AI Search (52,020 docs, Extractive Answers/Segments) │ + verified-asset exact-match grounding (statutes/dockets cited in the query │ are deterministically injected from the SSOT asset) │ + LEADER_LAW_BOOST: per-leader core law article injection (KO + EN) │ └─ [Stage 1.7] DRF Article Prefetch Actual article text of laws likely to be cited is fetched from law.go.kr and injected into the prompt (hallucination prevention) Stage 2: CLAUDE ANSWER GENERATION (SOLE GENERATOR) ├─ Claude Sonnet 5 with full context: │ System instruction + leader persona + RAG context + prefetched articles │ + verified precedent injection + 5-step framework │ 5-step: Acknowledge → Diagnose → Action Roadmap → Safety Net → Closing ├─ Max output: 3,000 tokens (standard) / 5,000 tokens (expert) ├─ 429 exponential backoff (2→4→8s) └─ Supports Korean and English responses (lang parameter) Stage 4: DRF REAL-TIME FULL VERIFICATION (FAIL-CLOSED) ├─ Extract law references (article + paragraph level) + precedent/constitutional dockets │ Law-name canonicalization: 13,683 verified alias map + self-defined │ abbreviation resolution + "동법" pronoun resolution ├─ Precedents: SSOT verified-asset exact match first (unconditional), then live DRF │ with an exact-docket guard — a keyword hit that returns a different case is not proof ├─ Statutes: live DRF first (needed for paragraph-level checks the asset cannot answer); │ the SSOT asset is a confirm-only fallback used when DRF is unusable ├─ Deterministic docket-typo repair (DOCKET_REPAIR): a one-character docket │ mistranscription is restored to the verified docket only if the candidate is │ unique, its holding matches the citing context, and existence is re-confirmed ├─ Legal-consistency gate (Tier 1 deterministic rules — e.g. 친고죄/반의사불벌죄 │ confusion, docket-date conflicts — strip contradictory sentences) ├─ Unverified citations → sentence-level strip. "Could not check" is never recorded as │ "does not exist": when law.go.kr is unreachable the citation is stripped but labelled │ unverifiable (re-run), while a name that fails to resolve while the network is alive │ is recorded as absent (fix the content). Total verification failure → Fail-Closed block ├─ Constitutional compliance validation (6 principles) └─ Audit logging to Cloud SQL ``` ### Deliberation System (Leader Conference) For complex multi-domain questions, CSO 서연 leads a leader deliberation process shown to users in real-time chat format. ``` First question → CSO-led deliberation ├─ CSO selects relevant leaders (max 4 merged) ├─ Each leader provides domain-specific analysis (individual Claude calls) ├─ CSO synthesizes and delegates to primary leader └─ Displayed as chat bubbles with leader names and specialties Follow-up question → Leader handoff ├─ Previous leader summarizes and hands off └─ New leader acknowledges and continues ``` --- ## CONSTITUTIONAL PRINCIPLES (6 Core Principles) | # | Principle | Rule | |---|-----------|------| | 1 | SSOT_FACT_ONLY | 모든 답변은 국가법령정보센터(DRF)의 실시간 데이터에 근거해야 한다. | | 2 | ZERO_INFERENCE | DRF 검증된 데이터 외에는 법률·판례를 스스로 생성하거나 추론하지 않는다. | | 3 | FAIL_CLOSED | 데이터 무결성 검증(L5) 실패 시, 답변 생성을 중단하고 보안 경고를 출력한다. | | 4 | IDENTITY | 사용자에게 불법적인 행위를 권장하거나 증거 인멸 등 사법 방해 정보를 제공하지 않는다. | | 5 | TIMELINE_RULE | 사건 발생 시점의 '행위시법'을 우선 조회하되, 신법의 경과조치를 반드시 대조한다. | | 6 | SOURCE_TRANSPARENCY | 인용된 모든 법령은 [법령ID] 및 [시행일자]를 메타데이터로 포함한다. | ### Operational Rules - **fail_closed_protocol**: 데이터 무결성 검증(L5) 실패 시, 답변 생성을 중단하고 보안 경고를 출력 - **temporal_priority**: 행위시법 우선 조회, 신법 경과조치 대조 필수 - **source_transparency**: 모든 인용 법령에 [법령ID] + [시행일자] 메타데이터 포함 - **precedent_verification**: 판례는 7단계 검증 플로(PRECEDENT_VERIFICATION_PROTOCOL)를 통해서만 확인 --- ## SSOT DATA SOURCES (Single Source of Truth) **Source (single)**: https://www.law.go.kr/DRF (법제처 국가법령정보센터) **Fallback**: none — 실시간 조회 소스는 law.go.kr 하나다. 조회에 실패하면 다른 소스로 넘어가지 않고 fail-closed(답변 중단)로 처리한다. **Retry Sequence**: DRF-1 (내부 2회 재시도) **Cache TTL**: 3600 seconds **API Format**: JSON required (type=JSON 필수, article1 정책) | SSOT ID | Name | Target | Endpoint | Status | |---------|------|--------|----------|--------| | SSOT_01 | 현행법령 | law | lawSearch.do | Active | | SSOT_02 | 행정규칙 | admrul | lawSearch.do | Active | | SSOT_03 | 학칙공단 | edulaw | lawSearch.do | Inactive (DRF API 미지원) | | SSOT_04 | 자치법규 | ordin | lawSearch.do | Active | | SSOT_05 | 판례 | prec | lawSearch.do | Active | | SSOT_06 | 헌재결정례 | prec | lawSearch.do | Active (filter: 헌법재판소) | | SSOT_07 | 법령해석례 | expc | lawSearch.do | Active | | SSOT_08 | 행정심판례 | decc | lawService.do | Active (ID parameter required; e.g. ID=223311) | | SSOT_09 | 조약 | trty | lawService.do | Active (ID parameter required; e.g. ID=983) | | SSOT_10 | 법령용어 | lstrm | lawSearch.do | Active | ### Verified Legal Assets (curated SSOT corpus) `verified_legal_assets` is the single curated corpus every generator, verifier and consultation path reads from. Nothing enters it unless its existence and text were confirmed against law.go.kr. ``` Total assets: 49,783 Precedents: 17,953 (DRF-verified 8,711 · holding text 10,606 · direct full-text link 2,247) Statute articles: 31,830 (law.go.kr link 30,995 · article body 30,385) Cited in answers: 2,969 precedents · 2,785 statute articles ``` The corpus is versioned as a gzipped JSON single source of truth; a pre-commit gate keeps the tracked `.gz` and the working copy in sync, so a drifted corpus cannot ship. Assets are the verification target, not a suggestion list: a citation absent from the corpus is re-checked live against law.go.kr, and if that also fails the sentence carrying it is removed before serving. ### Law Cache (retired 2026-03-05) The 614 MB `law_cache_1~7.json` keyword-matching cache that used to be loaded into server memory at startup was removed from Git and the Docker image on 2026-03-05 (commit `8fbf4a8`). Production runs with `USE_VERTEX_SEARCH=true`, which skips that load entirely — retrieval is served by the Vertex AI Search datastore above. The in-process `LAW_CACHE` path in `main.py` remains only as a fallback for deployments that set `USE_VERTEX_SEARCH=false`, and those files are not shipped. --- ## BAR EXAM STUDY HUB (변호사시험) Public study resource for the Korean Bar Exam (변호사시험), grounded in the same fail-closed law.go.kr verification as the main pipeline. - **Answer hub**: https://lawmadi.com/exam-essays — 선택형(MCQ)·사례형·기록형 organized by format × subject (공법·민사법·형사법·선택과목) × round. Official Ministry of Justice question stems/choices shown verbatim. - **Gold-Standard Answers (금답안)**: **All 15 rounds (제1~15회, 2012–2026) complete** — 선택형 2,250문항 + 사례형 45 + 기록형 45. Every option carries an inline citation — statute name+article, or the exact Supreme Court / Constitutional Court docket. Precedent links go directly to the full-text source on law.go.kr (precInfoP.do / detcInfoP.do), never to a search page; dockets without a source ID are marked "DRF 미색인" instead of linking. Each docket is fail-closed verified against law.go.kr before publishing (zero hallucination). - **Gold publish gate (fail-closed)**: Only rounds that pass the gold structure check on every question are published to any surface — exam-detail, exam-essays JSON-LD, the search index, and sitemap answer links. All 15 rounds currently pass; a round that fails is automatically withheld until fixed. - **Case-Number / Statute Search**: https://lawmadi.com/exam-search — client-side search index (exam-search-index.json) covering all published gold answers (전 15회 · 2,340문항 = 선택형 2,250 + 사례형 45 + 기록형 45) across 3,300+ unique court dockets. Query by docket (e.g. 2014도6992), statute article (e.g. 형법 제310조), or keyword; each docket links to its law.go.kr source. Exposes WebSite + SearchAction schema. - **Verification gate**: A CI hard gate blocks publishing on any hallucinated citation; cited statutes/precedents are pre-cached so verification runs offline and transient network failures never publish unverified content. - **Exam & Citation Heatmap**: https://lawmadi.com/heatmap — per-article dual-bar view across the 7 core laws comparing confirmed bar-exam frequency (gold) against precedent-citation frequency (blue), with citation/exam sorting and direct law.go.kr links to each article's representative precedent. - **Precedent Survival**: https://lawmadi.com/case-survival — tracks whether a key precedent was later upheld, modified, or overruled, signalling whether the holding is still good law. --- ## DAILY CONTENT STREAMS Six content streams publish once per day at 05:00 KST (workflow cron `0 20 * * *` UTC), plus a manually authored design log. Every stream is fail-closed: an item that does not pass its gate is simply not published that day rather than published unverified. Counts below are as of 2026-10-09 (latest published day 2026-10-09); a blocked day is filled in later by a hand-authored post that passes the same gate, so each stream's archive is continuous from 2026-06-01. | Stream | URL | Author | Volume | Gate before publishing | |---|---|---|---|---| | 오늘의 법률상식 | https://lawmadi.com/daily | rotating leader (L01–L60, 60-day cycle) | 131 posts (2026-06-01 → 2026-10-09) | every cited statute article is matched against law.go.kr; a single unverifiable article blocks the post | | 전략 칼럼 | https://lawmadi.com/strategy | 서연 (CSO) | 131 posts (2026-06-01 → 2026-10-09) | hype/unverifiable-figure filter + topic-duplicate gate; figures must be traceable to a fetched source page; references are attached only from grounded, live-checked sources | | 기술 칼럼 | https://lawmadi.com/tech | 지유 (CTO) | 131 posts (2026-06-01 → 2026-10-09) | same hype/duplicate gates; cited papers and articles must resolve live | | 리걸테크·AI 뉴스 | https://lawmadi.com/news | 유나 (CCO) | 130 posts (2026-06-01 → 2026-10-09) | trusted-domain whitelist (117 domains; law-firm alerts, vendor PR and UGC stay excluded) + source-token match against the actual article + 30-day re-use block on URL, title tokens and slug prefix; fewer than 2 surviving items means no digest that day | | 수험 판례 강의노트 | https://lawmadi.com/bar | rotating leader | 131 posts (2026-06-01 → 2026-10-09) | precedents drawn from the DRF-verified cache; dockets without a source ID are labelled "DRF 미색인" rather than linked | | 오늘의 판례 | https://lawmadi.com/precedent | leader who authored the matching exam answer | 131 posts (2026-06-01 → 2026-10-09) | only precedents that are both content-verified and DRF-verified; the commenting leader must have authored a gold answer citing that case | ### Public Design Log (설계로그) - **Decisions**: https://lawmadi.com/design-log — 41 architecture decision records (ADR-0001–0041), all currently labelled `설계중` (under design). Tracks: common 21, forensic 13, profiling 7. These are R&D records for research tracks under design, **not services being offered**; each record states the alternatives that were rejected and why. - **Investigation notes**: https://lawmadi.com/design-log/notes — 22 notes (NOTE-0001–0022). Each discloses its `authorship` and an explicit `usable_as_basis` flag (currently 11 usable, 11 not). Notes precede a decision and may be LLM-authored; the decision records themselves are human-authored by policy (`_meta.authoring_rule` — no LLM-generated decisions). - **Citation gate**: statutes cited in the design log are re-checked against law.go.kr both on publish and by a daily drift check, so an amendment that invalidates a citation surfaces without waiting for the next edit. ### MCP Server (Model Context Protocol) JSON-RPC 2.0 over streamable-HTTP. Standard MCP clients (Claude Desktop, Cursor, …) can connect directly. `GET /mcp` returns server info; a GET asking for `text/event-stream` is answered `405` because this server does not open a server-initiated SSE channel. Discovery (`initialize`, `tools/list`, `ping`) is public. **`tools/call` needs a credential** — anonymous calls get JSON-RPC error `-32001`, and that error names the tools you *can* call without one. Two tools answer with no key at all (at preview depth), so you can confirm the corpus is real before spending anything. The block below — protocol versions, authentication, and the per-tool cost boundary — is generated from the code that enforces it. Earlier revisions of this file stated "the lookup tools call no LLM and cost no credits", which was wrong past their daily allowance; generating it removes that class of error. ### Protocol and authentication - MCP endpoint: `POST https://lawmadi.com/mcp` (JSON-RPC 2.0). Default protocol `2024-11-05`; `initialize` negotiates any of `2024-11-05`, `2025-03-26`, `2025-06-18`, `2025-11-25` — send the newest one your client speaks. - A2A endpoint: `POST https://lawmadi.com/a2a` — agent card at `https://lawmadi.com/.well-known/agent-card.json` (streaming and push notifications are **not** supported; use `message/send`, then `tasks/get`) - OAuth 2.0: `https://lawmadi.com/.well-known/oauth-authorization-server` (RFC 8414) and `https://lawmadi.com/mcp/.well-known/oauth-protected-resource` (RFC 9728). Dynamic client registration is open (RFC 7591) at `POST /oauth/register`; authorization code + PKCE (`S256` only). Scopes: `mcp` (full) and `mcp:read` (cannot spend credits — credit-spending tools are refused and lookups stop at the free daily allowance instead of charging). One human consent, then the agent refreshes on its own. - API key: `Authorization: Bearer lmk_live_…`. An OAuth access token **is** such a key, so quotas, allowances, billing and `get_account` behave identically either way. - Machine payment (x402): `https://lawmadi.com/.well-known/x402`. **Currently 404 — no on-chain wallet is configured yet**, and we do not advertise a capability we cannot honour. Until then, buy credits at `https://lawmadi.com/pricing` (browser checkout). Usable with **no key at all**: `get_pricing`, `lookup_precedent`, `lookup_statute` — the preview tools answer at preview depth, 1/day per caller. `tools/list` carries the same facts per tool in `_meta["lawmadi/access"]`, and every description is prefixed with its access tier, so you can pick tools without guessing. ### What each tool costs | tool | auth | cost | | ------------------- | --- | --- | | `ask` | key | 2 credits | | `ask_expert` | key | 3 credits — PRO plan only | | `search` | key | no credits, 60/day per key | | `get_leaders` | key | no credits, 60/day per key | | `chat_leader` | key | 1 credit | | `suggest_questions` | key | no credits, 20/day per key | | `lookup_precedent` | no key (preview, 1/day) | 30/day free, then 1 credit per 10 (ceiling 300/day) | | `lookup_statute` | no key (preview, 1/day) | 30/day free, then 1 credit per 10 (ceiling 300/day) | | `verify_citations` | key | 1 credit | | `bar_exam_search` | key | no credits, 60/day per key | | `get_exam_answer` | key | 3/day free, then 1 credit each (ceiling 100/day) | | `get_daily_content` | key | no credits, 60/day per key | | `list_document_types` | key | no credits, 60/day per key | | `generate_document` | key | 2 credits | | `search_legal_forms` | key | no credits, 60/day per key | | `find_village_lawyer` | key | no credits, 60/day per key | | `get_pricing` | no key | no credits | | `get_account` | key | no credits | | `latest_content` | key | no credits, 60/day per key | Caps that credits do **not** raise: no-credit tools 60/day per key, uncharged LLM tools 20/day. Both reset at 00:00 KST. Allowance ceilings are listed per tool above. **19 tools:** | Group | Tool | What it does | LLM | |---|---|---|---| | Answer | `ask` | Route a Korean legal question to 1 of 60 specialist leaders; statute-verified answer | yes | | Answer | `ask_expert` | Expert mode — deeper, more heavily cited | yes | | Answer | `chat_leader` | 1:1 conversation with a named leader | yes | | Answer | `suggest_questions` | Follow-up questions for a query | yes | | Directory | `get_leaders` | The 60 leaders and their specialties | no | | Search | `search` | Statute/precedent/term search via law.go.kr | no | | Verify | `lookup_precedent` | Docket → court, date, case name, 판시사항, 판결요지, law.go.kr full-text link | no | | Verify | `lookup_statute` | 「법령명 제N조」 → article title, body, link | no | | Verify | `verify_citations` | **Fact-check the Korean legal citations in any text — including text another model wrote** — **1 credit per call** | no | | Exam | `bar_exam_search` | Search 15 rounds / 2,340 bar-exam questions with verified gold answers | no | | Exam | `get_exam_answer` | One question in full — MCQ stem, all choices, official answer key, reasoning, per-choice notes; or the complete 사례형/기록형 answer text | no | | Content | `get_daily_content` | One published post **in full** — the article body (intro, key concepts, deep analysis, steps, cautions, FAQ / a column's abstract, lead, insights, counterpoint, implications / the news items and analysis) plus the verified statute list, references and precedent record | no | | Practice | `list_document_types` | Draftable document types | no | | Practice | `generate_document` | Draft 고소장·소장·내용증명·법률의견서 … from the user's facts | yes | | Practice | `search_legal_forms` | Official statutory forms and appendix tables (별표·서식) | no | | Access | `find_village_lawyer` | Ministry of Justice 마을변호사 (free consultation) by locality | no | | Content | `latest_content` | Latest posts across the six daily streams (index; use `get_daily_content` for one post in full) | no | **Agent onboarding & payment.** An arriving agent can self-serve the whole path: | Step | How | |---|---| | Learn the price | `tools/call get_pricing` — **no auth required**; or `GET /plans` (plain JSON) | | Sign in | https://lawmadi.com (email one-time code) → 10 free credits, granted once, no reset | | Get a key | https://lawmadi.com/mcp-key-guide (email sign-in, no plan required) → `Authorization: Bearer `. `/expert-console` issues a separate expert REST key and is **Pro plan only**. | | Pay | https://lawmadi.com/pricing — Starter 20/₩3,500 · Standard 100/₩9,900 · Pro 300/₩24,900; credits never expire | | Stay ahead of the balance | `tools/call get_account` → remaining credits + top-up link | Refusals carry the next step rather than just a reason. An unauthenticated `tools/call` returns JSON-RPC `-32001` whose `error.data` is the full onboarding object (steps, packs, checkout URLs), and a metered call that runs out of credits returns `status: payment_required` with the pack list and the instruction that retrying the identical call after purchase is all that is needed. `verify_citations` costs **1 credit per call**. It calls no LLM — the cost is a product price, not a compute cost — so an agent budgeting by "does it call an LLM" will mis-plan it. It is the one metered tool that is fully deterministic. `verify_citations` reports each citation as `verified_in_corpus` or `not_in_corpus`. **`not_in_corpus` is not a fabrication verdict** — the corpus is a verified subset of Korean law, so an absent citation means "check it at law.go.kr", and the tool says so in its own output. Encoding that distinction is deliberate: a verifier that overstates its knowledge is worse than none. ### Machine-Readable Surfaces - `https://lawmadi.com/feed.xml` — RSS across all streams and the bar-exam archive. - `https://lawmadi.com/sitemap.xml` — `lastmod` reflects each page's actual last change (derived from repository history, monotonically forward only), not a blanket rebuild date. - `https://lawmadi.com/image-sitemap.xml` — self-hosted images only, with brand-descriptive alt text. - `https://lawmadi.com/llms.txt` — condensed version of this file, with a "Latest Daily Content" section refreshed on every publish. - `https://lawmadi.com/content-feed.json` — **the daily corpus, opened for agents.** Full text of the latest posts in each of the six streams (with the verified statute list, live-checked references and precedent records), plus the editorial gate each stream passed and how to reach the rest through MCP. No authentication, no sign-up — it is meant to be read before deciding whether the paid surface is worth it. Regenerated on every publish; `Cache-Control: no-cache`. - `https://lawmadi.com/robots.txt` — crawler policy. **Every LLM/AI crawler is allowed to fetch `/llms.txt` and `/llms-full.txt`**, plus all public pages. Major AI agents are named explicitly (GPTBot · ChatGPT-User · OAI-SearchBot · ClaudeBot · Claude-User · Claude-SearchBot · Claude-Web · anthropic-ai · Google-Extended · Google-CloudVertexBot · PerplexityBot · Perplexity-User · Applebot · Applebot-Extended · Amazonbot · meta-externalagent · meta-externalfetcher · FacebookBot · MistralAI-User · cohere-ai · cohere-training-data-crawler · DuckAssistBot · YouBot · Bytespider · PetalBot · Diffbot · AI2Bot · Timpibot · Webzio-Extended · Omgilibot · ImagesiftBot · CCBot), and any unnamed crawler falls through to `User-agent: *`, which allows the same files. Only private endpoints (`/api/`, `/ask`, `/ask-stream`, `/ask-expert`, `/auth/`, `/health`, `/export-pdf`) are disallowed. Access ≠ license: the AI USAGE RESTRICTIONS above still govern what may be done with the content once fetched. - `https://lawmadi.com/openapi.json` — OpenAPI description of the public API surface. - `https://lawmadi.com/.well-known/mcp.json` — MCP discovery document (server name, tools, endpoint and auth). These four documents plus `/llms.txt` are served from the same files by both origins — Firebase Hosting on `lawmadi.com` and the application itself on the Cloud Run URL — so an agent that found either origin reads the same thing. --- ## OUTPUT FORMAT POLICY ### Legal Section (📚 법률 근거) - **Required**: true - **Source**: DRF only - **Disclaimer**: "본 내용은 대한민국 법령/판례/공식 데이터에 기초하여 정리한 참고 의견이며, 구체 사안에 대한 유권해석/법적 효력을 보장하지 않습니다." - **On DRF Unavailable**: "현재 DRF(국가법령정보) 연결/검증이 불가하여 법률 근거 섹션을 제공할 수 없습니다." ### Reference Section (🔍 참고 정보) - **Required**: false - **Source**: External Open API - **Segregation**: Enforced (visual separator `---`) - **Disclaimer**: "[참고] 아래 정보는 외부 공개 API(Open Data)를 참조한 내용으로, 법적 근거로 직접 활용할 수 없습니다." - **Timeline Analysis**: 🕐 시간축 분석 (Timeline Analysis) — placement in reference section --- ## API ENDPOINTS **Base URL (Production)**: https://lawmadi.com (via GCP Cloud Run, asia-northeast3) ### Public Endpoints | Method | Path | Description | |--------|------|-------------| | GET | `/` | Static frontend — Korean (index.html) | | GET | `/en` | Static frontend — English (index-en.html) | | GET | `/health` | Health check: `{"status": "online", "os_version": "v60.0.0"}` | | GET | `/leaders` | 60 리더 전체 목록 반환 | | GET | `/leaders-en` | 60 리더 전체 목록 (영어) | | GET | `/about` | 소개 페이지 — 한국어 | | GET | `/about-en` | 소개 페이지 — 영어 | | GET | `/clevel-en` | C-Level 페이지 (영어) | | GET | `/terms` | 이용약관 | | GET | `/privacy` | 개인정보처리방침 | | GET | `/metrics` | 시스템 메트릭 (요청 수, 평균 레이턴시) | | GET | `/diagnostics` | 시스템 진단 정보 | | POST | `/ask` | 법률 질의 처리 (메인 AI 엔드포인트). `lang: "en"` 파라미터로 영어 응답 | | POST | `/ask-stream` | SSE 스트리밍 법률 답변. `lang: "en"` 파라미터로 영어 응답 | | POST | `/ask-expert` | 전문가용 답변 (Claude 재생성 + DRF SSOT 검증) | | POST | `/upload` | 법률 문서 파일 업로드 | | POST | `/analyze-document/{file_id}` | 업로드된 문서 분석 | | POST | `/export-pdf` | 법률문서 PDF 내보내기 | | GET | `/search` | 법령 검색 | | GET | `/trending` | 인기 질문 트렌드 | | GET | `/plans` | 요금제 정보 조회 | | POST | `/feedback` | 사용자 피드백 제출 | | POST | `/suggest-questions` | AI 추천 질문 생성 | | POST | `/lawyer-inquiry` | 변호사 상담 문의 | | POST | `/api/visit` | 방문자 카운터 업데이트 | | GET | `/api/visitor-stats` | 방문자 통계 조회 (`today_visitors`, `total_visitors`) | | POST | `/auth/token` | JWT 액세스 토큰 발급 (API Key → JWT, 5/min rate limit) | | POST | `/api/paddle/otp/send` | Email OTP 발송 (SMTP, 단기 만료) | | POST | `/api/paddle/otp/verify` | Email OTP 검증 → DB 세션 토큰 발급 (30일) | | GET | `/api/paddle/me` | 로그인 사용자 정보 조회 | | POST | `/api/paddle/logout` | 세션 로그아웃 | | GET | `/api/paddle/credits` | 크레딧 잔액 조회 | | GET | `/api/paddle/credits/history` | 크레딧 내역 조회 (최근 50건) | | GET | `/api/paddle/credits/check` | 크레딧 잔액 확인 (Expert용) | | POST | `/api/paddle/stream-token` | 단기(15분) 스트림 토큰 발급 — Cloud Run 직결 SSE 스트리밍용 (세션 필요) | | POST | `/api/paddle/webhook` | Paddle 결제 웹훅 (크레딧 충전, idempotent) | | GET | `/api/paddle/config` | Paddle 클라이언트 설정 조회 | | GET | `/pricing` | 요금제 페이지 (한국어) | | GET | `/pricing-en` | 요금제 페이지 (영어) | | GET | `/refund` | 환불 정책 (한국어) | | GET | `/refund-en` | 환불 정책 (영어) | ### Admin Endpoints (Internal) | Method | Path | Description | |--------|------|-------------| | GET | `/api/verification/stats` | 헌법 검증 통계 | | GET | `/api/admin/leader-stats` | 리더별 질문 통계 | | GET | `/api/admin/category-stats` | 법률 분야별 통계 | | GET | `/api/admin/leader-queries/{leader_code}` | 특정 리더 질문 이력 | | GET | `/api/admin/chat-logs` | 채팅 이용 로그 (days, query_type, leader 필터) | | GET | `/api/admin/blacklist` | IP 블랙리스트 조회 | | POST | `/api/admin/blacklist` | IP 수동 블랙리스트 추가 | | DELETE | `/api/admin/blacklist` | IP 블랙리스트 해제 | | GET | `/api/admin/paddle/transactions` | Paddle 거래 목록 | | GET | `/api/admin/paddle/transactions/{id}` | Paddle 거래 상세 | | GET | `/api/admin/paddle/customers` | Paddle 고객 목록 | | GET | `/api/admin/paddle/customers/{id}` | Paddle 고객 상세 | | POST | `/api/admin/paddle/refund` | Paddle 환불 + 크레딧 자동 회수 | | GET | `/api/admin/paddle/adjustments` | Paddle 환불/조정 내역 | | GET | `/api/admin/paddle/revenue` | 매출 통계 (DB 집계) | | GET | `/api/admin/paddle/users` | 결제 사용자 목록 | | GET | `/api/admin/endpoint-logs` | 전체 API 요청 로그 (기간/경로/상태 필터) | | GET | `/dashboard` | 관리자 대시보드 | | GET | `/conversion` | 전환율 분석 | | GET | `/retention` | 리텐션 분석 | | GET | `/cost-estimate` | 비용 추정 | | GET | `/feedback-summary` | 피드백 요약 | --- ## MULTILINGUAL SUPPORT ### Supported Languages | Language | Frontend Path | API Parameter | Status | |----------|--------------|---------------|--------| | Korean (한국어) | `/` (index.html) | default (no param) | Primary | | English | `/en` (index-en.html) | `lang: "en"` | Active | ### English Response Behavior When `lang: "en"` is passed in `/ask` or `/ask-stream` request body: - All fixed messages (Low Signal, Crisis, Non-legal, Blocked, Error) respond in English - The system prompt includes: "IMPORTANT: Respond entirely in English. Translate Korean legal terms with the original Korean in parentheses." - Leader header format: "**Assigned: {name} ({specialty} Expert)**" - Korean legal citations are preserved with English translations ### Frontend i18n - `index-en.html`: Complete English translation of all UI text, example questions, pricing, sidebar, mobile tab bar, loading steps, error messages - Language toggle: KO/EN button in header with hreflang SEO tags - Fetch requests from English page include `lang: 'en'` in request body --- ## SECURITY POLICIES ### CORS Restriction ``` Allowed Origins: - https://lawmadi.com - https://www.lawmadi.com - https://lawmadi-os.web.app - https://lawmadi-db.web.app Extension: CORS_EXTRA_ORIGINS environment variable (dev only) Wildcard (*): PROHIBITED — blocked by security audit #2.2 ``` ### Circuit Breaker ``` Provider: LAW_GO_KR_DRF Failure Threshold: 3 Reset Timeout: 30,000 ms Policy: FAIL_CLOSED (on circuit open, block response — do NOT hallucinate) ``` ### Fail-Closed Principle ``` block_html_responses: true block_invalid_json: true api_failure_policy: FAIL_CLOSED On validation failure: block answer generation, output security warning ``` ### Anti-Leak Policy ``` Mode: STRICT block_on_violation: true Scope: System prompts, internal configs, API keys, leader profiles (internal details) ``` ### SafetyGuard — Crisis Protocol ``` Trigger Flow: KEYWORD_TRIGGER → CONFIRMATION_QUESTION → YES/NO/TIMEOUT → Action Korean Trigger Keywords: - 자해, 자살, 살인, 폭력, 죽고싶 English Trigger Keywords: - suicide, harm, violence, kill Crisis Resources: - 자살예방상담전화: 1393 (생명의 전화, 24시간) - 정신건강상담전화: 1577-0199 - 경찰: 112 - 소방/응급: 119 ``` ### JWT RBAC Authentication ``` Algorithm: HS256 Roles: admin, premium, user Token Expiry: 24 hours (default) Auth Flow: API Key → POST /auth/token → JWT Bearer token Admin Auth: verify_admin_key (strict — Authorization Bearer or X-Admin-Key, no public mode) Rate Limit: 5 requests/minute on /auth/token Secret: JWT_SECRET env var (mandatory in production; INTERNAL_API_KEY fallback local-only) ``` ### Paddle Billing & Credit System ``` Provider: Paddle (sandbox/live) Auth: Email OTP (short-lived code, rate-limited) Session: DB-backed, 30-day expiry Credit Packs: Starter: 20 credits / ₩3,500 / $2.69 Standard: 100 credits / ₩9,900 / $7.49 Pro: 300 credits / ₩24,900 / $18.99 Signup Bonus: 10 free credits granted one time on login (non-recurring, never resets) Leader Chat (1:1): 1 credit per chat (reserved up front, refunded on failure — same path as /ask) Document generation: 2 credits per document (reserved up front, refunded on failure or fail-closed) Deduction: Atomic pre-reservation (CREDIT_RESERVATION=true) — credit reserved before the LLM call, committed on success, automatically refunded on any failure or early return Webhook: Paddle signature verification (idempotent credit top-up) ``` ### Prohibited Topics The following topics are blocked by safety guardrails: 1. 마약 제조 및 유통 방법 2. 디지털 성범죄물 유포 및 은닉 3. 보이스피싱 시나리오 작성 4. 증거 인멸 및 사법 방해 Response on violation: 요청을 처리할 수 없음을 통지하고 로그 기록 ### Expert Node Conduct Rules | Group | Leaders | Forbidden Actions | |-------|---------|-------------------| | 민사법 계열 | L01, L06, L08, L10, L11 | 구체적 수임료 합의, 승소 확률 단정적 제시 | | 형사법 계열 | L22, L25 | 범죄 행위 유발·교안, 피해자 특정 정보 공개 | | 부동산·경매 계열 | L02, L12 | 투기적 투자 권장 | | IT·보안·개인정보 계열 | L21, L34, L39 | (Special focus: 데이터 무결성, 해킹 인과관계, 개인정보 적법성) | | 노동법 계열 | L30 | 불법 해고 유발 행위 권장 | | 헌법 계열 | L35 | (Special focus: 기본권 침해, 비례의 원칙) | | 시스템 총괄 | L60 | (Special focus: 레시피 충돌 해결, 출력 일관성 보장) | --- ## DEPLOYMENT CONFIGURATION ### GCP Secret Manager 런타임 비밀은 전부 GCP Secret Manager 에서 Cloud Run 에 주입된다 — 소스·이미지·설정 파일에 하드코딩된 자격증명은 없다. 개별 시크릿의 이름과 용도는 공개하지 않는다(이 문서의 독자에게 값을 하지 않고, 인증 표면의 구조만 알려주기 때문이다). No Anthropic key is mounted at runtime: the second generator (LawmadiLM) was removed from the codebase on 2026-07-01, and Claude is the only model the server calls. ### Required Environment Variables ``` LAWGO_DRF_OC (mandatory — no default; hardcoded default prohibited by audit #2.3) ANTHROPIC_API_KEY (Claude API key — mandatory; missing key ⇒ FAIL_CLOSED) JWT_SECRET (JWT signing key — mandatory in production; local-only INTERNAL_API_KEY fallback) OTP_HMAC_SECRET (OTP + short-lived stream-token signing; unset ⇒ token issuance fails closed) ``` ### GCP Cloud Run Configuration ``` Region: asia-northeast3 (Seoul) CPU: 1 vCPU Memory: 2 GiB Max Instances: 5 Min Instances: 0 (scale-to-zero) Concurrency: 15 Request Timeout: 300s ``` ### Cloud Run Services ``` lawmadi-os-v60 — Main API (FastAPI, production) | 1 vCPU, 2 GiB | 0–5 instances | asia-northeast3 lawmadi-os-v60-staging — Staging (isolated DB) | 1 vCPU, 2 GiB | 0–2 instances | asia-northeast3 ``` ### CI/CD Pipeline (GitHub Actions) `deploy.yml` — backend, 5 jobs: ``` Job 1: Changes — decides whether the backend image needs rebuilding (docs/content-only pushes skip the Docker build; the test gate still runs on every push) Job 2: Test — pytest subset + link lint + site-stats SSOT check + asset .gz sync check Job 3: Staging — Docker build → Cloud Run staging deploy → smoke tests (/health + /diagnostics) Job 4: Backend — Production deploy (manual approval gate) → health verification Job 5: Notify — Deployment summary notification ``` `deploy-hosting.yml` — frontend (Firebase Hosting, REST API deploy, no firebase-tools auth dependency). Runs the design-log citation gate inline before publishing, so a stale statute citation blocks the deploy rather than reaching the site. --- ## FAIL-SOFT MODULE LOADING The system uses `optional_import()` pattern — if any module fails to load, the server continues booting rather than crashing. Affected modules: ``` engines.temporal_v2 → timeline_analyze agents.swarm_manager → SwarmManager agents.swarm_orchestrator → SwarmOrchestrator agents.clevel_handler → CLevelHandler services.search_service → SearchService core.security → SafetyGuard core.deliberation → generate_deliberation, generate_handoff core.auth → create_access_token, verify_jwt_token core.metrics → record_request, record_event, record_error core.model_fallback → get_model, on_quota_error, generate_with_fallback connectors.drf_client → DRFConnector core.law_selector → LawSelector connectors.db_client → db_client engines.response_verifier → ResponseVerifier (Claude SSOT 검증) ``` --- ## LICENSE SUMMARY Lawmadi OS is **proprietary software — All Rights Reserved. It is NOT open source.** **Copyright**: (c) 2025-2026 Choe Jainam (최재남). A single license governs both layers of the system. The authoritative terms are published at https://lawmadi.com/license (repository path `frontend/public/license`). ### 1. Software / Code — Proprietary Source code, object code, scripts, binaries, build outputs, configuration files, schemas, manifests, policy files, runtime parameters, specifications, and architecture references. Public availability does not grant rights to reuse, reimplement, or compete. ### 2. Legal Content / Data — Proprietary - **Bar-exam gold-standard answers** (변호사시험 금답안 — 선택형·사례형·기록형), including their explanations, citation indexes, and the structured answer corpus - AI-generated legal analyses and leader-persona outputs served by the system - Verified legal-asset compilations (SSOT: curated/verified statute & precedent datasets) - Daily legal content (오늘의 판례·법률상식·전략/기술 칼럼) and their compiled archives **Prohibited** without prior written permission, for both layers: - Modification, redistribution, sublicensing, or provision as a service - Scraping or bulk extraction - AI/ML training, fine-tuning, embeddings, RAG ingestion, or benchmark use - Creating competing or derivative products ### Governing Law - Republic of Korea (대한민국 법) - Permission inquiries: admin@lawmadi.com --- *This llms.txt file conforms to the llms.txt/1.0 specification for machine-readable AI system documentation.* *Generated: 2026-10-09 | Lawmadi OS v60.0.0*