# System Instructions

This prompt is divided into three sections:

1. **System Instructions** (this section) — structural orientation only. Do not treat this
   section as task input.

2. **Input Context** — begins with the heading `# Input Context`. All blocks are wrapped in
   `<pblock>` tags. Two block types:
   - File blocks: `<pblock filename="<name>" role="<role>" guidance="...">` — optional
     `guidance` attribute carries context-specific instructions; content is in a fenced block.
   - Metadata/section blocks: `<pblock label="<label>" kind="<kind>">` — job parameters,
     rules, instructions, or group headers.

3. **Agent Task** — begins with the heading `# Agent Task`. Defines your persona, constraints,
   and required outputs. Read all input context before acting on this section.


# Input Context

<pblock label="Build block job" kind="job">
## Build block job
- TARGET: ReadingList
- BUILD_DIRECTORY: /mnt/c/Users/barlo/projects/drydock/uat/ReadingList/runs/20261023.210132/build/ReadingList
- WORKING_DIRECTORY: /mnt/c/Users/barlo/projects/drydock/uat/ReadingList/runs/20261023.210132/build/ReadingList
- BUILD_BLOCK: Block 4 · Service (block-4)
- STORIES: Serve the ordered reading-list view. (reading-list), Add a valid book to the reading list. (add-book), Remove a selected book from the reading list. (remove-book), Reject incomplete book submissions with correction feedback. (validate-book)
- DATE: 2026-10-23
- BUILD_SCOPE: exactly one MANIFEST.md build block

</pblock>

<pblock label="Stories in this block" kind="section">
## Stories in this block
- Serve the ordered reading-list view. (reading-list) [story]
- Add a valid book to the reading list. (add-book) [story]
- Remove a selected book from the reading list. (remove-book) [story]
- Reject incomplete book submissions with correction feedback. (validate-book) [story]

</pblock>

<pblock label="Files on disk" kind="section">
## Files on disk in the build directory
- sources/full_test.sh

These are the only imported files present on disk. Every other file named in this prompt is supplied as prompt context and is not on disk; read it here and do not report it as a missing input.

</pblock>


## COMPASS - Target Orientation

<pblock filename="COMPASS.md" role="compass" path="/mnt/c/Users/barlo/projects/drydock/uat/ReadingList/runs/20261023.210132/workspace/targets/ReadingList/COMPASS.md" guidance="Important: This is the core project intent, constraints, and guardrails. It should have presecedence in conflicts.">
```markdown
# COMPASS: ReadingList

## Compass

ReadingList is a small web application for readers who want to maintain a personal list of books to read. A reader can add books with titles and authors, view them in insertion order, and remove them. The application must be easy to exercise through its primary web page and fully verifiable through its supplied test runner.

## Constraints

- The delivered `bin/test.sh` must be POSIX-compatible.
- `sh bin/test.sh` is the complete automated test command.
- The test runner must exit zero only when every automated test passes.
- Use local relational persistence suitable for repeatable automated tests.
- Preserve the order in which books are added.

## Guardrails

- Never store or display a book with an empty title or author.
- Always report a clear reason when validation rejects a submission.
- Never silently reorder books.
- After removal, do not show the removed book on the next read.
- Keep every described behavior covered by automated tests.

<!-- drydock:build-write-guardrail:start -->
## Build Write Guardrail

- Authorized build directory: `/mnt/c/Users/barlo/projects/drydock/uat/ReadingList/runs/20261023.210132/build/ReadingList`
- Authorized Target directory: `/mnt/c/Users/barlo/projects/drydock/uat/ReadingList/runs/20261023.210132/workspace/targets/ReadingList`
- Build agents have permission to create, modify, and remove files required by the active build block inside these authorized directories.
- No path outside these authorized directories may be modified.
- Protected Drydock artifacts:
  - `/mnt/c/Users/barlo/projects/drydock/uat/ReadingList/runs/20261023.210132/workspace/targets/ReadingList/blueprint/`
  - `/mnt/c/Users/barlo/projects/drydock/uat/ReadingList/runs/20261023.210132/workspace/targets/ReadingList/MANIFEST.md`
  - `/mnt/c/Users/barlo/projects/drydock/uat/ReadingList/runs/20261023.210132/workspace/targets/ReadingList/COMPASS.md`
  - `/mnt/c/Users/barlo/projects/drydock/uat/ReadingList/runs/20261023.210132/workspace/targets/ReadingList/QuarterDeck/`
  - `/mnt/c/Users/barlo/projects/drydock/uat/ReadingList/runs/20261023.210132/workspace/targets/ReadingList/evidence/`
<!-- drydock:build-write-guardrail:end -->
```
</pblock>


## STACK - Technology HOW

<pblock filename="python_compact.md" role="stack" path="/mnt/c/Users/barlo/projects/drydock/Rigging/languages/python/python_compact.md">
```
<!-- Compacted from Rigging/languages/python/python.md sha256=fe344456a351e3237cfe3bae2408a69758d401430b935f60c15f91b9a97e8016 on 2026-10-18 by Rigging maintenance -->

## Foundation Contract

- source_root: ./
- test_command: pytest -q
- environment: `.venv`, created by `uv venv` and activated by launchers in `bin/`
- dependencies: `pyproject.toml` and committed `uv.lock`

The language foundation owns the project root, environment, dependency manifest, and test runner.
Later foundations add their packages to this tree without replacing those contracts.

### How do we execute and measure Acceptance Criteria in this language?

An Acceptance Criterion (AC) is an executable check of Blueprint-required behavior. Use the
existing Programmatic Acceptance format: a Python script with assertions against the built
product. Drydock executes each criterion through `languages/python/acceptance/runner.py`; `pytest -q`
runs the project test suite. Retain the criterion ID, observed values, stdout/stderr and result;
an assertion failure fails the check. The harness reports failure operands and available case
counts. Code coverage and persistence interactions require explicit instrumentation; record
available observations as key/value data associated with the criterion. Missing observations
are unknown, not proof that code or an interaction was unused.

### How does this language provide the shared persistence contract?

Use `stack/persistence.md`. Drydock copies `Rigging/languages/python/persistence/{db,sqlite,postgres}.py` and generates
`persistence/{schema,__init__,testing}.py` plus `schema.sql` from `DATABASE.md`. Call
`open_database(dsn)` and `db.<table>.<operation>(...)`; use `persistence.testing.db_session()`
for criteria. SQLite uses the standard library; PostgreSQL needs `psycopg[binary]` in the project
dependencies. Both engines ship together and the DSN selects the engine. Library verification
lives in `tests/test_shipped_database.py`; a Target still verifies its own schema and operations.

## Consumer Rules

- Python >=3.11; use modern type hints on public interfaces and named cross-package data shapes.
- Centralize typed runtime settings; use Blueprint names and defaults. Keep secrets out of Git and logs.
- Keep behavior in importable modules; launchers activate `.venv` and invoke modules.
- Use pytest with isolated external state; all test gates run `pytest -q`.
```
</pblock>

