top of page

BUILDING A PRODUCTION-READY GITHUB RAG SYSTEM

5 days ago
14 min read

Build Chapter 5: Building Configurable File Security Policies


Part 1: Foundation and Repository Understanding   |   For engineers learning RAG   |   About 16 minutes to read, 35 to follow along


In Build Chapter 4 we created FileClassifier, which says what kind of file we found. That does not tell us whether the file is safe and useful to process. A repository holds secrets, binaries, generated folders, and files too large to index.


In this chapter we build a configurable file policy: a layer that evaluates every repository file before its content can enter the RAG ingestion pipeline, and records the reason whenever a file is rejected.


What you will take away

•   A YAML file that holds the policy rules, so they can change without touching Python code.

•   FilePolicyConfig, which validates those rules, and a loader that parses YAML safely.

•   FileEligibilityResult and FilePolicy, which decide whether a file is eligible, and why.

•   A check script that covers every outcome, and a clear list of what this policy does not catch.

Prerequisites: Build Chapter 4 completed, or the code from tag chapter-04. PyYAML was installed in Build Chapter 2. Series code: [link].

For technical leaders: the 60-second version

•   The decision. Put a gate between repository discovery and content extraction, driven by a reviewed configuration file, and record why each rejected file was rejected.

•   The cost. One YAML file to own and review, and a small component to maintain. The rules need updating as new repositories bring new file types.

•   The risk it reduces. Secrets, binaries, and generated noise reaching the index, and unexplained gaps when someone asks why a file was not searchable.

•   Questions to ask your team. Who approves changes to the exclusion list? Is the list an allowlist (only known types) or a blocklist? Can we prove why a given file was skipped?


1. What we will build


We create three files and update one:

config\file_policy.yaml                 new: the policy rules

src\github_rag\inventory
├── init.py       updated: exports the policy components
└── file_policy.py    new: FilePolicyConfig, FileEligibilityResult,
                           load_file_policy_config, FilePolicy

tests\check_file_policy.py              new: a script that checks every outcome

2. Why we need a file policy


A repository can contain files that should never enter the RAG pipeline:

.git   .venv   node_modules   pycache   .env   credentials.json
large generated files   compiled binaries   images   archives
empty files   unreadable files

Sending every discovered file to content extraction would cause several problems:

•   Sensitive files might be processed and indexed.

•   Generated and dependency folders would bury the useful project code in noise.

•   Binary content could cause decoding failures.

•   Very large files would raise memory and processing costs.

•   Empty files would add nothing to retrieval.


The policy creates a controlled boundary:

Discovered repository file
            |
            v
        FilePolicy
            |
      +-----+-----+
      v           v
  Eligible     Excluded
      |           |
      v           v
 Extraction   Reason recorded

Only eligible files proceed to content extraction.


3. Classification and eligibility stay separate


The classifier answers: what kind of file is this? The policy answers: should this file be processed? Keeping them apart, as in Build Chapter 3, gives more accurate metadata:

File

Classifier says

Policy says

.venv\Lib\example.py

PYTHON

EXCLUDED_DIRECTORY

assets\logo.png

UNKNOWN

EXCLUDED_EXTENSION

diagram.drawio

UNKNOWN

UNSUPPORTED_EXTENSION

FileClassifier describes the file. FilePolicy decides whether it can enter ingestion.


4. Why the rules live in YAML


We could hardcode the exclusions inside a Python class:

excluded_directories = {".git", ".venv", "node_modules"}

But policy values are configuration, not behavior. They change when a repository uses different generated folders, when the team supports another extension, when security flags another sensitive filename, or when the size limit needs tuning. In YAML, those changes are a reviewed one-line edit, not a code release.

Component

Responsibility

file_policy.yaml

Stores the configurable policy values.

FilePolicyConfig

Validates the configuration.

FilePolicy

Applies the configuration to a file.


5. Step 1: Create the YAML policy


Create config\file_policy.yaml:

excluded_directories:
  - .git
  - .venv
  - node_modules
  - pycache
  - .pytest_cache
  - dist
  - build

excluded_filenames:
  - .env
  - .env.local
  - .env.production
  - credentials.json
  - secrets.json
  - id_rsa
  - id_ed25519
  - poetry.lock
  - uv.lock
  - package-lock.json

excluded_extensions:
  - .exe
  - .dll
  - .so
  - .dylib
  - .zip
  - .tar
  - .gz
  - .7z
  - .png
  - .jpg
  - .jpeg
  - .gif
  - .pdf
  - .pyc
  - .pem
  - .key
  - .p12
  - .pfx

