aiocortex 0.3.0
Async Python library for Home Assistant configuration management
Requires Python: >=3.12

# aiocortex

Async Python library for Home Assistant configuration management. Provides git versioning (via dulwich), file management, YAML editing, and Pydantic models — all independent of Home Assistant internals.

This library is the core engine behind the [Cortex](https://github.com/ruaan-deysel/ha-cortex) HACS integration.

## Installation

```bash
pip install aiocortex
```

## Features

- **Git versioning** — Shadow git repository for HA config backups using [dulwich](https://www.dulwich.io/) (pure Python, no git binary required)
- **File management** — Async file operations with path security (directory traversal prevention)
- **YAML editing** — Safe YAML read/write/parse utilities + semantic patch preview/apply helpers
- **Pydantic models** — Typed data models for automations, scripts, helpers, files, git commits
- **Transactions** — Durable plan/apply/abort flow with rollback metadata for multi-step config changes
- **AI Instructions** — Bundled markdown instruction docs for AI-powered HA management (sync & async loaders)

## Quick Start

```python
from aiocortex import AsyncFileManager, GitManager, YAMLEditor

# File operations
file_mgr = AsyncFileManager(config_path=Path("/config"))
files = await file_mgr.list_files("", "*.yaml")
content = await file_mgr.read_file("automations.yaml")

# Git versioning
git_mgr = GitManager(config_path=Path("/config"), max_backups=30)
await git_mgr.init_repo()
await git_mgr.commit_changes("Add automation: motion sensor light")
history = await git_mgr.get_history(limit=10)

# Transaction operations
tx = await git_mgr.begin_transaction({"request": "update automation"})
await git_mgr.stage_file_write(tx.transaction_id, "automations.yaml", "- id: motion_1\n")
validation = await git_mgr.validate_transaction(tx.transaction_id)
if validation.valid:
    await git_mgr.commit_transaction(tx.transaction_id, "Apply automation updates")

# YAML editing
editor = YAMLEditor()
result = editor.remove_yaml_entry(content, "- id: 'old_automation'")

# Semantic YAML patch preview
from aiocortex.models import YAMLPatchOperation
preview = editor.preview_patch(
    content,
    [YAMLPatchOperation(op="set", path=["homeassistant", "name"], value="New Name")],
)
```

## Architecture

```text
aiocortex/
├── git/            # GitManager, sync, filters, cleanup (dulwich-based)
├── files/          # AsyncFileManager, YAMLEditor
├── instructions/   # AI instruction docs & loaders (sync + async)
├── models/         # Pydantic v2 models (common, config, files, git)
└── exceptions.py   # CortexError hierarchy
```

### Design Principle

If it imports `homeassistant.*`, it does **not** belong here. This library contains only HA-independent logic. The Cortex integration handles all HA-specific concerns (states, services, registries, auth, HTTP routing).

## Models

```python
from aiocortex.models import (
    AutomationConfig,   # Automation definition
    ScriptConfig,       # Script definition
    HelperSpec,         # Input helper specification
    ServiceCallSpec,    # Service call parameters
    FileInfo,           # File metadata
    FileWriteResult,    # Write operation result
    CommitInfo,         # Git commit metadata
    PendingChanges,     # Uncommitted changes
    CortexResponse,     # Standard API response
)
```

## Dependencies

- `pydantic>=2.0` — Data validation and models
- `pyyaml>=6.0` — YAML parsing
- `aiofiles>=23.0` — Async file I/O
- `dulwich>=0.22.0` — Pure Python git implementation

## Instructions

Bundled AI instruction documents can be loaded synchronously or asynchronously:

```python
from aiocortex import (
    load_all_instructions,          # sync
    async_load_all_instructions,    # async
    get_instruction_files,          # list available docs
)

# Sync — fine at startup
instructions = load_all_instructions(version="1.0.0")

# Async — preferred inside the HA event loop
instructions = await async_load_all_instructions(version="1.0.0")
```

## Development

```bash
git clone https://github.com/ruaan-deysel/aiocortex.git
cd aiocortex
python -m venv .venv && source .venv/bin/activate
pip install -e ".[dev]"
pytest --cov=aiocortex
```

## Contract Changes (0.3.0)

- Public file/git manager methods now return strongly typed Pydantic models instead of raw dicts.
- Consumers should migrate from dictionary key access to attribute access.

## License

MIT