code-style

A set of Python coding rules covering naming, type hints, documentation, formatting, linting, and asynchronous input and output. It is specific to the ha_gitops Home Assistant integration.

In plain words
What is it for?
Use it when writing or reviewing Python in the integration, especially public methods, asynchronous code, imports, and formatting. It also guides Ruff, Black, and mypy checks.
Why use it?
It gives contributors consistent code conventions and helps catch style, type, and blocking-operation problems. The rules also describe which tools are used to check the code.

Cursor rule for Cursor

Install

Getting it into your agent

One page per mod, every tool's command on it. A separate URL per tool would split the same page into five that compete with each other.

agentmods
npx agentmods add rules/ckrl/ha-gitops/code-style
Clone the repo
git clone --depth 1 https://github.com/ckrl/ha-gitops

Made for: Cursor.

Per session 0 Nothing until a file matches its globs; then the whole rule loads.
When invoked 943 The whole file, excluding the scripts and references it only reads on demand.
Security scan A 1 finding. Scan, not verified.
Origin original No closer match found in the catalogue.
Token cost

What it costs to keep this loaded

Counted locally with the o200k_base tokenizer, which is exact for GPT models; Claude uses its own tokenizer and its counts differ. Treat this as one consistent yardstick across the catalogue rather than a bill. Prices are per million input tokens.

ModelPer sessionOnce invoked
Fable 5 $0.00000 $0.00943
Opus 5 $0.00000 $0.00472
Sonnet 5 $0.00000 $0.00189
Haiku 4.5 $0.00000 $0.00094

Measured yesterday against content hash e3658e9a81e5, method: parsed. Prices are Anthropic first-party input rates as of 2026-08-30, from the pricing page.

Security

Grade A, and why

code-style scanned grade A with 1 finding against 26 rules in 11 categories — prompt injection, anti-refusal, data exfiltration, privilege escalation, supply chain, agent snooping, system-prompt leakage, SSRF and excessive agency — measured yesterday.

A static scan of the body, not an audit. Every finding is printed with the line that produced it so you can judge whether it matters here. A mod is markdown that instructs an agent; that is exactly why what it instructs is worth reading.

Runs shell commandslowCapability

Expected in a hook, worth knowing in a rule or an instructions file.

- Свои исключения — в `git_manager.py`: `GitError(Exception)`, опционально `GitAuthError`, `GitConflictError`. Не пробрасывать `subprocess.CalledProcessError` наружу.
.cursor/rules/code-style.mdc · 99 lines

How it starts

The opening of the file, as written. The whole thing — 99 lines — stays where its author put it; the contents beside it link to each section on GitHub.

Code Style & Practices

Базовые правила

  • Python 3.11+, from __future__ import annotations в каждом модуле.
  • Type hints обязательны на всех публичных функциях/методах и dataclass-полях. PEP 604 (X | None) предпочтительнее Optional[X].
  • Имена: snake_case для функций/переменных, PascalCase для классов, UPPER_SNAKE для констант. DOMAIN всегда ha_gitops.
  • Docstring — короткий, императивно, на английском. Достаточно одной строки для тривиальных методов.
  • Не писать комментарии-нарративы (# increment counter). Комментарии — только про неочевидные намерения, ограничения, edge cases.

Lint & Format

  • ruff (lint + import sort) и black (format) — настраиваются в pyproject.toml. Line length: 100.
  • Включённые ruff-наборы (рекомендуется): E,F,W,I,N,UP,B,SIM,ASYNC,PTH,RUF.
  • mypy --strict для custom_components/ha_gitops/** — желательно, минимум без Any в публичном API GitManager.

Async & I/O

  • Все методы GitManagerasync def. Никаких sync-обёрток над async (asyncio.run в продакшен-коде запрещён).
  • Любой блокирующий вызов (file I/O, chmod, Path.write_text) — через await hass.async_add_executor_job(...).
  • subprocess — только asyncio.create_subprocess_exec с stdout=PIPE, stderr=PIPE. Никогда shell=True.

Errors & Logging

  • Логгер: _LOGGER = logging.getLogger(__name__) на уровне модуля.
  • Свои исключения — в git_manager.py: GitError(Exception), опционально GitAuthError, GitConflictError. Не пробрасывать subprocess.CalledProcessError наружу.
  • Wrap внешних ошибок: raise GitError(f"git push failed: {stderr.strip()}") from exc.
  • Уровни: DEBUG — argv git-команды (БЕЗ env), INFO — успешные операции, WARNING — recoverable (нечего push), ERROR — провал операции.
  • НЕ логировать: содержимое GIT_SSH_COMMAND, путь к ключу с токенами, stderr с возможными credentials.

Snippets (use these by default)

  • Логгер модуля:

    import logging
    _LOGGER = logging.getLogger(__name__)
    

Read the full file on GitHub · 99 lines

Changes

What this file has done since we first saw it

Hashed on every crawl. A supply-chain change to an agent config is a question of when, not whether, so the history is kept rather than the latest state alone.

  1. yesterday First seen · 99 lines · 0 tokens per session scan A e3658e9a81e5

Subscribe to this mod's changes

code-style is a cursor rule published in the GitHub repository ckrl/ha-gitops (4 stars, last pushed 3mo ago), licensed MIT. It costs nothing until one of its globs matches a file; then it loads 943 tokens. A static security scan graded it A with 1 finding (runs shell commands). No closer match exists in the catalogue, so it is treated as the original; first seen 2026-08-31.