# chrisryugj/lexdiff architecture

> Architecture diagram of the GitHub repository chrisryugj/lexdiff, generated by GitDiagram from its file tree, README and a sample of source files (last updated 2026-04-15). It is an AI-made overview: check details against the source.

- Interactive diagram: https://gitdiagram.com/chrisryugj/lexdiff
- Repository: https://github.com/chrisryugj/lexdiff

## Overview

1. **What this repo is**
   - LexDiff is a Next.js 16 + React 19 legal research application.
   - It combines a browser UI, many server route handlers, and a large set of domain parsers/AI tools to answer Korean legal questions with citations.

2. **Top-level request flow**
   - A user enters a legal query in the frontend.
   - The app authenticates the user, checks quota, and may allow BYOK mode via a user-provided Gemini key.
   - If the request is AI-assisted, it enters the FC-RAG pipeline; otherwise it uses direct search/detail APIs.
   - Results stream back to the UI as text and tool events, not as a single blocking response.

3. **Frontend boundary**
   - The app router in `app/` provides the main screens: home, help, privacy, terms, settings, and the law-viewer experience.
   - `components/` contains the main interaction surfaces: search bars, law viewer, precedent panels, comparison modals, impact tracker, annex viewer, chat-style AI UI, and many dialog/sheet components.
   - The UI is stateful and modal-driven, with much of the behavior delegated to hooks in `hooks/` and feature-specific subcomponents.

4. **API boundary**
   - `app/api/*/route.ts` is the primary server boundary.
   - There are distinct routes for laws, articles, histories, annexes, precedents, interpretations, ordinances, customs, search suggestions, summaries, impact analysis, relation graph stats, quota, privacy, and debug traces.
   - This makes the backend more like a collection of specialized legal service endpoints than a single monolithic API.

5. **Legal content ingestion and parsing layer**
   - `lib/` contains the core legal-data parsers and normalizers: law XML/JSON parsing, annex parsing, precedent parsing, ordinance parsing, revision parsing, hierarchy parsing, and markdown conversion.
   - These parsers are the canonical boundary between external legal data formats and the app’s internal models.
   - The app appears to treat 법령 원문 as the source of truth, then layers HTML/markdown rendering and citation logic on top.

6. **FC-RAG AI subsystem**
   - `lib/fc-rag/` is the central AI subsystem.
   - It includes the router engine, Gemini and Claude/Hermes engine adapters, prompts, tool registry, tool tiers, caching, citations, decision domains, and result utilities.
   - The readme indicates the production path is Gemini-based function-calling RAG, while Hermes/Claude support exists but is disabled in beta.
   - This layer orchestrates multi-step tool use rather than relying on a single prompt/response.

7. **Tooling model for AI**
   - The FC-RAG engine uses many domain tools implemented directly in TypeScript, not just remote MCP calls.
   - Those tools reach law search, precedent search, interpretation search, hierarchy/related-law lookups, impact analysis, and citation verification.
   - The architectural pattern is: classify query → route to tool set → fetch authoritative legal sources → verify citations → stream answer.

8. **Search and query understanding**
   - `src/domain/search/` holds a cleaner domain layer for query classification, pattern detection, entity extraction, and compatibility logic.
   - This is a separate boundary from the UI and from raw parsers: it decides what kind of legal question the user is asking and what search path should be used.
   - `lib/unified-query-classifier.ts`, `lib/query-expansion.ts`, and related utilities support search normalization and intent routing.

9. **Relationship and impact analysis**
   - `lib/relation-graph/` and `lib/impact-tracker/` implement graph-based legal relationships and downstream impact detection.
   - These subsystems support features like “what changed”, delegation gaps, precedent/citation relations, and law-to-law impact propagation.
   - The app also exposes relation-graph stats and impact-analysis endpoints, so this is a first-class feature area, not just an internal helper.

10. **State, cache, quota, and privacy**
   - Persistent state is split across browser storage and backend stores.
   - Local/browser state handles things like BYOK API keys and some cached UI data.
   - Server-side quota, consent, favorites, and log-related data are backed by Supabase and related stores, while fast-path caching uses Redis/response caches.
   - Privacy is treated explicitly via consent, log deletion, anonymization, and scrubbers under `lib/privacy/`.

