Run artifact

evidence/prompts/20261026.203315.586Z_fxrates_build_codex.prompt.md

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.

  1. Input Context — begins with the heading # Input Context. All blocks are wrapped in

<pblock> tags. Two block types:

guidance attribute carries context-specific instructions; content is in a fenced block.

rules, instructions, or group headers.

  1. 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

</pblock>

<pblock label="Stories in this block" kind="section">

Stories in this block

</pblock>

<pblock label="Files on disk" kind="section">

Files on disk in the build directory

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/FxRates/runs/20261026.202600/workspace/targets/FxRates/COMPASS.md" guidance="Important: This is the core project intent, constraints, and guardrails. It should have presecedence in conflicts.">

# COMPASS: FxRates

## Compass

Build a currency rates service, an executable named `fxrates` at the application root, as
described in `sources/INSTRUCTIONS.md`. A command line loads the ECB euro reference rate history
into SQLite, and a FastAPI JSON API serves the rates on a date, conversions between any two
currencies, and a currency's history with minimum, maximum, and mean.

Correctness is measured by `sources/run.sh`: it loads the supplied ECB files, starts the server on
a free local port, and makes 35 checks of command output and HTTP status and JSON body. The goal is
every check passing.

## Constraints

- Implement in Python 3.11 or newer with FastAPI and uvicorn over SQLite.
- Provide an executable named `fxrates` at the application root, invoked as `./fxrates <command>`.
  `fxrates serve` runs the server in the foreground and stops cleanly on SIGTERM.
- Read the database location from `DATABASE_URL`, then `DATABASE_PATH`, then `data/app.db`.
- Store rates as the ECB's published text; compute with `decimal`, never with floating point.
- Check a file in full before its first write.
- Tests stub the ECB download; no test opens a network connection.
- Diagnostics go to standard error and are never compared.

## Guardrails

- Do not modify, rewrite, regenerate, or substitute any file under `sources/`.
- Do not read `sources/run.sh` or any supplied data file from application code. Data reaches the
  database only through `fxrates load` or `fxrates fetch`.
- Do not hardcode a rate, a date, a count, or a computed value. Every value comes from a query.
- Do not open a database driver outside the shipped persistence library.

## Verification Protocol

| Story kind | Command | Asserts |
|---|---|---|
| Every behavioral story | `sh bin/test.sh` | exit `0` |
| Terminal story (once, last) | `sh sources/run.sh` | exit `0` |

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

- Authorized build directory: `/mnt/c/Users/barlo/projects/drydock/uat/FxRates/runs/20261026.202600/build/FxRates`
- Authorized Target directory: `/mnt/c/Users/barlo/projects/drydock/uat/FxRates/runs/20261026.202600/workspace/targets/FxRates`
- 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/FxRates/runs/20261026.202600/workspace/targets/FxRates/blueprint/`
  - `/mnt/c/Users/barlo/projects/drydock/uat/FxRates/runs/20261026.202600/workspace/targets/FxRates/MANIFEST.md`
  - `/mnt/c/Users/barlo/projects/drydock/uat/FxRates/runs/20261026.202600/workspace/targets/FxRates/COMPASS.md`
  - `/mnt/c/Users/barlo/projects/drydock/uat/FxRates/runs/20261026.202600/workspace/targets/FxRates/QuarterDeck/`
  - `/mnt/c/Users/barlo/projects/drydock/uat/FxRates/runs/20261026.202600/workspace/targets/FxRates/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="common_compact.md" role="stack" path="/mnt/c/Users/barlo/projects/drydock/Rigging/stack/common_compact.md">

<!-- Compacted from /mnt/c/Users/barlo/projects/drydock/Rigging/stack/common.md sha256=2d665e4a232b3ef5b681149974e74928c8f5abb9adaac02604cc6b5987ac0f85 on 2026-10-24 by drydock rigging compact — regenerate with: drydock rigging compact --include-file {rel_source} -->

# Common Best Practices — Contract Surface

## Project Layout

### Rule: project-directory-layout

Every project must use the standard root layout and may add stack-specific directories.

Constraints: Include `bin/`, `data/` with `logs/` and `backups/`, `docs/`, `tests/`, optional `PROJECT/`, `.env`, `.env.example`, `.gitignore`, `CLAUDE.md`, and `Links.md`; keep runtime data under `data/`.

## Shell Scripts

### Rule: user-facing-operation-scripts

User-facing operations must be implemented as Bash scripts in `bin/`.

Constraints: Scripts must use standardized headers, `set -euo pipefail`, resolve project-relative paths, create `data/logs/`, log execution details, run from the project root, tee output to console and a timestamped log, and record completion.

### Rule: command-center-discovery-header

A discoverable script must begin with a Command Center header.

| Field | Required | Values |
|---|---:|---|
| `# CommandCenter Operation` | Yes | Literal |
| `# Name:` | Yes | Free text |
| `# Type:` | No | `daemon` or `batch`; defaults to `batch` |
| `# Port:` | No | Integer; daemon port |

Constraints: Scripts without `# CommandCenter Operation` remain valid but are not discoverable by Command Center.

### Rule: standard-scripts

Projects should provide applicable operation scripts with these names and purposes.

| Script | Type | Purpose |
|---|---|---|
| `bin/start.sh` | daemon | Start the development server |
| `bin/stop.sh` | batch | Stop the development server |
| `bin/test.sh` | batch | Run tests |
| `bin/build.sh` | batch | Build or compile |
| `bin/deploy.sh` | batch | Deploy to production |
| `bin/backup.sh` | batch | Back up data or databases |

### Rule: script-logging

Operation scripts must capture stdout and stderr in `data/logs/`.

Constraints: Log filenames must follow `<script>_<YYYY-MM-DD_HHMMSS>.log`; initial log lines must record timestamp, arguments, and working directory.

## Links

### Rule: links-file

Every project must provide a root-level `Links.md` containing one two-column Markdown table.

| Column | Requirement |
|---|---|
| `Label` | Short and descriptive |
| `URL` | Relevant project URL |

Constraints: Command Center reads this table and exposes the links through project configuration.

## Agent Instructions

### Rule: claude-file

Every project must provide a root-level `CLAUDE.md` with the following sections.

| Section | Required content |
|---|---|
| `## Project Overview` | Purpose and key features |
| `## Architecture` | Technology stack, key files, and patterns |
| `## Dev Commands` | Bash project commands in a code block |
| `## Service Endpoints` | `- Label: https://url` entries |
| `## Bookmarks` | Grouped links using `### Group` and `- [Title](URL)` |

Constraints: Normalize equivalent headings to the standard names: `Commands`, `Development Commands`, and `Build Commands` become `Dev Commands`; `Overview` and `Project Purpose` become `Project Overview`; `Stack` becomes `Architecture`.

## Version Control

### Rule: gitignore-and-secrets

Repositories must ignore secrets, generated files, and runtime data.

Constraints: Ignore `data/`, `*.db`, `*.log`, `.env`, `venv/`, `node_modules/`, Python caches and bytecode, `*.egg-info/`, `dist/`, `build/`, `.DS_Store`, and `Thumbs.db`; commit `.env.example` with placeholders.