<pblock filename="flask.md" role="stack" path="/mnt/c/Users/barlo/projects/drydock/Rigging/stack/flask.md">
````
# Flask Foundation

**Type:** web-server
**Version:** 20260922 V3
**Tier:** platform
**Category:** Web Server
**Foundation:** web-server
**Description:** Flask application boundary and test client contract

Prerequisites: `stack/common.md`, `languages/python/python.md`

## Foundation Contract

- package: app_server
- entry: create_app() -> Flask
- fixture: web_client
- fixture_source: app_server/testing.py

```python
# app_server/__init__.py
def create_app() -> Flask: ...

# app_server/testing.py
from app_server import create_app
def web_client():
    app = create_app()
    app.config["TESTING"] = True
    return app.test_client()
```

`app_server.testing.web_client()` is a plain callable used directly by programmatic acceptance.
The pytest `web_client` fixture delegates to it. The application factory registers the selected
Blueprint routes, extensions, and error handlers; it does not invent routes or settings.

## Rules

- Group related routes in Flask Blueprints. Keep handlers focused on HTTP input and output; put
  business behavior in importable services without a Flask dependency.
- Load configuration through the Python foundation's typed boundary before use. Use the Target's
  names and defaults. Keep `SECRET_KEY` out of source control and disable debug mode in production.
- Use the Blueprint's routes, schemas, templates, and error contracts. Return sanitized errors;
  never expose tracebacks to clients. Preserve Jinja autoescaping.
- Keep request-bound resources request-scoped. Do not share a SQLite connection or other
  thread-bound object created in `create_app()` across request threads.
- Keep startup side effects out of imports and account for the development reloader's extra
  process. The Python foundation owns launchers, dependencies, and the test command.
````
</pblock>

<pblock filename="persistence.md" role="stack" path="/mnt/c/Users/barlo/projects/drydock/Rigging/stack/persistence.md">
````
# Persistence & Service Encapsulation

**Type:** guidance
**Version:** 20260919 V3
**Category:** Persistence
**Description:** The single boundary rule for all persistent stores and external services — typed access classes, no raw access in application code

Technology reference. Framework-agnostic. This file does not change between projects.

Prerequisite: `stack/common.md`

---

## The Invariant

**Rule**: All persistence and external-service access goes through a typed encapsulation
class. Route, feature, and business-logic code never executes raw SQL, reads `os.environ`,
opens application files directly, or imports a cloud SDK (`boto3`). The typed class interface
— not the underlying schema or service — is the dependency boundary.

**Why**: A storage or service change is absorbed at the class. Downstream code depends on the
interface, so a schema change that does not change the interface changes nothing else. This is
the same swap-layer discipline a cloud client library enforces for AWS (`import boto3`
outside the wrapper fails review), generalized to every store.

A code review that finds raw SQL, `os.environ`, `open()` on application data, or a cloud SDK
import outside its encapsulation class fails.

**Relational rule**: the relational layer is generated, not written. Drydock emits it from
`DATABASE.md` and copies the engines in unchanged; the build writes callers. See section 1.

---

## 1. Relational stores → the generated persistence package

**You do not write this layer.** Drydock generates it from `DATABASE.md` at the DATABASE build
step and copies the engines in unchanged. Writing a repository, a connection helper, a session
factory, or a migration by hand is a review failure: the generated package already implements the
declaration, and a hand-written second path is storage access no Blueprint cites.

The build writes **callers**.

```text
route → service → db.<table>.<verb>(...) → generated package → database
```

Language bindings are shipped in `languages/<language>/persistence/`; generation templates live
beside them in `templates/`. Python and Go implement the same declared operations. The language
instructions own native names, dependencies and fixtures. Go uses `OpenDatabase(ctx, dsn)` and
generated typed repository methods; the Python examples below use `open_database(dsn)`.

The Python package lands at `persistence/` in the build:

| File | Origin |
|---|---|
| `db.py`, `sqlite.py`, `postgres.py` | shipped by Drydock, copied unchanged |
| `schema.py` | generated from `DATABASE.md` — tables, operations, row dataclasses |
| `schema.sql` (beside the package) | generated DDL, applied once at the DATABASE step |

### Calling it

```python
from persistence import open_database

db = open_database(config.database_url)

ticket = db.tickets.get(id=ticket_id)          # returns a frozen dataclass, or None
open_tickets = db.tickets.list(status="open")  # returns a list of them
new_id = db.tickets.create(status="open", title=title)
db.tickets.update(id=ticket_id, status="closed")
db.tickets.delete(id=ticket_id)
```

One attribute per declared table, one method per declared access pattern. The method name is the
verb of that pattern's `Repository operation` cell, and its keyword arguments are that pattern's
`Input:` fields — nothing else is accepted. A verb the table does not declare raises
`UnknownOperation` naming what it does grant.

**The declaration fixes the surface.** `DATABASE.md` names every operation in the
`Repository operation` cell of each access pattern, as `<table>.<verb>`. That is the persistence
surface, not a suggestion for one. To reach the store differently, change the declaration and
rebuild; there is no second door.

**Why**: the declaration is the only description of the store the rest of the plan is allowed to
depend on. Generating from it means the operations a Blueprint cites and the operations that exist
cannot drift — they are the same list. Plan already refuses to write a plan whose tables,
operations, and citations disagree; generating the layer keeps the built code in that agreement
rather than trusting each build to re-derive it from prose.

**Caller contract**: `Database` presents single-threaded semantics. Callers construct one instance,
share it freely, call methods synchronously, and never reason about threads, connections, or
locking. Connection lifetime is internal to the package and may change without affecting any
caller. Returned rows are frozen dataclasses and carry no connection state.

