코드 프로퍼티 그래프와 .NET 9로 소프트웨어 아키텍처의 AI 환각 해결

발행: (2026년 5월 23일 PM 07:31 GMT+9)
8 분 소요
원문: Dev.to

출처: Dev.to

생성형 인공지능 도구의 부상은 소프트웨어 엔지니어링 생산성을 급격히 바꾸어 놓았습니다. 오늘날 코드 어시스턴트는 전체 클래스를 생성하고, 복잡한 알고리즘을 리팩터링하며, 설계 패턴을 몇 초 만에 제안할 수 있습니다.
하지만 고복잡도 기업 환경에서 일하는 소프트웨어 엔지니어로서 저는 이 도구들의 가장 큰 병목 현상, 즉 맥락적 환각아키텍처 경계 파괴를 반복해서 겪었습니다.

파일을 전혀 다른 디렉터리에 만들라고 제안하는 AI를 본 적이 없나요? 혹은 더 심각하게, 도메인 레이어가 인프라스트럭처 컴포넌트에 직접 의존하도록 만들어 Clean Architecture 원칙을 명백히 위반하는 경우는요?

이 문제를 결정론적으로 해결하고자 저는 Code Property Graph (CPG) 를 만들기로 했습니다. CPG는 코드의 정적 구조(레이어, 네임스페이스, 클래스, 의존성)를 모두 매핑하고, AI 환각을 차단하는 “경계 경비원” 역할을 합니다.

🏗️ 개념: 코드를 지식으로 매핑하기

하이브리드 엔진: 그래프 영혼을 가진 SQL (1‑Sql)

순수 관계형 데이터베이스에 의존성을 매핑하면 복잡한 연관 테이블이 생기기 쉽습니다. 반면, 이 분석만을 위해 Neo4j 같은 네이티브 그래프 DB를 도입하도록 팀에 강요하면 운영상의 마찰이 발생합니다.

제 해결책은 탐색에 최적화된 관계형 DB를 만드는 것이었습니다. 중앙 테이블 CodeElement(그래프의 노드)에는 클래스, 인터페이스, 레코드가 저장되고, ElementDependency 같은 연관 테이블이 엣지 역할을 합니다.

이렇게 하면 AI가 코드를 생성하기 전에 시스템이 결정론적 검증을 수행할 수 있습니다.

-- 클래식한 위반 사례 식별: Domain이 Infrastructure에 의존
SELECT 
    SourceElem.Name AS ArquivoIncorreto,
    TargetElem.Name AS DependenciaProibida
FROM ElementDependency Dep
INNER JOIN CodeElement SourceElem ON Dep.SourceElementId = SourceElem.Id
INNER JOIN Layer SourceLayer ON SourceElem.LayerId = SourceLayer.Id
INNER JOIN CodeElement TargetElem ON Dep.TargetElementId = TargetElem.Id
INNER JOIN Layer TargetLayer ON TargetElem.LayerId = TargetLayer.Id
WHERE SourceLayer.Name = 'Domain' AND TargetLayer.Name = 'Infrastructure';

쿼리 결과가 하나라도 반환되면 AI는 해당 제안을 진행할 수 없도록 차단됩니다. 간단하면서도 확실합니다.

두뇌: .NET 9.0 백엔드 (2‑BackEnd)

이 로직을 오케스트레이션하기 위해 .NET 9.0 기반의 견고한 API를 구축했습니다. SOLID 원칙을 철저히 따르고, MediatR을 활용해 CQRS 패턴을 구현했습니다.

  • Commands: Roslyn 같은 정적 분석기에서 추출한 방대한 메타데이터를 ingest 처리
  • Queries: 실시간 아키텍처 검증 실행

모든 작업은 Repository Pattern 으로 추상화돼, 검증 비즈니스 규칙이 데이터 저장 방식과 분리됩니다.

비전: React 기반 인터랙티브 Knowledge Graph (3‑FrontEnd)

원시 데이터만으로는 아키텍처 직관을 얻기 어렵습니다. React로 만든 프론트엔드 모듈은 .NET 9 API를 호출해 전체 아키텍처를 인터랙티브 Knowledge Graph 로 시각화합니다(복잡한 마인드맵과 유사).