supported_extensions:
  - .py
  - .sql
  - .md
  - .markdown
  - .yaml
  - .yml
  - .json
  - .toml
  - .ini
  - .cfg
  - .conf
  - .txt
  - .sh
  - .bash
  - .bat
  - .cmd
  - .ps1
 
supported_filenames:
  - Dockerfile
  - Makefile
  - requirements.txt
  - requirements-dev.txt
  - pyproject.toml
  - package.json

maximum_file_size_bytes: 1000000


Understanding the configuration

Key

What it does

excluded_directories

A file is excluded if any folder in its path has one of these names, at any depth. For example, src\.venv\Lib\example.py contains the folder .venv.

excluded_filenames

Excluded wherever they appear. This is an early safeguard against common secret-bearing files, such as .env, credentials.json, and private SSH keys. It does not replace secret scanning.

excluded_extensions

Explicitly blocked: executables, compiled files, archives, images, and key or certificate formats (.pem, .key, .p12, .pfx).

supported_extensions

The only extensions allowed into the text-based pipeline. Anything not listed here, and not blocked above, is reported as unsupported. This makes the policy an allowlist, which fails safe: a new, unknown file type stays out until someone adds it deliberately.

supported_filenames

Files that matter but have no ordinary supported extension, such as Dockerfile and Makefile.

maximum_file_size_bytes

Files larger than this are excluded. 1,000,000 bytes is one decimal megabyte. This is a project choice, not a universal RAG limit, and can be tuned.


Why lock files are excluded. In Build Chapter 4 the classifier labelled uv.lock, poetry.lock, and package-lock.json as dependency files. Classification does not mean indexing. Lock files are generated, very large, and almost never help answer a question, so this policy excludes them by filename. Dependency declarations that people write, such as pyproject.toml, package.json, and requirements.txt, stay supported. 

6. Step 2: Create the policy models and loader


Create src\github_rag\inventory\file_policy.py:

"""Configurable eligibility policy for repository files."""
from pathlib import Path
from typing import Any
import yaml
from pydantic import BaseModel
from pydantic import ConfigDict
from pydantic import Field
from github_rag.core import ConfigurationError
from github_rag.domain import FileEligibilityStatus

class FilePolicyConfig(BaseModel):
    """Validated configuration used by the repository file policy."""

    model_config = ConfigDict(
        extra="forbid",
    )
    excluded_directories: set[str] = Field(
        default_factory=set,
    )

    excluded_filenames: set[str] = Field(
        default_factory=set,
    )

    excluded_extensions: set[str] = Field(
        default_factory=set,
    )

    supported_extensions: set[str] = Field(
        default_factory=set,
    )

    supported_filenames: set[str] = Field(
        default_factory=set,
    )
    maximum_file_size_bytes: int = Field(
        default=1_000_000,
        gt=0,
    )

class FileEligibilityResult(BaseModel):

    """Represents the outcome of evaluating one repository file."""
    model_config = ConfigDict(
        extra="forbid",
        frozen=True,
    )
    status: FileEligibilityStatus
    reason: str

    @property
    def is_eligible(self) -> bool:
        """Return whether the file passed all policy checks."""
        return self.status == FileEligibilityStatus.ELIGIBLE

def load_file_policy_config(config_path: str | Path,) -> FilePolicyConfig:

    """Load and validate file-policy configuration from YAML."""

    path = Path(config_path)

    if not path.exists():
        raise ConfigurationError(
            f"File-policy configuration does not exist: {path}"
        ) 

    if not path.is_file():
        raise ConfigurationError(
            f"File-policy configuration is not a file: {path}"
        )
 
    try:
        raw_content = path.read_text(
            encoding="utf-8",
        )
        raw_config: Any = yaml.safe_load(
            raw_content,
        )
    except OSError as error:
        raise ConfigurationError(
            f"Unable to read file-policy configuration: {path}"
        ) from error

    except yaml.YAMLError as error:
        raise ConfigurationError(
            f"Invalid YAML in file-policy configuration: {path}"
        ) from error

    if raw_config is None:
        raw_config = {}

    if not isinstance(raw_config, dict):
        raise ConfigurationError(
           "File-policy configuration must contain a YAML mapping."
        )
    try:
        return FilePolicyConfig.model_validate(
            raw_config,
        )
    except ValueError as error:
        raise ConfigurationError(
            f"Invalid file-policy configuration: {path}"
        ) from error