**Engine selection is runtime, not build time.** Both engines are copied into every build and
chosen from the DSN, because the same build runs SQLite in development and test and PostgreSQL in
production. `VARCHAR(n)` is declared once and emitted to both: PostgreSQL enforces the length,
SQLite parses the same declaration and ignores it.

**Schema is built once.** `schema.sql` is applied at the DATABASE build step and never again
within a release. Application startup does not create or alter schema.

**Guardrails**

- Do not write a repository, DAO, ORM model, or session factory.
- Do not import `sqlite3`, `psycopg`, or a SQL string anywhere outside `persistence/`.
- Do not edit anything under `persistence/` — edit `DATABASE.md` and rebuild.
- Do not create or alter schema at application startup.

### Acceptance transactions

**Acceptance store lifecycle.** The DATABASE step provisions and verifies the configured store
once. Criteria never replace DATABASE_URL/DATABASE_PATH, create a temporary database, apply DDL,
or assume an empty store. Database criteria use `with db_session() as db:` (Go:
`OpenSession(ctx, "")` with checked deferred cleanup) and pass that same database into feature
operations. Setup, behavior and assertions run inside one transaction; the shipped fixture always
rolls it back. Application operations outside that scope remain autocommitted. Never commit,
close the owned connection, or open another connection inside the rollback scope.

HTTP, CLI/subprocess, background-work and commit/restart criteria use committed behavior instead.
Use `persistence.testing.committed_session()` (Go: `OpenCommittedSession(ctx, "")`) for
setup/readback/cleanup on the configured store; this helper closes connections, not business records.
Each owns a stable criterion-specific identifier, reconciles only its own residue before setup,
asserts setup success, checks only owned records, and uses `try/finally` (Go: checked `defer`) for
cleanup through supported product interfaces. Cleanup failure fails the criterion; retries must
work even when prior cleanup never ran. Immutable ledger records remain identified or receive
supported reversal entries; never delete history or reset a shared store. Include independent
commit/reconnect durability coverage. Database acceptance must not be replaced by a project test
count: runtime catalog and row-count evidence proves provisioning, feature criteria prove behavior.

## 2. Config / `.env` → one typed Config class

One typed `Config` reads the environment once and validates at startup. Nothing else reads
`os.environ`. There are no `Dev`/`Prod`/`Test` subclasses — every field is inherited from the
environment, so the environment (`.env`) selects the configuration, not a Python subclass.

```python
# config.py
import os
from dataclasses import dataclass
from dotenv import load_dotenv
load_dotenv()

@dataclass(frozen=True)
class Config:
    secret_key: str
    database_path: str
    port: int
    debug: bool = False

    @classmethod
    def load(cls) -> "Config":
        try:
            return cls(
                secret_key=os.environ["SECRET_KEY"],
                database_path=os.environ.get("DATABASE_PATH", "data/app.db"),
                port=int(os.environ.get("APP_PORT", "5001")),
                debug=os.environ.get("APP_DEBUG") == "1",
            )
        except KeyError as e:
            raise RuntimeError(f"Missing required env var: {e}") from e
```

Typed fields mean a missing or malformed variable crashes at startup, not at first use.

---

## 3. Files → typed FileStore class

A `FileStore` owns a root directory and is the only code that opens application files. Callers
never build paths or call `open()`/`shutil` directly.

```python
# filestore.py
from pathlib import Path

class FileStore:
    def __init__(self, root: str): self._root = Path(root)
    def read(self, name: str) -> str:
        return (self._root / name).read_text(encoding="utf-8")
    def write(self, name: str, data: str) -> None:
        p = self._root / name; p.parent.mkdir(parents=True, exist_ok=True)
        p.write_text(data, encoding="utf-8")
    def list(self, pattern: str = "*") -> list[str]:
        return [p.name for p in self._root.glob(pattern)]
```

Path-traversal validation and atomic writes live here, once.

---

## 4. External services → wrapper modules over a shared base class

Every external-service wrapper extends one `ServiceClient` base class. The base owns the
backend handle, a named logger, and a uniform call guard; subclasses expose typed methods and
never leak the SDK client.

```python
# service.py — base class for all external-service wrappers
import logging

class ServiceClient:
    """Base for service wrappers. Owns the backend handle, logger, and a uniform
    call guard. Subclasses expose typed methods; they never expose the SDK client."""
    def __init__(self, backend, name: str | None = None):
        self._backend = backend
        self.log = logging.getLogger(name or type(self).__name__)

    def _guard(self, op, *args, **kwargs):
        try:
            return op(*args, **kwargs)
        except Exception:
            self.log.exception("%s call failed", type(self).__name__)
            raise
```

Wrappers subclass it. AWS commonly uses a project-owned cloud client library
(`client.queue`, `client.share`, `client.catalog`); any new service follows the same shape — e.g.
a `MessageBus` over SQS, even when it maps 1:1:

```python
# messagebus.py — the wrapper hides the transport
class MessageBus(ServiceClient):
    def publish(self, topic: str, payload: dict) -> str:
        return self._guard(self._backend.send, topic, payload)
    def subscribe(self, topic: str, handler) -> None: ...
```

**Why**: the base class makes logging and error handling uniform across services; the wrapper
is the seam. Swapping the transport, or stubbing it in tests, changes one class. See
`stack/cloud-client-library.md`, `stack/aws-sqs.md`, `stack/aws-s3.md`, `stack/aws-dynamodb.md`.

---

## Summary Checklist

- [ ] No hand-written repository, DAO, ORM model, session factory, or migration
- [ ] No raw SQL, `sqlite3`, or `psycopg` import outside the generated `persistence/` package
- [ ] Nothing under `persistence/` edited by hand
- [ ] No schema created or altered at application startup
- [ ] No `os.environ` reads outside the Config class
- [ ] No `open()`/`shutil` on application data outside FileStore
- [ ] No cloud SDK import outside its service wrapper
- [ ] One typed `Config`, ENV-driven, no Dev/Prod/Test subclasses
- [ ] Service wrappers extend the `ServiceClient` base class
- [ ] Downstream specs depend on the declared operations, not the schema
````
</pblock>


## CONTEXT - Read-Only Support

