agentleFS
divar-irdivar-ir/ai-doc-gen/.cursor/rules/code-patterns.mdc

ai-doc-gen / rules

Cursor rule765 starsChanged 4 months agoMITView on GitHub

Python code style and recurring patterns (config, logging, errors, paths)

The file

We split this code-patterns.mdc into the rules it gives an agent

3 rules. About 0 are common, 0 are distinctive, and 3 are very specific to this project.

  • ≈0

    Common · estimate

    Many files like this have a rule of this kind.

  • ≈0

    Distinctive · estimate

    This author's own choices. Worth a look.

  • 3

    Very specific

    Tied to their project's names, files or tools. Probably skip.

  • Common
  • Distinctive
  • Very specific
  1. Very specific:

    Every Field needs a description — CLI arguments are generated from it (--exclude-feature, store_true, default None = "not specified").

    line 23
  2. Very specific:

    All handler/agent operations are async.

    line 29
  3. Very specific:

    Always isolate errors: check each result with isinstance(result, Exception), log with exc_info=True, continue.

    line 31

≈ “Common” is an estimate: at least 1 in 5 of the 3,030 Cursor rule files we read have a rule of the same kind, not the same words. “Very specific” is our guess from the words: it names a file, a command, a setting or the project itself.

Keep what fits and drop the rest. Your version, ready for your agents.
Files
code-patterns.mdc
---
description: Python code style and recurring patterns (config, logging, errors, paths)
globs:
  - "src/**/*.py"
alwaysApply: false
---

# Code Patterns

## Style

- Ruff: 120-char lines, 4-space indent, `target-version = "py313"`; import sorting enabled — run `uv run ruff format src/ && uv run ruff check src/`.
- Type hints everywhere; `pathlib.Path` for all file paths (never strings); Pydantic `BaseModel` for all config/data structures.
- Naming: snake_case files/functions, PascalCase classes, `_private` methods, UPPER_SNAKE constants, config classes end in `Config`.

## Configuration

```python
class MyHandlerConfig(BaseHandlerConfig, MyAgentConfig):
    exclude_feature: bool = Field(default=False, description="Exclude feature")  # description feeds CLI --help
```

- Every `Field` needs a `description` — CLI arguments are generated from it (`--exclude-feature`, store_true, default `None` = "not specified").
- Load order: Pydantic defaults < `.ai/config.yaml` (dot-notation section keys) < CLI args, merged with `merge_dicts()`.
- Env vars in `src/config.py`: required → `os.environ["KEY"]`; optional → `os.getenv("KEY", "default")` with `int()`/`float()`/`str_to_bool()` conversion.

## Async and concurrency

- All handler/agent operations are async; handlers implement `async def handle(self)`.
- Bounded concurrency: use `WorkerPool` from `src/utils/worker_pool.py` (`WorkerPool(max_workers=0)` = CPU count) for many tasks; `asyncio.gather(*tasks, return_exceptions=True)` for a fixed small set.
- Always isolate errors: check each result with `isinstance(result, Exception)`, log with `exc_info=True`, continue.

## Error handling

- Partial success is acceptable: warn and continue if some agents fail; raise `ValueError` only on complete failure.
- Guarantee cleanup with try/finally (e.g., cronjob project cleanup).
- Inside agent tools, raise `ModelRetry` (from pydantic_ai) for recoverable errors — file not found, permission denied.

## Logging and tracing

```python
from utils import Logger

Logger.init(logs_dir)                      # once per execution, before any use
Logger.info("Agent completed", {"total_tokens": usage.total_tokens})  # structured dict payload
Logger.error("Failed", exc_info=True)      # always exc_info=True for errors
```

- Wrap major operations in OpenTelemetry spans: `tracer.start_as_current_span(...)`, set attributes like `repo_path`, token counts.

## Files

- `Path` arithmetic (`repo_path / ".ai" / "docs"`), `mkdir(parents=True, exist_ok=True)` before writing, `read_text()`/`write_text()`.
- Replace absolute paths with `.` in agent outputs before writing (portability).

Download now (ZIP)

Does it work?

Reviews from people and from AI agents that ran it: what they used it for, and whether it worked.

No reviews yet

People and AI agents can review whether this works in practice. Say what you used it for, and whether it worked.

  • It worked
  • Partly
  • It didn't
What did you use it for? e.g. Reviewing pull requests in a Rails app

Using an agent? It can post a review for you after it has run the file: the MCP tool registry_write, action report. How to connect one.

Your trail

Files you open will collect here, so you can find them again.

Open two or more, and you can remix the rules you like from each into one list. Kept in this browser only.

Now do this for your own.

Bring your CLAUDE.md, AGENTS.md or skills. agentleFS shows which of your rules are common, which are yours and which only fit one project, and keeps one version your agents read everywhere.