개발자는 특정 모듈을 클릭해 즉시 의존성 트리를 확인할 수 있습니다. 더 나아가 새로운 기능 의도를 “그려” 보면, 프론트엔드가 실시간으로 이 구조가 시스템 설계를 위반하는지 검증해 줍니다—코드 한 줄도 작성하기 전에 말이죠.

🚀 결론
코드를 자유롭게 탐색하고, PR을 제출하거나 아이디어를 논의하고 싶다면 프로젝트 저장소를 방문해 주세요!


English Version 🇬🇧 / 🇺🇸

Solving AI Hallucination in Software Architecture with Code Property Graphs and .NET 9

However, as a Software Engineer working in highly complex enterprise environments, I repeatedly hit the biggest bottleneck of these tools: contextual hallucination and the breaking of architectural boundaries.

Who hasn’t seen an AI suggest creating a file in completely the wrong directory? Or worse, make the Domain layer directly depend on an Infrastructure component, blatantly violating the principles of Clean Architecture?

To solve this problem deterministically, I decided to build the Code Property Graph (CPG): an ecosystem that maps the entire static structure of the code (layers, namespaces, classes, and dependencies) and acts as a “border guard” against AI hallucinations.

🏗️ The Concept: Mapping Code as Knowledge

The Hybrid Engine: SQL with a Graph Soul (1‑Sql)

Mapping dependencies in purely relational databases usually generates complex associative tables. On the other hand, forcing a team to adopt a native graph database (like Neo4j) just for this analysis can cause operational friction.

My solution was to create a relational database optimized for traversals. A central CodeElement table (the graph node) stores Classes, Interfaces, and Records. Associative tables like ElementDependency act as the edges.

With this setup, before the AI generates code, the system can run a deterministic validation:

-- Identifying a classic violation: Domain depending on Infrastructure
SELECT 
    SourceElem.Name AS IncorrectFile,
    TargetElem.Name AS ForbiddenDependency
FROM ElementDependency Dep
INNER JOIN CodeElement SourceElem ON Dep.SourceElementId = SourceElem.Id
INNER JOIN Layer SourceLayer ON SourceElem.LayerId = SourceLayer.Id
INNER JOIN CodeElement TargetElem ON Dep.TargetElementId = TargetElem.Id
INNER JOIN Layer TargetLayer ON TargetElem.LayerId = TargetLayer.Id
WHERE SourceLayer.Name = 'Domain' AND TargetLayer.Name = 'Infrastructure';

If the query returns any data, the AI is blocked from proceeding with the suggestion. Simple and bulletproof.

The Brain: .NET 9.0 Backend (2‑BackEnd)

To orchestrate this logic, I built a robust API in .NET 9.0. Strictly following SOLID principles, I implemented the CQRS pattern using MediatR.

  • Commands: Handle the heavy ingestion of code metadata extracted via static analyzers (like Roslyn).
  • Queries: Execute real-time architectural validations.

Everything is abstracted by the Repository Pattern, ensuring that the architectural validation business rules remain isolated from how the data is persisted.

The Vision: Interactive Knowledge Graph with React (3‑FrontEnd)

Raw data doesn’t provide architectural intuition. The front‑end module, built in React, consumes the .NET 9 API and renders the entire architecture as an interactive Knowledge Graph (similar to a complex mind map).

Developers can click on a specific module and immediately see its dependency tree. More importantly, they can “draw” the intent for a new feature, and the front‑end will validate in real‑time if this new structure violates the system’s design—before a single line of code is written.

🚀 Conclusion
Feel free to explore the code, submit PRs, or discuss ideas over at the project repository!

0 조회
Back to Blog

관련 글

더 보기 »

내 스킬

프로젝트를 위한 AI 지시문을 만들고, 설치하고, 관리하세요 — 코딩이 필요 없습니다. CREATE 이름을 정하고, 카테고리를 선택하고, 원하는 것을 설명하세요 — 마법사가 자동으로 구성합니다.