How chrisryugj/lexdiff works
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: route.ts Legal routes · router-engine.ts FC-RAG engine · law-go-kr-chain.pem External sources · index.tsx Search UI
Components 20
Browser UI
Next.js screens and interactive React components.
- App screens · Main app router pages and shared layout for home, help, privacy, terms, settings, and the law-viewer shell.
app/page.tsx - Search UI · Search bar, search-result view, and query-handling components that drive the main user flow.
components/search-result-view/index.tsx - Law viewer · Primary legal document experience combining article display, annexes, comparisons, related cases, and AI answers.
components/law-viewer.tsx - AI chat · Chat-style streaming answer surface with message, typing, and thinking states.
components/chat/ChatContainer.tsx - Dialogs · 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 · Specialized endpoints for law, article, history, annex, precedent, ordinance, search, summarize, and related lookups.
app/api/law-search/route.ts - FC-RAG API · Streaming function-calling RAG endpoint that coordinates tool use and answer generation.
app/api/fc-rag/route.ts - Analysis APIs · 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 · Intent, pattern, entity, and compatibility logic that decides how legal questions should be routed.
src/domain/search/services/QueryClassifier.ts - Query normalizer · Unified query classification, expansion, normalization, and search-type helpers.
lib/unified-query-classifier.ts - Law parsers · Core XML/JSON/markdown parsers and normalizers for statutes, annexes, revisions, and hierarchy data.
lib/law-parser.ts - Content links · Citation matching, link generation, and click-handler normalization for legal text navigation.
lib/citation-verifier.ts - FC-RAG engine · Router engine, shared engine logic, prompts, decision domains, and streaming result assembly.
lib/fc-rag/router-engine.ts - Tool registry · Domain tool adapters, tiers, cache, citations, and adapters used by the RAG engine.
lib/fc-rag/tool-registry.ts - Impact graph · Relation graph extraction, database access, and downstream impact analysis for law relationships.
lib/relation-graph/index.ts - Impact tracker · 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 · Login callback, sign-out, quota, and API-auth helpers that gate usage and BYOK access.
app/auth/callback/route.ts - Privacy store · Consent, anonymization, scrubber, and log deletion logic plus related persistence.
lib/privacy/scrubber.ts - Cache & state · Redis and in-app caches, favorites, recent searches, search-result stores, and Supabase access.
lib/rag-response-cache.ts - External sources · Gemini, Claude/Hermes, Law Ministry APIs, Supabase PostgreSQL, Upstash Redis, and OAuth-backed auth.
certs/law-go-kr-chain.pem
Connections 22
- 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.