Thank you for your interest in contributing to Code Graph RAG! We welcome contributions from the community. How the project is run, who decides what, and how to become a maintainer are described in GOVERNANCE.md.
- Browse Issues: Check out our issue tracker to find tasks that need work
- Look for issues labelled
good first issuefor beginner-friendly tasks - Issues labelled
help wantedare open for community contributions
- Look for issues labelled
- Pick an Issue: Choose an issue that interests you and matches your skill level
- Comment on the Issue: Let us know you're working on it to avoid duplicate effort
- Fork the Repository: Create your own fork to work on
- Create a Branch: Use a descriptive branch name like
feat/add-featureorfix/bug-description
Our repository uses standardised labels to categorise issues and PRs:
| Label | Purpose |
|---|---|
bug |
Something isn't working correctly |
enhancement |
New feature or improvement request |
documentation |
Documentation improvements |
question |
Questions about usage or functionality |
good first issue |
Good for newcomers |
help wanted |
Extra attention needed from the community |
poor-quality |
PR doesn't meet contribution standards (auto-closed after 7 days) |
language support |
Related to programming language support |
performance |
Performance improvements |
security |
Security vulnerability or concern |
tests |
Related to testing |
ci/cd |
CI/CD improvements |
Labels are automatically synced from .github/labels.yml.
-
Set up Development Environment:
git clone https://github.com/YOUR-USERNAME/code-graph-rag.git cd code-graph-rag make dev -
Install Pre-commit Hooks (mandatory): Handled by Makefile in
make dev, but if needed separately:pre-commit install pre-commit autoupdate
All commits must pass pre-commit checks. Do not skip hooks with
--no-verify. -
Make Your Changes:
- Follow the existing code style and patterns
- Add tests: this is project policy, not a suggestion. New functionality must come with tests that exercise it, and bug fixes must include a regression test that fails without the fix
- Update documentation if needed
- Add a comment only where it explains why, not what (see Comment Policy below)
-
Test Your Changes:
- Run the existing tests to ensure nothing is broken
- Test your new functionality thoroughly
- Run
uv run ruff checkanduv run ruff format --checkbefore committing
-
Submit a Pull Request:
- Push your branch to your fork
- Create a pull request against the main repository
- Reference the issue number in your PR description
- Provide a clear description of what you've changed and why
- Keep PRs focused on a single issue or feature
- Write clear, descriptive commit messages
- Tests are required for new functionality and for bug fixes; PRs adding major functionality without tests will not be merged
- Update documentation when necessary
- Be responsive to feedback during code review
- Show a user-visible change in the PR description (see below)
A pull request that changes something a user can see must show it working, in the PR description, before and after. This applies to humans and AI agents alike.
- What counts as user-visible: CLI commands, output and prompts; MCP tool results; the nodes, relationships and properties the graph holds for a real snippet; the realtime watcher; the docs site and the README.
- How to show it: a terminal change gets a GIF recorded with VHS, with the
.tapefile kept out of the repository. A graph, browser or docs change gets a screenshot. Record from the PR's own branch, running its own code. - How to attach it: embed it inline as a GitHub attachment, never committed. Reference the file in the body and let
ghupload it:gh pr create --attach ./after.pngorgh pr edit <n> --attach ./after.png(GitHub CLI 2.99 or later). A body line such asis rewritten to the uploadedgithub.com/user-attachmentsURL; without one the image is appended. By hand, drag or paste the file into the description. - When nothing is visible: an internal refactor, a test-only or CI-only change says so in one line instead, for example
No user-visible change: refactors the call resolver's cache key.
A change that breaks existing setups (a new default, a removed option, a renamed setting) is announced in its release under "
- Mark the title with
!, for examplefeat(vectors)!: default to the sqlite vector store. - A maintainer adds the
breaking changelabel. The label bumps the minor version and releases at once. - Add the release notes as
changes/breaking/<PR number>.md: what changed, how to keep the old behaviour, what happens to existing installs, and a link to the docs. Write them for users reading the release, in Markdown with no heading.
The Breaking Change Notes check fails until the title, the label and the file agree.
docs/reference/public-surface.json records everything users and agents reach: commands and options, exit codes, MCP tools and their input schemas, settings, graph labels and relationships, the export's records, the protobuf index and the Python SDK. test_public_surface.py fails when the code and the file differ. A change you intend: run uv run python scripts/public_surface.py and commit the file, so the change shows in the pull request. A removed or renamed entry is a breaking change (above). The Rust rewrite (RUST_REWRITE_PLAN.md) is held to this file.
No test disappears silently. A pull request that removes, renames or moves a test, a Python test function or a Rust #[test], adds an entry to codebase_rag/tests/removed_tests.toml naming the tests that now check what it checked: test is the removed test's id without parameters (file::Class::function, or rust/<crate>/<path>.rs::<mod>::<function> with the mod blocks around the function outermost first, none at file level), replaced_by lists its replacements, reason says what it checked and how they check the same, and pull_request is the pull request's number. Only when the same pull request deletes the code the test checked does obsolete = "<the deleted file>" take the place of replaced_by. The lint job runs python3 scripts/test_removals.py check --base <base commit>, which lists the tests of both commits without importing anything and fails on a removed test without an entry, a replacement the head does not have, an entry for a test that still exists, an obsolete file still there, or an entry for a test removed here that names another pull request; each failure prints the entry to add. Run it on your committed branch with --base origin/main. A dropped parametrize case is not checked: say so in the pull request. The Rust rewrite (PHASE1_SEAMS.md, section 4) is held to this map.
All pull requests are automatically validated by our CI workflow, which runs in parallel for faster feedback:
-
Lint & Format - Code style and security validation:
ruff checkwith GitHub annotationsruff format --check- Bandit, through the same pre-commit hook you run locally (high-severity findings fail the job)
- On a pull request,
scripts/test_removals.py check: every test the base has and the head lacks has an entry incodebase_rag/tests/removed_tests.toml(see Removing a test)
-
Type Check - Static type analysis:
ty checkon production code (excludes tests)
-
Unit Tests - Fast tests without Docker:
- Parallel execution with
pytest-xdist - Code coverage reporting to Codecov
- On the engine
--engine-modepicks (PHASE1_SEAMS.md, section 2):pythonin the Python 3.12 cells;rustin the Windows and macOS 3.13 cells, where the whole session, its shared fixtures and anycgra test starts run withCGR_INDEX_ENGINE=rust; andbothin the Ubuntu 3.13 cells, which also index each indexed repository afresh on each engine and fail the tests that indexed it, or that use the fixture that did, when the two runs' file plans, project indexes or graphs differ; the report takes them in that order and marks the first that differs. In therustandbothcells every index also compares the Rust engine's file plan (its walk of the repository and the files' hashes, PHASE2_FRAME.md, section 4) with Python's walk, its change detection (the in-sync check, the files new, changed and deleted, and the hash cache and folder times the run would publish, section 6) with Python's, its structure (the Package, Folder and File rows and the map of each folder's package, section 7) with Python's, and, on a run whose module map starts empty, its module-name plan (which file claims each module's name, section 10) with Python's module map, and fails the test on any difference; therustcells index with the Rust plan, changes and structure, and every cell with Python's module names. Thepythoncells run the frame as users do: on, beside Python's walk, and on a difference, or anything the frame raises, the run logs one warning and goes on with Python's answers. While no language runs on Rust, all three run the same suite. A test that must stay on Python sets@pytest.mark.index_engine("go=python").--engine-preview goputs a language whose port is under way on Rust for a local session (index_engine.PREVIEW, PHASE3_GO.md, section 10); no cell passes it
- Parallel execution with
-
Integration Tests - Full stack testing:
- Tests with real Memgraph database
- Service container orchestration
- Code coverage reporting to Codecov
-
PR Title Validation - Conventional Commits format check
-
Greptile 5/5 Gate - Greptile reviews every push, and the check fails when it scores the PR's latest commit below 5/5. If Greptile doesn't score that commit (out of credits, paused), the check passes with a warning
-
Reference Graphs - The graphs of pinned public repositories, one or more per language, listed in
fixtures/reference_graphs/repos.json. The job indexes each withcgr, exports it, and compares it line by line with the recorded.graphfile; it indexes each twice more, at another path under anotherPYTHONHASHSEED, and fails if any run differs. A pull request that changes what the indexer records changes these files too: runuv run --extra treesitter-full --extra ast-grep python scripts/reference_graphs.py record(or name the repositories it touches) and commit the result, so the difference shows in the review. The graphs are recorded and checked with every language tier installed, as the job installs them;environment.txtbeside them says what the recording could parse, and the job stops first, naming what is missing, on a machine that parses something else. No cgr setting of your shell reaches the index;--index-engine SPECindexes every run on thatCGR_INDEX_ENGINEselection, and the graphs must not change. The Rust rewrite (RUST_REWRITE_PLAN.md) is held to these graphs. -
Reference Answers - In the same job, what commands and MCP tools answer on those repositories.
fixtures/reference_answers/<repo>/cases.jsonlists the questions:cgr graphqueries,stats,dead-code,duplicates,contextand their refusals on the command line, and the read-only MCP tools, called over stdio as a client calls them. Each answer, the exit status and output or the tool'sisErrorand content, is kept beside the list as<case>.txt, with the checkout written as<root>, the scratch directory as<tmp>and a node's row number as<node_id>. The job asks each repository twice, the second time at another path under anotherPYTHONHASHSEED, and fails on any difference. A pull request that changes an answer changes the file: runuv run --extra treesitter-full --extra ast-grep python -m scripts.reference_answers record(or name the repositories) and commit the result. A wrong answer is recorded as it is, with an issue, and changes when the bug is fixed. The Rust rewrite is held to these answers too. -
Hand-off files - In the same job,
python -m scripts.handoff check --runs 2indexes each of those repositories twice by callingGraphUpdaterdirectly, each run in a Python process of its own and the second at another path under anotherPYTHONHASHSEED, and fails unless both runs wrote the same file plan and project index (files.txtandindex.txt, PHASE1_SEAMS.md, section 3) byte for byte, and unless in each run the Rust engine's file plan, its change detection, its structure, its module-name plan (against themodulelines ofindex.txt) and its reading of the ignore files equal Python's. These are what the Rust engine is compared on, live, so they are not checked in;record --out DIRwrites them for reading.--index-engine SPECruns every index on that selection, as it does for the reference graphs. Thenpython -m scripts.handoff compare --engines python,go=rustindexes each pinned repository whose language the two selections put on different engines once under each, with the Go type checker on (the job installs Go for it), and fails unless the type checker analysed every Go module in both runs and the two file plans, project indexes and graphs are the same (PHASE3_GO.md, section 6).--preview LANGUAGESruns languages whose port is under way on Rust in every run, wherever the selection asks for Rust.
All checks run in parallel and must pass before a PR can be merged. A summary job verifies all checks succeeded.
Run checks locally before pushing:
make lint # Lint check
make format # Apply formatting (ruff format writes files; CI uses ruff format --check)
make typecheck # Type check
make test-parallel # Unit tests in parallel
make test-integration # Integration tests (requires Docker)Or run all at once:
make check # Runs lint + typecheck + test
make pre-commit # Runs ALL pre-commit checks (comprehensive - mirrors CI)The make pre-commit command runs the exact same checks as your pre-commit hooks and CI pipeline, including:
- Code formatting verification
- Linting
- Type checking
- Documentation checks
- README generation
- Security scanning
- Unit tests
Use this before committing to catch issues early.
This project uses automated code review bots (Greptile and Gemini Code Assist) to provide initial feedback on PRs. Before requesting a human review:
- Address all bot comments: Every comment from Greptile and Gemini Code Assist must be resolved
- Accept or push back: For each bot suggestion, either:
- Accept: Implement the suggestion and resolve the comment
- Push back: Reply inline with a clear justification for why the suggestion doesn't apply
- Iterate as needed: Continue addressing new bot comments through multiple review rounds until all are resolved. When Greptile scores the PR's latest commit, the score must be 5/5, or the Greptile 5/5 Gate check fails and blocks the merge. It reviews each push on its own; to ask it again without pushing (after answering a finding it got wrong), comment
@greptile review, then re-run the check once the Greptile Review check has started - Then request human review: Only after all bot comments are cleared, assign the PR to core maintainers for human review
This process ensures that human reviewers focus on high-level design and logic rather than style and common issues that bots can catch.
- PydanticAI for now: PydanticAI is the agentic framework the project runs on today. That is a current choice, not a permanent commitment, and a well-argued case for moving is welcome. What it does rule out is arriving at a second framework by accident, so do not introduce one (LangChain, CrewAI, AutoGen) as part of a feature pull request. Open an issue first, as
GOVERNANCE.mdasks for architectural decisions.
Integrations with external services (search APIs, model hosts, data providers) are welcome, on these terms:
- Free tier only: The open-source tree carries capability that works without payment. Do not add configuration that selects a vendor's paid plan, and do not document a route to one. Paid capability belongs in Enterprise Services, not in an environment variable here.
- No single-vendor lock: A generic capability resolves its backend from configuration, the way model and embedding providers already do in
codebase_rag/config.py. A capability that works only for holders of one vendor's key is not a capability this project has. - Keyless default: Where a provider needs no account, it is the default, so the feature works on a fresh checkout.
- Disclose affiliation: If you work for, or are compensated by, the service you are integrating, say so in the pull request description.
- Heavy Pydantic Usage: Use Pydantic models extensively for data validation, serialisation, and configuration
- Package Management: Use
uvfor all dependency management and virtual environments - Code Quality: Use
rufffor linting and formatting - runruff checkandruff formatbefore submitting - Type Safety: Use type hints everywhere and run
uv run ty checkfor type checking
- uv: Package manager and dependency resolver
- ruff: Code linting and formatting (replaces flake8, black, isort)
- ty: Static type checking (from Astral)
- pytest: Testing framework
- ripgrep (
rg): Required for shell command text searching (install viabrew install ripgrepon macOS orapt install ripgrepon Linux)
This project uses pre-commit to automatically run checks before each commit, ensuring code quality and consistency.
To get started, first make sure you have the development dependencies installed:
make devThen, install the git hooks:
Automatically via Makefile in make dev, but if needed separately:
pre-commit install
pre-commit autoupdateNow, pre-commit will run automatically on git commit.
The harnesses under fuzz/ run in CI via
ClusterFuzzLite, in four
workflows:
| Workflow | When | What it does |
|---|---|---|
cflite_pr.yml |
every pull request | 600 seconds of fuzzing on every core, in a job per language (the harnesses, and the Rust targets below) capped at 45 minutes so it never holds a PR for long. It fuzzes only the targets the change can reach, judged by the latest coverage report, or all of them when there is no report |
cflite_batch.yml |
nightly at 03:17 UTC, or by hand | one job per harness, each fuzzing on every core for 7200 seconds (fuzz-seconds on a manual run) and growing the corpus the PR job starts from, and one job giving the Rust targets an hour between them |
cflite_cron.yml |
nightly at 06:17 UTC, or by hand | prunes each corpus to the inputs that still add coverage (a job per harness, one for the Rust targets), then replays the harnesses' pruned corpora under coverage.py and uploads the report as the cifuzz-coverage-latest artifact |
cflite_build.yml |
every push to main |
uploads the harnesses' fuzz build, so a crash a PR meets that already happens on main is not blamed on the PR |
A crash fails the job with the reproducing input attached as an artifact. The PR jobs and the harnesses' batch jobs also upload a SARIF report to code scanning, so crashes appear in the Security tab. The batch report is written even when nothing crashed, so an alert closes on the first night its crash is gone.
There are five targets:
| Harness | What it drives | What it asserts |
|---|---|---|
fuzz_parse_source.py |
a tree-sitter parse for a fuzzer-chosen language (through preprocessor recovery for C, C++ and C#, as indexing does), then every query and the name extraction over the tree | no pass raises, and no extracted name is silently truncated by an invalid byte beside it |
fuzz_incremental_update.py |
GraphUpdater.reingest over a fuzzer-chosen edit plan: truncate, splice, rewrite, delete, recreate, new file, rename, move |
the resulting graph equals a clean full index of the same tree |
fuzz_shell_command.py |
the production EXECUTE_SHELL gates: the pre-spawn screen in default and YOLO mode, the approval gate and the non-interactive confinement gate |
no gate raises; an allowed command spawns only segments allowed on their own; no prefix launders a structurally refused suffix; xargs never makes a refused command allowed; re-quoting never changes a verdict; non-interactive runs stay read-only and inside the project root |
fuzz_cypher_guard.py |
the read-only guard on generated Cypher: masking, validation and both plan parsers | write keywords, disallowed procedures and unbounded paths are refused wherever they hide, and a plan holding a write operator is refused |
fuzz_dependency_manifest.py |
parse_dependencies over every manifest format |
exactly the declared dependencies are reported, all as strings, and none is invented from a decoy or a wrong-typed section |
To run one locally:
uv run --extra fuzz python fuzz/fuzz_parse_source.py -max_total_time=60 \
-dict=fuzz/fuzz_parse_source.dictEach target ships a libFuzzer dictionary, fuzz/<harness>.dict, holding the
tokens its input language is built from. The build copies it next to the
target and smoke-runs the target with it, so a malformed dictionary fails the
build. codebase_rag/tests/test_fuzz_build.py checks every dictionary the way
libFuzzer reads it, and caps each entry at 64 bytes, because libFuzzer skips
any longer entry without saying so.
Seed corpora live in fuzz/corpus/<harness>/ and are regenerated with
uv run python fuzz/build_corpus.py. Seeds matter: starting from valid inputs
is what gets the fuzzer past the grammar's error recovery and into the
extraction code.
The fuzz image installs the locked dependency set (uv export --frozen), and
takes atheris, PyInstaller and coverage from .clusterfuzzlite/requirements.txt,
pinned by hash, so a fuzzing run never tests a dependency set the project
does not ship.
Rules for a harness:
- No
from __future__imports. The coverage build prepends a coverage stub to every harness, and a__future__import that is not the first statement is aSyntaxError, which leaves that target out of the report. - Silence logging (
logger.disable("codebase_rag")). One target's debug output once filled a 364 MB nightly log and hid its own statistics. - Assert a property, not just "does not raise", where the code under test has one. A crash-only harness misses every bug that returns a wrong answer.
atheris on macOS. Apple Clang ships no libFuzzer, so uv sync --extra fuzz fails with Failed to find libFuzzer. Homebrew's llvm@21 has it,
and atheris 3.0.0 is the last release with a source distribution:
L=/opt/homebrew/opt/llvm@21/bin; S=$(xcrun --show-sdk-path)
SDKROOT=$S CFLAGS="-isysroot $S" CXXFLAGS="-isysroot $S" \
LDFLAGS="-isysroot $S -L$S/usr/lib" CC=$L/clang CXX=$L/clang++ \
CLANG_BIN=$L/clang uv pip install "atheris==3.0.0"Otherwise fuzz on Linux, or let CI do it; the rest of the suite is unaffected either way.
When fuzzing finds a crash: add a regression test under codebase_rag/tests/
that fails without the fix, commit the reproducer into the harness' corpus
directory, and only then fix the bug.
The Rust extension has cargo-fuzz targets of its own, in
rust/cgr_graph_rs/fuzz/fuzz_targets/, and the PR, batch and cron workflows
run them in a separate rust job (a build holds one language's targets).
Coverage and the main build upload are the harnesses' alone:
ClusterFuzzLite names those artifacts by sanitizer, not language, so a Rust
one would take the Python one's place. Each target's header says what it
drives and checks:
| Target | What it drives |
|---|---|
cypher_parse |
the Cypher lexer and parser on any query text |
json_string |
json_text::push_string, against Python's json.dumps |
graph_algorithms |
the graph procedures and run on a graph and arguments the input chooses |
sqlite_graph |
the bulk writer, the variable-length walk and Graph::load, against a model of the graph |
xml_elements |
the XML project-file reader (formats::xml) on any bytes |
ignore_patterns |
the walk's ignore rules (engine::ignore) on any patterns and paths |
go_build_constraint |
the Go build-constraint reader, decide and the package clause (engine::go) on any file name and head |
To run one locally, with a nightly toolchain and cargo install cargo-fuzz:
cd rust/cgr_graph_rs && cargo +nightly fuzz run cypher_parse -- -max_total_time=60All tooling is from Astral:
| Tool | Purpose | Command |
|---|---|---|
| uv | Package management | uv sync, uv add, uv run |
| ty | Type checking | uv run ty check |
| ruff | Linting and formatting | uv run ruff check, uv run ruff format |
# Sync dependencies
make python
# Upgrade a package
uv sync --upgrade-package <pkg>
# Type check (excludes test files)
uv run ty check codebase_rag --exclude codebase_rag/tests
# Lint and format
uv run ruff check --fix .
uv run ruff format .| Structure | Use Case |
|---|---|
| StrEnum | Constrained string constants used in comparisons, defaults, assignments |
| NamedTuple | Immutable records with named fields (lightweight, hashable) |
| TypedDict | Dict shapes for function return types or JSON-like data |
| dataclass | Mutable class instances with behaviour/methods |
| Pydantic BaseModel | Configs needing validation, serialisation, or schema generation |
from dataclasses import dataclass
from enum import StrEnum
from typing import NamedTuple, TypedDict
# StrEnum - string constants
class Status(StrEnum):
PENDING = "pending"
DONE = "done"
# NamedTuple - immutable record
class Point(NamedTuple):
x: float
y: float
# TypedDict - dict shape
class Result(TypedDict):
success: bool
data: str
# dataclass - mutable with behavior
@dataclass
class User:
name: str
def greet(self) -> str:
return f"Hello, {self.name}"- Use
Literaltypes for constrained string values used only as type hints - Use
StrEnumwhen values need defaults or are used in code (not just type hints) - Never use loose dict types like
dict[str, Any]ordict[str, str | int | None]- use TypedDict instead - Use explicit TypedDict constructors instead of plain dict literals
Forward references are type hints wrapped in quotes like "ASTNode". These are NOT allowed.
How to identify forward references:
- Type hints with quotes:
def foo(x: "SomeClass") -> "Result" - These appear when a type is used before it's defined or to avoid circular imports
How to fix forward references:
- Add
from __future__ import annotationsat the top of the file - Remove the quotes from the type hints
IMPORTANT: Only add from __future__ import annotations to files that HAVE forward references. Do NOT add it to files that don't need it.
# Bad - forward reference with quotes (THIS IS NOT ALLOWED)
def process(node: "ASTNode") -> "Result": ...
# Good - add future import and remove quotes
from __future__ import annotations
def process(node: ASTNode) -> Result: ...# Bad - loose dict type
def process(args: dict[str, str | int | None]) -> dict[str, Any]: ...
# Good - TypedDict with known shape
class ProcessArgs(TypedDict):
name: str
count: int
def process(args: ProcessArgs) -> Result: ...
# Bad - dict literal
return {"success": True, "data": data}
# Good - TypedDict constructor
return Result(success=True, data=data)In Protocols and mixin classes, use regular method definitions instead of Callable attributes. Callables are not bound (don't receive self implicitly) and descriptors are not invoked.
from abc import abstractmethod
from typing import Callable, Protocol
# Bad - Callable attribute (not bound, not recommended)
class MyMixin:
process: Callable[[str], int]
class MyProtocol(Protocol):
handler: Callable[[str, int], bool]
# Good - regular method definition
# Mixin classes: use @abstractmethod for method stubs
class MyMixin:
@abstractmethod
def process(self, data: str) -> int: ...
# Protocols: no decorator needed (structural typing)
class MyProtocol(Protocol):
def handler(self, name: str, count: int) -> bool: ...Only use Callable attributes when reusing complex callable types is necessary.
Standard files in each module:
types_defs.py- Type aliases, TypedDicts, NamedTuples (immutable structural types)models.py- Dataclasses only (runtime data structures with behaviour)constants.py- StrEnums, string literals, and application constantsconfig.py- Pydantic settings, environment config, and runtime configuration instancesschemas.py- All Pydantic BaseModel classes (data transfer objects, results, responses)logs.py- Log message templates for logger calls (info, debug, warning, error, success)tool_errors.py- Error messages returned by tools to the LLM/userexceptions.py- Exception classes and their error message templates (for raise statements)
- Soft rule: keep files under 700 lines (after linting); split larger files into submodules
- Group related functionality into submodules (e.g.,
stem_ops/,tools/,srg_parser/) - Use descriptive file names that reflect purpose (e.g.,
editor.py,factory.py,loader.py) - Each submodule can have its own
__init__.pyto expose public API
- Import from the module's public API, not internal files:
# Bad
from policy_digitization_tasks.srg_parser.editor import apply_edits
# Good
from policy_digitization_tasks.srg_parser import apply_edits- Group imports: stdlib, third-party, local (separated by blank lines)
- Use explicit imports, avoid
from module import *
When importing 5+ items from a module, use module-level import with a 2-letter alias:
# Bad - many lines of imports
from .constants import (
CLI_ERR_CONFIG,
CLI_MSG_DONE,
Color,
Provider,
# ... 20 more items
)
# Good - 1 line with 2-letter alias
from . import constants as cs
from . import exceptions as ex
from . import tool_errors as te
from . import logs as ls
# Usage
logger.info(ls.PROCESSING_FILE.format(path=path))
raise ex.LLMGenerationError(ex.CONFIG.format(error=e))Define constants, patterns, and types once. Import everywhere.
Use StrEnum when string values are used in code (defaults, comparisons, assignments):
from enum import StrEnum
# Bad - hardcoded strings scattered in code
def process(mode: str = "fast"): ...
if status == "pending":
...
# Good - centralized StrEnum
class Mode(StrEnum):
FAST = "fast"
SLOW = "slow"
def process(mode: Mode = Mode.FAST): ...
if status == Status.PENDING:
...Use an Enum with __call__ for parameterised error messages:
from enum import Enum
class Error(str, Enum):
NOT_FOUND = "Item '{id}' not found"
INVALID = "Invalid value"
def __call__(self, **kwargs) -> str:
return self.value.format(**kwargs) if kwargs else self.value
# Usage
raise ValueError(Error.NOT_FOUND(id="abc"))Use StrEnum for error type names passed to exception classes:
class ErrorCode(StrEnum):
VALIDATION = "ValidationError"
NOT_FOUND = "NotFoundError"
raise CustomError(ErrorCode.VALIDATION, Error.INVALID())Use loguru for all output instead of print:
# Bad
print(f"Processing: {file}")
print(f"Error: {e}", file=sys.stderr)
# Good
from loguru import logger
logger.info(f"Processing: {file}")
logger.error(f"Error: {e}")
logger.success("Done!")Use typer for CLI argument parsing instead of argparse:
# Bad
parser = argparse.ArgumentParser()
parser.add_argument("name", type=str)
parser.add_argument("--count", type=int, default=1)
args = parser.parse_args()
# Good
from typing import Annotated
import typer
def main(
name: Annotated[str, typer.Argument(help="Name")],
count: Annotated[int, typer.Option(help="Count")] = 1,
) -> None: ...
typer.run(main)Use click with @click.group() for nested subcommand groups that integrate with a typer main app:
- Typer's
add_typer()requires more boilerplate for this pattern - Bridge typer → click via
ctx.argsandstandalone_mode=False - Use
click.echo()/click.secho()for user-facing CLI output (not logging) - Add
logurufor actual error logging in exception handlers
# subcommands.py - click subcommand group
@click.group(help="Manage resources")
def cli() -> None:
pass
@cli.command(help="Add a new resource.")
def add(name: str) -> None:
try:
do_add(name)
click.echo(f"Added {name}")
except Exception as e:
logger.error(f"Failed to add: {e}") # loguru for logging
click.secho(f"Error: {e}", fg="red") # click for user output
# main.py - typer main app bridges to click
from .subcommands import cli as subcommand_cli
@app.command(
name="resource",
context_settings={"allow_extra_args": True, "allow_interspersed_args": False},
)
def resource_command(ctx: typer.Context) -> None:
subcommand_cli(ctx.args, standalone_mode=False)Use dataclasses with methods instead:
# Bad
HANDLERS = {
"create": lambda x: {"action": "create", "id": x.id},
}
# Good
@dataclass
class Handler:
action: str
template: str
def build(self, x) -> ActionDict:
return ActionDict(action=self.action, id=x.id)
HANDLERS = {"create": Handler(action="create", template="...")}# Bad
if action == "create":
return handle_create(data)
elif action == "update":
return handle_update(data)
else:
return handle_default(action, data)
# Good
match action:
case "create":
return handle_create(data)
case "update":
return handle_update(data)
case other:
return handle_default(other, data)When the if body does nothing (pass) and all logic is in the else clause, invert the condition and remove the empty else:
# Bad - empty if body with logic in else
if location == OUTSIDE:
pass
else:
take_off_hat()
# Good - inverted condition, no empty else
if location != OUTSIDE:
take_off_hat()This also applies when the if body is a guard condition that allows dropping the else entirely.
Use named expressions (:=) to merge assignment followed by a conditional check:
# Bad - separate assignment and condition
env_base = os.environ.get("PYTHONUSERBASE", None)
if env_base:
return env_base
chunk = file.read(8192)
while chunk:
process(chunk)
chunk = file.read(8192)
# Good - named expression
if env_base := os.environ.get("PYTHONUSERBASE", None):
return env_base
while chunk := file.read(8192):
process(chunk)Named expressions can also simplify nested conditions:
# Bad - nested if statements
if self._is_special:
ans = self._check_nans(context=context)
if ans:
return ans
# Good - merged with named expression
if self._is_special and (ans := self._check_nans(context=context)):
return ansIf a helper function is trivial and used once, inline it.
Declare variables as close to their usage as possible to minimise cognitive load and prevent stranded variables:
# Bad - assignment far from usage
cubes = []
function_unrelated_to_cubes()
if another_unrelated_condition():
more_unrelated_logic()
for i in range(20):
cubes.append(i**3)
# Good - assignment immediately before usage
function_unrelated_to_cubes()
if another_unrelated_condition():
more_unrelated_logic()
cubes = []
for i in range(20):
cubes.append(i**3)Extract repeated code blocks into helpers:
# Bad - same 4 lines repeated 3 times (12 lines)
def save_user(user):
conn = db.connect()
conn.execute(SQL_USER, user.dict())
conn.commit()
conn.close()
def save_order(order):
conn = db.connect()
conn.execute(SQL_ORDER, order.dict())
conn.commit()
conn.close()
def save_item(item):
conn = db.connect()
conn.execute(SQL_ITEM, item.dict())
conn.commit()
conn.close()
# Good - helper + 3 one-liners (7 lines)
def _save(sql: str, data: dict) -> None:
conn = db.connect()
conn.execute(sql, data)
conn.commit()
conn.close()
def save_user(user):
_save(SQL_USER, user.dict())
def save_order(order):
_save(SQL_ORDER, order.dict())
def save_item(item):
_save(SQL_ITEM, item.dict())Never use # type: ignore comments, cast(), Any type, or object as a type hint. These provide no useful type information. Fix the underlying type issue using proper typing, type narrowing, specific union types (e.g., str | int | bool | None), or TypedDict for dict values.
All repeated string literals should be constants or StrEnum members:
# Bad
if node.type == "predicate_definition":
...
artifact_type = "srg_v1"
# Good
if node.type == ElementType.PREDICATE:
...
artifact_type = ARTIFACT_SRGFiles that are NOT config.py, models.py, constants.py, logs.py, or CLI modules should have almost no string literals. Move all strings to:
logs.py- all log messages (info, debug, warning, error, success)constants.py- non-log constants, StrEnums, format stringstool_descriptions.py- tool/function descriptions (for tools modules)config.py- configuration defaults
# Bad - strings in service/tool files
logger.info(f"Processing file: {path}")
description = "Reads file content from disk."
# Good - import from dedicated modules
from .. import logs
from . import tool_descriptions as td
logger.info(logs.PROCESSING_FILE.format(path=path))
description = td.FILE_READERUse StrEnum types in function signatures, not str:
# Bad
def extract(guideline_type: str, outcome: str = "Approve"): ...
# Good
def extract(
guideline_type: GuidelineType, outcome: OutcomeType = OutcomeType.APPROVE
): ...Use Pydantic model_validator for cross-field validation:
class Config(BaseModel):
options: list[str] | None = None
default: str = "fallback"
@model_validator(mode="after")
def validate_default_in_options(self):
if self.options and self.default not in self.options:
raise ValueError(f"default '{self.default}' must be in options")
return self- Conventional Commits format
- One-liner only
- No emoji
- No attribution or Co-Authored-By
Uses Conventional Commits format with this regex pattern:
^(build|chore|ci|docs|feat|fix|perf|p?refactor|revert|style|test)(\([a-zA-Z0-9_-]+\))?!?: .+$
Allowed prefixes:
| Prefix | Purpose |
|---|---|
build |
Build system or external dependencies |
chore |
Routine tasks, maintenance |
ci |
CI configuration changes |
docs |
Documentation only |
feat |
New feature |
fix |
Bug fix |
perf |
Performance improvement |
refactor or prefactor |
Code refactoring |
revert |
Reverting changes |
style |
Formatting, whitespace, etc. |
test |
Adding or modifying tests |
Format:
<type>[(<scope>)][!]: <description>
Examples:
feat: add user authenticationfix(api): resolve null pointer exceptionchore(deps): update dependenciesfeat!: breaking change to API(the!indicates a breaking change)refactor(core): simplify validation logic
The scope (in parentheses) is optional and can contain alphanumeric characters, underscores, and hyphens.
Write comments that explain why and how, not what. A comment that only restates the adjacent code adds no value; one that captures a non-obvious reason, a tricky invariant, or a concrete edge case earns its place.
This project is licensed under the MIT licence. By submitting a contribution, you agree that it is your own work (or that you have the right to submit it) and that it is licensed to the project and its users under the same MIT licence. You retain copyright in your contribution; no copyright assignment is required.
If you have questions about contributing, feel free to:
- Open a discussion on GitHub
- Comment on the relevant issue
- Reach out to the maintainers
We appreciate your contributions!
This project uses a Makefile for streamlined development workflow:
# Set up complete development environment (recommended for new contributors)
make dev
# Run all tests
make test
# Run tests in parallel for faster execution
make test-parallel
# Clean up build artifacts and cache
make clean
# View all available commands
make help