7. Understanding FilePolicyConfig


FilePolicyConfig is a Pydantic model that validates the data loaded from YAML [1]. After validation, the application receives a typed configuration object, not a loose dictionary. For example, config.maximum_file_size_bytes is guaranteed to be a positive integer if the model was created.


Why sets, not lists


The fields are set[str] because policy evaluation constantly asks "is this value in the collection?", duplicates are pointless, and order does not matter. The YAML still uses readable lists, and Pydantic converts them to sets when it builds the model.


Rejecting unexpected fields


extra="forbid" catches misspelled keys. If the YAML says excluded_directores, the policy would otherwise silently ignore it and apply no directory exclusions at all. With forbid, loading fails and the mistake is visible. Silent security gaps are worse than loud errors.


A positive size limit


gt=0 means maximum_file_size_bytes: -1 fails validation, while 1000000 passes. If the key is missing, the default is 1,000,000.


8. Understanding FileEligibilityResult


FileEligibilityResult holds the outcome of applying the policy to one file. It has two stored fields: status is machine-readable, and reason is a human-readable explanation, for example Filename '.env' is excluded by policy.


The is_eligible property


The @property decorator lets code read result.is_eligible like an attribute, with no parentheses. It is True only when the status is FileEligibilityStatus.ELIGIBLE, which keeps later code readable: if result.is_eligible:.

Why the result is frozen

frozen=True means a result cannot be edited after creation. A completed evaluation should not be changed from EXCLUDED_FILENAME to ELIGIBLE by accident. To re-evaluate a file, the policy creates a new result.


9. Understanding the YAML loader


load_file_policy_config() checks the path, reads the file as UTF-8, parses the YAML, and validates the result with FilePolicyConfig. Every failure becomes a ConfigurationError, the exception from Build Chapter 2.1, so callers handle one error type:

What went wrong

Message

The path does not exist

File-policy configuration does not exist: <path>

The path is a folder

File-policy configuration is not a file: <path>

The file cannot be read

Unable to read file-policy configuration: <path>

The YAML is malformed

Invalid YAML in file-policy configuration: <path>

The YAML is a list, not a mapping

File-policy configuration must contain a YAML mapping.

A key is misspelled or a value is invalid

Invalid file-policy configuration: <path>

The original error is attached with raise ... from error, so a traceback still shows the detail, such as which key Pydantic rejected. An empty YAML file is treated as an empty mapping, which produces a policy with no rules.


Why yaml.safe_load()


PyYAML's documentation warns that yaml.load() should not be used with untrusted input because it can construct arbitrary Python objects, and recommends yaml.safe_load() for ordinary data [2]. Configuration still needs validation, and the two steps do different jobs: yaml.safe_load() restricts YAML to safe data types, and FilePolicyConfig checks that the structure and values are the ones we expect.


10. Step 3: Add FilePolicy


Add this class to the end of src\github_rag\inventory\file_policy.py, below load_file_policy_config():