### Rule: commit-message

Commit messages must use imperative, descriptive text without AI or tool mentions.

## Development Workflow

### Rule: task-commit

Completed, error-free tasks must be committed immediately.

### Rule: local-only-commit

Changes must be committed locally and must not be pushed.

### Rule: co-authorship

Commits must not contain `Co-authored-by` lines.

### Rule: restart-notice

Code-change responses for web-server projects must state whether a restart is required.

Constraints: Template, CSS, or static-only changes require the notice `No restart needed — browser refresh is enough.`; Python or JavaScript server changes require `Restart required — run the start script or equivalent.`

</pblock>

<pblock filename="persistence.md" role="stack" path="/mnt/c/Users/barlo/projects/drydock/Rigging/stack/persistence.md">

# Persistence & Service Encapsulation

**Type:** guidance
**Version:** 20261023 V5
**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>.<name>(...) → 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)                 # a frozen dataclass, or None
open_tickets = db.tickets.list(status="open")         # a list of them
history = db.rates.history(currency="USD", start_date=start)  # range list; end_date omitted
ticket = db.tickets.create(status="open", title=title)  # the declared Output row
db.tickets.update(id=ticket_id, status="closed")      # the row, or None
rate = db.rates.replace_rate(date=day, currency="USD", rate="1.0393")  # upsert: the row
changed = db.rates.reprice_currency(currency="USD", rate="1.0400")     # many-row update: a count
db.tickets.delete(id=ticket_id)                       # the Output built from the Match, or None
```

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

### Operations: a name and a Kind

An operation's **name** is the contract callers depend on. Its **Kind** is how the package runs
it, one of six: `get`, `list`, `create`, `update`, `upsert`, `delete`.

- **Simple:** the name is the Kind. `rates.get`, `rates.update` — no Kind row is written.
- **Named:** any other name declares its Kind: `rates.reprice_currency` with `| Kind | update |`.
  A table may hold several operations of one Kind, each under its own name. Two names with the
  same Kind, Match, Sets, and Output are synonyms, and the plan refuses the second.

**Which rows an operation reaches is declared, never inferred.** A pattern's `| Match |` row names
the Input fields that select rows, joined with AND, every field required except on a `list`. A
bare field is compared by equality with the column of its name; a term `<column> <op> <field>`
(`=`, `<`, `<=`, `>`, `>=`) compares an argument with a column, as `date >= start_date`. A Match
whose equality fields cover the table's `PK` or a declared `UNIQUE` reaches at most one row; any
other Match reaches many. A `list` with `| Order | `date` asc |` returns its rows in that order,
and in no stated order otherwise; do not re-sort or filter what an operation already returns. Every write is one statement inside the package, so a caller never composes a
read-then-write.

| Kind | Selects rows by | Writes | Rows | Returns |
|---|---|---|---|---|
| `get` | Match: a unique key | — | 0..1 | the row, or `None` |
| `list` | each supplied Input field, compared as its Match term states (optional filters) | — | 0..n | a list of rows, in its Order |
| `create` | — | every Input field | 1 | the row |
| `update` | Match (default: the `PK`); comparison terms allowed | the other Input fields supplied | 0..1 on a unique key, else 0..n | the row or `None`; the count when it reaches many |
| `upsert` | Match: exactly one unique key | inserts the row, or replaces its other Input fields | 1 | the row |
| `delete` | Match: every Input field; comparison terms allowed | — | 0..1 on a unique key, else 0..n | the Output built from the Match or `None`; the count when it reaches many |

No other operator, no OR, no join, and no SQL exists outside the package.

### The operation contract

`DATABASE_compact.md` ends with a generated `## Operation Surface`: per table, one block per
operation, rendered from the declaration by Drydock, never by a model. Build against it.

````markdown
#### `db.rates.replace_rate` — FEATURE-RATE-004

| Kind | Rows | Match | Sets | Contract |
|---|---|---|---|---|
| upsert | 1 | `date`, `currency` | `rate` | `3f9a1c04be72` |

- Input: `{"date": "str", "currency": "str", "rate": "str"}`
- Output: `{"id": "int", "date": "str", "currency": "str", "rate": "str"}`

```sql
INSERT INTO "rates" ("date", "currency", "rate") VALUES (?, ?, ?) ON CONFLICT ("date", "currency") DO UPDATE SET "rate" = excluded."rate";
SELECT "id", "date", "currency", "rate" FROM "rates" WHERE "date" = ? AND "currency" = ?;
```
````

- **Call:** `db.<table>.<name>(...)`; Go `db.<Table>.<Name>(ctx, <Table><Name>Input{...})`.
- **Input / Output:** JSON field names with caller types `str`, `int`, `float`, `bool`, `bytes`.
  `?` marks a field the caller may omit: a `list` filter or bound, or a column an `update` sets
  only when supplied. A `- Order:` line states a `list`'s sort keys. Output is `{...}`, `{...} | null`, `[{...}]`, or `"int" (rows changed)`.
- **SQL:** the statements the runtime executes, in SQLite placeholder form; PostgreSQL binds the
  same positions. A test holds it byte-identical to the shipped driver.
- **Contract:** the operation's fingerprint, the first 12 hex digits of a SHA-256.

### What forces a rebuild

Only a contract change. The fingerprint hashes the name, Kind, Match terms, Order, rows, return shape, and each
Input and Output field's name and caller type. It excludes everything a caller cannot see: column
length (`VARCHAR(12)` and `VARCHAR(40)` are both `str`), nullability, `Required`, `DEFAULT`,
indexes, and the SQL. Refit rebuilds the callers of an operation only when its fingerprint moves;
any other `DATABASE.md` edit rebuilds the generated package alone.

**The declaration fixes the surface.** `DATABASE.md` names every operation in the
`Repository operation` cell of each access pattern, as `<table>.<name>`. 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. The store may hold data before any criterion runs: assert on records the
criterion created, or on a count read before setup (`after == before + 5`), never on an absolute
table count.

The acceptance harness owns isolation. It begins one transaction before each Python criterion and
rolls it back when the criterion ends, pass or fail. Every database the criterion's process opens
joins it: `db_session()`, the application behind `web_client()`, and commands run through
`cli_runner()`. Setup, behavior and readback therefore see one another's writes, and none persists;
leaving a `with db_session() as db:` block rolls nothing back. Seed with `with db_session() as db:`
and pass that database into feature operations. Never commit, clean up, or open a transaction.

A criterion that launches a process (`subprocess`, a server on a port, a shell script) cannot see
that transaction. It does not open the store and does not depend on rows it wrote; exercise stored
behavior in-process instead. Go criteria use `OpenSession(ctx, "")` with checked deferred cleanup,
which rolls back its own transaction. Go HTTP, CLI and restart criteria use
`OpenCommittedSession(ctx, "")` with a criterion-owned identifier and checked `defer` cleanup
through supported product interfaces. 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
- [ ] Callers built against the Operation Surface contract: name, Input/Output JSON, rows