<pblock filename="ARCHITECTURE_compact.md" role="context" path="/mnt/c/Users/barlo/projects/drydock/uat/ReadingList/runs/20261023.210132/workspace/targets/ReadingList/blueprint/ARCHITECTURE_compact.md">
```
<!-- Compacted from ARCHITECTURE.md sha256=b6aaa721727d6d785b4ddbf830818102584f78446b4f2e57ba1bfddb1dfa554a on 2026-10-23 by drydock build agent -->

Provides `app_server.create_app()` and `app_server.testing.web_client()`. The factory composes feature-owned Flask Blueprints; feature routes own HTTP workflows, while generated `persistence` owns storage. Required routes: `GET /`, `POST /books`, and `POST /books/<book_id>/delete`. Configuration belongs to `app_server`; the primary workflow is reachable at `/`.
```
</pblock>

<pblock filename="DATABASE.md" role="context" path="/mnt/c/Users/barlo/projects/drydock/uat/ReadingList/runs/20261023.210132/workspace/targets/ReadingList/blueprint/DATABASE.md" guidance="Database and PersistenceSpecification">
```markdown
# DATABASE: ReadingList

| Field       | Value |
|-------------|-------|
| Version     | 20261023 V1 |
| Description | Persistence stores and typed interfaces for ReadingList. |
| Depends On  | ARCHITECTURE.md |
| Provides    | persistence.books |
| Build Order | 1 |

## Persistence Boundary

| Boundary | Rule |
|----------|------|
| Raw storage access | Only the generated `persistence/` package reaches the store. |
| Caller dependency | Features depend on declared access patterns and their DTOs, not on schemas. |
| Implementation | Generated from this file at the DATABASE build step; never written by hand. |

## Access Patterns

### FEATURE-READING-LIST-001 — List books

| Field | Value |
|-------|-------|
| Owner | FEATURE-READING-LIST.md |
| Access | read |
| Repository operation | `books.list` |
| Compatibility | unchanged |

Input: `BookListInput`

| Field | Type | Required |
|-------|------|----------|
| — | — | — |

Output: `BookRow[]`

| Field | Type |
|-------|------|
| id | INTEGER |
| title | TEXT |
| author | TEXT |
| insertion_order | INTEGER |

### FEATURE-ADD-BOOK-001 — Create a book

| Field | Value |
|-------|-------|
| Owner | FEATURE-ADD-BOOK.md |
| Access | write |
| Repository operation | `books.create` |
| Compatibility | unchanged |

Input: `BookCreateInput`

| Field | Type | Required |
|-------|------|----------|
| title | TEXT | yes |
| author | TEXT | yes |
| insertion_order | INTEGER | yes |

Output: `BookRow`

| Field | Type |
|-------|------|
| id | INTEGER |
| title | TEXT |
| author | TEXT |
| insertion_order | INTEGER |

### FEATURE-REMOVE-BOOK-001 — Delete a book

| Field | Value |
|-------|-------|
| Owner | FEATURE-REMOVE-BOOK.md |
| Access | write |
| Repository operation | `books.delete` |
| Compatibility | unchanged |

Input: `BookDeleteInput`

| Field | Type | Required |
|-------|------|----------|
| id | INTEGER | yes |

Output: `DeletedBook`

| Field | Type |
|-------|------|
| id | INTEGER |

## Schemas

## `books`

| Field | Type | Notes |
|-------|------|-------|
| id | INTEGER PK | Stable book identifier. |
| title | TEXT NOT NULL | Book title. |
| author | TEXT NOT NULL | Book author. |
| insertion_order | INTEGER NOT NULL UNIQUE | Monotonic order assigned when the book is added. |

## Migrations

| Access Pattern | Revision | State |
|----------------|----------|-------|
| FEATURE-READING-LIST-001 | MIGRATION-FEATURE-READING-LIST-001 | planned |
| FEATURE-ADD-BOOK-001 | MIGRATION-FEATURE-ADD-BOOK-001 | planned |
| FEATURE-REMOVE-BOOK-001 | MIGRATION-FEATURE-REMOVE-BOOK-001 | planned |

## Config (.env)

| Key | Type | Required | Notes |
|-----|------|----------|-------|
| DATABASE_URL | string | no | Optional database DSN; overrides `DATABASE_PATH`. |
| DATABASE_PATH | string | no | Optional local database path; defaults to `data/app.db`. |

## File Stores

| Store | Root dir | Notes |
|-------|----------|-------|
| — | — | No file store. |

## External Services

| Service | Wrapper | Notes |
|---------|---------|-------|
| — | — | No external services. |

## External Libraries

| Library | Ownership | Distribution | Consumer Contract |
|---------|-----------|--------------|-------------------|
| — | — | — | No external persistence libraries. |

## Programmatic Acceptance

=== AC database-books-create ===
Intent: The books create operation returns the declared book row with the supplied values.

from persistence.testing import db_session

title = "The Left Hand of Darkness"
author = "Ursula K. Le Guin"
insertion_order = 1

with db_session() as db:
    row = db.books.create(
        title=title,
        author=author,
        insertion_order=insertion_order,
    )
    assert row.title == title
    assert row.author == author
    assert row.insertion_order == insertion_order
=== END AC database-books-create ===

=== AC database-books-list ===
Intent: The books list operation returns books in insertion order.

from persistence.testing import db_session

first_title = "Dune"
first_author = "Frank Herbert"
second_title = "Kindred"
second_author = "Octavia E. Butler"

with db_session() as db:
    db.books.create(
        title=first_title,
        author=first_author,
        insertion_order=1,
    )
    db.books.create(
        title=second_title,
        author=second_author,
        insertion_order=2,
    )
    rows = db.books.list()

    assert [row.title for row in rows] == [first_title, second_title]
    assert [row.author for row in rows] == [first_author, second_author]
=== END AC database-books-list ===

=== AC database-books-delete ===
Intent: The books delete operation returns the selected identifier and removes that book from subsequent reads.

from persistence.testing import db_session

title = "A Wizard of Earthsea"
author = "Ursula K. Le Guin"

with db_session() as db:
    created = db.books.create(
        title=title,
        author=author,
        insertion_order=1,
    )
    deleted = db.books.delete(id=created.id)
    assert deleted.id == created.id

    remaining = db.books.list()
    assert all(row.id != created.id for row in remaining)
=== END AC database-books-delete ===

## User Acceptance

- None.

## Guardrails

- Empty titles and authors are rejected by the feature validation boundary before persistence.
- Books retain insertion order and are never silently reordered.
- Raw storage access remains encapsulated by the generated persistence package.
```
</pblock>