class FilePolicy:

    """Evaluates whether repository files are eligible for ingestion."""

    def init(self,config: FilePolicyConfig,) -> None:
        """Initialize the policy with validated configuration."""

        self._config = config
        self._excluded_directories = {
            value.lower()
            for value in config.excluded_directories
        }
        self._excluded_filenames = {
            value.lower()
            for value in config.excluded_filenames
        }
        self._excluded_extensions = {
            self._normalize_extension(value)
            for value in config.excluded_extensions
        }
        self._supported_extensions = {
            self._normalize_extension(value)
            for value in config.supported_extensions
        }
        self._supported_filenames = {
            value.lower()
            for value in config.supported_filenames
        }

    @classmethod
    def from_yaml(cls,config_path: str | Path,) -> "FilePolicy":
        """Create a file policy from a YAML configuration file."""

        config = load_file_policy_config(
            config_path,
        )
        return cls(
            config=config,
        )

    def evaluate(self,file_path: str | Path,) -> FileEligibilityResult:
        """Evaluate whether a repository file is eligible."""

        path = Path(file_path) 
        directory_result = self._check_directories(
            path,
        )

        if directory_result is not None:
            return directory_result

        filename_result = self._check_filename(
            path,
        )

        if filename_result is not None:
            return filename_result

        extension_result = self._check_extension(
            path,
        )

        if extension_result is not None:
            return extension_result

        file_state_result = self._check_file_state(
            path,
        )

        if file_state_result is not None:
            return file_state_result

        return FileEligibilityResult(
            status=FileEligibilityStatus.ELIGIBLE,
            reason="File passed all policy checks.",
        )

    def checkdirectories(
        self,path: Path,) -> FileEligibilityResult | None:
        """Return an exclusion when the path contains a blocked directory."""
        normalized_parts = {
            part.lower()
            for part in path.parts[:-1]
        }

        matching_directories = (
            normalized_parts
            & self._excluded_directories
        )

        if not matching_directories:
            return None
 
        excluded_directory = sorted(
            matching_directories,
        )[0]

        return FileEligibilityResult(
            status=FileEligibilityStatus.EXCLUDED_DIRECTORY,
            reason=(
                f"Directory '{excluded_directory}' "
                "is excluded by policy."
            ),
        )

    def checkfilename(self,path: Path,) -> FileEligibilityResult | 			 None:

        """Check whether a filename is explicitly excluded."""
        normalized_filename = path.name.lower()

        if normalized_filename not in self._excluded_filenames:
            return None

        return FileEligibilityResult(
            status=FileEligibilityStatus.EXCLUDED_FILENAME,
            reason=(
                f"Filename '{path.name}' "
                "is excluded by policy."
            ),
        )


    def checkextension(self,path: Path,) -> FileEligibilityResult | None:

        """Check whether the filename or extension is supported."""
        normalized_filename = path.name.lower()
 
        if normalized_filename in self._supported_filenames:
            return None

        normalized_extension = path.suffix.lower() 

        if normalized_extension in self._excluded_extensions:
            return FileEligibilityResult(
                status=FileEligibilityStatus.EXCLUDED_EXTENSION,
                reason=(
                    f"Extension '{normalized_extension}' "
                    "is excluded by policy."
                ),
            )

        if normalized_extension not in self._supported_extensions:
            displayed_extension = (
                normalized_extension
                if normalized_extension
                else "<none>"
            )

            return FileEligibilityResult(
                status=FileEligibilityStatus.UNSUPPORTED_EXTENSION,
                reason=(
                    f"Extension '{displayed_extension}' "
                    "is not supported."
                ),
            )
 
        return None

    def checkfile_state(
        self,
        path: Path,
    ) -> FileEligibilityResult | None:
        """Check readability, file size, and empty-file status."""
        try:
            size_bytes = path.stat().st_size
        except OSError:
            return FileEligibilityResult(
                status=FileEligibilityStatus.UNREADABLE_FILE,
                reason="File metadata could not be read.",
            )

        if size_bytes == 0:
            return FileEligibilityResult(
                status=FileEligibilityStatus.EMPTY_FILE,
                reason="File is empty.",
            )

        if size_bytes > self._config.maximum_file_size_bytes:
            return FileEligibilityResult(
                status=FileEligibilityStatus.FILE_TOO_LARGE,
                reason=(
                    f"File size {size_bytes} bytes exceeds "
                    f"the configured maximum of "
                    f"{self._config.maximum_file_size_bytes} bytes."
                ),
            )
        try:
            with path.open(
                mode="r",
                encoding="utf-8",
            ) as file:
                file.read(1)
        except (OSError, UnicodeError):
            return FileEligibilityResult(
                status=FileEligibilityStatus.UNREADABLE_FILE,
                reason="File could not be read as UTF-8 text.",
            )

        return None

    @staticmethod
    def normalizeextension(extension: str,) -> str:
        """Normalize an extension to lowercase with a leading period."""
        normalized_extension = extension.strip().lower()
        if not normalized_extension:
            return normalized_extension
 
        if normalized_extension.startswith("."):
            return normalized_extension
        return f".{normalized_extension}"

Check your underscores. This file relies on names such as init, config, check_directories, and normalizeextension. Word processors and chat tools sometimes strip or format underscores. If you see AttributeError or TypeError after pasting, compare the underscores first.

 

11. Understanding the evaluation order


evaluate() runs the checks in a deliberate order and returns at the first match:

1.    Excluded directory.

2.    Excluded filename.

3.    Supported filename, excluded extension, or unsupported extension.

4.    File state: readable, not empty, not too large, decodes as UTF-8.

5.    Eligible.


The principle is to reject unnecessary files as early as possible, and to avoid opening a file that can already be rejected from its path or name. A file under .venv is excluded without being opened, and credentials.json is excluded before its contents are read.


How each check works