</pblock>

<pblock filename="sqlite.md" role="stack" path="/mnt/c/Users/barlo/projects/drydock/Rigging/stack/sqlite.md">

# SQLite

**Type:** database
**Version:** 20261023 V3
**Tier:** platform
**Category:** Persistence
**Foundation:** database
**Description:** SQLite as a Drydock store: what it enforces, what it ignores, and how a Target reaches it.

Technology reference. This file does not change between projects.

Prerequisite: `stack/persistence.md`

---

## Foundation Contract

The published Python binding follows. Go callers use the language-native API in
`languages/go/go.md`; Go tests run through the existing Blueprint AC container.
Carried verbatim into `sqlite_compact.md`.

- package: persistence
- entry: open_database(dsn) -> Database
- fixture: db_session
- fixture_source: persistence/testing.py

### How is this engine configured and initialized?

For the shipped Python binding, use the standard-library `sqlite3` driver and a file path or
`sqlite://` DSN. Configuration resolves `DATABASE_URL`, then `DATABASE_PATH`, then `data/app.db`.
Drydock applies generated `schema.sql` only at the DATABASE step; later acceptance verifies the existing store without DDL. Declare
schema changes in `DATABASE.md`; rebuilding applies idempotent creation statements, not a
migration of existing tables. The engine owns connections and enables foreign keys.

### How does this engine implement the shared persistence contract?

The shipped Python binding is `Rigging/languages/python/persistence/sqlite.py`, used through `persistence.db` and
`open_database(dsn)`. Call declared table operations and use `db_session()` for criteria; do not
import the driver in application code. SQLite does not prove PostgreSQL length/type enforcement.
Library verification is in `tests/test_shipped_database.py`; verify Target-specific operations
separately. The Go binding is `languages/go/persistence/sqlite.go`, verified against this engine.
Use `OpenDatabase(ctx, dsn)` and generated typed methods; `OpenSession(ctx, dsn)` supplies
a test store. The Go library is linked as `drydock.local/persistence`. The detailed Python interface follows.

**How the Python binding is built.** Drydock builds this foundation deterministically. No build agent writes,
edits, or replaces any file listed below.

1. Plan declares the store in `DATABASE.md`: every table, every column, and each access pattern's
   `Repository operation` as `<table>.<verb>`.
2. Plan emits the story that implements `DATABASE.md`, with `persistence.md` and `sqlite.md` in
   `stack:`. That story is the DATABASE step. Its builder writes no persistence code.
3. Before that story's step runs, Drydock writes the package into the build root, so a story in
   the same step can import it:

| Layer | File | Origin |
|---|---|---|
| Library | `persistence/db.py` | shipped `Rigging/languages/python/persistence/db.py`, copied unchanged: `Database`, statement construction, parameter binding, engine selection |
| Engines | `persistence/sqlite.py`, `persistence/postgres.py` | shipped, copied unchanged; the DSN selects one at runtime |
| Declaration | `persistence/schema.py` | generated from `DATABASE.md`: `SCHEMA` (tables, operations, row dataclasses) and `open_database(dsn)`; contains no SQL |
| Interface | `persistence/__init__.py` | generated; exports `Database`, `PersistenceError`, `UnknownOperation`, `SCHEMA`, `open_database` |
| Verification | `schema-verification.json` | generated runtime catalog and count probes |
| Fixture | `persistence/testing.py` | generated; `db_session()` |
| DDL | `schema.sql` | generated from `DATABASE.md`; `CREATE ... IF NOT EXISTS` throughout |

4. Drydock applies `schema.sql` through `open_database` to the configured store — `DATABASE_URL`,
   else `DATABASE_PATH`, else `data/app.db` — at the DATABASE step and again before every
   acceptance run, so a criterion that drives the application through its own client finds the
   declared tables.

Every later story writes callers only: `route → service → db.<table>.<name>(...)`. The package
exposes one attribute per declared table and one method per declared operation. Changing the
store means changing `DATABASE.md` and rebuilding.

Each Kind returns one fixed shape, so a pattern's Output declares the row, never a wrapper
around it:

| Kind | Returns |
|---|---|
| `get` | the Output row, or `None` (Go `nil`) when nothing matches |
| `list` | a list of Output rows, one per record; the Output names the row's columns |
| `create` | the Output row, read back by key; the key when no Output is declared |
| `update` | the Output row, read back by its Match, or `None` when nothing matched; the count when it reaches many rows or no Output is declared |
| `upsert` | the Output row inserted or replaced, read back by its Match |
| `delete` | the Output built from its Match, or `None` when nothing matched; the count when it reaches many rows or no Output is declared |

```python
# persistence/testing.py — generated by Drydock
@contextmanager
def db_session() -> Iterator[Database]: ...
def committed_session() -> Iterator[Database]: ...

# application code
from persistence import open_database

db = open_database(config.database_path)

# a criterion
from persistence.testing import db_session

with db_session() as db:
    row = db.<table>.create(...)  # the declared Output row

# conftest.py
import pytest
from persistence import testing

@pytest.fixture
def db_session():
    with testing.db_session() as db:
        yield db
```