## IMPLEMENTS - Authoritative Step Specifications

<pblock label="Implementation recency anchor" kind="section">
The files in this section are the load-bearing specifications for this build block.
Build these files exactly. Treat earlier sections as constraints and context.

</pblock>

<pblock filename="FEATURE-READING-LIST.md" role="implements" path="/mnt/c/Users/barlo/projects/drydock/uat/ReadingList/runs/20261023.210132/workspace/targets/ReadingList/blueprint/FEATURE-READING-LIST.md" guidance="Feature Specification">
```markdown
# FEATURE: Reading List

| Field       | Value |
|-------------|-------|
| Version     | 20261023 V1 |
| Description | Serves the ordered reading-list workflow for persisted books. |
| Depends On  | ARCHITECTURE.md, DATABASE.md |
| Provides    | GET `/` |
| Consumes    | `app_server.create_app`, `persistence.books.list` |

## Purpose

The primary reading-list page retrieves persisted books through `persistence.books.list` and presents them in insertion order. It renders a clear empty state when no books are available.

## Database Interface

- `FEATURE-READING-LIST-001` — read: list books - supplies: — - returns: `id`, `title`, `author`, `insertion_order`

## Workflow

1. A reader requests `GET /`.
2. The feature reads books through `books.list`.
3. The page renders the returned books without reordering them.
4. An empty result renders the empty-list state.

## Programmatic Acceptance

=== AC reading-list-reachable ===
Intent: The primary reading-list route is reachable and returns a successful page response.

from app_server.testing import web_client

client = web_client()
response = client.get("/")
assert response.status_code == 200
=== END AC reading-list-reachable ===

=== AC reading-list-order ===
Intent: The reading-list route presents persisted books in insertion order.

from persistence.testing import committed_session
from app_server.testing import web_client

first_title = "Reading List First"
first_author = "Reading List Author One"
second_title = "Reading List Second"
second_author = "Reading List Author Two"

with committed_session() as db:
    first = db.books.create(
        title=first_title,
        author=first_author,
        insertion_order=900001,
    )
    second = db.books.create(
        title=second_title,
        author=second_author,
        insertion_order=900002,
    )

try:
    client = web_client()
    response = client.get("/")
    assert response.status_code == 200
    body = response.get_data(as_text=True)
    first_position = body.index(first_title)
    second_position = body.index(second_title)
    assert first_position < second_position
finally:
    with committed_session() as db:
        db.books.delete(id=first.id)
        db.books.delete(id=second.id)
=== END AC reading-list-order ===

=== AC reading-list-empty ===
Intent: The reading-list route successfully renders when no matching books are present.

from app_server.testing import web_client

title = "No Matching Reading List Fixture"
client = web_client()
response = client.get("/")
assert response.status_code == 200
assert response.request.path == "/"
=== END AC reading-list-empty ===

## User Acceptance

- A reader can open the primary page and understand whether books are present.
- Books appear in the order they were added.

## Guardrails

- The route never silently reorders books.
- Removed books are absent on the next read.
- Empty titles and authors are never displayed.
```
</pblock>

<pblock filename="FEATURE-ADD-BOOK.md" role="implements" path="/mnt/c/Users/barlo/projects/drydock/uat/ReadingList/runs/20261023.210132/workspace/targets/ReadingList/blueprint/FEATURE-ADD-BOOK.md" guidance="Feature Specification">
```markdown
# FEATURE: Add Book

| Field       | Value |
|-------------|-------|
| Version     | 20261023 V1 |
| Description | Adds valid books to the persisted reading list. |
| Depends On  | ARCHITECTURE.md, DATABASE.md |
| Provides    | POST `/books` |
| Consumes    | `app_server.create_app`, `persistence.books.create` |

## Purpose

A reader submits a title and author to `POST /books`. The feature persists the book through `books.create` and returns the reader to a usable reading-list workflow where the new book can be seen.

## Database Interface

- `FEATURE-ADD-BOOK-001` — write: create a book - supplies: `title`, `author`, `insertion_order` - returns: `id`, `title`, `author`, `insertion_order`

## Workflow

1. Receive title and author form values.
2. Create the book through the persistence contract.
3. Redirect to the primary list page.
4. The subsequent list read includes the created book.

## Programmatic Acceptance

=== AC add-book-route ===
Intent: The book-creation route accepts a valid title and author submission.

from app_server.testing import web_client

title = "Add Book Acceptance Title"
author = "Add Book Acceptance Author"

client = web_client()
response = client.post(
    "/books",
    data={"title": title, "author": author},
)
assert response.status_code == 302

follow_up = client.get("/")
assert follow_up.status_code == 200
body = follow_up.get_data(as_text=True)
assert title in body
assert author in body
=== END AC add-book-route ===

=== AC add-book-persistence ===
Intent: A valid submission is persisted and readable through the public list workflow.

from app_server.testing import web_client

title = "Persisted Add Book Title"
author = "Persisted Add Book Author"

client = web_client()
created_response = client.post(
    "/books",
    data={"title": title, "author": author},
)
assert created_response.status_code == 302

read_response = client.get("/")
assert read_response.status_code == 200
body = read_response.get_data(as_text=True)
assert title in body
assert author in body
=== END AC add-book-persistence ===

## User Acceptance

- A reader can submit a title and author and see the new book in the list.

## Guardrails

- Valid submissions use the generated persistence contract.
- A created book is not silently omitted from the next list read.
- Empty fields are rejected by the validation boundary.
```
</pblock>

