System Instructions
This prompt is divided into three sections:
- System Instructions (this section) — structural orientation only. Do not treat this
section as task input.
- 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.
- 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: LayersTesting
- BUILD_DIRECTORY: /mnt/c/Users/barlo/projects/drydock/uat/LayersTesting/runs/20261020.191708/build/LayersTesting
- WORKING_DIRECTORY: /mnt/c/Users/barlo/projects/drydock/uat/LayersTesting/runs/20261020.191708/build/LayersTesting
- BUILD_BLOCK: Block 2 · Foundational (block-2)
- STORIES: Establish the relational ledger schema and persistence contract. (database-schema)
- DATE: 2026-10-20
- BUILD_SCOPE: exactly one MANIFEST.md build block
</pblock>
<pblock label="Stories in this block" kind="section">
Stories in this block
- Establish the relational ledger schema and persistence contract. (database-schema) [story]
</pblock>
<pblock label="Files on disk" kind="section">
Files on disk in the build directory
- sources/run.sh
- sources/seed_accounts.csv
- sources/seed_categories.csv
- sources/seed_transactions.csv
- sources/seed_transactions_bad.csv
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>
<pblock label="Missing context files" kind="section"> Missing context files (named by the plan but not found):
- context: INSTRUCTIONS.md
</pblock>
COMPASS - Target Orientation
<pblock filename="COMPASS.md" role="compass" path="/mnt/c/Users/barlo/projects/drydock/uat/LayersTesting/runs/20261020.191708/workspace/targets/LayersTesting/COMPASS.md" guidance="Important: This is the core project intent, constraints, and guardrails. It should have presecedence in conflicts.">
# COMPASS: LayersTesting
## Compass
Build a command-line cash ledger, an executable named `ledger` at the application root, as
described in `sources/INSTRUCTIONS.md`. It keeps accounts, categories, and cash transactions in a
relational database reached only through the shipped persistence library, rejects a failing command
before it writes, enforces non-negative balances, and reports balances, category totals, and monthly totals.
Correctness is measured by `sources/run.sh`: 43 checks of exit code and standard output against
known answers computed from the seed files. The goal is every check passing.
## Constraints
- Implement in the language and database named under `## Stack` in `sources/INSTRUCTIONS.md`.
- Provide an executable named `ledger` at the application root, invoked as `./ledger <command>`.
- Read the database location from `DATABASE_URL`, then `DATABASE_PATH`, then `data/app.db`.
- Store amounts as integer cents.
- Check every command in full before its first write.
- Run without network access other than to a PostgreSQL server named by `DATABASE_URL`.
- 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 seed file from application code. Seed files reach the
database only through `ledger load`.
- Do not hardcode a report row, a count, or a total. Every value comes from a query.
- Do not open a database driver outside the shipped persistence library.
- Do not use floating point for money at any layer.
## 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/LayersTesting/runs/20261020.191708/build/LayersTesting`
- Authorized Target directory: `/mnt/c/Users/barlo/projects/drydock/uat/LayersTesting/runs/20261020.191708/workspace/targets/LayersTesting`
- 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/LayersTesting/runs/20261020.191708/workspace/targets/LayersTesting/blueprint/`
- `/mnt/c/Users/barlo/projects/drydock/uat/LayersTesting/runs/20261020.191708/workspace/targets/LayersTesting/MANIFEST.md`
- `/mnt/c/Users/barlo/projects/drydock/uat/LayersTesting/runs/20261020.191708/workspace/targets/LayersTesting/COMPASS.md`
- `/mnt/c/Users/barlo/projects/drydock/uat/LayersTesting/runs/20261020.191708/workspace/targets/LayersTesting/QuarterDeck/`
- `/mnt/c/Users/barlo/projects/drydock/uat/LayersTesting/runs/20261020.191708/workspace/targets/LayersTesting/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="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.
## 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>
<pblock filename="sqlite.md" role="stack" path="/mnt/c/Users/barlo/projects/drydock/Rigging/stack/sqlite.md">
# SQLite
**Type:** database
**Version:** 20261018 V4
**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` at the DATABASE step and before acceptance runs. 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, ddl)` 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` |
| 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>.<verb>(...)`. The package
exposes one attribute per declared table and one method per declared operation. Changing the
store means changing `DATABASE.md` and rebuilding.
```python
# persistence/testing.py — generated by Drydock
@contextmanager
def db_session(dsn: str | None = None) -> 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 `dsn`, or a fresh temporary SQLite store, with `schema.sql` applied. A
criterion imports it from `persistence.testing` and uses it as a context manager —
`with db_session() as db:` — against the built database layer, without pytest. The pytest suite
receives the same store through the `conftest.py` fixture. Neither opens a connection of its
own, and a criterion never imports `sqlite3`.
---
## 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>
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/LayersTesting/runs/20261020.191708/workspace/targets/LayersTesting/blueprint/DATABASE.md" guidance="Database and PersistenceSpecification">
# DATABASE: Ledger Persistence
| Field | Value |
|-------------|-------|
| Version | 20261020 V1 |
| Description | Define the relational ledger schema and typed persistence operations. |
| Depends On | ARCHITECTURE.md |
| Provides | accounts table, categories table, transactions table, schema initialization |
| Consumes | — |
## Stores
The application uses the relational database selected by `DATABASE_URL`, then `DATABASE_PATH`, then `data/app.db`. SQLite paths may be prefixed with `sqlite://`; PostgreSQL DSNs begin with `postgres://` or `postgresql://`. Application callers use only `persistence.open_database`.
## Access Patterns
### FEATURE-DB-001 — Initialize schema
| Field | Value |
|---|---|
| Owner | DATABASE.md |
| Access | write |
| Repository operation | `accounts.create` |
| Compatibility | rebuild |
Input: `InitializeSchema`
| Field | Type |
|---|---|
| drop_existing | INTEGER |
Output: `SchemaStatus`
| Field | Type |
|---|---|
| tables | TEXT |
### FEATURE-DB-002 — Account operations
| Field | Value |
|---|---|
| Owner | FEATURE-Account-Category-Loading.md |
| Access | read-write |
| Repository operation | `accounts.create` |
| Compatibility | unchanged |
Input: `AccountInput`
| Field | Type |
|---|---|
| account | VARCHAR(12) |
| name | VARCHAR(40) |
Output: `AccountRow`
| Field | Type |
|---|---|
| account | VARCHAR(12) |
| name | VARCHAR(40) |
### FEATURE-DB-003 — Category operations
| Field | Value |
|---|---|
| Owner | FEATURE-Account-Category-Loading.md |
| Access | read-write |
| Repository operation | `categories.create` |
| Compatibility | unchanged |
Input: `CategoryInput`
| Field | Type |
|---|---|
| category | VARCHAR(12) |
| description | VARCHAR(40) |
Output: `CategoryRow`
| Field | Type |
|---|---|
| category | VARCHAR(12) |
| description | VARCHAR(40) |
### FEATURE-DB-004 — Transaction operations
| Field | Value |
|---|---|
| Owner | FEATURE-Transaction-Loading.md |
| Access | read-write |
| Repository operation | `transactions.create` |
| Compatibility | unchanged |
Input: `TransactionInput`
| Field | Type |
|---|---|
| txn_id | INTEGER |
| date | VARCHAR(10) |
| account | VARCHAR(12) |
| category | VARCHAR(12) |
| amount | INTEGER |
| memo | VARCHAR(60) |
Output: `TransactionRow`
| Field | Type |
|---|---|
| txn_id | INTEGER |
| date | VARCHAR(10) |
| account | VARCHAR(12) |
| category | VARCHAR(12) |
| amount | INTEGER |
| memo | VARCHAR(60) |
### FEATURE-DB-005 — Account reads and mutations
| Field | Value |
|---|---|
| Owner | FEATURE-Account-Management.md |
| Access | read-write |
| Repository operation | `accounts.get` |
| Compatibility | unchanged |
Input: `AccountLookup`
| Field | Type |
|---|---|
| account | VARCHAR(12) |
Output: `AccountBalanceRow`
| Field | Type |
|---|---|
| account | VARCHAR(12) |
| name | VARCHAR(40) |
| transactions | INTEGER |
| balance | INTEGER |
### FEATURE-DB-006 — Transaction reads and mutations
| Field | Value |
|---|---|
| Owner | FEATURE-Transaction-Management.md |
| Access | read-write |
| Repository operation | `transactions.get` |
| Compatibility | unchanged |
Input: `TransactionLookup`
| Field | Type |
|---|---|
| txn_id | INTEGER |
Output: `TransactionRow`
| Field | Type |
|---|---|
| txn_id | INTEGER |
| date | VARCHAR(10) |
| account | VARCHAR(12) |
| category | VARCHAR(12) |
| amount | INTEGER |
| memo | VARCHAR(60) |
### FEATURE-DB-007 — Report reads
| Field | Value |
|---|---|
| Owner | DATABASE.md |
| Access | read |
| Repository operation | `accounts.list` |
| Compatibility | unchanged |
Input: `ReportQuery`
| Field | Type |
|---|---|
| report | TEXT |
Output: `ReportRow`
| Field | Type |
|---|---|
| values | TEXT |
## Schema
## `accounts`
| Field | Type | Notes |
|---|---|---|
| account | VARCHAR(12) PK NOT NULL | Account code |
| name | VARCHAR(40) NOT NULL | Account name |
## `categories`
| Field | Type | Notes |
|---|---|---|
| category | VARCHAR(12) PK NOT NULL | Category code |
| description | VARCHAR(40) NOT NULL | Category description |
## `transactions`
| Field | Type | Notes |
|---|---|---|
| txn_id | INTEGER PK NOT NULL | Transaction identifier |
| date | VARCHAR(10) NOT NULL | Calendar date in `YYYY-MM-DD` form |
| account | VARCHAR(12) NOT NULL REFERENCES accounts(account) | Account code |
| category | VARCHAR(12) NOT NULL REFERENCES categories(category) | Category code |
| amount | INTEGER NOT NULL | Integer cents |
| memo | VARCHAR(60) NOT NULL | Transaction memo |
## Atomicity and Invariants
Schema initialization drops and recreates all three tables. Foreign keys are enforced. Every command validates all inputs and prospective balance effects before its first write. Transactions are committed atomically.
## Programmatic Acceptance
- None. Drydock validates declared SQLite schema construction and connectivity invariants deterministically.
## User Acceptance
- None.
## Guardrails
- Amounts are stored as integer cents.
- No application module may open a database driver directly.
- Every rejected command must preserve all existing rows.
- Schema initialization must leave all three tables empty.
</pblock>
<pblock label="Build instructions" kind="instructions">
Build instructions for this block
Establish the relational ledger schema and persistence contract. (database-schema)
Declare the accounts, categories, and transactions tables and every repository operation required by the ledger. Use integer cents, primary keys, foreign keys, and the shipped persistence package. Ensure init can recreate an empty schema through the persistence boundary.
</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:
- Follow the write authorization and protected paths in the stacked
COMPASS.mdexactly.
That persisted guardrail is the sole authority for paths this build may modify.
- 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.
- Implement only this step. Use
context,stack, andrulesas constraints,
not as additional work to perform.
- Follow the stack and rules for languages, structure, naming, and branding.
- The programmatic acceptance assertions in the
implementsspecifications 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.
- 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 — each test arranges its own data, with a fresh store or explicit teardown, so a run leaves no residue behind in the build directory. 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.
- Treat
User Acceptanceentries as review evidence requirements. Implement
the supporting behavior, but do not claim to have performed human judgment.
- The
implementssection is authoritative and intentionally stacked late in
the prompt as the recency anchor. Build that WHAT exactly; do not substitute generic framework defaults.
- 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.
- 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.
- 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.
- 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.
- 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.
FILES CHANGEDmust list only files actually written in the build working
directory. If no files were written, use RESULT: FAILED.
- 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>
- 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.