BUILDING A PRODUCTION-READY GITHUB RAG SYSTEM
Build Chapter 3: Designing the Core Domain Models
Part 1: Foundation and Repository Understanding | For engineers learning RAG | About 14 minutes to read, 30 to follow along
In Build Chapters 2 and 2.1 we created the Python project and added shared support for configuration, logging, and exceptions. Now we define the core domain models: the objects that represent a repository, a file inside it, the decision about whether that file may enter the pipeline, and a summary of everything inspected.
These models are the data contract between repository discovery, file policies, content extraction, parsing, and the chunking stage that comes later.
What you will take away
• Three enums that limit repository sources, file types, and eligibility outcomes to valid values.
• Three Pydantic models, RepositoryReference, RepositoryFile, and RepositoryInventory, with validation built in.
• A clear reason to keep file classification and file eligibility as two separate pieces of information.
• A way to turn the models into dictionaries and JSON, and a small script that checks them.
Prerequisites: Build Chapter 2.1 completed,
Series code: Link
For technical leaders: the 60-second version • The decision. Define one validated description of a repository file, and make every pipeline stage use it, instead of each stage inventing its own dictionary or tuple. • The cost. A few small files and no visible feature, plus the discipline to extend the shared models instead of working around them. • The risk it reduces. Silent data mismatches between components, typos in metadata that go unnoticed, and files that are ingested when they should have been excluded. • Questions to ask your team. Do all our pipeline stages exchange one validated object? Is the reason a file was skipped recorded and queryable? Would a misspelled field raise an error or be ignored? |
1. What we will build
We create two files and update one:
src\github_rag\domain
├── init.py updated: exports the public components
├── enums.py new: RepositorySource, FileType, FileEligibilityStatus
└── models.py new: RepositoryReference, RepositoryFile, RepositoryInventory
tests\check_domain_models.py new: a small script that checks the models2. Why we need domain models
Repository information will pass through several stages:
repository connector -> file policy -> inventory service -> content extraction-> file-specific parser -> chunking -> embeddings -> retrieval -> citationsWithout common models, each stage could describe the same file differently. One component might return a dictionary with file and size, another might expect file_path and size_bytes, and a third might pass a tuple:
{"file": "README.md", "size": 2500}
{"file_path": "README.md", "size_bytes": 2500}
("README.md", 2500)All three hold the same information in three incompatible shapes. A domain model gives the project one shared definition, and it checks the values when the object is created.
Model | What it represents |
RepositoryReference | Identifies the repository being processed. |
RepositoryFile | Describes one discovered file and the decision made about it. |
RepositoryInventory | Summarizes all inspected files of one repository. |
3. What is a domain model, and why use enums?
A domain model represents an important concept in the application. For this project the concepts include the repository, its source, a file, the file type, file eligibility, the inventory, and later the extracted document, parsed document, chunk, retrieval result, and citation. We will not build all of them now. This chapter covers only what repository discovery and inventory generation need. The rest arrive when their stages do.
An enum defines a controlled set of valid values. Without one, a file type is just a string, and a typo passes unnoticed:
file_type = "python"
file_type = "pyhton" # a plain string accepts this misspellingWith an enum, Pydantic can reject unsupported values when it validates a model:
class FileType(str, Enum):
PYTHON = "python"
SQL = "sql"Enums also improve type checking, editor autocomplete, readability, and refactoring safety.
4. Step 1: Create the domain enums
Create src\github_rag\domain\enums.py:
"""Enumerations used by the GitHub RAG domain models."""
from enum import Enum
class RepositorySource(str, Enum):
"""Supported sources from which a repository can be accessed."""
LOCAL = "local"
GITHUB = "github"
class FileType(str, Enum):
"""Supported categories of repository files."""
PYTHON = "python"
SQL = "sql"
MARKDOWN = "markdown"
YAML = "yaml"
JSON = "json"
CONFIGURATION = "configuration"
TEXT = "text"
SHELL = "shell"
DEPENDENCY = "dependency"
UNKNOWN = "unknown"
class FileEligibilityStatus(str, Enum):
"""Possible eligibility outcomes for an inspected file."""
ELIGIBLE = "eligible"
EXCLUDED_DIRECTORY = "excluded_directory"
EXCLUDED_FILENAME = "excluded_filename"
EXCLUDED_EXTENSION = "excluded_extension"
UNSUPPORTED_EXTENSION = "unsupported_extension"
FILE_TOO_LARGE = "file_too_large"
EMPTY_FILE = "empty_file"
UNREADABLE_FILE = "unreadable_file"RepositorySource
RepositorySource says where repository data comes from. The first connector reads a local directory (RepositorySource.LOCAL), but the project goal is a GitHub-connected system, so we also define RepositorySource.GITHUB now. Downstream components can then use the same repository model whatever the source. We are not building GitHub access in this chapter. We only define a valid value for later.
Each enum inherits from both str and Enum [3], so its members behave like controlled string values: RepositorySource.LOCAL.value is "local".
FileType
FileType is the broad category assigned to a file.
Value | Typical files | Notes |
PYTHON |
| |
SQL | monthly_summary.sql |
|
MARKDOWN |
| |
YAML | file_policy.yaml, config.yml |
|
JSON | settings.json |
|
CONFIGURATION | .ini, .cfg, .toml | Config formats not covered by YAML or JSON. |
TEXT | notes.txt |
|
SHELL | deploy.sh, setup.bat, build.cmd |
|
DEPENDENCY | requirements.txt, pyproject.toml, package.json | Files whose main job is declaring dependencies. The classifier can use the filename, so requirements.txt is a dependency file and not just text. |
UNKNOWN | Anything unrecognized | A safe value for files the classifier does not know. It does not make the file eligible. |
FileEligibilityStatus
FileEligibilityStatus records the outcome of applying the file policy.
Value | Meaning | Examples |
ELIGIBLE | Passed every check and may proceed to content extraction. |
|
EXCLUDED_DIRECTORY | Lives in an excluded directory. | .git, .venv, node_modules, pycache |
EXCLUDED_FILENAME | The filename is explicitly excluded. | .env, credentials.json |
EXCLUDED_EXTENSION | The extension is explicitly blocked. | .exe, .dll, .zip |
UNSUPPORTED_EXTENSION | Not blocked, but the pipeline does not support it yet. |
|
FILE_TOO_LARGE | Exceeds the configured maximum size. |
|
EMPTY_FILE | Has no content to extract or index. |
|
UNREADABLE_FILE | The application could not read the file safely. |
|
The actual excluded names and extensions will live in a YAML policy file, not hardcoded in the policy logic.
Why file type and eligibility are separate
File type answers: what kind of file is this? Eligibility answers: should this file enter the ingestion pipeline? Compare two files:
File | File type | Eligibility |
src\service.py | PYTHON | ELIGIBLE |
.venv\Lib\site-packages\example.py | PYTHON | EXCLUDED_DIRECTORY |
A file does not stop being Python because it sits in an excluded directory. Keeping the two facts apart gives more accurate metadata, and later lets us answer questions such as how many Python files were excluded, and why.
5. Test the enums
Run this from the project root:
uv run python -c "from github_rag.domain.enums import RepositorySource, FileType, FileEligibilityStatus; print(RepositorySource.LOCAL.value); print(FileType.PYTHON.value); print(FileEligibilityStatus.ELIGIBLE.value)"
Expected output:
local
python
eligibleThen check that members compare with their string values:
uv run python -c "from github_rag.domain.enums import FileType; print(FileType.PYTHON == 'python'); print(FileType.SQL == 'python')"
Expected output:
True
False
Because the enum inherits from str, members compare equal to their string values. Even so, application code should compare against the enum member, as in if file_type == FileType.PYTHON:. It is clearer, and a typo then fails loudly instead of quietly evaluating to False.
6. Step 2: Create the repository models
Create src\github_rag\domain\models.py:
"""Core domain models for repository discovery and inventory."""
from pathlib import Path
from pydantic import BaseModel
from pydantic import ConfigDict
from pydantic import Field
from github_rag.domain.enums import FileEligibilityStatus
from github_rag.domain.enums import FileType
from github_rag.domain.enums import RepositorySource
class RepositoryReference(BaseModel):
"""Identifies a repository being processed by the application."""
model_config = ConfigDict(
frozen=True,
extra="forbid",
)
name: str = Field(
min_length=1,
)
source: RepositorySource
root_path: Path
branch: str | None = None
commit_sha: str | None = None
github_url: str | None = None
class RepositoryFile(BaseModel):
"""Describes one file discovered inside a repository."""
model_config = ConfigDict(
extra="forbid",
)
repository: RepositoryReference
relative_path: Path
absolute_path: Path
filename: str = Field(
min_length=1,
)
extension: str
file_type: FileType = FileType.UNKNOWN
size_bytes: int = Field(
ge=0,
)
eligibility_status: FileEligibilityStatus
eligibility_reason: str | None = None
content_hash: str | None = None
class RepositoryInventory(BaseModel):
"""Contains the result of inspecting a repository."""
model_config = ConfigDict(
extra="forbid",
)
repository: RepositoryReference
files: list[RepositoryFile] = Field(
default_factory=list,
)
total_files: int = Field(
default=0,
ge=0,
)
eligible_files: int = Field(
default=0,
ge=0,
)
excluded_files: int = Field(
default=0,
ge=0,
)7. Understanding RepositoryReference
RepositoryReference identifies the repository currently being processed. It does not hold the files. It holds the metadata needed to refer to the repository consistently.
Field | Purpose |
name | The repository name. min_length=1 means an empty name raises a validation error. |
source | A RepositorySource. Pydantic also converts the string "local" into RepositorySource.LOCAL. |
root_path | The root of the local repository, for example D:\projects\example-repository. Path gives platform-aware path handling. |
branch | Optional, because local processing may begin before branch information is collected. A remote reference could hold "main". |
commit_sha | Optional. Identifies the exact repository version, which later supports reproducibility, incremental synchronization, citations, and detecting updates. |
github_url | Optional. The repository URL, used later to link citations back to the original source. |
What model_config does
The model_config setting changes how Pydantic treats the whole model [2].
Option | Effect |
frozen=True | Fields cannot be changed after creation. The application should not silently switch branch from "main" to "development" halfway through processing. If a different reference is needed, create a new one. |
extra="forbid" | Unknown fields raise an error instead of being ignored. A misspelled field such as brnach="main" is reported, not silently dropped. |
Test the model and its validation. First a valid reference:
uv run python -c "from github_rag.domain.models import RepositoryReference; repository = RepositoryReference(name='example-repository', source='local', root_path='.', branch='main'); print(repository)"
Expected output (the path type differs by system, such as WindowsPath or PosixPath):
name='example-repository' source=<RepositorySource.LOCAL: 'local'> root_path=WindowsPath('.') branch='main' commit_sha=None github_url=NoneNow an empty name, which must fail:
uv run python -c "from github_rag.domain.models import RepositoryReference; RepositoryReference(name='', source='local', root_path='.')"
Expected: a ValidationError ending in
String should have at least 1 characterAnd a misspelled field, which must also fail:
uv run python -c "from github_rag.domain.models import RepositoryReference; RepositoryReference(name='example', source='local', root_path='.', brnach='main')"
Expected: a ValidationError ending in
Extra inputs are not permittedBoth errors are expected. They confirm the validation works.
8. Understanding RepositoryFile
RepositoryFile represents one discovered file. It holds filesystem metadata and the result of inspecting the file.
Field | Purpose |
repository | The RepositoryReference the file belongs to. Every file stays tied to its source repository, even when several repositories are indexed later. |
relative_path | The path from the repository root, for example sql\analytics\monthly_summary.sql. Useful for showing structure, filtering, building GitHub links, producing citations, and moving a repository between machines. |
absolute_path | The physical location on this machine, used by the local connector and extraction service. It is local processing metadata and should not normally appear in a public citation. |
filename | The final name only, such as monthly_summary.sql. It cannot be empty. |
extension | The normalized extension: .py, .sql, .md, .yaml. A later classifier will lowercase it. A file such as .env has an empty extension. |
file_type | Defaults to FileType.UNKNOWN. The classifier will later replace it with a recognized category. |
size_bytes | Cannot be negative (ge=0). The policy compares it with the configured maximum file size. |
eligibility_status | The policy decision, such as ELIGIBLE or FILE_TOO_LARGE. |
eligibility_reason | Optional readable explanation, for example "Directory '.venv' is excluded by policy." The enum is for machines, the reason is for people. |
content_hash | Optional. Will later hold a SHA-256 value. It stays empty for excluded files that are never read, unreadable files, and anything not yet hashed. |
Test a valid file:
uv run python -c "from github_rag.domain.models import RepositoryReference, RepositoryFile; repository = RepositoryReference(name='example-repository', source='local', root_path='.'); file = RepositoryFile(repository=repository, relative_path='README.md', absolute_path='README.md', filename='README.md', extension='.md', file_type='markdown', size_bytes=2500, eligibility_status='eligible', eligibility_reason='File passed all policy checks'); print(file.relative_path); print(file.file_type.value); print(file.eligibility_status.value)"
Expected output:
README.md
markdown
eligibleNow a negative size, which must fail:
uv run python -c "from github_rag.domain.models import RepositoryReference, RepositoryFile; repository = RepositoryReference(name='test', source='local', root_path='.'); RepositoryFile(repository=repository, relative_path='README.md', absolute_path='README.md', filename='README.md', extension='.md', size_bytes=-1, eligibility_status='eligible')"
Expected: a ValidationError ending in
Input should be greater than or equal to 09. Understanding RepositoryInventory
RepositoryInventory is the complete result of inspecting a repository: the repository reference, the file records, and three counts.
Field | Purpose |
| |
files | The discovered RepositoryFile records. We use default_factory=list, not = [], so every inventory gets its own new list instead of sharing one mutable list. |
| |
total_files | The number of files inspected. |
| |
eligible_files | The number of files allowed to continue into content extraction. |
| |
excluded_files | The number of files that did not pass the file policy. This includes every status other than ELIGIBLE: excluded, unsupported, too large, empty, and unreadable files. |
| |
| A limit of this design. The three counts are ordinary fields, so the model does not check that they match files. Passing total_files=99 with an empty list is accepted. For now the inventory service will calculate the counts. If they ever drift out of step in practice, a validator or computed fields can enforce the rule. | ||
Test an empty inventory, which is valid before scanning begins:
uv run python -c "from github_rag.domain.models import RepositoryReference, RepositoryInventory; repository = RepositoryReference(name='example-repository', source='local', root_path='.'); inventory = RepositoryInventory(repository=repository); print(inventory.total_files); print(inventory.eligible_files); print(inventory.excluded_files); print(inventory.files)"
Expected output:
0
0
0
[]10. Step 3: Export the domain components
Update src\github_rag\domain\__init__.py:
"""Domain models and enums for the GitHub RAG application."""
from github_rag.domain.enums import FileEligibilityStatus
from github_rag.domain.enums import FileType
from github_rag.domain.enums import RepositorySource
from github_rag.domain.models import RepositoryFile
from github_rag.domain.models import RepositoryInventory
from github_rag.domain.models import RepositoryReference
all = [
"FileEligibilityStatus",
"FileType",
"RepositoryFile",
"RepositoryInventory",
"RepositoryReference",
"RepositorySource",
]Without these exports, other code imports from github_rag.domain.enums and github_rag.domain.models. With them, it imports from one place: from github_rag.domain import FileType, RepositoryFile. The code stays split across enums.py and models.py, while the rest of the project sees one consistent public interface. Test it:
uv run python -c "from github_rag.domain import FileType, RepositoryReference, RepositoryInventory; repository = RepositoryReference(name='example', source='local', root_path='.'); inventory = RepositoryInventory(repository=repository); print(FileType.PYTHON.value); print(inventory.repository.name)"
Expected output:
python
example11. Step 4: Serialize the models to JSON
Pydantic converts models to dictionaries with model_dump() and straight to JSON strings with model_dump_json(). Nested models are converted too [1]. Try it on an empty inventory:
uv run python -c "from github_rag.domain import RepositoryReference, RepositoryInventory; repository = RepositoryReference(name='example-repository', source='local', root_path='.', branch='main'); inventory = RepositoryInventory(repository=repository); print(inventory.model_dump_json(indent=2))"
Expected output:
{
"repository": {
"name": "example-repository",
"source": "local",
"root_path": ".",
"branch": "main",
"commit_sha": null,
"github_url": null
},
"files": [],
"total_files": 0,
"eligible_files": 0,
"excluded_files": 0
}Enum members become their string values, and the Path becomes a string. A later InventoryWriter will use this to save a repository inventory as formatted JSON.
12. Step 5: Run a complete domain test
The long one-line commands above are fine for single checks, but a full example is easier to read as a file. Create tests\check_domain_models.py. It builds a repository reference, an eligible Markdown file, an excluded .env file, and an inventory that holds both:
"""Manual check of the domain models. Run it from the project root."""
from github_rag.domain import RepositoryFile
from github_rag.domain import RepositoryInventory
from github_rag.domain import RepositoryReference
repository = RepositoryReference(
name="example-repository",
source="local",
root_path=".",
branch="main",
)
readme = RepositoryFile(
repository=repository,
relative_path="README.md",
absolute_path="README.md",
filename="README.md",
extension=".md",
file_type="markdown",
size_bytes=1200,
eligibility_status="eligible",
)
environment = RepositoryFile(
repository=repository,
relative_path=".env",
absolute_path=".env",
filename=".env",
extension="",
file_type="configuration",
size_bytes=200,
eligibility_status="excluded_filename",
eligibility_reason="Sensitive filename excluded by policy",
)
inventory = RepositoryInventory(
repository=repository,
files=[readme, environment],
total_files=2,
eligible_files=1,
excluded_files=1,
)
print(inventory.total_files, inventory.eligible_files, inventory.excluded_files)
print(inventory.files[1].model_dump_json(indent=2))Run it:
uv run python tests\check_domain_models.py
Expected output:
2 1 1
{
"repository": {
"name": "example-repository",
"source": "local",
"root_path": ".",
"branch": "main",
"commit_sha": null,
"github_url": null
},
"relative_path": ".env",
"absolute_path": ".env",
"filename": ".env",
"extension": "",
"file_type": "configuration",
"size_bytes": 200,
"eligibility_status": "excluded_filename",
"eligibility_reason": "Sensitive filename excluded by policy",
"content_hash": null
}Notice that the file record carries its whole repository block. That is the price of every file knowing which repository it came from. For a very large repository the repeated block adds up, which is a trade-off to keep in mind when we start writing inventories to disk.
13. Step 6: Run and verify
Run these checks from the project root. Use them as the checkpoint for this chapter.
uv run python tests\check_domain_models.py
uv run python -m compileall -f src
tree src\github_rag /fExpected:
• The first command prints the counts line and the JSON shown in section 12.
• The syntax check lists src\github_rag\domain\enums.py and models.py as compiled, with no SyntaxError. The -f option forces a recompile. Without it, Python skips files it has already compiled and prints nothing for them.
• The tree should match this:

On macOS or Linux, use forward slashes in the paths (tests/check_domain_models.py) and tree src/github_rag for the listing. The uv run python -c commands are the same on every system.
14. Common issues
Symptom | Likely cause | Fix |
Input should be 'python', 'sql', ... (enum error) | A value that is not in the enum, such as file_type="document". | Use a supported value, "markdown" or FileType.MARKDOWN, or add the new type to FileType on purpose. |
Extra inputs are not permitted | A misspelled or unknown field, such as fileame="README.md". This is intentional. | Correct the field name. Ignoring metadata mistakes would cause quiet problems later in the pipeline. |
Instance is frozen | Assigning to a RepositoryReference field, such as repository.branch = "development". | Create a copy: repository.model_copy(update={"branch": "development"}). Note that model_copy does not validate the values you pass. |
Path prints differently | WindowsPath on Windows, PosixPath on Linux and macOS. | Expected. In JSON the path is always a string. |
total_files does not match files | The counts are plain fields and are not checked. | Calculate them from the file list when you build the inventory. |
ModuleNotFoundError: No module named 'github_rag' | Not run from the project root, or run with plain python instead of uv run. | Run from the folder that holds pyproject.toml, with uv run. |
Conclusion and next chapter
Domain models give the application a shared language. A connector, file policy, inventory service, extraction service, and parser should not each invent their own idea of a repository file. They should exchange validated objects with clearly defined fields. In this chapter we created three enums and three models, separated classification from eligibility, made repository references immutable, rejected unexpected fields, and serialized nested models to JSON.
Next, Build Chapter 4: Classifying Files in a GitHub Repository. It covers:
• Why classification happens before parsing
• Creating FileClassifier and normalizing extensions
• Recognizing Python, SQL, Markdown, YAML, and JSON files
• Recognizing configuration and dependency files
• Returning FileType.UNKNOWN safely
• Testing classification from the command line
About SNPaul Infotech We help engineering and data teams design, evaluate, and secure retrieval and GenAI systems like this one. If you are weighing RAG for your own repositories or documents, get in touch: www.snpaulinfotech.com |
References
[1] Pydantic. Serialization (model_dump and model_dump_json)
[2] Pydantic. Configuration (frozen and extra)
[3] Python. enum module


Comments