<pblock filename="FEATURE-REMOVE-BOOK.md" role="implements" path="/mnt/c/Users/barlo/projects/drydock/uat/ReadingList/runs/20261023.210132/workspace/targets/ReadingList/blueprint/FEATURE-REMOVE-BOOK.md" guidance="Feature Specification">
```markdown
# FEATURE: Remove Book

| Field       | Value |
|-------------|-------|
| Version     | 20261023 V1 |
| Description | Removes a selected persisted book from the reading list. |
| Depends On  | ARCHITECTURE.md, DATABASE.md |
| Provides    | POST `/books/<book_id>/delete` |
| Consumes    | `app_server.create_app`, `persistence.books.delete` |

## Purpose

A reader submits the removal action for a selected book. The feature deletes only that persisted identifier through `books.delete`, then returns to the list workflow.

## Database Interface

- `FEATURE-REMOVE-BOOK-001` — write: delete a book - supplies: `id` - returns: `id`

## Workflow

1. A book identifier is submitted to `POST /books/<book_id>/delete`.
2. The selected book is deleted through the persistence contract.
3. The reader returns to the reading-list page.
4. The next read omits the removed book.

## Programmatic Acceptance

=== AC remove-book-route ===
Intent: The removal route deletes the selected book and returns to the reading-list workflow.

from persistence.testing import committed_session
from app_server.testing import web_client

title = "Remove Book Acceptance Title"
author = "Remove Book Acceptance Author"

with committed_session() as db:
    created = db.books.create(
        title=title,
        author=author,
        insertion_order=900003,
    )

try:
    client = web_client()
    response = client.post(f"/books/{created.id}/delete")
    assert response.status_code == 302

    follow_up = client.get("/")
    assert follow_up.status_code == 200
    body = follow_up.get_data(as_text=True)
    assert title not in body
finally:
    with committed_session() as db:
        db.books.delete(id=created.id)
=== END AC remove-book-route ===

=== AC remove-book-readback ===
Intent: Removing a book changes subsequent persisted reads so the selected identifier is absent.

from persistence.testing import committed_session

title = "Remove Book Readback Title"
author = "Remove Book Readback Author"

with committed_session() as db:
    created = db.books.create(
        title=title,
        author=author,
        insertion_order=900004,
    )
    deleted = db.books.delete(id=created.id)
    assert deleted.id == created.id

    remaining = db.books.list()
    assert all(row.id != created.id for row in remaining)

    db.books.delete(id=created.id)
=== END AC remove-book-readback ===

## User Acceptance

- A reader can remove a selected book and no longer sees it on the next list read.

## Guardrails

- Removal affects only the selected persisted book.
- A removed book is not shown on the next reading-list request.
- The feature does not silently reorder remaining books.
```
</pblock>

<pblock filename="FEATURE-VALIDATE-BOOK.md" role="implements" path="/mnt/c/Users/barlo/projects/drydock/uat/ReadingList/runs/20261023.210132/workspace/targets/ReadingList/blueprint/FEATURE-VALIDATE-BOOK.md" guidance="Feature Specification">
```markdown
# FEATURE: Validate Book

| Field       | Value |
|-------------|-------|
| Version     | 20261023 V1 |
| Description | Validates book submissions and returns correction feedback for incomplete entries. |
| Depends On  | ARCHITECTURE.md, DATABASE.md, FEATURE-ADD-BOOK.md |
| Provides    | validation for POST /books |
| Consumes    | POST /books, app_server.create_app, persistence.books.list |

## Purpose

The validation boundary protects the reading list from incomplete books. Submissions with an empty title, empty author, or both are rejected before persistence with a client-error response. The form remains usable so the reader can correct and resubmit.

## Workflow

1. Receive title and author form values at `POST /books`.
2. Reject the submission with HTTP 400 when either required value is empty.
3. Preserve the submitted values and identify the missing field or fields in the rendered feedback.
4. Do not create a persistence record for rejected input.
5. Accept corrected values through the existing add-book workflow.

## Database Interface


- None — persistence is owned by FEATURE-ADD-BOOK.md, FEATURE-READING-LIST.md, FEATURE-REMOVE-BOOK.md.

## Programmatic Acceptance

=== AC validate-book-route ===
Intent: The book submission route rejects an empty title with a client-error response and does not persist the invalid submission.

from app_server.testing import web_client
from persistence.testing import db_session

title = ""
author = "Validation Author"

client = web_client()
response = client.post("/books", data={"title": title, "author": author})

assert response.status_code == 400

with db_session() as db:
    rows = db.books.list()
    assert all(row.title != title or row.author != author for row in rows)
=== END AC validate-book-route ===

=== AC validate-book-author ===
Intent: The book submission route rejects an empty author with a client-error response and does not persist the invalid submission.

from app_server.testing import web_client
from persistence.testing import db_session

title = "Validation Title"
author = ""

client = web_client()
response = client.post("/books", data={"title": title, "author": author})

assert response.status_code == 400

with db_session() as db:
    rows = db.books.list()
    assert all(row.title != title or row.author != author for row in rows)
=== END AC validate-book-author ===

=== AC validate-book-correction ===
Intent: A reader can correct an invalid submission and successfully add the corrected book.

from app_server.testing import web_client

invalid_title = ""
invalid_author = "Correctable Author"
valid_title = "Corrected Title"
valid_author = "Corrected Author"

client = web_client()
invalid_response = client.post(
    "/books",
    data={"title": invalid_title, "author": invalid_author},
)
assert invalid_response.status_code == 400

valid_response = client.post(
    "/books",
    data={"title": valid_title, "author": valid_author},
)
assert valid_response.status_code == 302

list_response = client.get("/")
assert list_response.status_code == 200
body = list_response.get_data(as_text=True)
assert valid_title in body
assert valid_author in body
=== END AC validate-book-correction ===

## User Acceptance

- None.

## Guardrails

- Empty titles and authors are rejected before persistence.
- Validation returns HTTP 400 and keeps the form workflow recoverable.
- Validation feedback identifies the missing required field or fields.
```
</pblock>

<pblock label="Build instructions" kind="instructions">
### Build instructions for this block

#### Serve the ordered reading-list view. (reading-list)
Implement the read workflow for the primary reading-list page. Retrieve books through the persistence contract in insertion order, render the collection or a clear empty-list state, and expose the primary GET / route.

#### Add a valid book to the reading list. (add-book)
Implement the valid book submission workflow at POST /books. Accept title and author form values, create the book through the persistence contract, and redirect or render the updated list so the newly stored book is visible.

#### Remove a selected book from the reading list. (remove-book)
Implement removal at POST /books/<book_id>/delete. Delete only the selected persisted book through the repository contract and ensure the next reading-list request omits it.

#### Reject incomplete book submissions with correction feedback. (validate-book)
Add boundary validation for POST /books. Reject an empty title, an empty author, or both before persistence, report which required field is missing, and preserve a usable form workflow so the reader can correct and resubmit.

