# Coding conventions

How AlphaAvatar's Python reads. The models are `avatar-core/alphaavatar/core/perception/runtime.py` and the Memory plugin (`MemoryRuntime`, `MemoryStore`, `MemoryContextState`, `PassiveRecall`).

## Code order

Modules and classes read top to bottom, every name defined before it is used:

- A module starts with its license header and `from __future__ import annotations`, then imports grouped standard library, third party, `alphaavatar` absolute, relative; imports for typing alone go under `TYPE_CHECKING`. Its private helpers and private classes come before the public code that uses them.
- A class is ordered: its one-line docstring, class constants (`_UPPER_CASE`, grouped by purpose), `__init__`, properties, static methods, then its other methods.
- Define a function before the code that calls it: a private method above the methods that call it. Mutually recursive functions are the one exception.
- Private methods come before public ones, unless the class is divided into functional areas by section strings such as `"""Source state operations"""` or `"""Runtime operations"""`; within each area the order holds again.
- Lifecycle comes last: the private implementation (`_start`, `_stop`, `_close`) before its public entry (`start` and `stop`, or `on_start` and `on_stop`).
- A method that must run with a lock held ends in `_locked`; a background loop is `_consume_*`; a task's done callback is `_*_done` or `_observe`.

A class divided into areas, for example:

```python
class PerceptionRuntime:
    """Session-scoped full-duplex perception runtime."""

    _MAX_SPEECH_SOURCES = 256

    def __init__(self, *, session_id: str, clock: RuntimeClock | None = None) -> None: ...

    @property
    def has_active_speech(self) -> bool: ...

    """Helper"""

    def _publish_event_locked(self, ...) -> PerceptionEvent: ...

    """Cutoff operations"""

    def _capture_cutoff_locked(self) -> PerceptionCutoff: ...

    def capture_cutoff(self) -> PerceptionCutoff: ...
```

## Data types, enums and configuration

A package keeps its data types and enums apart from the code that works with them:

- A class that carries data rather than behavior goes in the package's `schemas/` subpackage, one module per topic (`schemas/report.py`, `schemas/session.py`): a dataclass, a `NamedTuple`, a pydantic model of a record or message. A method that only reads or converts its own data, such as `to_dict`, does not change that.
- An enum (`Enum`, `StrEnum`, `IntEnum`) goes in the package's `enums/` subpackage the same way. A fixed set of states or kinds is an enum, not a `Literal` of strings.
- Each subpackage's `__init__.py` re-exports its names with `__all__`, and other modules import them from the subpackage: `from .schemas import Report`, `from ..enums import CheckStatus`.
- A class with behavior and an exception stay in the module that owns them.
- Configuration is not a schema: configuration models, and the configuration objects built from them such as `ApplicationConfig`, stay with their owner. A configuration that serves only its own directory, such as a processor's, is that directory's `config.py`. One that other configuration composes, or that has to be told apart from others, is named for what it configures, `<topic>_config.py`: `avatar_config.py` and `runtime_config.py` in `alphaavatar.agents.configs`, `host_config.py` beside the Host application.
- A module named `config.py` or `<topic>_config.py` defines configuration, and holds besides only the logic that processes what it defines, such as reading or normalizing its values. Other operations do not belong in it: a module that holds them, or defines no configuration, is named for what it does. `utils/vdb/backend.py` (a vector store's backend, the package it needs, its embeddings and its directory) is an example, not `utils/vdb/config.py`.

`alphaavatar.core.session` and `alphaavatar.host.tools.doctor` are laid out this way.

## Constructor fields

An `__init__` that sets more than a handful of fields groups them by purpose: borrowed services and settings, identity, budgets, the state being worked on, lifecycle. Each group is preceded by a blank line and a one-line comment naming what the group holds. The first group follows the signature directly, without a blank line. A field built from another comes after it, in the groups and within each. For example, `LoopExecution` in the Loop plugin:

```python
    def __init__(self, request: LoopRequest, ...) -> None:
        # The run (its run, Turn and context IDs), its request and settings, and what it borrows.
        self._identity = LoopIdentity(uuid4().hex, request.turn_id, request.context_id)
        self._request = request
        self._runtime = runtime

        # Its limits, and the options its model requests start from.
        self._budget = ExecutionBudget(request, asyncio.get_running_loop().time())
        self._generation_options = self._budget.options(config.reasoning, finalizing=False)

        # Lifecycle: why it is cancelled, whether its task has begun, and its one shared close.
        self._cancel_reason: str | None = None
        self._started = False
        self._close_task: asyncio.Task[None] | None = None
```

## Function bodies

Inside a function, blocks that do clearly different things, or each span several lines, are
separated by a blank line. A comment is not required: a block gets one short comment only where
it stands clearly apart and its purpose is not plain from the code; one that repeats the code or
the docstring is left out. For example, `_vertex` in the Provider plugin:

```python
def _vertex(kwargs: dict) -> bool:
    """Whether the Google SDK authenticates through Vertex AI, as it decides itself: its
    ``vertexai`` setting, else GOOGLE_GENAI_USE_VERTEXAI, else a project or credentials given.
    Vertex AI takes its own credentials (ADC) and needs no API key."""
    from pydantic import TypeAdapter, ValidationError

    # Its own setting first, parsed as the SDK's ``bool | None`` field parses it: "false",
    # "0", "no" or "off", as an interpolated setting gives them, are False.
    try:
        vertexai = TypeAdapter(bool | None).validate_python(kwargs.get("vertexai"))
    except ValidationError:
        return True  # Not a flag: the SDK refuses it, by its own name, before any key is read.
    if vertexai is not None:
        return vertexai

    chosen = os.getenv("GOOGLE_GENAI_USE_VERTEXAI", "").lower()
    if chosen in ("true", "1", "yes", "false", "0", "no"):
        return chosen in ("true", "1", "yes")

    return kwargs.get("project") is not None or kwargs.get("credentials") is not None
```

A guard, an `if` that returns, raises, continues or breaks, stays with the value it checks:
the statement that produces the value and the guards after it are one block, with no blank line
inside. The code that goes on past them begins the next block, after a blank line. Guards followed
only by the one-line `return`, `raise`, `continue` or `break` that ends the same decision stay one
block. In `_vertex`, the `try` produces `vertexai` and its checks follow it directly; `chosen`, the
next source, starts after a blank line.

Examples, each the wrong way first.

**Each value with its guard, a blank line after the guards.** Not:

```python
if (client := _client(report)) is None:
    return NO_HOST
status, answer = client.call("POST", "/v1/avatar/stop")

if status != 202:
    _refused(report, answer)
    return 1
report.pending("Stopping…")
```

But:

```python
if (client := _client(report)) is None:
    return NO_HOST

status, answer = client.call("POST", "/v1/avatar/stop")
if status != 202:
    _refused(report, answer)
    return 1

report.pending("Stopping…")
```

**The same inside a loop.** Not:

```python
for key, item in items:
    if key in seen:
        continue
    seen.add(key)
    kept.append(item)
```

But:

```python
for key, item in items:
    if key in seen:
        continue

    seen.add(key)
    kept.append(item)
```

**A decision stays one block.** Not:

```python
if source.default:
    return f"alphaavatar {name}"

return f"alphaavatar {name} {source.bundle}"
```

But:

```python
if source.default:
    return f"alphaavatar {name}"
return f"alphaavatar {name} {source.bundle}"
```

**A comment says what the code does not.** Not:

```python
# Copy the environment.
environ = dict(os.environ)
```

But:

```python
environ = dict(os.environ)  # Before the .env file and any credentials fill it.
```

The shell scripts under `packaging/` and `scripts/` follow the same rule.

Code being changed follows these rules; code nobody touches is not reordered for them alone.