•   Directories. The path is split into parts, the last part (the filename) is dropped, and the remaining folder names are compared in lowercase with the excluded set.

•   Filenames. The lowercase name is compared with the excluded set, so .ENV is treated like .env.

•   Extensions. A name in supported_filenames, such as Dockerfile, passes straight away because it has no extension to judge. Otherwise the extension is checked against the blocked set, then against the supported set. A file with no extension is reported as <none>.

•   File state. The size comes from the file's metadata, so empty and oversized files are rejected without reading them. Only then does the policy open the file and read the start of it as UTF-8.

•   Normalization. normalizeextension() lets the YAML say py or PY or .py, and all become .py.


12. Step 4: Export the policy components


Update src\github_rag\inventory\__init__.py:

"""Repository inventory generation components."""

from github_rag.inventory.classifier import FileClassifier
from github_rag.inventory.file_policy import FileEligibilityResult
from github_rag.inventory.file_policy import FilePolicy
from github_rag.inventory.file_policy import FilePolicyConfig
from github_rag.inventory.file_policy import load_file_policy_config

all = [
    "FileClassifier",
    "FileEligibilityResult",
    "FilePolicy",
    "FilePolicyConfig",
    "load_file_policy_config",
]

Other code can now write from github_rag.inventory import FilePolicy.


13. Step 5: Test the policy


Run these from the project root. First, load the configuration:

uv run python -c "from github_rag.inventory import load_file_policy_config; config = load_file_policy_config('config/file_policy.yaml'); print(len(config.excluded_directories)); print(config.maximum_file_size_bytes)"

Expected output:
7
1000000

This confirms the YAML was read and validated, the list became a set, and the size was loaded as an integer.


Then an eligible file. The README exists and has content:

uv run python -c "from github_rag.inventory import FilePolicy; policy = FilePolicy.from_yaml('config/file_policy.yaml'); result = policy.evaluate('README.md'); print(result.status.value); print(result.is_eligible); print(result.reason)"

Expected output:
eligible
True
File passed all policy checks.

And an excluded filename. The policy checks the name before touching the disk, so the file does not need to exist:

uv run python -c "from github_rag.inventory import FilePolicy; policy = FilePolicy.from_yaml('config/file_policy.yaml'); result = policy.evaluate('.env'); print(result.status.value); print(result.is_eligible); print(result.reason)"

Expected output:
excluded_filename
False
Filename '.env' is excluded by policy.

The complete check script


To cover every outcome without creating and deleting files by hand, create tests\check_file_policy.py. It uses a temporary folder for the empty, non-UTF-8, and large files, so the same script runs on Windows, macOS, and Linux:


"""Manual check of FilePolicy. Run it from the project root."""

import tempfile
from pathlib import Path
from github_rag.core import ConfigurationError
from github_rag.inventory import FilePolicy
from github_rag.inventory import FilePolicyConfig
from github_rag.inventory import load_file_policy_config

policy = FilePolicy.from_yaml("config/file_policy.yaml")

paths = [
    "README.md",
    ".env",
    ".venv/Lib/example.py",
    "assets/logo.png",
    "diagram.drawio",
    "uv.lock",
    "missing_file.md",
]

for path in paths:
    result = policy.evaluate(path)
    print(f"{path}: {result.status.value}")

with tempfile.TemporaryDirectory() as folder:
    empty_file = Path(folder) / "empty.md"
    empty_file.write_text("", encoding="utf-8")
    print("empty file:", policy.evaluate(empty_file).status.value)
    broken_file = Path(folder) / "broken.md"
    broken_file.write_bytes(b"\xff\xfe not valid UTF-8")
    print("not UTF-8:", policy.evaluate(broken_file).status.value)
    large_file = Path(folder) / "large.md"
    large_file.write_text("x" * 50, encoding="utf-8")
    small_policy = FilePolicy(
        FilePolicyConfig(
            supported_extensions={"md"},
            maximum_file_size_bytes=10,
        )
    )
    print("large file:", small_policy.evaluate(large_file).status.value)

    bad_config = Path(folder) / "bad.yaml"
    bad_config.write_text("excluded_directores:\n  - .git\n", encoding="utf-8")

    try:
        load_file_policy_config(bad_config)
    except ConfigurationError:
        print("invalid config: ConfigurationError")

Run it:

uv run python tests\check_file_policy.py

