|
| 1 | +"""The repository interface: the abstraction over persisted task state. |
| 2 | +
|
| 3 | +A backend-agnostic interface (ADR 0001/0006). The task service is its sole owner and the |
| 4 | +single writer; adapters implement it (in-memory and SQLite in this slice; Postgres later). |
| 5 | +
|
| 6 | +Integrity rules every adapter must enforce — the "transition enforcement at the boundary": |
| 7 | +
|
| 8 | +* ``create_task`` — the task id is unique, its ``repo_id`` exists, its history is |
| 9 | + non-empty, and ``state`` equals the last history entry's ``to_state``. |
| 10 | +* ``save_task`` — the task exists, its history is **append-only** (the stored history is a |
| 11 | + prefix of the supplied one), and ``state`` equals the last history entry's ``to_state``. |
| 12 | +
|
| 13 | +The *legality* of a transition (which state may follow which) is decided by the engine |
| 14 | +before save; the repository guarantees the persisted record stays internally consistent. |
| 15 | +""" |
| 16 | + |
| 17 | +from __future__ import annotations |
| 18 | + |
| 19 | +from abc import ABC, abstractmethod |
| 20 | +from collections.abc import Sequence |
| 21 | + |
| 22 | +from panopticon.core.models import HistoryEntry, Repo, Task |
| 23 | + |
| 24 | + |
| 25 | +class RepositoryError(Exception): |
| 26 | + """Base class for repository failures.""" |
| 27 | + |
| 28 | + |
| 29 | +class NotFound(RepositoryError): |
| 30 | + """Raised when an entity referenced by id does not exist.""" |
| 31 | + |
| 32 | + |
| 33 | +class AlreadyExists(RepositoryError): |
| 34 | + """Raised when creating an entity whose id is already taken.""" |
| 35 | + |
| 36 | + |
| 37 | +class IntegrityError(RepositoryError): |
| 38 | + """Raised when a write would violate an integrity rule (e.g. non-append-only history).""" |
| 39 | + |
| 40 | + |
| 41 | +class Repository(ABC): |
| 42 | + """Persistence boundary for repos and tasks.""" |
| 43 | + |
| 44 | + # -- repos -------------------------------------------------------------------- |
| 45 | + |
| 46 | + @abstractmethod |
| 47 | + def create_repo(self, repo: Repo) -> None: |
| 48 | + """Persist a new repo. Raises :class:`AlreadyExists` if its id is taken.""" |
| 49 | + |
| 50 | + @abstractmethod |
| 51 | + def get_repo(self, repo_id: str) -> Repo | None: |
| 52 | + """Return the repo, or ``None`` if it does not exist.""" |
| 53 | + |
| 54 | + @abstractmethod |
| 55 | + def list_repos(self) -> list[Repo]: |
| 56 | + """Return all repos.""" |
| 57 | + |
| 58 | + # -- tasks -------------------------------------------------------------------- |
| 59 | + |
| 60 | + @abstractmethod |
| 61 | + def create_task(self, task: Task) -> None: |
| 62 | + """Persist a new task and its initial history. Enforces the create-time rules.""" |
| 63 | + |
| 64 | + @abstractmethod |
| 65 | + def get_task(self, task_id: str) -> Task | None: |
| 66 | + """Return the task (with full history), or ``None`` if it does not exist.""" |
| 67 | + |
| 68 | + @abstractmethod |
| 69 | + def list_tasks(self) -> list[Task]: |
| 70 | + """Return all tasks (with full history).""" |
| 71 | + |
| 72 | + @abstractmethod |
| 73 | + def save_task(self, task: Task) -> None: |
| 74 | + """Persist an updated task. Enforces the append-only and consistency rules.""" |
| 75 | + |
| 76 | + |
| 77 | +# -- Shared integrity checks (adapters call these so the rules live in one place) -------- |
| 78 | + |
| 79 | + |
| 80 | +def validate_task_invariants(task: Task) -> None: |
| 81 | + """Check a task is internally consistent: non-empty history, state matches its tail.""" |
| 82 | + if not task.history: |
| 83 | + raise IntegrityError(f"task {task.id!r} has empty history") |
| 84 | + if task.state != task.history[-1].to_state: |
| 85 | + raise IntegrityError( |
| 86 | + f"task {task.id!r}: state {task.state!r} != last history to_state " |
| 87 | + f"{task.history[-1].to_state!r}" |
| 88 | + ) |
| 89 | + |
| 90 | + |
| 91 | +def _facts(entry: HistoryEntry) -> tuple[str, str | None, str, str | None, str | None]: |
| 92 | + """An entry's transition facts — everything that is immutable once recorded.""" |
| 93 | + return (entry.at, entry.from_state, entry.to_state, entry.trigger, entry.note) |
| 94 | + |
| 95 | + |
| 96 | +def validate_append_only( |
| 97 | + stored: Sequence[HistoryEntry], incoming: Sequence[HistoryEntry] |
| 98 | +) -> None: |
| 99 | + """Check ``incoming`` only extends ``stored``. |
| 100 | +
|
| 101 | + Transition facts are immutable for every recorded entry. The sole permitted in-place |
| 102 | + change is the **current (last) entry's responsibilities**, which the agent fulfils over |
| 103 | + the course of that turn (the promise-on-entry model); once an entry is followed by another |
| 104 | + it is frozen. |
| 105 | + """ |
| 106 | + if len(incoming) < len(stored): |
| 107 | + raise IntegrityError("history shrank (not append-only)") |
| 108 | + for i, prev in enumerate(stored): |
| 109 | + cur = incoming[i] |
| 110 | + if _facts(prev) != _facts(cur): |
| 111 | + raise IntegrityError("existing history was modified (not append-only)") |
| 112 | + # Only the current entry's promises may still change; earlier entries are final. |
| 113 | + if i < len(stored) - 1 and list(prev.responsibilities) != list(cur.responsibilities): |
| 114 | + raise IntegrityError("a finalized entry's responsibilities were modified") |
0 commit comments