11. **External services and infrastructure**
   - The main external dependencies are Google Gemini APIs, Law Ministry open APIs, Supabase PostgreSQL, and Upstash Redis.
   - The app also uses Google OAuth-style login flows, and it separates user-owned API keys from server-managed keys.
   - `proxy.ts`, `middleware`, and auth/callback routes form the request-gating layer around those external integrations.

12. **Rendering and interaction model**
   - The law viewer is a major composite surface: it renders articles, annexes, histories, related cases, AI answers, and comparison panels in one place.
   - Many interactions are handled through specialized hooks in `hooks/` and submodules in `components/law-viewer`, `components/search-result-view`, and `components/chat`.
   - The architecture is “feature surface + hook/controller + server route” rather than a thin presentational UI.

13. **Testing and evaluation boundary**
   - `__tests__/` contains broad coverage for API routes, search logic, parsers, RAG engines, relation graph logic, middleware, and UI hooks/components.
   - `evaluation/` contains offline RAG evaluation scripts and datasets, showing that answer quality is measured outside the app runtime.
   - `scripts/` contains operational utilities for downloads, conversions, sync jobs, endpoint tests, and data maintenance, which suggests the repo includes both product code and data ops tooling.

14. **Architecture takeaway for a diagram**
   - A good diagram should show four main zones: browser UI, Next.js route layer, legal/AI domain services, and external data providers.
   - The most important flows are: user query → auth/quota → query classification → legal data retrieval/tool calls → citation verification → streamed answer → UI rendering.
   - Secondary flows include law parsing/import, relation-graph/impact analysis, and cache/log persistence.