`db_session()` opens the configured application store (DATABASE_URL, else DATABASE_PATH,
else data/app.db). Schema is provisioned only at the DATABASE step. Pass the yielded database into
the feature. Under the acceptance harness, every database the criterion's process opens, including
this fixture, the application behind `web_client()`, and commands run through `cli_runner()`, joins
one transaction that the harness rolls back when the criterion ends, pass or fail. Leaving the
`with` block rolls nothing back, so a later request still sees the setup. Outside the harness (the
project's pytest suite) the fixture starts its own transaction and rolls it back on exit. It never
creates a temporary database or applies schema. `committed_session()` opens the same store with
autocommit for project tests that need committed state, and joins the harness transaction under
acceptance. A process the criterion launches cannot see that transaction and must not depend on
its rows. Never reset the database or delete unrelated records.

---

## You do not write the access layer

Drydock generates the persistence package from `DATABASE.md` and copies the SQLite engine in
unchanged. Connection handling, thread discipline, PRAGMAs, parameter binding, and row mapping all
live there. A hand-written connection helper, cursor, or SQL string is a review failure.

**By language**

| Language | Adapter | What the build writes |
|---|---|---|
| Python | `Rigging/languages/python/persistence/sqlite.py`, shipped | callers only — `db.<table>.<verb>(...)` |
| Go | `Rigging/languages/go/persistence/sqlite.go`, shipped | typed callers; declarations and fixtures are generated |
| other languages | none yet | a Target declaring `DATABASE.md` fails before planning |

## Role

SQLite is the development and test engine. It is a file, it needs no server, and it opens from a
plain path or a `sqlite://` DSN. Production relational storage is PostgreSQL; see
`stack/postgres.md`.

Both engines are copied into every build and selected at runtime from the DSN, so the same build
runs SQLite in test and PostgreSQL in production without rebuilding.

## What it enforces

`PRIMARY KEY`, `NOT NULL`, `UNIQUE`, `DEFAULT`, and — with `PRAGMA foreign_keys=ON`, which the
shipped engine sets — `REFERENCES`.

## What it ignores

**Column length.** SQLite has type affinity, not length. `VARCHAR(50)` parses and is stored as
`TEXT`, and a 500-character value is accepted. The same declaration is emitted to PostgreSQL,
which does enforce it, so **a length violation passes in test and fails in production.** Declare
lengths for the production engine and do not rely on SQLite to catch them.

**Type strictness.** Any value may be stored in any column. A test that passes on SQLite has not
proven the column types.

**`ALTER TABLE`.** Only `ADD COLUMN` and `RENAME` are supported; there is no `DROP COLUMN` before
3.35, no type change, and no `ADD CONSTRAINT`. Within a release this never arises — the schema is
built once, at the DATABASE build step, from `schema.sql`.

## Guardrails

- Never import `sqlite3` outside the generated `persistence/` package.
- Never hold a `sqlite3.Connection` on an application object; the engine owns connection lifetime.
- Never create or alter schema at application startup.
- Never treat a green SQLite test as proof that column lengths or types hold in production.

</pblock>

<pblock filename="fastapi.md" role="stack" path="/mnt/c/Users/barlo/projects/drydock/Rigging/stack/fastapi.md">

# FastAPI Foundation

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

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

## Foundation Contract

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

```python
# app_server/main.py
def create_app() -> FastAPI: ...
app = create_app()

# app_server/testing.py
from app_server.main import create_app
def web_client() -> TestClient: ...
```

`app_server.main` exposes `create_app()` and a module-level `app` for
`uvicorn app_server.main:app`. `app_server.testing.web_client()` is a plain callable that
returns `fastapi.testclient.TestClient(create_app())`. Programmatic acceptance imports and calls
it directly. The pytest `web_client` fixture delegates to the same callable.

## Rules

- Keep routes in `app_server` routers. Route handlers parse HTTP input, call application services,
  and return responses; services own business behavior and have no FastAPI dependency.
- Provide shared resources through dependencies that tests can replace with
  `app.dependency_overrides`. Do not create a second application or test client in acceptance code.
- Validate request and response shapes at the HTTP boundary. Use the Blueprint's routes, schemas,
  configuration names, defaults, and error contracts; sample routes are not part of this foundation.
- For server-rendered pages, include `request` in Jinja template context and serve static assets
  through the application. Return sanitized errors in the format required by the Blueprint.
- Put startup and shutdown work in lifespan handlers. Use Uvicorn reload only in development.
- Declare `fastapi`, `uvicorn`, and the TestClient transport as needed by runtime and tests. Add `jinja2` only when
  the application serves templates. Use the Python foundation's environment and test command.

## Test dependency compatibility

Keep `fastapi.testclient.TestClient` as the client API. Starlette 1.2 and newer prefer `httpx2`;
plain `httpx` is deprecated there. Declare `fastapi` and `httpx2` inside every TestClient acceptance
criterion with `Requires: python-package=<name>; scope=test`. Older selected Starlette versions
use `httpx` instead. Resolve and lock the compatible FastAPI/Starlette/transport set together;
do not override FastAPI's Starlette constraints or suppress deprecation warnings. Verify client
construction and a request with deprecations treated as errors before accepting the lockfile.
Reference: https://www.starlette.io/testclient/

</pblock>

<pblock filename="cli.md" role="stack" path="/mnt/c/Users/barlo/projects/drydock/Rigging/stack/cli.md">

# Command-Line Application

**Type:** cli
**Version:** 20260920 V1
**Tier:** platform
**Category:** Technologies
**Foundation:** cli
**Description:** Command-line application structure: entry point, argument parsing, exit codes, cross-platform launchers, and testing without spawning a process.

Technology reference. This file does not change between projects.

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

---

## Foundation Contract

The published shape of this foundation. Drydock synthesizes the story that builds it and every
acceptance criterion writes against these names. Carried verbatim into `cli_compact.md`.

- package: cli
- entry: main(argv: list[str] | None = None) -> int
- fixture: cli_runner
- fixture_source: cli/testing.py

```python
# cli/__init__.py
def main(argv: list[str] | None = None) -> int:
    ...

# cli/testing.py
import contextlib
import io
from cli import main

def cli_runner(*args: str) -> tuple[int, str, str]:
    """Return (exit_code, stdout, stderr) without spawning a process."""
    out, err = io.StringIO(), io.StringIO()
    with contextlib.redirect_stdout(out), contextlib.redirect_stderr(err):
        code = main(list(args))
    return code, out.getvalue(), err.getvalue()

# conftest.py
import pytest
from cli import testing

@pytest.fixture
def cli_runner():
    return testing.cli_runner
```

A criterion imports `cli_runner` from `cli.testing`, calls `cli_runner("status", "--json")`, and
asserts on the returned tuple. It does not call `subprocess.run`, which measures the installed
console script and the shell rather than the code the story wrote.

---

## 1. Directory Layout

**Rule**: Command code lives in `cli/`. The root holds only packaging and infrastructure files.

```
project/
  pyproject.toml            # [project.scripts] declares the console script
  cli/
    __init__.py             # main() — the single entry point
    commands.py             # one function per command; no argument parsing
    parser.py               # argparse construction; no behavior
  bin/
    run.sh                  # bash launcher
    run.ps1                 # PowerShell launcher
  tests/
```

**Why**: Parsing, behavior, and launching are three contracts. Collapsing them produces a command
that cannot be tested without a shell.

---

## 2. Entry Point and Exit Codes

**Rule**: `main(argv=None) -> int` parses, dispatches, and returns an exit code. It never calls
`sys.exit` and never raises for an expected failure. The console script is the only caller that
translates the return value into a process exit.

```python
# cli/__init__.py
import sys
from cli.parser import build_parser
from cli import commands

def main(argv: list[str] | None = None) -> int:
    args = build_parser().parse_args(argv)
    try:
        return commands.dispatch(args)
    except OperationalError as exc:
        print(f"error: {exc}", file=sys.stderr)
        return 1
```

```toml
# pyproject.toml
[project.scripts]
mytool = "cli:main"
```

**Exit codes**: `0` success, `1` operational failure, `2` usage error. `argparse` already returns
`2` for a usage error; do not override it.

**Why**: A `main` that returns rather than exits is callable from a test in-process. A `main` that
calls `sys.exit` forces every criterion to spawn a subprocess and measure the shell.

---

## 3. Parsing Is Separate From Behavior

**Rule**: `parser.py` builds the `argparse` tree and returns it. `commands.py` holds one function
per command taking plain arguments, not a `Namespace`. Neither imports the other.

```python
# cli/parser.py
import argparse

def build_parser() -> argparse.ArgumentParser:
    parser = argparse.ArgumentParser(prog="mytool")
    sub = parser.add_subparsers(dest="command", required=True)
    status = sub.add_parser("status", help="Report current state")
    status.add_argument("--json", action="store_true")
    return parser
```

```python
# cli/commands.py
def status(*, as_json: bool) -> int:
    ...

def dispatch(args) -> int:
    if args.command == "status":
        return status(as_json=args.json)
    return 2
```

**Why**: Behavior tested through a `Namespace` is behavior tested through the parser. Separating
them lets a criterion call `status(as_json=True)` directly.

---

## 4. Cross-Platform Launchers

**Rule**: Ship both launchers. They locate the environment and invoke the package entry point;
they contain no business logic. A launcher that makes a decision is a second implementation of the
command.

```bash
#!/usr/bin/env bash
# bin/run.sh — locate the environment and hand off. No business logic.
set -euo pipefail
ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"
if [ -d "$ROOT/.venv" ]; then
    source "$ROOT/.venv/bin/activate"
fi
exec python -m cli "$@"
```

```powershell
# bin/run.ps1 — locate the environment and hand off. No business logic.
$ErrorActionPreference = "Stop"
$Root = Split-Path -Parent $PSScriptRoot
$Activate = Join-Path $Root ".venv\Scripts\Activate.ps1"
if (Test-Path $Activate) { & $Activate }
python -m cli @args
exit $LASTEXITCODE
```

```python
# cli/__main__.py — makes `python -m cli` work identically on both platforms
import sys
from cli import main

sys.exit(main())
```

**Why**: `python -m cli` is the one invocation both launchers share, so the two scripts cannot
drift in behavior — only in how they find the interpreter. `exit $LASTEXITCODE` is required in
PowerShell; without it the exit code is discarded and a failing command reports success.

---

## 5. Output and Streams

**Rule**: Results go to stdout, diagnostics to stderr. A `--json` mode prints one JSON document to
stdout and nothing else. Never interleave progress text into a machine-readable stream.

**Why**: A caller piping stdout to `jq` receives the progress lines too, and the command becomes
unusable in a pipeline.

---

## 6. Testing Without a Process

**Rule**: Test through `main(["status", "--json"])` or the `cli_runner` fixture. Reserve
`subprocess.run` for one packaging test asserting the installed console script exists and runs.

```python
def test_status_reports_json(cli_runner):
    code, out, err = cli_runner("status", "--json")
    assert code == 0
    assert json.loads(out)["state"] == "ready"
    assert err == ""
```

**Why**: In-process tests are fast, debuggable, and measure the code. Subprocess tests measure the
installed environment, which is a different and much smaller question.

---

## Checklist

- [ ] `cli/` package; `main(argv=None) -> int` that returns rather than exits
- [ ] `[project.scripts]` declares the console script
- [ ] `cli/__main__.py` so `python -m cli` works
- [ ] Both `bin/run.sh` and `bin/run.ps1`, neither holding logic; `.ps1` ends with `exit $LASTEXITCODE`
- [ ] Parsing in `parser.py`, behavior in `commands.py`, no import between them
- [ ] Exit codes `0` / `1` / `2` used consistently
- [ ] Results on stdout, diagnostics on stderr, `--json` emits nothing else
- [ ] Criteria use `cli_runner`; at most one subprocess test for packaging

</pblock>

CONTEXT - Read-Only Support

<pblock filename="ARCHITECTURE.md" role="context" path="/mnt/c/Users/barlo/projects/drydock/uat/FxRates/runs/20261026.202600/workspace/targets/FxRates/blueprint/ARCHITECTURE.md" guidance="Foundational Architecture Specification">

# ARCHITECTURE: FxRates Application

| Field       | Value |
|-------------|-------|
| Version     | 20261026 V1 |
| Description | Defines the application modules and ownership boundaries for the FxRates command line and API. |

## Module Boundaries

| Module | Owns | Allowed dependencies |
|--------|------|---------------------|
| `cli` | The `fxrates` executable, argument handling, command dispatch, and diagnostics. | Feature services, configuration |
| `app_server` | The FastAPI application factory and HTTP route registration. | Feature services, configuration |
| `services` | ECB CSV validation and loading, fetching, store initialization, rate queries, and exact decimal calculations. | `persistence`, configuration, standard library |
| `persistence` | The generated relational layer and shipped database library. | Database engine and schema |
| `config` | Resolving the database location from `DATABASE_URL`, then `DATABASE_PATH`, then `data/app.db`. | Standard library |

HTTP handlers call services. CLI commands call services. Services call the generated persistence operations through the shipped persistence library. Only the persistence boundary reaches the database. No application module opens a database driver directly.

The load workflow validates the complete input file before its first write. The fetch workflow extracts the archive's CSV and passes it through the same validation and loading behavior. Rate calculations use `decimal.Decimal`; published values remain text in storage and API responses.

## Technology Stack

| Technology | Use |
|------------|-----|
| Python 3.11 or newer | Application, CLI, services, and tests |
| FastAPI | JSON HTTP API |
| uvicorn | Serving the API on `127.0.0.1` |
| SQLite | Local rates store, accessed through the shipped persistence library |
| pytest | Offline automated tests |
| FastAPI `TestClient` | In-process API checks |

## Programmatic Acceptance

=== AC architecture-service-boundary ===
Intent: The application provides an importable services boundary for shared CLI and API behavior.

import importlib.util

services_spec = importlib.util.find_spec("services")
assert services_spec is not None
=== END AC architecture-service-boundary ===

## User Acceptance

- None.

## Guardrails

- Application code reaches SQLite only through the shipped persistence library and generated relational layer.
- Preserve rates as ECB-published text; use `decimal.Decimal` for arithmetic and never floating point.
- Keep file validation ahead of the first database write.
- Resolve database configuration in this order: `DATABASE_URL`, `DATABASE_PATH`, then `data/app.db`.

</pblock>

<pblock filename="DATABASE.md" role="context" path="/mnt/c/Users/barlo/projects/drydock/uat/FxRates/runs/20261026.202600/workspace/targets/FxRates/blueprint/DATABASE.md" guidance="Database and PersistenceSpecification">

# DATABASE: FxRates

| Field | Value |
|-------|-------|
| Version | 20261026 V1 |
| Description | Declares the rates store and typed repository operations used by FxRates. |
| Depends On | ARCHITECTURE.md |
| Provides | rates repository operations |

## Persistence Boundary

| Boundary | Rule |
|----------|------|
| Raw storage access | Only the generated `persistence/` package reaches the store. |
| Caller dependency | Features use the declared repository operations and DTOs, not the schema. |
| Implementation | Drydock generates the persistence package and DDL from this declaration. |

## Access Patterns

### FEATURE-RATE-001 — Store or replace a published rate

| Field | Value |
|-------|-------|
| Owner | DATABASE.md |
| Access | write |
| Repository operation | `rates.upsert` |
| Compatibility | unchanged |
| Match | `date`, `currency` |

Input: RateUpsertInput

| Field | Type |
|-------|------|
| date | str |
| currency | str |
| rate | str |

Output: RateUpsertOutput

| Field | Type |
|-------|------|
| date | str |
| currency | str |
| rate | str |

### FEATURE-RATE-002 — List rates for a publication date

| Field | Value |
|-------|-------|
| Owner | DATABASE.md |
| Access | read |
| Repository operation | `rates.by_date` |
| Kind | list |
| Match | `date` |
| Order | `currency` asc |
| Compatibility | unchanged |

Input: RatesByDateInput

| Field | Type |
|-------|------|
| date | str |

Output: RatesByDateOutput

| Field | Type |
|-------|------|
| date | str |
| currency | str |
| rate | str |

### FEATURE-RATE-003 — Find publications on or before a date

| Field | Value |
|-------|-------|
| Owner | DATABASE.md |
| Access | read |
| Repository operation | `rates.publications_through` |
| Kind | list |
| Match | `date <= requested_date` |
| Order | `date` desc |
| Compatibility | unchanged |

Input: RatesPublicationsThroughInput

| Field | Type |
|-------|------|
| requested_date | str |

Output: RatesPublicationsThroughOutput

| Field | Type |
|-------|------|
| date | str |
| currency | str |
| rate | str |

### FEATURE-RATE-004 — List a currency's rates within optional date bounds

| Field | Value |
|-------|-------|
| Owner | DATABASE.md |
| Access | read |
| Repository operation | `rates.history` |
| Kind | list |
| Match | `currency`, `date >= start_date`, `date <= end_date` |
| Order | `date` asc |
| Compatibility | unchanged |

Input: RatesHistoryInput

| Field | Type |
|-------|------|
| currency | str |
| start_date | str |
| end_date | str |

Output: RatesHistoryOutput

| Field | Type |
|-------|------|
| date | str |
| currency | str |
| rate | str |

### FEATURE-RATE-005 — List stored rates

| Field | Value |
|-------|-------|
| Owner | DATABASE.md |
| Access | read |
| Repository operation | `rates.list` |
| Kind | list |
| Compatibility | unchanged |

Input: RatesListInput

| Field | Type |
|-------|------|

Output: RatesListOutput

| Field | Type |
|-------|------|
| date | str |
| currency | str |
| rate | str |

## Schemas

## `rates`

| Field | Type | Notes |
|-------|------|-------|
| id | INTEGER PK | Generated row identifier. |
| date | TEXT NOT NULL | ECB publication date in `YYYY-MM-DD` form. |
| currency | TEXT NOT NULL | Three-letter uppercase currency code. |
| rate | TEXT NOT NULL | ECB-published rate text, preserved exactly. |

- UNIQUE (date, currency)

## Migrations

| Access Pattern | Revision | State |
|----------------|----------|-------|

## Config (.env)

| Key | Type | Required | Notes |
|-----|------|----------|-------|
| DATABASE_URL | str | No | Database DSN; takes precedence over `DATABASE_PATH`. |
| DATABASE_PATH | str | No | Database file path used when `DATABASE_URL` is unset. |

## File Stores

| Store | Root dir | Notes |
|-------|----------|-------|

## External Services

| Service | Wrapper | Notes |
|---------|---------|-------|

## External Libraries

| Library | Ownership | Distribution | Consumer Contract |
|---------|-----------|--------------|-------------------|
| ECB reference rates | Fetch feature | ECB history ZIP | Fetch downloads and extracts the archive before passing its CSV through the load workflow. |

## Programmatic Acceptance

=== AC rates-upsert ===
Intent: The repository stores a rate and replaces the value for the same date and currency.

from persistence.testing import db_session

date = "2099-01-02"
currency = "QAA"
rate = "1.234"
replacement = "1.235"

with db_session() as db:
    first = db.rates.upsert(date=date, currency=currency, rate=rate)
    assert first.date == date
    assert first.currency == currency
    assert first.rate == rate

    second = db.rates.upsert(date=date, currency=currency, rate=replacement)
    assert second.rate == replacement

    stored = db.rates.by_date(date=date)
    assert len([row for row in stored if row.currency == currency]) == 1
    assert next(row for row in stored if row.currency == currency).rate == replacement
=== END AC rates-upsert ===

=== AC rates-by-date ===
Intent: The repository returns the stored rates for a requested publication date.

from persistence.testing import db_session

date = "2099-02-03"
currency = "QAB"
rate = "2.50"

with db_session() as db:
    db.rates.upsert(date=date, currency=currency, rate=rate)
    rows = db.rates.by_date(date=date)
    assert any(row.date == date and row.currency == currency and row.rate == rate for row in rows)
=== END AC rates-by-date ===

=== AC rates-publications-through ===
Intent: The repository returns stored publications on or before the requested date in descending date order.

from persistence.testing import db_session

earlier = "2099-03-01"
later = "2099-03-02"
requested = later
currency = "QAC"

with db_session() as db:
    db.rates.upsert(date=earlier, currency=currency, rate="3")
    db.rates.upsert(date=later, currency=currency, rate="4")
    rows = db.rates.publications_through(requested_date=requested)
    dates = list(dict.fromkeys(row.date for row in rows))
    assert dates == sorted(dates, reverse=True)
    assert earlier in dates
    assert later in dates
=== END AC rates-publications-through ===

=== AC rates-history ===
Intent: The repository returns a currency's rates within inclusive optional date bounds in ascending date order.

from persistence.testing import db_session

currency = "QAD"
start = "2099-04-02"
end = "2099-04-03"
before = "2099-04-01"
after = "2099-04-04"

with db_session() as db:
    db.rates.upsert(date=before, currency=currency, rate="1")
    db.rates.upsert(date=start, currency=currency, rate="2")
    db.rates.upsert(date=end, currency=currency, rate="3")
    db.rates.upsert(date=after, currency=currency, rate="4")
    rows = db.rates.history(currency=currency, start_date=start, end_date=end)
    assert [row.date for row in rows] == [start, end]
=== END AC rates-history ===

=== AC rates-list ===
Intent: The repository lists stored rates with their published text.

from persistence.testing import db_session

date = "2099-05-06"
currency = "QAE"
rate = "5.006"

with db_session() as db:
    db.rates.upsert(date=date, currency=currency, rate=rate)
    rows = db.rates.list()
    assert any(row.date == date and row.currency == currency and row.rate == rate for row in rows)
=== END AC rates-list ===

## User Acceptance

- None.

## Guardrails

- Preserve every ECB rate as published text; do not store or compute rates as floating-point values.
- Application code accesses the database only through the shipped persistence library and generated relational layer.
- Database location resolves from `DATABASE_URL`, then `DATABASE_PATH`, then `data/app.db`.
- Keep the `(date, currency)` uniqueness rule so loading an existing rate replaces that stored value.

</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="DATABASE.md" role="implements" path="/mnt/c/Users/barlo/projects/drydock/uat/FxRates/runs/20261026.202600/workspace/targets/FxRates/blueprint/DATABASE.md" guidance="Database and PersistenceSpecification">

# DATABASE: FxRates

| Field | Value |
|-------|-------|
| Version | 20261026 V1 |
| Description | Declares the rates store and typed repository operations used by FxRates. |
| Depends On | ARCHITECTURE.md |
| Provides | rates repository operations |

## Persistence Boundary

| Boundary | Rule |
|----------|------|
| Raw storage access | Only the generated `persistence/` package reaches the store. |
| Caller dependency | Features use the declared repository operations and DTOs, not the schema. |
| Implementation | Drydock generates the persistence package and DDL from this declaration. |

## Access Patterns

### FEATURE-RATE-001 — Store or replace a published rate

| Field | Value |
|-------|-------|
| Owner | DATABASE.md |
| Access | write |
| Repository operation | `rates.upsert` |
| Compatibility | unchanged |
| Match | `date`, `currency` |

Input: RateUpsertInput

| Field | Type |
|-------|------|
| date | str |
| currency | str |
| rate | str |

Output: RateUpsertOutput

| Field | Type |
|-------|------|
| date | str |
| currency | str |
| rate | str |

### FEATURE-RATE-002 — List rates for a publication date

| Field | Value |
|-------|-------|
| Owner | DATABASE.md |
| Access | read |
| Repository operation | `rates.by_date` |
| Kind | list |
| Match | `date` |
| Order | `currency` asc |
| Compatibility | unchanged |

Input: RatesByDateInput

| Field | Type |
|-------|------|
| date | str |

Output: RatesByDateOutput

| Field | Type |
|-------|------|
| date | str |
| currency | str |
| rate | str |

### FEATURE-RATE-003 — Find publications on or before a date

| Field | Value |
|-------|-------|
| Owner | DATABASE.md |
| Access | read |
| Repository operation | `rates.publications_through` |
| Kind | list |
| Match | `date <= requested_date` |
| Order | `date` desc |
| Compatibility | unchanged |

Input: RatesPublicationsThroughInput

| Field | Type |
|-------|------|
| requested_date | str |

Output: RatesPublicationsThroughOutput

| Field | Type |
|-------|------|
| date | str |
| currency | str |
| rate | str |

### FEATURE-RATE-004 — List a currency's rates within optional date bounds

| Field | Value |
|-------|-------|
| Owner | DATABASE.md |
| Access | read |
| Repository operation | `rates.history` |
| Kind | list |
| Match | `currency`, `date >= start_date`, `date <= end_date` |
| Order | `date` asc |
| Compatibility | unchanged |

Input: RatesHistoryInput

| Field | Type |
|-------|------|
| currency | str |
| start_date | str |
| end_date | str |

Output: RatesHistoryOutput

| Field | Type |
|-------|------|
| date | str |
| currency | str |
| rate | str |

### FEATURE-RATE-005 — List stored rates

| Field | Value |
|-------|-------|
| Owner | DATABASE.md |
| Access | read |
| Repository operation | `rates.list` |
| Kind | list |
| Compatibility | unchanged |

Input: RatesListInput

| Field | Type |
|-------|------|

Output: RatesListOutput

| Field | Type |
|-------|------|
| date | str |
| currency | str |
| rate | str |

## Schemas

## `rates`

| Field | Type | Notes |
|-------|------|-------|
| id | INTEGER PK | Generated row identifier. |
| date | TEXT NOT NULL | ECB publication date in `YYYY-MM-DD` form. |
| currency | TEXT NOT NULL | Three-letter uppercase currency code. |
| rate | TEXT NOT NULL | ECB-published rate text, preserved exactly. |

- UNIQUE (date, currency)

## Migrations

| Access Pattern | Revision | State |
|----------------|----------|-------|

## Config (.env)

| Key | Type | Required | Notes |
|-----|------|----------|-------|
| DATABASE_URL | str | No | Database DSN; takes precedence over `DATABASE_PATH`. |
| DATABASE_PATH | str | No | Database file path used when `DATABASE_URL` is unset. |

## File Stores

| Store | Root dir | Notes |
|-------|----------|-------|

## External Services

| Service | Wrapper | Notes |
|---------|---------|-------|

## External Libraries

| Library | Ownership | Distribution | Consumer Contract |
|---------|-----------|--------------|-------------------|
| ECB reference rates | Fetch feature | ECB history ZIP | Fetch downloads and extracts the archive before passing its CSV through the load workflow. |

## Programmatic Acceptance

=== AC rates-upsert ===
Intent: The repository stores a rate and replaces the value for the same date and currency.

from persistence.testing import db_session

date = "2099-01-02"
currency = "QAA"
rate = "1.234"
replacement = "1.235"

with db_session() as db:
    first = db.rates.upsert(date=date, currency=currency, rate=rate)
    assert first.date == date
    assert first.currency == currency
    assert first.rate == rate

    second = db.rates.upsert(date=date, currency=currency, rate=replacement)
    assert second.rate == replacement

    stored = db.rates.by_date(date=date)
    assert len([row for row in stored if row.currency == currency]) == 1
    assert next(row for row in stored if row.currency == currency).rate == replacement
=== END AC rates-upsert ===

=== AC rates-by-date ===
Intent: The repository returns the stored rates for a requested publication date.

from persistence.testing import db_session

date = "2099-02-03"
currency = "QAB"
rate = "2.50"

with db_session() as db:
    db.rates.upsert(date=date, currency=currency, rate=rate)
    rows = db.rates.by_date(date=date)
    assert any(row.date == date and row.currency == currency and row.rate == rate for row in rows)
=== END AC rates-by-date ===

=== AC rates-publications-through ===
Intent: The repository returns stored publications on or before the requested date in descending date order.

from persistence.testing import db_session

earlier = "2099-03-01"
later = "2099-03-02"
requested = later
currency = "QAC"

with db_session() as db:
    db.rates.upsert(date=earlier, currency=currency, rate="3")
    db.rates.upsert(date=later, currency=currency, rate="4")
    rows = db.rates.publications_through(requested_date=requested)
    dates = list(dict.fromkeys(row.date for row in rows))
    assert dates == sorted(dates, reverse=True)
    assert earlier in dates
    assert later in dates
=== END AC rates-publications-through ===

=== AC rates-history ===
Intent: The repository returns a currency's rates within inclusive optional date bounds in ascending date order.

from persistence.testing import db_session

currency = "QAD"
start = "2099-04-02"
end = "2099-04-03"
before = "2099-04-01"
after = "2099-04-04"

with db_session() as db:
    db.rates.upsert(date=before, currency=currency, rate="1")
    db.rates.upsert(date=start, currency=currency, rate="2")
    db.rates.upsert(date=end, currency=currency, rate="3")
    db.rates.upsert(date=after, currency=currency, rate="4")
    rows = db.rates.history(currency=currency, start_date=start, end_date=end)
    assert [row.date for row in rows] == [start, end]
=== END AC rates-history ===

=== AC rates-list ===
Intent: The repository lists stored rates with their published text.

from persistence.testing import db_session

date = "2099-05-06"
currency = "QAE"
rate = "5.006"

with db_session() as db:
    db.rates.upsert(date=date, currency=currency, rate=rate)
    rows = db.rates.list()
    assert any(row.date == date and row.currency == currency and row.rate == rate for row in rows)
=== END AC rates-list ===

## User Acceptance

- None.

## Guardrails

- Preserve every ECB rate as published text; do not store or compute rates as floating-point values.
- Application code accesses the database only through the shipped persistence library and generated relational layer.
- Database location resolves from `DATABASE_URL`, then `DATABASE_PATH`, then `data/app.db`.
- Keep the `(date, currency)` uniqueness rule so loading an existing rate replaces that stored value.

</pblock>

<pblock filename="FEATURE-AppServer.md" role="implements" path="/mnt/c/Users/barlo/projects/drydock/uat/FxRates/runs/20261026.202600/workspace/targets/FxRates/blueprint/FEATURE-AppServer.md" guidance="Feature Specification">

# FEATURE: Application Server Foundation

| Field       | Value |
|-------------|-------|
| Version     | 20261026 V1 |
| Description | Establishes the FastAPI application factory and its in-process test client. |
| Depends On  | ARCHITECTURE.md |

## Purpose

Provide the shared FastAPI application entry point used by `uvicorn app_server.main:app` and by in-process acceptance checks.

## Interface

- `app_server.main.create_app()` returns a FastAPI application.
- `app_server.main.app` is the module-level application used by uvicorn.
- `app_server.testing.web_client()` returns a `fastapi.testclient.TestClient` for a newly created application.

This foundation registers no feature endpoints. Endpoint behavior belongs to the stories that provide those routes.

## Programmatic Acceptance

=== AC app-server-factory ===
Intent: The application factory and published test client are importable and construct the declared FastAPI interfaces.
Requires: python-package=fastapi; scope=test
Requires: python-package=httpx2; scope=test

from fastapi import FastAPI
from fastapi.testclient import TestClient
from app_server.main import app, create_app
from app_server.testing import web_client

created = create_app()
client = web_client()
assert isinstance(created, FastAPI)
assert isinstance(app, FastAPI)
assert isinstance(client, TestClient)
assert isinstance(client.app, FastAPI)
=== END AC app-server-factory ===

## User Acceptance

- None.

## Guardrails

- Do not implement or claim endpoints owned by later feature stories in this foundation.
- Expose `create_app()` and the module-level `app` from `app_server.main`.
- The published `web_client()` callable returns a TestClient built from `create_app()`.

</pblock>

<pblock filename="FEATURE-CLI.md" role="implements" path="/mnt/c/Users/barlo/projects/drydock/uat/FxRates/runs/20261026.202600/workspace/targets/FxRates/blueprint/FEATURE-CLI.md" guidance="Feature Specification">

# FEATURE: CLI Foundation

| Field       | Value |
|-------------|-------|
| Version     | 20261026 V1 |
| Description | Establishes the root executable and the published in-process CLI entry point. |
| Depends On  | ARCHITECTURE.md |

## Purpose

Provide the application-root executable `./fxrates`, the `cli.main(argv: list[str] | None = None) -> int` entry point, and the `cli.testing.cli_runner(*args)` helper. Feature stories own command behavior and its implementation.

## Interface

- `./fxrates <command>` invokes `cli.main`.
- `cli.testing.cli_runner(*args)` returns `(exit_code, stdout, stderr)` without spawning a process.
- Diagnostics are written to standard error.

## Programmatic Acceptance

=== AC cli-foundation-interfaces ===
Intent: The CLI entry point and in-process runner expose the published callable interfaces.
from cli import main
from cli.testing import cli_runner
import inspect

assert callable(main)
assert inspect.signature(main).parameters["argv"].default is None
result = cli_runner()
assert isinstance(result, tuple)
assert len(result) == 3
assert isinstance(result[0], int)
assert isinstance(result[1], str)
assert isinstance(result[2], str)
=== END AC cli-foundation-interfaces ===

## User Acceptance

- None.

## Guardrails

- Place an executable named `fxrates` at the application root.
- Keep command diagnostics on standard error.
- Command-specific behavior and error statuses are implemented by their owning stories.

</pblock>

<pblock label="Build instructions" kind="instructions">

Build instructions for this block

Declare the rates schema and generated repository contract. (database)

Declare the rates table with a unique (date, currency) key and text columns for date, currency, and the ECB-published rate. Declare the repository operations required to insert or replace rates, query rates by date, select the effective publication date, count dates and rates, list currencies, retrieve currency history over optional inclusive bounds, and find the latest publication. Use only operations supported by the generated persistence contract. Include executable acceptance for every declared repository operation.

Establish the FastAPI application and test client. (app_server)

Establish app_server.main.create_app() returning a FastAPI application and the module-level app used by uvicorn. Provide app_server.testing.web_client() as the published in-process test client callable. Do not implement endpoints owned by later stories.

Establish the fxrates executable and CLI entry point. (cli)

Establish the executable at the application root and the published cli.main(argv) and cli.testing.cli_runner() interfaces. Route commands to their owning capabilities; do not claim command behavior before those stories implement it. Keep diagnostics on standard error. Declare the usage and operational error conventions used by the command implementations.

</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:

</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:

authoritative; implement them exactly.

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.

  1. Start by inspecting the build working directory. Read the current contents of each file before

applying a contextual patch. If patch verification fails, re-read that file and rebuild the patch against its current text; do not repeat stale context or overwrite unrelated changes. 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.

  1. Implement only this step. Use context, stack, and rules as constraints,

not as additional work to perform.

  1. Follow the stack and rules for languages, structure, naming, and branding.
  2. 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 targeted tests for the behavior you change and preserve existing passing behavior. Drydock executes every declared acceptance assertion after your call and owns the verdict. Use available failure logs before rerunning suites to rediscover failures; use section or example filters to diagnose the underlying behavior, never example-specific exceptions. If you run a suite, wait for completion or its declared timeout; silence is not a hang.

  1. 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. When Drydock supplies a disposable SQLite store in DATABASE_URL/DATABASE_PATH, use those inherited values for development tests. Each agent call receives a fresh provisioned test store. Never delete a default database path to clean test failures. Project tests still need fixture-owned setup and cleanup so repeated tests in the same call do not depend on order. A managed-state violation stops the block and retains a recovery snapshot; do not restore or reprovision shared state yourself. Preserve published text even when a conflicting criterion requests formatting: report the source conflict and its evidence instead of changing semantics. Where a staged authoritative suite already covers a surface, use it as the coverage; do not duplicate its cases. Any invocation must respect this step's declared scope. Do not run the unscoped entry point for a Suite: scoped story, or run a suite this step does not declare. Report only completed checks and their observed results.

  1. Treat User Acceptance entries as review evidence requirements. Implement

the supporting behavior, but do not claim to have performed human judgment.

  1. 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.

  1. 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.

  1. 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.

  1. 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.

  1. 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.

  1. End your response with this exact closing structure:
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:

<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.

  1. FILES CHANGED must list only files actually written in the build working

directory. When the existing implementation already satisfies this step, report RESULT: SUCCESS, list no changed files, and state the checks performed and their results. A verification-only step requires no application changes. Drydock runs the declared deterministic checks and decides the outcome independently of this report.

  1. 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.

FAILURE_SUMMARY: <one line naming the cause>
FAILURE_DETAIL: <what happened, why, and what to change before rerunning>
  1. 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:

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.