</pblock>

<pblock label="Reusable compact request" kind="section">
## Reusable compacts

The Blueprint sources below are consumed as context by later Manifest blocks.
In this same response, extract their consumer-facing contract surface. Preserve
interfaces, schemas, constraints, configuration, and cross-file obligations; drop
implementation narrative and repetition. Do not write these files yourself.

Before the required RESULT block, emit one optional payload per source exactly as:
<reusable-compact filename="SOURCE.md">
compact content
</reusable-compact>

Emit no payload when a source has no useful technical surface. These payloads are
advisory and do not change the required build result or file-change report.

Sources eligible for reusable compaction:
- DATABASE.md

</pblock>


# Agent Task

You are a Drydock build agent implementing exactly one build step of a larger plan.
The build job block below names the target, the build working directory, and the
step. Everything you need is stacked into this prompt under role headings:

- `compass` — the Target's COMPASS.md orientation.
- `implements` — the Typed Specification files this step builds. These are
  authoritative; implement them exactly.
- `context` — read-only support specifications. Do not reimplement them.
- `stack` — enterprise stack and technology rules. Honor them.
- `rules` — governance and branding rules. Honor them.

Operating contract:

1. Follow the write authorization and protected paths in the stacked `COMPASS.md` exactly.
   That persisted guardrail is the sole authority for paths this build may modify.
2. Start by inspecting the build working directory. Preserve existing application
   files unless this step's specifications require a change.
   Its `sources/` subdirectory holds staged build assets — imported test corpora,
   conformance harnesses, and fixtures — placed there for you. They are read-only
   inputs: run them, import them, and write code against them, but never create,
   rewrite, trim, regenerate, or substitute one, even to make a check pass. A step
   that modifies a staged asset fails and the asset is restored. If an asset you
   expect is absent, report that; do not author a replacement.
3. Implement only this step. Use `context`, `stack`, and `rules` as constraints,
   not as additional work to perform.
4. Follow the stack and rules for languages, structure, naming, and branding.
5. The programmatic acceptance assertions in the `implements` specifications are
   this step's **Definition of Done** — human-owned, declared before the build,
   and fixed. Build the story and, in this same step, write the deterministic
   tests that prove each declared assertion, as a TDD master would; add finer
   tests for coverage. Every test you write follows the same rule the acceptance
   assertions do: **act on the system, read the state back, compare to expected.**
   The oracle is a return value, parsed JSON, a status code, a stored row, file
   contents read back, or an exit status — never a substring of captured stdout or
   stderr, a test-runner tally, or a log line. Write tests in the project's own
   language using that language's libraries; an in-language HTTP client yields a
   status code and a parsed body, where `curl` yields text to scrape. Round-trip
   anything that stores state: act, then read back through the public interface.
   Assert declared failure signals on negative paths, never message wording. You may add tests but must never remove, soften, or weaken
   a declared acceptance assertion. A `Suite: full` conformance check gates on the
   entire imported test suite: the step is done only when it passes in full, never on a
   representative subset — reproduce the standard exactly rather than wrapping a
   third-party library that approximates it. For a suite, the runner's exit status is the
   verdict and the whole verdict: print its captured output for diagnosis, never assert on the
   text of its summary. When an assertion is a static or filesystem
   scan (import boundary, "X never appears outside Y," grep/AST gate), honor the
   scope the specification states and never widen it: scan production source only,
   exclude `.venv/`, `site-packages`, and vendored or generated code, and do not
   flag test doubles or fixtures that use the guarded dependency.
   Run every declared acceptance assertion before returning. For a conformance suite,
   use its section or example filters to diagnose coherent root-cause clusters, but
   rerun the full declared scope before reporting the result. Treat failing examples as
   a work queue for fixing general behavior; never add example-specific exceptions.
6. Grow the project's own test suite as you write the code, and treat it as the project's
   real coverage. The acceptance assertions in `implements` are gates: few, fixed, and
   written before any code existed, so every expectation in them is a prediction. The tests
   you write are written *beside* the finished code, so their expected values are observed
   rather than predicted — which is why exhaustive coverage belongs here and not there.
   Extend the suite in the project's established location and runner, keep it runnable by the
   project's declared test command, and leave it green when you return.
   Cover, at minimum: every public entry point and every verb it declares, including declared
   error paths; the boundaries — empty, exactly one, many, absent optional fields, declared
   maxima; declared idempotence, applied twice; one behavior per test, named for the behavior;
   and isolation — database criteria use the provisioned application store and the shipped rollback
   fixture, passing its connection into the feature. Other connections and durability tests use
   criterion-owned records, idempotent setup and checked cleanup through supported interfaces.
   Never replace the configured store, reapply schema, or delete unrelated business records.
   Where a staged authoritative suite already covers a surface, that suite is the coverage:
   run it, and do not restate its cases. Run it **only through the invocation this step's
   acceptance criteria declare**. A criterion marked `Suite: scoped` names the whole of this
   step's obligation to that suite; running the suite's unscoped entry point instead is not
   extra rigor, it is a different step's gate executed early. A partial capability fails most
   of an authoritative corpus by construction and its unimplemented cases exhaust the runner's
   per-case timeout rather than returning, so the unscoped run costs the most where it teaches
   the least, and interrupting it forfeits the step. If no criterion in this step invokes the
   staged suite, do not invoke it. Report the pass/fail counts of the invocations you did run
   in your `SUMMARY` so a reader can see coverage moving across steps.
7. Treat `User Acceptance` entries as review evidence requirements. Implement
   the supporting behavior, but do not claim to have performed human judgment.
8. The `implements` section is authoritative and intentionally stacked late in
   the prompt as the recency anchor. Build that WHAT exactly; do not substitute
   generic framework defaults.
9. Before adding or installing Python dependencies, verify each package name
   against the declared registry. Do not invent package names. If a needed
   package cannot be verified or appears newly published, fail explicitly
   instead of installing it.
10. Use the stack's required package manager workflow for dependency changes.
   When the stack requires `uv`, update manifests through `uv` conventions
   rather than bare `pip install`.
11. Do not claim success unless you actually created or modified project files in
   the build working directory. If you cannot write files or cannot complete the
   step, report failure explicitly.
