# Durable Task Store Service

## PURPOSE
A standalone persistence + integration service that implements the storage contract Pi
Durable relies on: `Task`, `Checkpoint`, `Conversation`, and `Submission` tables in
SQLite via SQLAlchemy, plus an `httpx` client that talks to a local llama.cpp server
(OpenAI-compatible `/v1/chat/completions`) or any hosted model endpoint. It is the piece
that lets an agent "pick up where it left off" after a crash.

## WHY THIS MATTERS
The video stresses that Pi Durable "ships a harness class" backed by storage — and that
SQLite is the recommended backend for production (JSONL and in-memory also exist, but
memory is erased on exit and is really just for experimentation). It also stresses model
portability: you configure a model provider adapter (the speaker used a llama.cpp server
running a tiny model, plus an OpenAI key) so you are not locked to one vendor. This
service isolates exactly those two concerns — durable state and model access — behind a
clean repository API.

## HOW TO BUILD
1. Declare SQLAlchemy models with relationships:
   `Conversation -> Task -> Checkpoint`, and a `Submission` row per `submit()`.
2. `DurableStore` exposes `create_conversation`, `submit`, `write_checkpoint`,
   `mark_complete`, and `resume_incomplete()` (returns tasks with a pending checkpoint).
3. `ModelClient` wraps `httpx.AsyncClient` against the base URL, with a deterministic
   stub when `DRY_RUN=1`.
4. A `run_task()` loop writes a checkpoint after each tool step so a crash is safe.

```python
def resume_incomplete(self):
    return (self.session.query(Task)
            .filter(Task.status.in_(["running", "interrupted"]))
            .all())  # daemon re-reads these after a restart
```

## WHEN TO USE IN PRODUCTION
Use it as the durable core of an always-on assistant reachable over Slack, email, or
Telegram, where the process may be killed at any moment. It also fits batch jobs that run
for hours or days: submit once, poll the submission record, resume on restart. Do NOT use
it as the model-serving layer itself — point it at llama.cpp or a hosted API. Do not use
it for short-lived interactive sessions where a plain JSONL session file is sufficient.

## HOW IT HELPS STUDENTS
Students practice relational schema design for agent state, SQLAlchemy sessions and
relationships, safe checkpointing order (write-ahead before the side effect), and async
HTTP integration with `httpx`. They learn the production habit of separating a durable
store from the agent loop so recovery is a property of the storage, not the process.

## STARTER CODE
See `starter/main.py` for models, a store, an httpx model client with a dry-run stub, and
a `resume_incomplete()` demo. TODO markers show where to add retries and migrations.