Main entry points: [`app/api/law-search/route.ts`](https://github.com/chrisryugj/lexdiff/blob/main/app/api/law-search/route.ts) (Legal routes), [`lib/fc-rag/router-engine.ts`](https://github.com/chrisryugj/lexdiff/blob/main/lib/fc-rag/router-engine.ts) (FC-RAG engine), [`certs/law-go-kr-chain.pem`](https://github.com/chrisryugj/lexdiff/blob/main/certs/law-go-kr-chain.pem) (External sources), [`components/search-result-view/index.tsx`](https://github.com/chrisryugj/lexdiff/blob/main/components/search-result-view/index.tsx) (Search UI)

## Diagram (Mermaid)

```mermaid
flowchart TD

subgraph group_ui["Browser UI"]
  node_app_pages["App screens<br/>Next.js routes<br/>[page.tsx]"]
  node_search_ui["Search UI<br/>Search surface<br/>[index.tsx]"]
  node_law_viewer["Law viewer<br/>Composite view<br/>[law-viewer.tsx]"]
  node_chat_ai["AI chat<br/>Streaming UI<br/>[ChatContainer.tsx]"]
  node_dialogs_modals["Dialogs<br/>Modal layer<br/>[annex-modal.tsx]"]
end

subgraph group_api["Server API"]
  node_search_routes["Legal routes<br/>Route handlers<br/>[route.ts]"]
  node_rag_route["FC-RAG API<br/>AI route<br/>[route.ts]"]
  node_analysis_routes["Analysis APIs<br/>Analysis routes<br/>[route.ts]"]
end

subgraph group_domain["Legal Intelligence"]
  node_query_classifier["Query classifier<br/>Search domain<br/>[QueryClassifier.ts]"]
  node_query_normalization["Query normalizer<br/>Search utils"]
  node_law_parsers["Law parsers<br/>Parsing layer<br/>[law-parser.ts]"]
  node_content_links["Content links<br/>Citation layer"]
  node_fcrag_engine["FC-RAG engine<br/>AI orchestration<br/>[router-engine.ts]"]
  node_fcrag_tools["Tool registry<br/>AI tools<br/>[tool-registry.ts]"]
  node_impact_graph["Impact graph<br/>Graph analysis<br/>[index.ts]"]
  node_impact_tracker["Impact tracker<br/>Change analysis<br/>[engine.ts]"]
end

subgraph group_infra["State & Ops"]
  node_auth_quota["Auth & quota<br/>Access control<br/>[route.ts]"]
  node_privacy_store["Privacy store<br/>Consent & logs<br/>[scrubber.ts]"]
  node_cache_storage["Cache & state<br/>Persistence"]
  node_external_sources[("External sources<br/>Providers")]
end

node_app_pages -->|"renders"| node_search_ui
node_app_pages -->|"renders"| node_law_viewer
node_search_ui -->|"submits AI"| node_rag_route
node_search_ui -->|"submits search"| node_search_routes
node_law_viewer -->|"loads content"| node_search_routes
node_law_viewer -->|"opens"| node_dialogs_modals
node_chat_ai -->|"streams from"| node_rag_route
node_search_routes -->|"normalizes"| node_law_parsers
node_search_routes -->|"fetches"| node_external_sources
node_rag_route -->|"orchestrates"| node_fcrag_engine
node_fcrag_engine -->|"routes by intent"| node_query_classifier
node_fcrag_engine -->|"expands"| node_query_normalization
node_fcrag_engine -->|"invokes"| node_fcrag_tools
node_fcrag_tools -->|"calls legal APIs"| node_search_routes
node_fcrag_tools -->|"verifies citations"| node_content_links
node_law_parsers -->|"ingests"| node_external_sources
node_content_links -->|"anchors to text"| node_law_parsers
node_impact_graph -->|"exposes stats"| node_analysis_routes
node_impact_tracker -->|"serves analysis"| node_analysis_routes
node_auth_quota -->|"checks identity"| node_external_sources
node_privacy_store -->|"scrubs"| node_cache_storage
node_cache_storage -->|"persists"| node_external_sources

click node_app_pages "https://github.com/chrisryugj/lexdiff/blob/main/app/page.tsx"
click node_search_ui "https://github.com/chrisryugj/lexdiff/blob/main/components/search-result-view/index.tsx"
click node_law_viewer "https://github.com/chrisryugj/lexdiff/blob/main/components/law-viewer.tsx"
click node_chat_ai "https://github.com/chrisryugj/lexdiff/blob/main/components/chat/ChatContainer.tsx"
click node_dialogs_modals "https://github.com/chrisryugj/lexdiff/blob/main/components/annex-modal.tsx"
click node_search_routes "https://github.com/chrisryugj/lexdiff/blob/main/app/api/law-search/route.ts"
click node_rag_route "https://github.com/chrisryugj/lexdiff/blob/main/app/api/fc-rag/route.ts"
click node_analysis_routes "https://github.com/chrisryugj/lexdiff/blob/main/app/api/impact-analysis/route.ts"
click node_query_classifier "https://github.com/chrisryugj/lexdiff/blob/main/src/domain/search/services/QueryClassifier.ts"
click node_query_normalization "https://github.com/chrisryugj/lexdiff/blob/main/lib/unified-query-classifier.ts"
click node_law_parsers "https://github.com/chrisryugj/lexdiff/blob/main/lib/law-parser.ts"
click node_content_links "https://github.com/chrisryugj/lexdiff/blob/main/lib/citation-verifier.ts"
click node_fcrag_engine "https://github.com/chrisryugj/lexdiff/blob/main/lib/fc-rag/router-engine.ts"
click node_fcrag_tools "https://github.com/chrisryugj/lexdiff/blob/main/lib/fc-rag/tool-registry.ts"
click node_impact_graph "https://github.com/chrisryugj/lexdiff/blob/main/lib/relation-graph/index.ts"
click node_impact_tracker "https://github.com/chrisryugj/lexdiff/blob/main/lib/impact-tracker/engine.ts"
click node_auth_quota "https://github.com/chrisryugj/lexdiff/blob/main/app/auth/callback/route.ts"
click node_privacy_store "https://github.com/chrisryugj/lexdiff/blob/main/lib/privacy/scrubber.ts"
click node_cache_storage "https://github.com/chrisryugj/lexdiff/blob/main/lib/rag-response-cache.ts"
click node_external_sources "https://github.com/chrisryugj/lexdiff/blob/main/certs/law-go-kr-chain.pem"

classDef toneNeutral fill:#f8fafc,stroke:#334155,stroke-width:1.5px,color:#0f172a
classDef toneBlue fill:#dbeafe,stroke:#2563eb,stroke-width:1.5px,color:#172554
classDef toneAmber fill:#fef3c7,stroke:#d97706,stroke-width:1.5px,color:#78350f
classDef toneMint fill:#dcfce7,stroke:#16a34a,stroke-width:1.5px,color:#14532d
classDef toneRose fill:#ffe4e6,stroke:#e11d48,stroke-width:1.5px,color:#881337
classDef toneIndigo fill:#e0e7ff,stroke:#4f46e5,stroke-width:1.5px,color:#312e81
classDef toneTeal fill:#ccfbf1,stroke:#0f766e,stroke-width:1.5px,color:#134e4a
class node_app_pages,node_search_ui,node_law_viewer,node_chat_ai,node_dialogs_modals toneBlue
class node_search_routes,node_rag_route,node_analysis_routes toneAmber
class node_query_classifier,node_query_normalization,node_law_parsers,node_content_links,node_fcrag_engine,node_fcrag_tools,node_impact_graph,node_impact_tracker toneMint
class node_auth_quota,node_privacy_store,node_cache_storage,node_external_sources toneRose
```

## Components

### Browser UI

Next.js screens and interactive React components.

- [App screens](https://github.com/chrisryugj/lexdiff/blob/main/app/page.tsx): Next.js routes · Main app router pages and shared layout for home, help, privacy, terms, settings, and the law-viewer shell. · `app/page.tsx`
- [Search UI](https://github.com/chrisryugj/lexdiff/blob/main/components/search-result-view/index.tsx): Search surface · Search bar, search-result view, and query-handling components that drive the main user flow. · `components/search-result-view/index.tsx`
- [Law viewer](https://github.com/chrisryugj/lexdiff/blob/main/components/law-viewer.tsx): Composite view · Primary legal document experience combining article display, annexes, comparisons, related cases, and AI answers. · `components/law-viewer.tsx`
- [AI chat](https://github.com/chrisryugj/lexdiff/blob/main/components/chat/ChatContainer.tsx): Streaming UI · Chat-style streaming answer surface with message, typing, and thinking states. · `components/chat/ChatContainer.tsx`
- [Dialogs](https://github.com/chrisryugj/lexdiff/blob/main/components/annex-modal.tsx): Modal layer · Feature dialogs and sheets for annexes, comparisons, consent, favorites, admin rules, and debug/report flows. · `components/annex-modal.tsx`

### Server API

Route handlers and request gating around legal services.

- [Legal routes](https://github.com/chrisryugj/lexdiff/blob/main/app/api/law-search/route.ts): Route handlers · Specialized endpoints for law, article, history, annex, precedent, ordinance, search, summarize, and related lookups. · `app/api/law-search/route.ts`
- [FC-RAG API](https://github.com/chrisryugj/lexdiff/blob/main/app/api/fc-rag/route.ts): AI route · Streaming function-calling RAG endpoint that coordinates tool use and answer generation. · `app/api/fc-rag/route.ts`
- [Analysis APIs](https://github.com/chrisryugj/lexdiff/blob/main/app/api/impact-analysis/route.ts): Analysis routes · Impact analysis, relation-graph stats, quota, privacy, debug traces, and benchmark endpoints. · `app/api/impact-analysis/route.ts`

### Legal Intelligence

Parsing, search, RAG, and analysis logic.

- [Query classifier](https://github.com/chrisryugj/lexdiff/blob/main/src/domain/search/services/QueryClassifier.ts): Search domain · Intent, pattern, entity, and compatibility logic that decides how legal questions should be routed. · `src/domain/search/services/QueryClassifier.ts`
- [Query normalizer](https://github.com/chrisryugj/lexdiff/blob/main/lib/unified-query-classifier.ts): Search utils · Unified query classification, expansion, normalization, and search-type helpers. · `lib/unified-query-classifier.ts`
- [Law parsers](https://github.com/chrisryugj/lexdiff/blob/main/lib/law-parser.ts): Parsing layer · Core XML/JSON/markdown parsers and normalizers for statutes, annexes, revisions, and hierarchy data. · `lib/law-parser.ts`
- [Content links](https://github.com/chrisryugj/lexdiff/blob/main/lib/citation-verifier.ts): Citation layer · Citation matching, link generation, and click-handler normalization for legal text navigation. · `lib/citation-verifier.ts`
- [FC-RAG engine](https://github.com/chrisryugj/lexdiff/blob/main/lib/fc-rag/router-engine.ts): AI orchestration · Router engine, shared engine logic, prompts, decision domains, and streaming result assembly. · `lib/fc-rag/router-engine.ts`
- [Tool registry](https://github.com/chrisryugj/lexdiff/blob/main/lib/fc-rag/tool-registry.ts): AI tools · Domain tool adapters, tiers, cache, citations, and adapters used by the RAG engine. · `lib/fc-rag/tool-registry.ts`
- [Impact graph](https://github.com/chrisryugj/lexdiff/blob/main/lib/relation-graph/index.ts): Graph analysis · Relation graph extraction, database access, and downstream impact analysis for law relationships. · `lib/relation-graph/index.ts`
- [Impact tracker](https://github.com/chrisryugj/lexdiff/blob/main/lib/impact-tracker/engine.ts): Change analysis · Classifier, engine, prompts, and parsers that identify ordinance and rule impacts. · `lib/impact-tracker/engine.ts`

### State & Ops

Persistence, privacy, caching, auth, and deployment support.

- [Auth & quota](https://github.com/chrisryugj/lexdiff/blob/main/app/auth/callback/route.ts): Access control · Login callback, sign-out, quota, and API-auth helpers that gate usage and BYOK access. · `app/auth/callback/route.ts`
- [Privacy store](https://github.com/chrisryugj/lexdiff/blob/main/lib/privacy/scrubber.ts): Consent & logs · Consent, anonymization, scrubber, and log deletion logic plus related persistence. · `lib/privacy/scrubber.ts`
- [Cache & state](https://github.com/chrisryugj/lexdiff/blob/main/lib/rag-response-cache.ts): Persistence · Redis and in-app caches, favorites, recent searches, search-result stores, and Supabase access. · `lib/rag-response-cache.ts`
- [External sources](https://github.com/chrisryugj/lexdiff/blob/main/certs/law-go-kr-chain.pem): Providers · Gemini, Claude/Hermes, Law Ministry APIs, Supabase PostgreSQL, Upstash Redis, and OAuth-backed auth. · `certs/law-go-kr-chain.pem`

## Connections

- App screens → Search UI: renders · Pages compose the main search entry and results experience.
- App screens → Law viewer: renders · Pages mount the law-viewer shell for document-centric workflows.
- Search UI → FC-RAG API: submits AI · AI-assisted searches stream to the FC-RAG endpoint.
- Search UI → Legal routes: submits search · Basic searches hit specialized legal routes.
- Law viewer → Legal routes: loads content · The viewer fetches laws, articles, annexes, history, and related records.
- Law viewer → Dialogs: opens · Viewer actions open annex, comparison, consent, favorites, and debug dialogs.
- AI chat → FC-RAG API: streams from · AI chat consumes streamed tool events and answer text.
- Legal routes → Law parsers: normalizes · Route handlers rely on canonical parsers and content normalization.
- Legal routes → External sources: fetches · Routes query external legal data providers and backend stores.
- FC-RAG API → FC-RAG engine: orchestrates · The route delegates to the FC-RAG orchestration layer.
- FC-RAG engine → Query classifier: routes by intent · Query classification determines the tool and answer path.
- FC-RAG engine → Query normalizer: expands · The engine uses unified query normalization and expansion.
- FC-RAG engine → Tool registry: invokes · The engine selects and executes legal tools through the registry.
- Tool registry → Legal routes: calls legal APIs · Tools reach law, precedent, interpretation, hierarchy, and summary endpoints.
- Tool registry → Content links: verifies citations · Tool results are checked and linked back to authoritative legal text.
- Law parsers → External sources: ingests · Parsers transform upstream XML, JSON, HTML, PDF, and HWPX sources.
- Content links → Law parsers: anchors to text · Citation and link logic resolves against parsed legal content.
- Impact graph → Analysis APIs: exposes stats · Graph analysis powers relation-graph statistics endpoints.
- Impact tracker → Analysis APIs: serves analysis · Impact workflows back the dedicated analysis endpoints and viewer panels.
- Auth & quota → External sources: checks identity · Auth and quota depend on backend identity and data services.
- Privacy store → Cache & state: scrubs · Privacy workflows remove or anonymize stored logs and cached data.
- Cache & state → External sources: persists · Server state relies on Supabase and Redis-backed storage.