12. Do not run `git add`, `git commit`, create branches, create tags, rewrite
   history, or otherwise mutate Git history. Drydock checkpoints application changes
   and Target evidence after each execution and completed step. File lineage comes
   from Git and the Manifest's `implements:` entries; no additional attribution
   response is required.
13. End your response with this exact closing structure:

```text
RESULT: SUCCESS | FAILED

FILES CHANGED:
- relative/path

SUMMARY:
<brief reviewable summary>

BLOCKERS:
- <only if any>
```
   Before `RESULT`, you may emit one optional JSON payload when implementation required a bounded
   choice not already settled by the owning specification. This records what you did; it does not
   ask permission, create a questionnaire, or excuse incomplete work:

```text
<blueprint-decisions>
[{"spec":"FEATURE-Example.md","severity":"Material","subject":"Chosen behavior","decision":"Options A and B were available. I implemented B because ... Is that acceptable, or should this change on replan?"}]
</blueprint-decisions>
```

   Name only a specification implemented by this build block. Use `Low` or `Material`; Build never
   emits a Blocking decision. Omit the payload when no implementation decision was necessary.

14. `FILES CHANGED` must list only files actually written in the build working
   directory. If no files were written, use `RESULT: FAILED`.
15. On `RESULT: FAILED`, append two additional lines so the failure is actionable
   without opening logs. `FAILURE_SUMMARY` is one line naming the cause;
   `FAILURE_DETAIL` states what happened, why, and what to change before a rerun.
   Name concrete conditions when they apply: token or context limit exceeded,
   could not execute commands in this environment, a required input was missing,
   or a specific tool or command failed.

```text
FAILURE_SUMMARY: <one line naming the cause>
FAILURE_DETAIL: <what happened, why, and what to change before rerunning>
```

16. When a declared acceptance criterion cannot pass no matter how the code is written,
   say so with this exact token. You may not edit the criterion — it is staged and
   restored before grading:

```text
AC_BROKEN: <check-id>[, <check-id>]
```

   This is a report, not a verdict, and it stops nothing. A criterion reaches you only
   when its expected value is one its author could not have invented — a status code, a
   staged suite's exit status, a value the criterion itself supplied as input — so your
   claim that the criterion rather than the code is at fault is the less likely
   explanation, and the budget is spent as it would be for any other failure. A
   criterion whose expectation *was* hand-typed already settles `DISPUTED` on its own,
   without you naming it. Emit the token only after running the criterion and confirming
   the underlying command succeeded while the assertion still failed. Name the affected
   check ids, emit it alongside your normal `RESULT` line, state the reasoning in
   `FAILURE_DETAIL`, and emit it even when `RESULT: SUCCESS`. Do not use it for a
   criterion you merely failed to satisfy.


# Repair Feedback

## Repair pass

A previous build pass wrote partial work into BUILD_DIRECTORY and did not pass
every deterministic acceptance check. Iterate the existing files in
BUILD_DIRECTORY to make the checks below pass. Do not restart from scratch, do
not weaken or remove any declared acceptance assertion, and keep every check
that already passes green.

The diagnostic excerpts below are truncated. Before editing, rerun each failing
acceptance assertion from its authoritative specification and inspect the complete
failure output. For a conformance suite, use its section or example filters to
diagnose coherent root-cause clusters, then rerun the full declared scope. Fix the
general parser or renderer behavior; do not add example-specific exceptions. Keep
working through failing examples while the deterministic tally is improving.

If a check below cannot pass however the code is written — the command it runs
succeeds and the assertion still fails — report it with `AC_BROKEN: <check-id>`
and explain the contradiction in `FAILURE_DETAIL`. The report is recorded as
evidence and stops nothing: the repair budget is spent as for any other failure,
so keep the code correct and every other check green.

### Regression — fix this first

The criteria below belong to earlier stories that were already proven. They were
green before this block ran and are red now, so this block's edits broke them.
Restore the behavior they assert without discarding this block's own work, and do
not edit the criteria.

- database-books-create (DATABASE.md): The books create operation returns the declared book row with the supplied values.
    assertion: persistence.db.PersistenceError: FEATURE-ADD-BOOK-001 failed: UNIQUE constraint failed: books.insertion_order
    output:
        File "/mnt/c/Users/barlo/projects/drydock/uat/ReadingList/runs/20261023.210132/build/ReadingList/persistence/db.py", line 188, in <lambda>
          return lambda **arguments: self._database.run(operation, arguments)
                                     ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
        File "/mnt/c/Users/barlo/projects/drydock/uat/ReadingList/runs/20261023.210132/build/ReadingList/persistence/db.py", line 291, in run
          raise PersistenceError(f"{operation.identifier} failed: {exc}") from exc
      persistence.db.PersistenceError: FEATURE-ADD-BOOK-001 failed: UNIQUE constraint failed: books.insertion_order
- database-books-list (DATABASE.md): The books list operation returns books in insertion order.
    assertion: persistence.db.PersistenceError: FEATURE-ADD-BOOK-001 failed: UNIQUE constraint failed: books.insertion_order
    output:
        File "/mnt/c/Users/barlo/projects/drydock/uat/ReadingList/runs/20261023.210132/build/ReadingList/persistence/db.py", line 188, in <lambda>
          return lambda **arguments: self._database.run(operation, arguments)
                                     ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
        File "/mnt/c/Users/barlo/projects/drydock/uat/ReadingList/runs/20261023.210132/build/ReadingList/persistence/db.py", line 291, in run
          raise PersistenceError(f"{operation.identifier} failed: {exc}") from exc
      persistence.db.PersistenceError: FEATURE-ADD-BOOK-001 failed: UNIQUE constraint failed: books.insertion_order
- database-books-delete (DATABASE.md): The books delete operation returns the selected identifier and removes that book from subsequent reads.
    assertion: persistence.db.PersistenceError: FEATURE-ADD-BOOK-001 failed: UNIQUE constraint failed: books.insertion_order
    output:
        File "/mnt/c/Users/barlo/projects/drydock/uat/ReadingList/runs/20261023.210132/build/ReadingList/persistence/db.py", line 188, in <lambda>
          return lambda **arguments: self._database.run(operation, arguments)
                                     ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
        File "/mnt/c/Users/barlo/projects/drydock/uat/ReadingList/runs/20261023.210132/build/ReadingList/persistence/db.py", line 291,
… (feedback truncated)