Expected output:
README.md: eligible
.env: excluded_filename
.venv/Lib/example.py: excluded_directory
assets/logo.png: excluded_extension
diagram.drawio: unsupported_extension
uv.lock: excluded_filename
missing_file.md: unreadable_file
empty file: empty_file
not UTF-8: unreadable_file
large file: file_too_large
invalid config: ConfigurationError

Two details are worth noticing. The large-file test builds its own small policy with supported_extensions={"md"}, with no leading period, and it still reaches the size check, which shows the extension was normalized. And a missing file is reported as unreadable_file, because its metadata cannot be read.


14. What this policy does not catch


The policy is simple on purpose. Testing it against awkward inputs shows where its edges are, and you should know them before relying on it:

Case

What happens today

Why it matters

Absolute paths, and folders above the repository

The directory check looks at every folder in the path it is given. If the repository sits inside a folder named build or dist, every file in it is excluded.

Pass paths relative to the repository root, and run from that root, until the inventory service handles the root explicitly.

Legitimate folders with a blocked name

src\build\utils.py is excluded because the folder is called build.

Names are matched at any depth, so choose the blocked folder names carefully.

Content that is not UTF-8 text

Only the start of the file is read. Invalid bytes later in the file, or binary data inside a .txt, still pass. A Latin-1 SQL file is rejected as unreadable.

Full decoding problems must be handled again during content extraction.

Secrets with other names

Only exact names are matched. service-account.json is eligible. .env.staging is blocked only because .staging is not a supported extension.

Pattern rules (for example .env.*) and real secret scanning are still needed.

Windows-style path strings on Linux or macOS

.venv\Lib\example.py is read as one long filename, so the directory check misses it.

Pass paths from your own operating system.

 

An ingestion control, not a security solution

The policy helps exclude common secret-bearing names, unsupported binaries, generated folders, oversized files, and unreadable content. It does not replace GitHub repository permissions, secret scanning, malware scanning, data-loss prevention, user authorization, retrieval-time access control, or prompt-injection defenses. Those controls arrive at the appropriate stages of this series.

 

15. 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_file_policy.py
uv run python -m compileall -f src
tree src\github_rag /f

Expected:

•   The first command prints the eleven lines shown in section 13.

•   The syntax check lists src\github_rag\inventory\file_policy.py and init.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_file_policy.py) and tree src/github_rag for the listing. The uv run python -c commands are the same on every system.


16. Common issues


Symptom

Likely cause

Fix

ConfigurationError: File-policy configuration does not exist

The command was run from another folder, or the file is not at config\file_policy.yaml.

Run from the project root and check the path.

Invalid file-policy configuration

A misspelled key or a bad value, for example excluded_directores or maximum_file_size_bytes: -1.

Read the chained error in the traceback. It names the key Pydantic rejected.

Every file is excluded

The paths passed in include a folder above the repository named build, dist, or similar.

Pass paths relative to the repository root. See section 14.

README.md is reported as unreadable or empty

The command ran from a different folder, or the README has no content.

Run from the project root and check the file is not empty.

ModuleNotFoundError: No module named 'yaml'

PyYAML is not installed in this environment.

Run uv add pyyaml, or re-run the Build Chapter 2 install step.

AttributeError or NameError after pasting code

Underscores were lost in init, config, or _all__.

Compare every underscore with the code in this chapter.


Conclusion and next chapter


The file policy creates a configurable boundary between repository discovery and content extraction. Instead of scattering excluded folders, filenames, extensions, and size limits across the codebase, we keep them in one YAML file. FilePolicyConfig validates the rules, FilePolicy applies them in a fixed order, and every rejected file keeps a recorded reason. The application can now answer both "what type of file is this?" and "should this file enter the ingestion pipeline?"

Eligible files can continue toward hashing, inventory generation, extraction, and parsing. Excluded files stay visible in the repository metadata, together with the reason they were rejected.


Next, Build Chapter 6: Adding Content Hashing for Incremental Processing. It covers:

•   Why file modification timestamps are not enough on their own

•   Creating ContentHashService and generating SHA-256 hashes

•   Reading files in binary chunks to limit memory use

•   Comparing previous and current hashes

•   Supporting future incremental reprocessing

•   Tests using real repository files

 

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. Models

[2]  PyYAML. PyYAML Documentation

Recent Posts

See All
BUILDING A PRODUCTION-READY GITHUB RAG SYSTEM

Build Chapter 4: Classifying Files in a GitHub Repository Part 1: Foundation and Repository Understanding | For engineers learning RAG | About 12 minutes to read, 25 to follow along In Build C

 
 
 

Comments


bottom of page