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="Planning job" kind="job">
Planning job
- TARGET: LayersTesting
- BLUEPRINT_PATH: /mnt/c/Users/barlo/projects/drydock/uat/LayersTesting/runs/20261027.135355/workspace/targets/LayersTesting/blueprint
- DATE: 2026-10-27
- SYSTEM_SHAPE: unknown
- ANALYSIS_QUALITY: Ready
</pblock>
<pblock label="Unattended UAT policy" kind="unattended-policy">
Unattended UAT policy
- No Commander is available. Do not emit a question, questionnaire, blocker, or an undecided DECISIONS.json record.
- Resolve every ambiguity from the imported sources, Compass, fixture inputs, and precedence; choose the narrowest behavior consistent with them.
- Record a material DECISIONS.json disclosure only after selecting its system_choice; continue with that choice.
- An unstated response contract (status code, exit status, error channel) is never Error Mode: choose the conventional narrowest one, record it in DECISIONS.json, and plan on it.
</pblock>
<pblock filename="COMPASS.md" role="compass" path="/mnt/c/Users/barlo/projects/drydock/uat/LayersTesting/runs/20261027.135355/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.
- 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/20261027.135355/build/LayersTesting`
- Authorized Target directory: `/mnt/c/Users/barlo/projects/drydock/uat/LayersTesting/runs/20261027.135355/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/20261027.135355/workspace/targets/LayersTesting/blueprint/`
- `/mnt/c/Users/barlo/projects/drydock/uat/LayersTesting/runs/20261027.135355/workspace/targets/LayersTesting/MANIFEST.md`
- `/mnt/c/Users/barlo/projects/drydock/uat/LayersTesting/runs/20261027.135355/workspace/targets/LayersTesting/COMPASS.md`
- `/mnt/c/Users/barlo/projects/drydock/uat/LayersTesting/runs/20261027.135355/workspace/targets/LayersTesting/QuarterDeck/`
- `/mnt/c/Users/barlo/projects/drydock/uat/LayersTesting/runs/20261027.135355/workspace/targets/LayersTesting/evidence/`
<!-- drydock:build-write-guardrail:end -->
</pblock>
<pblock filename="TECHNOLOGY_STACK.md" role="technology stack" path="/mnt/c/Users/barlo/projects/drydock/uat/LayersTesting/runs/20261027.135355/workspace/targets/LayersTesting/TECHNOLOGY_STACK.md" guidance="Edit freely. Adding a technology never requires a matching Rigging file, and this file never blocks planning.">
# Technology Stack
**Approved:** 2026-10-19
Technology decisions of record for this Target. One row per technology, naming the
Rigging best-practice file that governs building it.
A `—` in the Rigging column means no Rigging guidance exists for that technology; the
builder applies general best practice instead. Adding a row never requires a matching
Rigging file.
This file is owned by the UAT kit. It is seeded into the Target before `analyze`, which
never overwrites it, and `drydock plan` reads it to assign per-story `stack:` guidance.
| Technology | Rigging | Notes |
|---|---|---|
| Python | python.md | Implementation language; Python 3.11 or newer. |
| SQLite | sqlite.md | Database, reached through the shipped persistence library. |
| CLI | cli.md | The `ledger` executable at the application root. |
| pytest | python.md | Test runner behind `bin/test.sh`. |
| Shell | common.md | POSIX sh for `bin/test.sh` and the supplied grader. |
## 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.
## 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.
---
## 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.
---
</pblock>
<pblock filename="ANALYSIS.md" role="planning basis" path="/mnt/c/Users/barlo/projects/drydock/uat/LayersTesting/runs/20261027.135355/workspace/targets/LayersTesting/ANALYSIS.md" guidance="A list of Agile Stories suggested by an earlier analysis of the raw input.">
# Blueprint Analysis: drydock Layers Testing Uat Case
## Commander Expectations
- assert the completed ledger is a command-line cash ledger that stores all data in SQLite through the shipped persistence library
- assert every command either completes in full or changes nothing
- assert the supplied grader `sources/run.sh` passes with exit code zero
- assert every report is computed from the database and never embedded as an answer
- assert a rejected command leaves all previously stored records unchanged
## Crew
| Crew | Charge |
|---|---|
| Commander | Defines intent and decides what done means. |
| Team Lead | Confirms epic completeness and stakeholder expectations. |
| Planning Crew | Authors atomic specifications and the ordered Manifest. |
| Shipyard Crew | Builds the tickets without synchronous Commander access. |
## Story List
### Feature: Schema and Bulk Load
| ID | Story | High-level AC |
|---|---|---|
| LEDGER-SCHEMA-001 | Initialize an empty ledger with `ledger init` | `init` prepares three tables (accounts, categories, transactions) with the specified columns and keys, writes nothing, and removes existing records when rerun; `count` reports 0 rows for each table |
| LEDGER-LOAD-001 | Load accounts from CSV with `ledger load accounts <csv>` | Header must match `account,name`; all rows accepted; writes `table,loaded` and `accounts,<rows>`; invalid row rejects the whole file with exit 3 |
| LEDGER-LOAD-002 | Load categories from CSV with `ledger load categories <csv>` | Header must match `category,description`; all rows accepted; writes `table,loaded` and `categories,<rows>`; invalid row rejects the whole file with exit 3 |
| LEDGER-LOAD-003 | Load transactions from CSV with `ledger load transactions <csv>` | Header must match `txn_id,date,account,category,amount,memo`; keeps file `txn_id`; all rows accepted or none; unknown account or category rejects the whole file with exit 3 |
| LEDGER-LOAD-004 | Reject a load file with unreadable path | Unreadable file named on command line exits 1 with no writes |
### Feature: Account Management
| ID | Story | High-level AC |
|---|---|---|
| LEDGER-ACCT-001 | Add an account with `ledger account add <code> <name>` | Validates code (1–12 chars `A-Z0-9`) and name (1–40 chars, no comma/newline); duplicate key rejected with exit 3; returns account row with 0 transactions and 0.00 balance |
| LEDGER-ACCT-002 | Retrieve an account with `ledger account get <code>` | Returns current account row; absent code exits 4 |
| LEDGER-ACCT-003 | Rename an account with `ledger account rename <code> <name>` | Updates name only; returns updated row; absent code exits 4 |
| LEDGER-ACCT-004 | Delete an account with `ledger account delete <code>` | Removes account and writes `deleted` and code; refused with exit 3 while transactions exist; absent code exits 4 |
### Feature: Transaction Management
| ID | Story | High-level AC |
|---|---|---|
| LEDGER-TXN-001 | Post a transaction with `ledger txn post` | Validates account, category (must exist), amount (`-?DIGITS[.D[D]]`, nonzero, ≤2 decimals), date (real calendar date), memo (0–60 chars); assigns `txn_id` as max+1 or 1; returns row; invalid input exits 3 |
| LEDGER-TXN-002 | Retrieve a transaction with `ledger txn get <id>` | Returns current transaction row; absent id exits 4 |
| LEDGER-TXN-003 | Amend a transaction amount with `ledger txn amend <id> <amount>` | Changes only amount; returns updated row; rejected if resulting balance would go negative; absent id exits 4 |
| LEDGER-TXN-004 | Delete a transaction with `ledger txn delete <id>` | Removes row and writes `deleted` and id; rejected if resulting balance would go negative; absent id exits 4 |
### Feature: Transfers
| ID | Story | High-level AC |
|---|---|---|
| LEDGER-XFER-001 | Transfer cash between accounts with `ledger transfer <from> <to> <amount> <date>` | Records two rows in category `TRANSFER` (outgoing `-amount` then incoming `+amount`) with specified memos and consecutive ids; accounts must differ and amount must be positive; rejected entirely if source would go negative |
### Feature: Reporting
| ID | Story | High-level AC |
|---|---|---|
| LEDGER-RPT-001 | Report account balances with `ledger report balances` | Per-account rows ordered by code with count and balance, then `TOTAL,,<count>,<sum>` |
| LEDGER-RPT-002 | Report category totals with `ledger report categories` | Per-category rows ordered by code (including empty categories) with inflow, outflow, net, then TOTAL row |
| LEDGER-RPT-003 | Report monthly totals with `ledger report monthly` | Per `YYYY-MM` with transactions, ascending, with inflow, outflow, net, then TOTAL row |
### Feature: Command Contract
| ID | Story | High-level AC |
|---|---|---|
| LEDGER-CLI-001 | Enforce the CSV output contract and exit codes | Successful commands write CSV headers, `\n` endings, two-decimal amounts, no trailing spaces; failures write nothing to stdout and one diagnostic to stderr; exit 2 for unknown commands, tables, reports, or wrong argument counts |
| LEDGER-CLI-002 | Enforce the no-negative-balance rule across all writing commands | Loading, posting, amending, deleting, and transferring each check every resulting balance before any write and reject the whole command with exit 3 |
## Story Guidance
Named stories planning must produce. Authoritative record: `STORY_GUIDANCE.json`.
None.
## Surfaced Acceptance Criteria
| ID | Story ID | Criterion |
|---|---|---|
| AC-001 | LEDGER-SCHEMA-001 | `init` writes nothing to standard output and exits 0 |
| AC-002 | LEDGER-LOAD-001 | A rejected accounts load stores none of the rows before the rejected row |
| AC-003 | LEDGER-LOAD-003 | A rejected transactions load stores none of the rows before the rejected row |
| AC-004 | LEDGER-ACCT-001 | Account code validation rejects lowercase letters, codes longer than 12 characters, and empty codes with exit 3 |
| AC-005 | LEDGER-TXN-001 | Amount input with three decimal places is rejected with exit 3 |
| AC-006 | LEDGER-TXN-001 | Date `2026-02-30` is rejected with exit 3 |
| AC-007 | LEDGER-TXN-003 | Amending a transaction to an amount that would drive its account below zero exits 3 and leaves the original amount |
| AC-008 | LEDGER-TXN-004 | Deleting a transaction that would drive its account below zero exits 3 and keeps the row |
| AC-009 | LEDGER-XFER-001 | A transfer whose source would go negative stores neither of its two rows |
| AC-010 | LEDGER-XFER-001 | A transfer with equal source and destination accounts exits 3 |
| AC-011 | LEDGER-RPT-002 | Categories with no transactions appear in the report with zero values |
## Source Inventory
| Path | Content kind | Disposition | Reason |
|---|---|---|---|
| `sources/INSTRUCTIONS.md` | markdown | analyzed | readable UTF-8 |
| `sources/run.sh` | code | analyzed | readable UTF-8 |
| `sources/seed_accounts.csv` | text | analyzed | readable UTF-8 |
| `sources/seed_categories.csv` | text | analyzed | readable UTF-8 |
| `sources/seed_transactions.csv` | text | analyzed | readable UTF-8 |
| `sources/seed_transactions_bad.csv` | text | analyzed | readable UTF-8 |
## Relationship Model
| Source or group | Relationship type | Related source or group | Evidence | Delivery implication |
|---|---|---|---|---|
| `sources/run.sh` | instruction-to-test | `sources/INSTRUCTIONS.md` | Grader known answers mirror the CLI contract and rules in INSTRUCTIONS.md | Grader is the final acceptance gate; stories must reproduce its outputs exactly |
| `sources/seed_accounts.csv` | dependency | `sources/run.sh` (B1, D2, C1) | Grader loads these rows and asserts their counts and balances | Account load story must precede balance report stories |
| `sources/seed_categories.csv` | dependency | `sources/run.sh` (B2, C2) | Grader loads these rows and asserts category totals | Category load story must precede category report story |
| `sources/seed_transactions.csv` | dependency | `sources/run.sh` (B3, C1–C3) | Grader loads 120 rows and asserts all report totals | Transaction load story must precede all report stories |
| `sources/seed_transactions_bad.csv` | instruction-to-test | `sources/run.sh` (D1) | Row 11 names unknown account `NOSUCH`; grader expects exit 3 with no writes | Load validation must be atomic |
| `sources/INSTRUCTIONS.md` | dependency | `sources/run.sh` | Output formats and exit codes are fixed by INSTRUCTIONS.md | Output and exit-code stories derive from this file |
## Source Roles
| Path | Role | Plan disposition | Build disposition |
|---|---|---|---|
| sources/INSTRUCTIONS.md | normative specification | context | prompt-only |
| sources/run.sh | conformance harness | compass | stage |
| sources/seed_accounts.csv | test helper | context | stage |
| sources/seed_categories.csv | test helper | context | stage |
| sources/seed_transactions.csv | test helper | context | stage |
| sources/seed_transactions_bad.csv | test helper | context | stage |
## Planning Instructions
### Delivery Shape
The system is a Python 3.11+ command-line executable named `ledger` at the application root. Inputs are command-line arguments and CSV files named on the command line. Outputs are CSV on standard output and diagnostics on standard error. All persistence goes through the shipped persistence library over SQLite, with `DATABASE_URL` or `DATABASE_PATH` selecting the database file. Each writing command validates all inputs and rules before its first write, so it either completes fully or changes nothing.
### Story Realization Map
- LEDGER-SCHEMA-001: `sources/INSTRUCTIONS.md` Commands table (`init`, `count`); `sources/run.sh` A1–A2, Z1–Z2. Requires persistence library schema setup and a `count` command.
- LEDGER-LOAD-001: `sources/INSTRUCTIONS.md` Database and Commands (`load accounts`); `sources/seed_accounts.csv`; `sources/run.sh` B1, D2. Requires the accounts table and atomic load.
- LEDGER-LOAD-002: `sources/seed_categories.csv`; `sources/run.sh` B2. Requires the categories table and atomic load.
- LEDGER-LOAD-003: `sources/seed_transactions.csv`, `sources/seed_transactions_bad.csv`; `sources/run.sh` B3, D1. Requires foreign-key validation before any write.
- LEDGER-LOAD-004: `sources/INSTRUCTIONS.md` Exit codes (1); `sources/run.sh` (no direct check; covered by the exit-code contract).
- LEDGER-ACCT-001 through LEDGER-ACCT-004: `sources/INSTRUCTIONS.md` account commands and rules 3–4; `sources/run.sh` E1–E8.
- LEDGER-TXN-001 through LEDGER-TXN-004: `sources/INSTRUCTIONS.md` transaction commands and rules 5–7; `sources/run.sh` F1–F10, G3–G5.
- LEDGER-XFER-001: `sources/INSTRUCTIONS.md` transfer command and rule 1; `sources/run.sh` G1–G2.
- LEDGER-RPT-001 through LEDGER-RPT-003: `sources/INSTRUCTIONS.md` report commands; `sources/run.sh` C1–C3, H1–H3.
- LEDGER-CLI-001: `sources/INSTRUCTIONS.md` Output and Exit codes; `sources/run.sh` U1–U2.
- LEDGER-CLI-002: `sources/INSTRUCTIONS.md` Rule 2; `sources/run.sh` G3–G5.
### Test and Acceptance Strategy
Focused story tests run the story's own slice of the Python test suite in `bin/test.sh`, scoped per story. The terminal verification story runs the grader `sh sources/run.sh` and the unfiltered suite. Sea Trials are verified by the SEA_TRIALS.md criteria, and the grader is the authoritative proof for report and workflow correctness.
### Sequencing and Dependencies
1. LEDGER-SCHEMA-001 (init and count) first.
2. LEDGER-LOAD-001, LEDGER-LOAD-002 in parallel after LEDGER-SCHEMA-001.
3. LEDGER-LOAD-003 after LEDGER-LOAD-001 and LEDGER-LOAD-002.
4. Account, transaction, and transfer stories after the loads.
5. Report stories after all write stories are in place.
6. LEDGER-CLI-001 and LEDGER-CLI-002 cross-cut and are verified during each story they touch.
7. Terminal verification story runs the full grader after all others.
### Source Conflicts and Gaps
- Source conflict: none. INSTRUCTIONS.md and run.sh agree on every output format, exit code, and rule checked by the grader.
- Gap: INSTRUCTIONS.md does not state the exit code for a missing or invalid `DATABASE_URL` value. Resolved by choosing the narrowest behavior: exit 1 as an operational failure, with no writes.
- Gap: The behavior when `ledger init` is run with no prior database file is not stated. Resolved by creating the file and schema.
## Analysis Notes
generated: 2026-10-27
blueprint: /mnt/c/Users/barlo/projects/drydock/uat/LayersTesting/runs/20261027.135355/workspace/targets/LayersTesting/blueprint
Quality: Ready
blockers: 0
questions: 0
features: 6
stories: 15
stack: Python 3.11+, SQLite, pytest
display_name: not proposed
short_description: not proposed
Observations:
- SEA_TRIALS.md is a prior project acceptance contract; its stable IDs st-001, st-004 through st-008, st-010, and st-011 are preserved. st-002, st-003, and st-009 are retired and not re-emitted.
- The grader `sources/run.sh` is the single authoritative project-level verification command.
- `count` appears in the Commands table and the grader but is not listed in the Story List's original commands; it is folded into LEDGER-SCHEMA-001.
- `init` requires no separate schema-building story; the persistence library generates the schema.
</pblock>
<pblock filename="SEA_TRIALS.md" role="project acceptance contract" path="/mnt/c/Users/barlo/projects/drydock/uat/LayersTesting/runs/20261027.135355/workspace/targets/LayersTesting/SEA_TRIALS.md">
# Sea Trials: LayersTesting
## Policy
| Consequence | On FAIL | On INCONCLUSIVE |
|---|---|---|
| blocks | fail | attest |
| scores | score | score |
| attests | report | report |
## Acceptance scope
Sea Trials assess ledger workflows and their observable results. Database preparation is a
prerequisite exercised by the supplied grader, not a separate release criterion. Verification
uses the declared ledger commands and supplied data; it does not introduce schema mutations,
schema-replacement requirements, or database-engine qualification tests. Stack and persistence
implementation constraints remain in the build instructions.
The supplied grader and the behavioral criteria below are required release evidence. Its exit
status establishes grader conformance; it is not the sole verdict for all Sea Trials. Criterion
identifiers are retained; st-002, st-003, and st-009 are retired.
## st-001: The supplied grader passes
Type: technical
Required: yes
Criterion: The completed ledger shall pass every check in the supplied end-to-end workflow grader, sh sources/run.sh, with exit code zero.
Testability: deterministic
Consequence: blocks
Verification: proof
Command: ["sh", "sources/run.sh"]
Pattern: ubiquitous
## st-004: The seed files load exactly
Type: behavioral
Required: yes
Criterion: When the supplied accounts, categories, and transactions files are loaded in order into an empty ledger, the application shall accept all records, report the loaded counts, and retain 4 accounts, 7 categories, and 120 transactions across subsequent command invocations.
Testability: deterministic
Consequence: blocks
Verification: proof
Pattern: event
## st-005: Reports match the known answers
Type: behavioral
Required: yes
Criterion: The application shall compute account balances, category totals, and monthly totals from stored ledger data, matching the known answers in sources/run.sh byte for byte both before and after the supplied transaction and transfer workflows.
Testability: deterministic
Consequence: blocks
Verification: proof
Pattern: ubiquitous
## st-006: Accounts and transactions support create, read, update, and delete
Type: behavioral
Required: yes
Criterion: The application shall retain account additions and renames and transaction postings and amendments across command invocations, return their current values on retrieval, remove successfully deleted records, refuse deletion of an account with transactions with exit code 3, and report an absent record with exit code 4.
Testability: deterministic
Consequence: blocks
Verification: proof
Pattern: ubiquitous
## st-007: A failed command changes nothing
Type: behavioral
Required: yes
Criterion: If a load, account change, transaction change, or transfer violates a validation or business rule, then the application shall exit 3 and preserve all previously stored ledger records without adding, altering, or removing any record.
Testability: deterministic
Consequence: blocks
Verification: proof
Pattern: unwanted
## st-008: No balance goes negative
Type: behavioral
Required: yes
Criterion: If loading transactions, posting, amending, deleting, or transferring would leave any account balance below zero, then the application shall reject the entire command with exit code 3 and preserve the prior balances.
Testability: deterministic
Consequence: blocks
Verification: proof
Pattern: unwanted
## st-010: Transfers conserve cash
Type: behavioral
Required: yes
Criterion: When a valid transfer is requested between distinct accounts, the application shall record an equal debit and credit in category TRANSFER, return both transaction rows, and update both account balances without changing the total cash held.
Testability: deterministic
Consequence: blocks
Verification: proof
Pattern: event
## st-011: Command results follow the CLI contract
Type: behavioral
Required: yes
Criterion: The application shall return the CSV headers, row ordering, two-decimal monetary values, and exit codes specified in sources/INSTRUCTIONS.md, returning exit 2 for unknown commands or reports and incorrect argument counts, and writing failures only to standard error.
Testability: deterministic
Consequence: blocks
Verification: proof
Pattern: ubiquitous
</pblock>
<pblock filename="STORY_GUIDANCE.json" role="governed story guidance" path="/mnt/c/Users/barlo/projects/drydock/uat/LayersTesting/runs/20261027.135355/workspace/targets/LayersTesting/STORY_GUIDANCE.json">
{
"stories": []
}
</pblock>
<pblock filename="ACCEPTANCE.json" role="governed acceptance contract" path="/mnt/c/Users/barlo/projects/drydock/uat/LayersTesting/runs/20261027.135355/workspace/targets/LayersTesting/ACCEPTANCE.json">
{
"full": [
"sh",
"sources/run.sh"
]
}
</pblock>
<pblock filename="MANIFEST_CONTRACT.md" role="contract" path="/mnt/c/Users/barlo/projects/drydock/prompts/MANIFEST_CONTRACT.md" guidance="MANIFEST output contract. Follow it exactly.">
---
name: Manifest Contract
description: Contract governing the format, story types, field semantics, lifecycle states, block grouping, and execution rules for `MANIFEST.md` — the single generated executable build plan for a Drydock Target.
version: 20261026 V16
---
## Overview
`MANIFEST.md` is the single generated execution view of the Blueprint. It determines build order,
selects required context, keeps work within useful context limits, identifies stale work, and
preserves unaffected accepted work. It is not a second product definition.
**Location:** `$DRYDOCK_WORKSPACE/targets/<Target>/MANIFEST.md`
The Manifest manages the full product lifecycle:
- specifications for individual components can be changed, resulting in context-minimized
incremental builds
- new files (such as change tickets) can be discovered and applied
---
## Plan Header
```markdown
# MANIFEST: {ProjectName}
updated: 2026-06-08T12:00:00
plan_hash: abc123456789
applied_specs: |
DATABASE.md sha256=<content_sha256> commit=<file_commit_sha> applied_by=foundation applied_at=2026-06-26T14:22:00Z
planning_feedback: |
decision-0123456789abcdef applied FEATURE-CATALOG.md
decision-fedcba9876543210 retained
```
Build execution evidence lives in the execution log. The Manifest preamble carries build-state
provenance required to detect stale previously applied Blueprint Specifications. `applied_specs`
records one line per Blueprint Specification file applied by a successful story. The path
is relative to `blueprint/`. `sha256` is the authoritative dirty signal. `commit` is the latest git
commit that touched that file, or `-` when unavailable. `applied_by` identifies the story
that last applied the file. `applied_at` is the UTC application timestamp.
---
## Story Types
The Manifest is a list of stories. A `type` field is the only variation.
| Type | Contains | Runs |
|---|---|---|
| `foundational` | Foundation and scaffolding | Early; work depends on it |
| `service` | Everything that does work | After its prerequisites |
| `feature` | Acceptance criteria plus assembly and intent; no implementation instructions | After its members |
Foundational work is structure and scaffolding. Standing up S3 and proving the connection is
architecture. Everything S3 subsequently does is a service. Everything that is not architecture is
a service. Services may be reordered only when their declared prerequisites permit it. Much of what source
material labels architecture is service work: the web server and the database are foundation; a
voice service interpreter is a service wearing an architecture filename.
Foundation status derives from the dependency graph, not from a filename prefix. The rule is
*build the foundation that is needed*, not *build all foundation first*.
There is no fourth type. A "foundational service" — voice-to-text, for example — is foundational to
whatever depends on it, which the edges already state more precisely than a label could.
`spike` is not a story type. Research questions are handled by questionnaires before Plan and by the
owning story's `## Questions` section after. `ac` is not a story type: Programmatic Acceptance is
verification the build runs to prove a story is complete. A story is not "built and failed" — it is
built or it is not, so acceptance is a field the story owns and passing is part of the story's own
state transition.
### Feature is an assembly story
A feature is a story that depends on its member stories, carries acceptance criteria, and carries
assembly and intent instructions instead of implementation instructions. Same node, same execution
path, different content shape. When its member stories complete, the feature story runs and is made
to pass like any other story, so integration testing is a real build step rather than an implicit
hope. A feature story runs in a later block after its members have passed their gates.
### Story
```markdown
## story N: {Name}
id: foundation
summary: One-line description.
type: foundational
kind: capability
phase: 1
block: 1
implements: ARCHITECTURE.md
covers: CATALOG-001
accepts: st-001
context: DATABASE.md
stack: common.md, python.md, fastapi.md
stack_mode: builder
provides: GET /health
consumes:
instructions: |
Stand up the application factory and health check.
acceptance: yes
depends:
state: pending
```
**Field reference:**
| Field | Required | Authored by | Description |
|-------|----------|-------------|-------------|
| `id` | Yes | Model | Stable unique slug within the Manifest |
| `summary` | Yes | Model | One-line description |
| `origin` | No | `drydock refit` | Provenance of a story authored from a source change, as `<source>@<commit>`. Absent on stories authored by `plan`. |
| `created` | No | `drydock refit` | ISO date the story was appended to the graph. |
| `type` | Yes | Model | `foundational` \| `service` \| `feature` |
| `kind` | Yes | Model | Delivery kind: `capability` \| `integration` \| `migration` \| `test harness` |
| `phase` | Yes | Model | Commander build sequencing; see below |
| `block` | Generated | Drydock | Context-optimization group; computed, never authored |
| `implements` | Yes | Model | The single governed specification this story builds |
| `covers` | No | Model | `ANALYSIS.md` Story IDs this story delivers. Every analyzed Story ID is named by exactly one story, whatever its `type`; a story with no analyzed counterpart omits the field |
| `accepts` | No | Model | `SEA_TRIALS.md` IDs this story implements |
| `context` | No | Model | Read-only support context files. Never a Compass file |
| `stack` | No | Model | Rigging stack files this story builds with |
| `stack_mode` | Generated | Drydock | `builder` \| `consumer`; computed from first use in build order |
| `provides` | No | Model | Routes, commands, symbols, datasets, queues, or events this story defines |
| `consumes` | No | Model | Interface points this story calls |
| `rules` | No | Model | Rigging rules files to inject |
| `copy` | No | Model | `source -> destination` file copies applied before build |
| `instructions` | Yes | Model | Freeform build instructions. A `feature` carries assembly and intent, not implementation |
| `acceptance` | Yes | Model | `yes` when the story has real acceptance to honor |
| `depends` | No | Model | Story ids that must be `closed/verified` first |
| `state` | Yes | Drydock | Current block state |
| `evidence` | No | Drydock | Path to the evidence file written after execution |
| `scope` | No | Model | `blueprint` \| `target` \| `both` — what this story changes |
Stories and governed specifications are one-to-one: every story implements exactly one
specification, and every specification is implemented by exactly one story. The story is the atomic
build primitive.
**Story sizing.** A story is a normal Agile story: 1 to 5 story points. Never a half point — that is
a task, folded into the story it serves. Never twelve — that is split. A story does one thing
completely, carries test criteria, and is releasable on its own; a task is not releasable and is
therefore not a story. A story has no token dimension. Token cost is measured against the block a
story is built in, never against the story. Story count is not capped: it is an output of correct
decomposition, not a target.
### Authorship versus verification
The model authors relationships, the actual topology (the story dependency graph), the high-level
topology (phases), and Programmatic Acceptance. Drydock verifies all of it, groups blocks, orders
the work, and serializes the Manifest.
The model declares and reviews what each story requires and provides, including source-required
processing order and prerequisites exercised by acceptance. It does not compute the schedule.
Drydock validates the declaration and computes order and grouping.
Contradictions become a deterministic error with a precise message instead of a shape failure.
Use the same exact interface name in a provider's `provides:` and its consumer's `consumes:`.
When an interface has a provider in this plan, the consumer has a direct or transitive `depends:`
path to a provider. External inputs without a provider remain legal. A shared executable alone
does not declare the processing stages behind it; preserve their input/output contracts and
source-required dependency edges. File order is not a dependency.
`drydock plan create` therefore does not emit this file. It emits a flat `TOPOLOGY.md` declaration
carrying the Model-authored fields below — one `## story <id>` heading per governed specification,
no ordering, no `block:`, no `stack_mode:`, no `state:` — and Drydock serializes `MANIFEST.md` from
it. The field semantics in this contract govern both forms.
**Two-topology check.** The high-level and actual topologies must agree: a story in phase 2 cannot
depend on a story in phase 3.
### Phase
`Phase` is Commander instruction on how to build: *build Feature X, then Feature Y*. It is not a
layer chain. The layer stack repeats inside each phase rather than running once across the project —
foundational / database / service / ui, then service / ui, then foundational / service / service /
ui. Commander ordering direction is input the model weighs, not an override applied afterward.
`Phase` describes when a file is built, not the file, so it lives in the Manifest and never in a
Blueprint header.
### Tier
The chain that repeats inside each phase is ordered, and each Rigging file declares its position
with a `**Tier:**` header. A tier is a rank inside a phase — never a phase, never a block.
Tiers 1 to 5 are the foundation. Each holds at most one selected file per kind, each publishes a
contract, and each is built into the one before it.
| Tier | Name | Builds | Holds |
|---|---|---|---|
| 1 | `language` | The tree, the environment, the test runner everything else is built into. | `python.md`, `go.md`, `typescript.md` |
| 2.1 | `platform` · database | The one database, built into that tree. | `sqlite.md`, `postgres.md` |
| 2.2 | `platform` · web server | The one web server. | `fastapi.md`, `flask.md`, `django.md` |
| 2.3 | `platform` · CLI | The one command-line entry point. | `cli.md` |
| 3 | `branding` | The palette, the typography, the voice. | `BRANDING_MAIN.md`, `BRANDING_WEBSITE.md`, `BRANDING_DOCUMENTATION.md` |
| 4 | `interface` | The shared UI shell, built with that palette. | `bootstrap5.md` |
| 5 | `screen-foundation` | The screen idiom, built on that shell. | `ui-flask.bootstrap-client.md` |
Tier 2's three kinds are independent — none is built into another — so 2.1, 2.2 and 2.3 order by
what imports what: a web server and a CLI import persistence, and persistence imports neither.
Tier 6 is `application`: every service and every screen the Blueprints describe. It publishes no
contract and has no internal order — a service and a screen are ranked against each other by
`depends:` alone. A file or story with no `**Tier:**` belongs to tier 6, which is how a service
stays free to land either side of the interface tier.
Each foundation is its own story. Tiers describe responsibility; declared dependencies
establish delivery gates between blocks.
### Blocks
A **block** groups independent ready stories to share stack and context files in one agent call.
Drydock computes the groups from the declared graph and measured assembled prompt cost.
- Stories share a topology type, phase, and screen/non-screen work kind.
- Every known prerequisite belongs to an earlier block; selecting a story does not make its
dependents ready inside the same block.
- Compatible stories share the union of their stack and context files, counted once, within
configured token limits and minimum savings. Criterion count does not bound a block.
- A started block keeps its members and number for resume; only wholly pending work is regrouped.
### Builder and consumer mode
The model authors the foundational story that stands a stack up. Drydock assigns the
builder/consumer flag from first use in the computed order: by definition the first story using a
stack is the builder and later ones are consumers. Ordering is build-order-global, as compact
substitution already is — not per-block, not phase-based. A builder story receives the full stack
file; a consumer story receives the interface view.
If the model assigned the flag it would be asserting a position in an order it has not computed.
Disagreement is a defect signal, not a tie to break: if the first user of a stack is not a
`foundational` story, an edge or a foundational story is missing and Drydock reports it. Ambiguity
defaults to builder, because consumer-when-it-should-be-builder starves the build agent while
builder-when-it-should-be-consumer merely costs tokens.
---
## Acceptance
Acceptance lives in one place per audience:
- **Programmatic Acceptance** — executable assertions authored in each owning Blueprint's
`## Programmatic Acceptance` section. The Manifest references that Blueprint with `implements:`
and declares `acceptance: yes`; execution evidence carries the measured results.
- **User Acceptance** — human-readable intent. Lives in the Blueprint specification.
The discriminator for every other fact is the same question: **does the fact describe the artifact
or the schedule?**
| Fact | Home | Why |
|---|---|---|
| `Provides`, `Consumes`, `Depends On` | Blueprint header | Describe the file — what it offers and requires |
| Story `type` | Topology, projected into Manifest | Authored responsibility |
| `Phase` | Manifest | Describes when the file is built, not the file |
| Programmatic Acceptance | Owning Blueprint | Executable checks authored with the behavior |
| User Acceptance, `## Questions` | Blueprint | Human intent |
Durability is not a discriminator: the Blueprint does not survive a replan. Only the `## Questions`
section, harvested deterministically beforehand, survives.
---
## Block States
Every story uses the same four states:
| State | Meaning |
|-------|---------|
| `pending` | Not run yet |
| `implemented` | Work done, waiting to be accepted |
| `closed/verified` | Passed or accepted |
| `closed/failed` | Failed or rejected |
---
## Execution Rules
A story runs only when everything in `depends:` is `closed/verified`.
Programmatic Acceptance runs after the story build and is part of the story's own state
transition: a story that fails its acceptance becomes `closed/failed` and blocks dependent work.
There is no separate acceptance node with independent state.
A `feature` story runs after its member stories close. Its assembly and intent instructions are
made to pass like any other story's, which is what turns integration testing into a real build step
covering the seams between stories where multi-story builds actually break.
`closed/failed` is not terminal. The product owner reopens failed work from the QuarterDeck —
revising instructions, acceptance, or scope interactively — and the decision writer returns it to
`pending` with the revision recorded. Recovery never requires hand-editing the Manifest.
An open `Blocking` Blueprint question projects the story state as `blocked/questions`. That story
and its dependents are unavailable, while independent frontier stories remain buildable. Open `Low`
and `Material` decisions remain visible without gating.
`User Acceptance` entries are Commander review signals and do not block ordinary downstream build
unless modeled as explicit dependencies.
---
## Sea Trials Traceability
`accepts:` lists stable project-acceptance IDs from `SEA_TRIALS.md` that the story implements.
Every required technical or behavioral Sea Trial is referenced by at least one story or by a
Blueprint Programmatic Acceptance proof. Unknown IDs are invalid.
## Plan State Writer
The **decision writer** is the only mutator of Manifest block state. It is invoked by:
- the QuarterDeck review controls (approve, revise, reject, add defect on individual blocks)
- the `drydock build` engine (state transitions during execution)
Review decisions written in the QuarterDeck write back to `MANIFEST.md` through the same
decision writer used by the CLI.
---
## Relationship to Blueprint
The Manifest is generated from the Blueprint; it is not a second product definition. `drydock plan
create` reads all Blueprint inputs and writes `MANIFEST.md` — the single work graph carrying build
order, grouping, and per-step prompt-assembly fields. It regenerates after each planning cycle.
The Blueprint remains the source of truth for what the project is and must do. The Manifest is
the source of truth for build state. The QuarterDeck renders Manifest state and records decisions
through the plan writer — the console can be deleted and regenerated at any time.
</pblock>
<pblock filename="BLUEPRINTS_CONTRACT.md" role="contract" path="/mnt/c/Users/barlo/projects/drydock/prompts/BLUEPRINTS_CONTRACT.md" guidance="Blueprint output contract. Follow it exactly.">
---
name: Blueprints Contract
description: Contract governing the layout, file types, header format, and dependency conventions for Drydock Blueprint files.
version: 20261027 V43
---
## Overview
A **Blueprint** is the complete Typed Specification for one project. It lives at
`$DRYDOCK_WORKSPACE/targets/<Target>/blueprint/` and contains all human-authored and
process-created specification files. The Blueprint is the single source of truth for what the
project is, what it must do, and how it is built.
---
## Specification File Types
`VERIFICATION.md` is the standard optional release-verification Blueprint, with a FEATURE header and the terminal full-suite acceptance gate.
| File | Purpose | Required |
|------|---------|----------|
| `METADATA.md` | Project identity: name, display_name, short_description, status, stack, code_root | Yes |
| `COMPASS.md` | Project guidance: intent, constraints, and guardrails | Yes |
| `ARCHITECTURE.md` | Modules, routes, boundaries, interfaces, technical decisions | Yes |
| `README.md` | One-line description and `## Intent` section | Yes |
| `DATABASE.md` | Persistence contract: access patterns, typed interfaces, all stores, schemas, migrations | If has persistent state |
| `UI-GENERAL.md` | Shared UI patterns across screens | If has UI |
| `SCREEN-{Name}.md` | Per-screen: route, layout, interactions, programmatic and user acceptance | If has UI |
| `FEATURE-{Name}.md` | Per-feature: purpose, status, trigger, sequence, routes, reads, writes, acceptance, guardrails | As needed |
| `ARCHITECTURE_compact.md` | Compact architecture derivative for downstream build-step injection | Optional |
| `DATABASE_compact.md` | Compact persistence derivative for downstream build-step injection | Optional |
| `HOMEPAGE.md` | Portfolio homepage: branding, contact, bio | If publishes a portfolio |
| `HOMEPAGE-PUBLISHER.md` | Template-based homepage publishing configuration | If publishes a portfolio |
| `IDEAS.md` | Feature ideas and backlog — no typed header required | No |
| `*-AC.md` / `AC-*.md` / `*-AC-*.md` | Acceptance criteria — any file where `AC` is a whole word in the filename | As needed |
| `changes/TICKET-NNN-{Name}.md` | Post-baseline change, defect, or spike request | As needed |
Every authored Specification file ends with `## Programmatic Acceptance`, `## User Acceptance`,
and `## Guardrails`. Use `- None.` when no entries apply, except that a spec a story implements
carries at least one Programmatic Acceptance criterion. Planning disclosures and Commander
responses are records in the target's `DECISIONS.json`.
`ARCHITECTURE_compact.md` is a compact derivative of `ARCHITECTURE.md` produced by
`drydock rigging compact`. Drydock uses filename-selected compaction algorithms rather than
phase-aware compact variants.
`DATABASE_compact.md` is a compact derivative of `DATABASE.md` produced by `drydock rigging compact`.
---
## Specification File Header Format
Every authored Specification file except `METADATA.md` and `README.md` must begin with a typed
header. Operational and generated files (`IDEAS.md`, build plans, analysis outputs, and AC files)
are not authored Specification files.
```markdown
# {FileType}: {ObjectName}
| Field | Value |
|-------------|-------|
| Version | YYYYMMDD V1 |
| Description | One sentence summary. |
| Depends On | FEATURE-SERVICE-CATALOG.md, UI-GENERAL.md |
| Provides | GET /welcome, GET /welcome/summary |
| Phase | 2 |
```
**FileType values:** `COMPASS`, `SCREEN`, `FEATURE`, `DATABASE`, `UI-GENERAL`, `ARCHITECTURE`,
`HOMEPAGE`, `CHANGE`
**ObjectName:** Human-readable name matching the file subject (e.g., `Welcome Summary`,
`Service Catalog`).
**Fields:**
| Field | Set By | Required | Description |
|-------|--------|----------|-------------|
| `Version` | Author | Yes | Date + increment: `YYYYMMDD V1`. Every agent write must set this to the current date with the next increment. If the existing version is already today's date, increment the number. Never carry forward a stale date. |
| `Description` | Author | Yes | One sentence |
| `Depends On` | `drydock plan create` | No | Filenames this file requires to exist before build |
| `Provides` | `drydock plan create` | No | HTTP routes or interfaces this file exposes |
| `Phase` | `drydock plan create` | No | Build phase hint (integer); tooling may override |
**Additional optional fields for SCREEN files:**
| Field | Required | Description |
|-------|----------|-------------|
| `Route` | No | The URL this screen is served at |
| `Parent` | No | Parent menu item or `—` |
| `Main Menu` | No | Menu label and position |
| `Sub Menu` | No | Submenu label and position |
| `Tab Order` | No | Tab index within parent, or `—` |
`Depends On` and `Provides` are written by `drydock plan create` — do not edit manually.
`Phase` is written by `drydock plan create` — do not edit manually unless overriding.
**Additional required fields for CHANGE files (`changes/TICKET-NNN-{Name}.md`):**
| Field | Set By | Required | Description |
|-------|--------|----------|-------------|
| `Amends` | Author / `drydock refit` | Yes | The parent Blueprint spec this ticket modifies (e.g. `FEATURE-Copy.md`). `drydock refit` reads this field to resolve dependency inheritance and inject parent context. |
| `Depends On` | `drydock refit` | Yes | Copied from the parent spec's `Depends On` set plus the parent spec filename itself. Do not edit manually. |
| `Scope` | Author / `drydock refit --sources` | Yes | `additive` or `amending`. Governs what the ticket supersedes. |
| `Created` | `drydock refit` | Yes | ISO date the ticket was authored. |
| `Origin` | `drydock refit --sources` | No | The source version this ticket came from, as `<source>@<commit>`. Absent on hand-authored tickets. |
| `Stories` | `drydock refit --sources` | No | The Manifest story ids this ticket owns. When present, `drydock refit` emits exactly these ids and never invents new ones. |
**Scope semantics.** A ticket declares its authority over its parent in one sentence directly
below the header table.
- `additive` — the ticket adds behavior. It supersedes nothing, and every assertion in the parent
Blueprint remains in force. Sentence: *"This ticket is additive. It supersedes nothing; every
assertion in `<parent>` remains in force."*
- `amending` — the ticket alters behavior already specified. It supersedes only the sections
listed under `## Amended Sections`, each of which must exist as a heading in the parent.
Sentence: *"This ticket amends `<parent>`. It supersedes only the sections named under
`## Amended Sections`; every other assertion in `<parent>` remains in force."*
An additive ticket must never claim authority over its whole parent: a single added requirement
would otherwise supersede assertions it does not mention and that have already been proven.
---
## Common Authored Specification Sections
Plan and Build disclosures use the existing `DECISIONS.json` schema. `severity: blocking` is the
only decision gate and blocks only the attached story while its Commander response is absent.
Analyze questionnaire answers are converted to `origin: analyze-questionnaire` records. Commander
responses remain in the same records across replans.
Every authored Specification file ends with these sections, using `- None.` when no entries apply:
```markdown
## Programmatic Acceptance
- None.
## User Acceptance
- None.
## Guardrails
- None.
```
`Programmatic Acceptance` contains executable Python assertion snippets. Each check is one
explicitly delimited block that can run from the build directory after the story implementing the
file completes:
```
=== AC {check-id} ===
Intent: One or two lines stating what the check proves and why its fixtures exercise it.
Suite: scoped
Requires: executable=python3; scope=test
Probe: --list
Probe Count: summary
<Python source, verbatim, to the end marker>
=== END AC {check-id} ===
```
The delimiters are the whole format. The id lives in the opening marker, so it is never inferred
from a nearby heading. Declarations are the `Key: value` lines at the top of the block, ending at
the first blank line; `Intent:` is required and the rest are optional. Everything after that blank
line is the proof body, taken character for character to the matching end marker.
Every criterion declares one or two nonblank `Intent:` lines: the behavior it proves, the expected
relationship, and, where useful, why its example inputs exercise that behavior. A table of cases
shares one explanation. Plan selects the inputs and calculates the expected results from the
specification; those constants need not appear in source material and need no citation. Repair
quotes these lines verbatim, and a failing criterion never authorizes changing its expected result.
`Probe:`/`Probe Count:` are required together whenever the body invokes a staged runner with a
literal selection option (a flag choosing a subset of an imported corpus, such as `--sections` or
`--select`). All runner arguments after the staged script must be statically resolvable: use
string literals or module-level literal string bindings for the product, corpus and selector.
Canonical `os.path.abspath("literal-path")` is supported with an unmodified `import os`.
Do not use getcwd f-strings, dynamic imports or runtime argument construction; they can run in
Python but Drydock cannot use them to prove the selected corpus before Build.
Drydock re-invokes that same runner with all literal arguments, including corpus
paths and selector options, plus the `Probe:` flag(s) appended — flags that make the runner list or count the matched cases with no
candidate present, e.g. `--list`. `Probe Count:` names how to read the probe's stdout: `lines`
(one selected case per non-blank line) or `summary` (the count is the leading integer of the
trailing non-blank line, e.g. `27 cases, 2 excluded`). Drydock runs the declared probe before
build and refuses the plan if the selector proves to match nothing.
Use only flags and output formats the supplied runner actually implements; the `--list` example
is not a default. `Probe Count: json` counts elements of a JSON array, including zero for `[]`.
For a runner whose `--dump-tests` emits a JSON array, declare `Probe: --dump-tests` and
`Probe Count: json`. Never count pretty-printed JSON lines as cases or declare a summary for JSON.
Program and corpus-path options do not select cases. Preserve the criterion's actual section
filter and corpus path when declaring its probe; never change supplied read-only runners to
accommodate a probe protocol.
Put each `Requires:` declaration inside its `=== AC ... ===` block, before the Python body;
repeat it for each criterion that needs it. A declaration before the opener belongs to no
criterion. Selecting a framework in TECHNOLOGY_STACK.md does not declare the criterion's tools. Each criterion declares every imported
external package and its test transport. For FastAPI TestClient on Starlette 1.2 or newer, declare
`fastapi` and `httpx2` with `scope=test`; use `httpx` only for a compatible older selected stack.
Pin the resolved compatible dependency set in the application lockfile. Import every name inside
each criterion, including a criterion re-emitted by artifact repair.
A foundation criterion verifies its factory/client interface without invoking an endpoint owned
by a later service story; endpoint criteria assert the exact required status, never 200-or-404.
Nothing inside the body can move a boundary. A Markdown fence, a `##` line, a `###` line, or a
`Requires:` line inside a string is ordinary content — which matters, because a target that
processes markup will legitimately embed all of them in its proof. Write the body as plain Python;
do not wrap it in a fence.
Generate valid structured input with its standard serializer. For CSV success cases, use
`csv.writer` with `lineterminator="\n"`; do not concatenate or replace quote characters to
construct records. To test trimming and quoting together, pass padded values such as
`" red, green "` to the writer so the padding stays inside the quoted field. Spaces outside
quotes are CSV syntax, not decoded value padding. A success criterion follows the source's
parser contract (including RFC 4180 when required); it never demands permissive parsing to
accept a malformed fixture. For a strict CSV source contract, construct malformed records
explicitly only in rejection criteria.
Write `=== END AC {check-id} ===` for every `=== AC {check-id} ===` you open, with the same id.
The end marker is not optional and the next opening marker does not stand in for it. Where the
boundary is decidable Drydock inserts the missing marker and reports having done so; where it is
not, planning stops.
An end marker naming a different id, a stray end marker, and a duplicate id are hard errors that
stop planning. None of them degrade into a criterion that silently stops gating.
A backslash in the proof body belongs in a raw string or is doubled. Write `r"\d+"`, `"\\("`, or
`r"\("` — never a bare `"\("`. A bare backslash before a character Python does not recognize as
an escape is not the escape you wrote: it survives today only by a rule scheduled to become a
hard error, and it costs the criterion its binding status. This applies to every proof that
embeds a regular expression, a Windows path, or a target language's own escape syntax.
### The oracle rule
> **Act on the system. Read the state back. Compare to expected.**
Arrange–Act–Assert, where the assertion reads *state*, never text a process printed.
| Oracle | Verdict |
|---|---|
| Return value, parsed JSON, status code, DB row, file contents read back, exit status | **Correct** |
| Substring of captured stdout/stderr, test-runner tally text, log lines | **Forbidden** |
A state oracle cannot pass against a stub and cannot fail because a runner printed the word
"warning". Almost every acceptance defect observed in practice has the same shape: the oracle was
a string in captured output.
### The expected value must be one you could not get wrong
An expected sequence follows its declared sort keys, including secondary keys and mixed directions.
Derive the expected rows from fixture inputs, then sort by those keys; never copy insertion order
into a sorted-output assertion. For `date asc, currency asc`, `YYY` precedes `ZZZ` on one date.
Plan and verify reject a statically resolvable expected row sequence that contradicts a declared
repository `Order` (`ordered-oracle`). This check does not execute proof code or prove arbitrary
ordering expressions correct. Mechanical `plan repair` preserves these assertions for source-based
authoring rather than choosing a new expected order.
A service-start criterion waits within a fixed deadline for the required endpoint or port at the
configured address. It asserts the source's exact response, fails if the process exits or the
deadline expires, retains startup diagnostics, and terminates and reaps the child in `finally`.
An immediate `Popen.poll() is None` proves only process creation and is rejected as
`process-readiness`. Do not substitute a sleep for a readiness probe or use the probe to require
an endpoint owned by a later story; give the criterion the dependency it actually exercises.
For computed numeric output, derive the oracle from the fixture inputs using the source formula.
Never hand-calculate a formatted decimal answer. Use `Decimal` for decimal contracts, preserve
unrounded intermediate values, and apply the specified rounding only at the stated boundary.
For example, with amount `"2.00"`, source rate `"2"`, and target rate `"5"`:
```
from decimal import Decimal, ROUND_HALF_EVEN
expected = (Decimal(amount) * Decimal(target_rate) / Decimal(source_rate)).quantize(
Decimal("0.01"), rounding=ROUND_HALF_EVEN
)
assert body["result"] == f"{expected:.2f}"
```
Read `body` from the application response. This oracle is `5.00`; typing `10.00` invents a
requirement. Preserve published text exactly when the source requires a round trip; do not add
rounding or normalization merely to make an oracle look derived. Static analysis reports
unrecognized decimal provenance as an advisory, never as proof of an invalid expectation or a
reason to rewrite it. Known fixture values may be embedded in CSV, JSON, ZIP members or other
serialized inputs. A derived expression is also not proof of a correct formula: source intent
remains the authority. Moving a guessed answer into a variable does not establish correctness.
Reading state back is half the rule. The other half is what you compare it *to*.
> **Never type an expected value twice. Bind it to a name and use the name on both sides.**
You are authoring this criterion before the code exists, so a hand-typed expectation is a
prediction about bytes you have not seen. When the prediction is wrong the criterion fails against
a correct implementation, and nothing downstream can tell that from a real defect. This is the
single largest source of wasted build budget on record.
| Expected value | Verdict |
|---|---|
| A name bound to the value the criterion supplied as input | **Correct** |
| A status code, exit status, or count | **Correct** |
| A contract token read off a declared interface — `"integer"`, `"application/json"`, `"POST"` | **Correct** |
| A staged suite's exit status | **Correct** |
| A string literal you typed out as the expected result | **Forbidden** |
The forbidden row is judged mechanically: a string expectation carrying anything escapable —
whitespace, a backslash, a quote, a newline, a non-ASCII character — that the criterion did not
also supply as input. An expectation assembled in the criterion — an f-string, a `+`
concatenation with a string, `"..." % args`, or `"...".format(...)` — is forbidden the same way,
unless that same expression is what the criterion supplied as input. A criterion that breaks the
rule still runs and is still reported, but it settles `DISPUTED` and gates nothing, so it buys the
story no coverage at all.
One exception is mechanical too. When the source material under `sources/` states the exact
expected value, cite it: `Cite: sources/<file>:<line>` or `Cite: sources/<file>:<start>-<end>`. A
literal that appears verbatim in the cited lines is derived, not re-typed, because the source is
the authority. `drydock plan verify` refuses a citation that does not resolve or whose lines
contain none of the criterion's expected literals.
The case this comes from. Wrong:
```
source = 'basic = "line\\nvalue"\nraw = \'C:\\\\Users\\\\nodejs\'\n'
result = subprocess.run(["./toml-decoder"], input=source, capture_output=True, text=True)
decoded = json.loads(result.stdout)
assert decoded["raw"]["value"] == r"C:\Users\nodejs" # re-typed, and wrong
```
A TOML literal string preserves its backslashes verbatim, so the decoder returned the doubled
form and the expectation was wrong. Right:
```
raw = "C:\\Users\\nodejs"
source = f"raw = '{raw}'\n"
result = subprocess.run(["./toml-decoder"], input=source, capture_output=True, text=True)
decoded = json.loads(result.stdout)
assert decoded["raw"]["value"] == raw # one spelling, cannot disagree
```
The same rule applies when the re-typed value is not a string literal but an independently
reconstructed expression — a rebuilt path, URL, or timestamp compared against one the code under
test computes itself. Two spellings of "the same" value can disagree exactly where a normalization
step is involved (`.resolve()` against a relative join, a trailing slash, case folding), and the
criterion has no way to know which spelling the implementation is entitled to produce. Read the
value back from what the code exposes; do not reconstruct a second copy to compare it to.
Wrong:
```
from pathlib import Path
sources = Path("sources")
import run_conformance
assert run_conformance.CORPUS == sources / "jq.test" # rebuilt, and not the same path shape
```
`run_conformance.CORPUS` is `Path(__file__).resolve().parent / "jq.test"` — absolute, because the
module resolves its own location. `sources / "jq.test"` is relative. Nothing the implementation
does can make these equal; the criterion is unsatisfiable regardless of correctness. Right:
```
from pathlib import Path
sources = Path("sources")
import run_conformance
assert run_conformance.CORPUS == (sources / "jq.test").resolve()
```
or, when the criterion only needs to know the module points at the right file, assert what it
actually claims rather than reconstructing a value to compare:
```
assert run_conformance.CORPUS.samefile(sources / "jq.test")
```
When a transform's output genuinely cannot be derived from its input — a renderer turning `# h`
into `<h1>h</h1>` — do not hand-write the expectation at all. Bind the criterion to the
authoritative suite that defines correctness for that transform. Where no such suite exists, put
the case in the project's own test suite, where the implementer writes it against real output,
rather than predicting it here.
### Two test destinations
A project carries tests in two places, and they are not the same artifact with different names.
| | **Story AC** — `=== AC <id> ===` | **The project's own test suite** |
|---|---|---|
| Job | gate the block | know the code works |
| Count | few | unbounded |
| Authored | here, by planning, **before the code exists** | by the build agent, **alongside the code** |
| Oracle discipline | the rules above, without exception | full latitude — expectations are observed, not predicted |
| Effect | binding: it decides whether the block closes | diagnostic: it guides repair, and its command is what a project criterion runs |
| Runs | at its block | continuously, cumulatively |
The split is not a matter of taste. Every expected value written here is a *prediction* about
bytes that do not exist yet, and a wrong prediction fails a correct implementation — which is why
the oracle rule and the no-re-typed-literal rule are absolute in this file. A test written beside
the finished code compares against output its author has actually seen, so the same assertion that
is hazardous here is safe there.
So this is *more* testing, not less. Exhaustive coverage belongs to the project's suite, which has
no ceiling. An AC block is permanently constrained by having to survive as a gate, so author few
and author them bulletproof. Coverage is never demonstrated by the number of AC blocks a story
carries; it is demonstrated by the suite, and it is graded at the project level through the Sea
Trial that runs that suite.
**Where an authoritative suite exists, it is the coverage.** A conformance corpus staged into
`sources/` defines correctness for the surface it covers. Bind one criterion to it and do not
restate its cases in either destination — a restated case adds no coverage and adds one more
expectation that can be wrong.
**The terminal story is the last story in the build order** — the one on which every other story
is a transitive dependency and after which no further story runs. It is decided by position in the
graph, never by name, type, or kind. A story is not terminal because it is called "verify", because
its `kind` is a test harness, or because it stages the test assets: staging the corpus is
foundational work that runs first, and running the corpus is terminal work that runs last. When a
plan contains several verification stories, exactly one of them is terminal and it is the one every
other story precedes. Identify it by resolving `depends` before writing any suite criterion.
**Only the terminal story runs the whole suite.** No intermediate story's acceptance invokes the
runner unscoped. A partial capability fails most of an authoritative corpus by construction, so an
unscoped mid-build run reports the schedule rather than a defect — and it is slow in exact
proportion to how incomplete the code is, because unimplemented cases exhaust the runner's per-case
timeout instead of returning. It costs most at the point in the build where it teaches least, and a
build agent that starts one mid-story typically abandons it and reports the suite as hung.
**An intermediate story runs its own slice, and the slice executes.** Scoped to the cases that
story implements, the run is neither slow nor red by construction: those are exactly the cases its
code is supposed to pass, so the result is a verdict about the story rather than a report on the
schedule. This is what makes build progress visible — the corpus goes green in the order the plan
builds it, and a regression in an earlier story is caught by the later story that re-runs it.
A section title is not a prerequisite boundary. Review the supplied selected examples for
cross-feature interactions and preserve the frozen topology's coverage assignments. A nonempty
probe does not establish that every selected capability is available. Use only documented
runner options to select an implementable slice. If the runner supports only a mixed section
that requires future work, test the current story's own API directly (without restating corpus
examples), then assign that entire section to a later integration with all required providers.
That integration runs the real corpus before the terminal gate. No case is dropped, expected
result changed, or dependency cycle introduced; the early gate measures the delivered capability.
Executing is the whole point, so:
- The slice **runs cases**. A criterion that invokes the runner's list or dry-run mode executes
nothing, passes before the story's code exists, and proves only that the runner starts. Such a
criterion is a defect: it is green from the first build call to the last and steers no repair.
- The slice is **selected by the story's capability**, using the runner's own scoping flag — not by
case count, not at random, and never by a selector that silently pulls in cases belonging to
unbuilt stories. Size and inspect each selector with the runner's list mode **while planning**;
that is where list mode belongs, not in a criterion.
- Every slice invocation supplies each environment variable the runner declares required.
**Together the slices cover the corpus.** Every case an authoritative suite contains belongs to
some story's slice. A case no intermediate slice reaches is first executed by the terminal gate,
where a failure arrives with the whole build already spent and no story to attribute it to.
Overlap between slices is expected and costs nothing — a case exercised by two capabilities
legitimately belongs to both — but a gap is a story whose work no one checked.
**A story that only stages the suite asserts staging.** Where a story's obligation is that the
corpus parses, the exclusion list applies, and the runner starts — and it implements none of the
behavior under test — its criterion invokes the runner's list or dry-run mode and asserts the
runner exits `0` and reports the expected count. This is the one criterion for which executing
nothing is correct, because there is nothing of the product to execute yet. Leaving such a story
with no criterion at all is a defect: it produces a story that cannot be verified and a build block
that closes advisory.
If an imported instruction states where the suite may run, that statement governs.
### What a criterion is worth
Every criterion you write lands in one of four tiers. The tier is decided by how the criterion is
written, not by how it is labelled, and it decides what the criterion can do:
| Tier | What it is | What it does |
|---|---|---|
| **BLOCKING** | a Commander-governed gate, or a criterion bound to a staged authoritative suite | fails the block |
| **CONSULTATIVE** | a criterion whose expected value could not have been invented — a status code, an exit status, a value the criterion itself supplied as input | drives repair; unattended, it marks the block implemented-but-unverified rather than stalling the run |
| **ADVISORY** | a criterion that re-types an expected literal | runs, is reported `DISPUTED`, **gates nothing** |
| **VOID** | malformed: does not compile, or an unclosed container | not a criterion; recorded as a decision and gates nothing |
Aim deliberately. A hand-typed expectation does not merely risk being wrong — it demotes the
criterion to ADVISORY, so the story it was written to protect ends up with no gate at all. Binding
the value to a name is what buys the criterion its authority back.
None of these tiers reaches the release verdict. Story AC decides whether an increment was built;
project acceptance is decided by Sea Trials alone.
### Authoring patterns
Patterns **1, 4, 6, 9, and 10** are the discipline of a gate and govern what you write here.
Patterns **2, 3, 5, 7, and 8** are the discipline of a test suite: state them as expectations on
the project's own suite, which the build agent grows beside the code, rather than enumerating them
into AC blocks.
**1 — Round trip (the default form).** For anything that stores, mutates, or removes state:
```
create → read back → assert present, with expected field values
update → read back → assert changed, and only the intended fields changed
delete → read back → assert absent
```
The read-back is a *separate call through the public interface*, not an inspection of the object
returned by the write. A write that returns a plausible object while persisting nothing must fail.
**2 — Exercise every callable workflow.** *Suite pattern.* One test per public entry point, per
verb. Coverage is enumerated from the interface, not sampled: every HTTP route × every method it
declares including declared error paths; every CLI subcommand and every flag that changes
behavior; every exported library function. This belongs to the project's suite. Here, name the
routes a SCREEN provides — that gate is real — and leave the enumeration to the suite. Where a
staged authoritative suite already covers the surface, it is the coverage.
**3 — Idempotence.** *Suite pattern.* Where a verb claims idempotence (PUT, DELETE), apply it twice and assert the
second is a no-op — same resulting state, and the declared status for a repeat. Where a verb is not
idempotent (POST), apply twice and assert the declared behavior: two resources, or the declared
conflict. Prefer idempotent verbs where the semantics allow; the assertion is stronger.
**4 — Negative paths assert the contract, not the message.** Invalid input asserts the declared
failure signal — status code, exception type, exit status — never the wording of an error message.
Message text is prose and belongs to no contract.
**5 — Boundaries.** *Suite pattern.* Empty collection, exactly one, many. Absent optional fields.
Declared maxima. This is where a plausible-looking implementation actually breaks — and where a
predicted expectation is most likely to be wrong, which is why the cases belong beside the code
rather than here. Where a staged authoritative suite covers the surface, it is the coverage.
**6 — RED before GREEN.** The assertion must fail against the pre-implementation tree and pass
after. A check that passes against a stub is not a check.
**7 — Isolation and determinism.** *Suite pattern, and it applies here too.* Each test arranges its own data and does not depend on another
test's residue or on ordering. No wall-clock dependence, no third-party network, no unseeded
randomness, no sleep-based timing. Fresh store per test, or explicit teardown.
**8 — One behavior per test, named for the behavior.** *Suite pattern.* A failure should be
diagnosable from the test's name alone.
**9 — Subprocess discipline.** Where a check must shell out, **exit status is the verdict**. A
substring check beside an exit-status assertion is redundant at best and a false-positive generator
at worst. Never assert that a literal is absent from captured output.
**10 — In-language tooling.** A check is written in the project's own language and uses that
language's libraries — Python check, Python libraries; Go check, Go libraries. An in-language HTTP
client yields a status code and a parsed body, which is state. `curl` yields stdout, which is text
to scrape. Pattern 10 and the oracle rule are the same rule seen twice.
### Declaring external tooling
Reaching for an external executable is the exception, not the norm, and `curl` in particular will
not work in every environment. When a check genuinely needs one, the tool belongs in the project's
Rigging or `TECHNOLOGY_STACK.md`, declared once by the Commander and true for every check in the
project. A per-check declaration is also accepted and is recorded as a report:
```markdown
Requires: python-package=httpx2; scope=test
Requires: executable=node; scope=test
```
Kinds are `python-package` and `executable`; scopes are `runtime` and `test`. Framework test
clients include their transport dependencies. `Requires:` metadata is not acceptance intent, and
a missing declaration never fails planning — a tool that is present and undeclared works fine.
A declared tool that is *absent* when the check runs reports UNVERIFIED, not FAIL: the check never
reached the code under test, so it says nothing about the build.
### Satisfiability
Every assertion must be satisfiable by a correct implementation. An expectation no implementation
can meet is a defect, not a red baseline. Escaping is the usual source of one: inside a raw
literal, `\n` and `\r` are a backslash followed by a letter, not a control character, so
`r"text\n"` asserts against six characters ending in a literal backslash. Binding the value to a
name and using it on both sides removes the question entirely, which is why that is the rule.
### Runnability
**Subprocess mode.** Match the mode to `input=`. Text input declares `text=True` or `encoding=...`;
binary input uses a bytes-like value and does not declare `text`, `encoding`, `errors`, or
`universal_newlines`. A mismatch raises `TypeError` before the program under test starts, which
reports UNVERIFIED — the criterion buys the story nothing. Write:
```
payload = "one line\n"
result = subprocess.run(["./program"], input=payload, capture_output=True, text=True)
assert result.returncode == 0
```
For a binary or invalid-encoding criterion, write:
```
result = subprocess.run(["./program"], input=b"\xff", capture_output=True)
assert result.returncode != 0
```
**ASCII test data.** Acceptance data is ASCII. Do not invent an encoding requirement: characters
outside ASCII test a property the specification never stated, and a criterion that fails on them
fails the build for something nobody asked the product to do. When the imported specification does
state an encoding requirement, the criterion says so and may then use that encoding:
```
=== AC runtime-utf8 ===
Intent: The executable round-trips UTF-8 source, per INSTRUCTIONS.md.
Encoding: utf-8
source = "café\n"
result = subprocess.run(
["./program"], input=source, capture_output=True, text=True, encoding="utf-8"
)
assert result.returncode == 0
assert source.strip() in result.stdout
=== END AC runtime-utf8 ===
```
`Encoding:` is a declaration of deliberate intent, reviewable as such. Absent it, ASCII.
**Stated behavior only.** A criterion asserts behavior the source states, not behavior its phrasing
implies. "Takes no arguments", "has no configuration", and "has no side effects" describe the
surface a program offers; they are not requirements that it detect and reject an argument, a
configuration file, or a write. Where the source supplies a reference implementation, that
implementation bounds what the criteria may demand: a criterion the reference shape would fail is a
criterion the source did not ask for.
**Every check is standalone.** Drydock writes each fenced block to its own script and runs it in
its own process from the build directory. Checks in the same file share no imports, no variables,
and no execution order. A snippet that reads a name another snippet bound raises `NameError` on
every run — it reports UNVERIFIED rather than failing the build, which means it verifies nothing
and buys nothing. Each snippet imports what it uses and binds every name it reads.
**Every check creates the state it depends on.** A check starts from the existing provisioned application store. Before
the action under test, it creates every row, file, or record that its input refers to and that a
source rule requires to exist. A check that loads a transaction for account `A` first loads account
`A`. Without that setup, a correct product rejects the input: an expected success fails, and an
expected rejection passes for the wrong reason. Every setup call asserts the success its source
declares: a valid staged asset loads with exit `0`, never `1`. A setup call that expects failure
creates nothing, and the action under test then runs against the empty application.
**A check exercises the built application through the client its foundation publishes.** The
Rigging file for the Target's web server, database and CLI publishes a `## Foundation Contract`
naming the package, the entry point, and the client callable — `web_client`, `db_session`,
`cli_runner` — a plain function in `<package>/testing.py`. A check imports it from there and calls
it: `from app_server.testing import web_client`, then `client = web_client()`. That runs the
application the build wrote, in-process, without pytest; the pytest suite receives the same
callable through `conftest.py`. The names are fixed by the technology the Commander selected, so a
criterion writes them rather than inventing a package or constructing a client of its own.
Constructing one is how a Blueprint set ends up split between two package names and calling a
framework's method on another framework's object.
A check may also run the application's own pytest suite through the language foundation's
`test_command`. It imports the foundation package before it does, so against an application that
is not built it fails as `foundation not built` rather than inside pytest. A suite run is never a
story's only proof: the builder writes those tests, so at least one check asserts behavior the
Blueprint states.
A check importing a foundation package the build directory does not contain is not run and fails
as `foundation not built`. That is the expected red before the foundation story builds it.
`app_server`, `persistence`, and `cli` are reserved: each names the selected foundation of that
kind, whichever file the Commander selected. A criterion importing one the stack did not select,
or importing a published entry point from any other package, is refused as `unknown-package` and
the plan is written `unbuildable`.
**A check never reads a Blueprint document.** The Blueprint is the build's *input*; the build
directory holds the code written from it and nothing copies a specification next to that code.
`pathlib.Path("ARCHITECTURE.md").read_text()` raises `FileNotFoundError` on every run, so no
implementation and no repair pass can turn it green. It is also worthless where it succeeds:
grepping a specification for the words it was written with asserts that the document contains
itself, and passes against an empty build directory. Assert against the built artifact — import
the module, call the route, read the value off the settings object. Only paths under `sources/`
are staged into the build and may be named. `drydock plan verify` refuses a criterion that reads
one, and the plan is written `unbuildable`.
**A check that shells out prints what it captured before it asserts.** `capture_output=True`
routes the runner's tally and its failing cases into a variable; asserting on the exit code alone
then discards them, and the failure reports the assertion with no evidence of what went wrong.
Print the captured `stdout` and `stderr` first, so the console, the evidence file, and the repair
pass all carry the runner's own account of the failure. Printing is for diagnosis; it is never the
oracle.
**A check that drives a suite prints its tally.** A criterion answers one yes-or-no question, so a
run that fixes a hundred cases and a run that fixes none report the same failure, and the build
reads that as a stalled repair and stops paying for calls that were working. The count is what
separates them. Where the runner reports a machine-readable summary, parse it and print the
counts on one line before asserting:
```
report = json.loads(result.stdout)
summary = report["summary"]
print(f"{summary['pass']} passed, {summary['fail']} failed, {summary['error']} errored")
assert summary["fail"] == 0 and summary["error"] == 0
```
Print the counts even when the criterion asserts on the parsed object rather than on the text.
Requesting `--json` and asserting straight off the parsed report leaves nothing on either stream,
and a suite of hundreds of cases then reports its progress as a single bit.
```markdown
## Programmatic Acceptance
=== AC health-check ===
Intent: The health endpoint returns an OK response.
from app_server.testing import web_client
client = web_client()
response = client.get("/health")
assert response.status_code == 200
=== END AC health-check ===
=== AC suite-conformance ===
Intent: The implementation passes the conformance sections this story owns.
Suite: scoped
Probe: --list
Probe Count: summary
import os
import subprocess
import sys
# tests/run_suite.py documents RUNNER as required: it is the runner's only knowledge of the
# implementation. Read the asset and supply every variable it declares required.
result = subprocess.run(
[sys.executable, "tests/run_suite.py", "--sections", "headings,lists"],
capture_output=True, text=True,
env={**os.environ, "RUNNER": os.path.abspath("program")},
)
print(result.stdout)
print(result.stderr, file=sys.stderr)
assert result.returncode == 0
=== END AC suite-conformance ===
```
`User Acceptance` contains only Commander-observed checks that cannot be honestly automated,
such as look-and-feel or subjective workflow acceptance. Do not place deterministic behavior in
`User Acceptance`.
Do not tag an assertion with a project-acceptance ID. Sea Trials flow into planning as context for
authoring acceptance; nothing points back at them. Project acceptance is settled at `score release`
by observing the finished tree, never by looking up which assertion claimed which criterion.
**Programmatic acceptance is the story's definition of done, and a deterministic definition of
done is never sampled.** Drydock builds each block in a single pass with no iterate loop, so the
acceptance you author *is* the objective handed to the builder: sample the checks and the builder
builds to the sample. When an authoritative, externally-authored test suite already defines
"correct" for what a story builds — an imported conformance suite and its runner (for example a
specification's example suite plus a `*_tests.py` runner) — the acceptance runs that suite and
requires a full pass over the story's scope, never a hand-picked subset. A feature story binds to
the sections it owns and declares `Suite: scoped`; a terminal verification story gates on the whole
suite and declares `Suite: full`. The marker is one of the block's declaration lines and tells the
runner the check gates on the whole test suite rather than a story-scoped sample.
**A scoped selector must select something.** A check that runs a suite with a section filter
matching no cases exits zero and reports a pass while proving nothing. Select on a heading that
actually owns cases, never on a chapter title that merely contains such headings. Drydock fails a
criterion that is already green before the story's code exists. This is checked mechanically, not
only reasoned about: declare `Probe:`/`Probe Count:` for every such selector, and Drydock runs the
declared probe before build and refuses the plan if it counts zero.
**The runner's exit status is the verdict, and it is the whole verdict.** A conformance runner
already decides pass or fail and reports it the one way a caller can rely on. Asserting on its
printed summary as well adds no information and adds a failure mode: the case count belongs to the
installed suite rather than to the specification, and runners column-align their summaries
(`valid tests: 205 passed, 0 failed` carries two spaces), so a literal such as
`assert "valid tests: 210 passed, 0 failed" in result.stdout` is false on correct code and no
implementation can move it. The same holds for tallies of errors, skips, and warnings: a runner
with none of them commonly prints no such line at all, so requiring one is false on a clean run.
Print the captured output for diagnosis, assert `result.returncode == 0`, and stop there. This
holds for both `Suite: scoped` and `Suite: full`.
Place a whole-project deterministic suite on the story that **completes the runnable capability**
— never on a foundation step that cannot yet run it, where it would fail vacuously. Naming the suite file or asserting it is staged (`Path(...).is_file()`)
is staging, not testing: a stubbed or absent definition of done for an available suite is a defect,
not an acceptable check.
An assertion that invokes a staged asset obeys that asset's own documented interface. Read the
asset before writing the call. Every environment variable it declares required is supplied, and it
is supplied by extending the inherited environment — `env={**os.environ, "NAME": value}`. Never
write `env={"NAME": value}`: that replaces the environment, leaving the child with no `PATH`, so
nothing it invokes resolves and the assertion fails at every level of implementation quality. Never
repair a staged asset's interface by editing the asset; it is restored before grading, so the edit
is reported as tampering rather than honored.
An assertion that feeds input to a program passes it through `subprocess` `input=` rather than a
shell. When a shell is unavoidable, `printf '%s'` copies its argument verbatim: `\n` reaches the
program as a backslash and a letter, not a newline, so the program is graded on input the author
never wrote. Use `printf '%b'` or a real line break.
`COMPASS.md` uses `## Compass`, `## Constraints`, and `## Guardrails` as its body sections.
Success criteria belong in `SEA_TRIALS.md`; open questions in spike questionnaires. Do not add
those sections to `COMPASS.md`.
---
---
## Acceptance Criteria Files
**Naming rule:** any file where `AC` is a whole word in the filename is an acceptance criteria
file. `AC` must be delimited by `-`, `_`, or file boundaries — not embedded in another word.
Examples: `AC-001-login.md`, `FEATURE-LOGIN-AC.md`, `AC-NAVIGATION.md`.
`ACCEPTANCE_CRITERIA.md` does NOT follow this standard (AC is not a standalone word).
AC files enable test-driven design and a way to enforce specific behaviors without polluting the
parent specification.
**Two types of AC statements:**
| Type | Example | Rule |
|------|---------|------|
| Positive assertion | "The status badge color is red" | Reconcile into parent spec, then archive this entry |
| Negative/guardrail | "Field X must not appear on this screen" | Keep permanently in AC — these guard against model hallucination, not spec omission |
**Reconciliation:** When a positive AC fact has been implemented and verified, move it to the
parent spec body and delete the AC entry. Negative guardrails are permanent — never move them to
the spec.
**AC file format:**
```markdown
# AC: {ObjectName}
| Field | Value |
|-------------|-------|
| Version | YYYYMMDD V1 |
| Description | Acceptance criteria for {ObjectName}. |
| Parent | FEATURE-{Name}.md |
## Guardrails
- Field X must not appear on this screen.
- The delete button must not be shown to read-only users.
## Assertions
- The status badge is rendered in red when severity is HIGH.
```
**Standard AC filename forms:**
- `AC-NNN-{Name}.md` — numbered sequential acceptance-criteria ticket (authored)
- `{Parent}-AC.md` — paired directly with a spec file (e.g. `FEATURE-LOGIN-AC.md`)
- `AC-{Topic}.md` — topic-scoped AC file (e.g. `AC-NAVIGATION.md`)
**All fix and change tickets use AC naming** — `AC` as a whole word in the filename. A targeted
bug fix is expressed as a testable acceptance criterion.
---
## Dependency Declarations
`drydock plan create` scans spec file headers to populate `Depends On` and `Provides`. The
following conventions apply automatically without explicit header declaration:
| Convention | Rule |
|------------|------|
| `SCREEN-*.md` → `UI-GENERAL.md` | All screens depend on shared UI patterns |
| `DATABASE.md` → Phase 1 | Always first phase; always base context |
| `ARCHITECTURE.md` → base context | Included in every phase prompt |
| `FEATURE-*.md` providing routes → listed in `Provides` | Extracted from route tables in file |
| `SCREEN-*.md` using a route → depends on providing `FEATURE` | Matched from route references in body |
The `Depends On` and `Provides` fields form a simple directed dependency graph. `drydock plan
create` traverses this graph to assign phases, assign build order, and compute context sizes.
A file can only be built in a phase after all its `Depends On` files are built.
---
## Acceptance Strength
A criterion states one expectation. Pin the status the implementation answers with: a stub that
answers `200` is a real contract and a real test, and specifying a stub is legitimate.
`404` means the endpoint is absent. Asserted alone it is a deliberate negative probe and one of the
strongest checks available. Admitted beside any other status it makes the criterion true of an
application that implements nothing, so `in {200, 404}` and `in {400, 404}` are both defects. A set
admitting both success and a `5xx` is a defect for the same reason.
A criterion that needs a row to exist creates it through the public interface first. Admitting the
status that says the row never existed is not a substitute for building the state the criterion
depends on.
## Persistence Encapsulation (DATABASE.md scope)
`DATABASE.md` is the project's persistence contract — not SQL schema alone. It documents every
persistent store and the typed repository contract that encapsulates it:
- **Relational stores** — declared tables, the access patterns that reach them, and their DTO
inputs and outputs. Drydock generates the implementation from this; no Blueprint describes one.
- **Config / `.env`** — required keys and the typed `Config` class.
- **File stores** — directories and the `FileStore` class.
- **External services** — the service contract and its wrapper.
Routes call services; services call the generated persistence package — `db.<table>.<verb>(...)`,
one method per declared access pattern. SQL, sessions, table names, and column names never cross
that boundary, and no Blueprint describes a repository implementation: Drydock generates it from
this declaration. A storage change that leaves the named
repository-call contract unchanged does not invalidate downstream features.
Every `DATABASE.md` includes `## Access Patterns` before schema details. Every access pattern has a stable feature-owned `FEATURE-<DOMAIN>-<NNN>` id, Owner,
`read`, `write`, or `read-write` access, repository method, DTO input and output shapes, and
compatibility level: `unchanged`, `data`, or `rebuild`. Route and screen Blueprints cite only those
ids through a `## Database Interface` section, including only fields they supply or receive; they
do not cite a physical store. Persistence interfaces name the repository, module location, and
allowed callers.
A Feature cites only access patterns whose Owner names that exact Feature or the shared owner
`DATABASE.md`. When several Features use an operation, declare the shared owner in `DATABASE.md`;
never claim another Feature's private pattern. Derive each interface's DTO field list from the
current `DATABASE.md` rather than from a remembered draft.
`## Database Interface` is required, not optional, for every Blueprint that `DATABASE.md` names
as the `Owner` of an access pattern. Ownership is read from the declaration, never guessed from a
story's `stack:`: a stack selection says which technology the story is built with, not whether it
reaches a repository. Each citation is one bullet on one line, in this exact form:
```text
## Database Interface
- `FEATURE-ORDER-001` — write: create an order - supplies: `customer_id`, `items` - returns: `id`, `status`
- `FEATURE-ORDER-002` — read: retrieve an order by id - supplies: `order_id` - returns: `status`, `total`
```
The id is an `## Access Patterns` id in backticks, the em dash is literal, the access is `read`,
`write`, or `read-write`, and `supplies:` and `returns:` carry comma-separated backticked field
names from that pattern's Input and Output DTOs. Author an empty list explicitly as `—`:
`- supplies: — - returns: —`. The reader also accepts an omitted `supplies:` or `returns:`
as an empty claim when the other field clause is present. Required inputs, declared fields
and access grants remain validated against DATABASE.md; omission never supplies a required input.
A Blueprint that reaches no repository — a Screen
that delegates to a Feature's service routes — writes one bullet and no other:
```text
- None — persistence is owned by FEATURE-ORDER.md.
```
`- None` is available only to a Blueprint the declaration names nowhere. A Feature named as an
`Owner` states the operations it owns, or the `| Owner |` row moves to the Feature that does own
them. A pattern owned by `DATABASE.md` is shared: any Blueprint may cite it, and none is required
to.
Every bullet under the heading is an entry and every entry is checked, so a sentence of prose there
fails the plan as a malformed citation. Say it in `## Purpose` instead. A citation may claim less
access than the pattern grants — a read-only consumer of a `read-write` surface is a real claim —
but never more. Drydock checks each citation
against the declaration. An unknown operation, a wrong owner, access the pattern does not grant, a
field the DTO does not carry, or a required field left out is a conflict Build would implement, and
it fails the plan. A Blueprint whose story selects a persistence stack and cites nothing fails it
the same way. Persistence is the one part of a plan decidable from the artifacts alone, so none of
it is left to a Commander to answer: Drydock repairs the cited Blueprint and re-validates, and a
defect that survives repair stops the run.
Each access pattern is its own `### FEATURE-<DOMAIN>-<NNN> — <Operation>` section over a
`| Field | Value |` table carrying Owner, Access, Repository operation, and Compatibility, followed
by an `Input: <DTO>` and an `Output: <DTO>` field table. Never collapse the operations into one
table of rows.
An Output DTO name has one ordered field/type definition throughout `DATABASE.md`. Reuse a
name only for the same record shape. For a distinct projection, derive a descriptive name
from the complete repository operation: `rates.get` becomes `RatesGetOutput`, and
`rates.delete` becomes `RatesDeleteOutput`. The latter may carry only `date` and `currency`
while the former also carries `rate`; they never both use `Rate`. Preserve the required fields
and caller expectations when repairing a name conflict. Do not add a field to a delete output
merely to match another DTO, and do not add arbitrary numeric suffixes. Python class-name
normalization also applies: spellings such as `Rate` and `R-ate` name the same generated class.
`Owner` is the file name of the Feature that reaches this pattern — `FEATURE-ORDER.md` — and
never a service, module, or layer name. Only a Feature owns data: a Screen renders it through a
Feature's service and never holds a repository. It is the only place the plan says which Feature
owns which data, so it is compared to the emitted file names rather than read as prose: an Owner
naming something that is not a Feature in this plan fails the plan, as does a Feature that owns a
pattern and cites nothing.
A pattern no single Feature owns — an activity log or other shared surface several Features write
and several Screens read — names `DATABASE.md` as its `Owner`. That states the fact: the data is
declared here and no Feature claims it. Any Blueprint may cite a shared pattern, no Blueprint is
required to, and `DATABASE.md` cites nothing itself. Never invent a Blueprint file name for a
surface that has no Feature; name `DATABASE.md` instead.
`Repository operation` names one declared table and one operation as `<table>.<name>`,
lowercase snake_case: `` `settings.get` `` or `` `rates.replace_rate` ``. The name is the method
callers use, `db.<table>.<name>(...)`, and it is the contract they depend on. Its `| Kind |` row
says how it runs: `get`, `list`, `create`, `update`, `upsert`, or `delete`, and no other. A name
that is itself one of those words is its own Kind and needs no Kind row, so a simple table
declares `rates.get` and `rates.update`. Any other name declares its Kind:
```markdown
| Repository operation | `rates.reprice_currency` |
| Kind | update |
| Match | `currency` |
```
One access pattern declares exactly one operation, because it carries exactly one `Input:` and
one `Output:` table — a cell naming two operations leaves which fields belong to which
undeclared. Give each operation its own `### <FEATURE-DOMAIN-NNN>` section with its own DTO
tables. A table may hold several operations of one Kind under different names, such as
`rates.update` by `PK` and `rates.reprice_currency` by currency. Each name is declared once, and
two names that run the same Kind, Match, Sets, and Output are synonyms: declare one and cite it
everywhere.
An optional `| Match | `a`, `b` |` row names the Input fields that select the rows an operation
reaches. Every Match field is an Input field, required at call time except on a `list`, and the
terms are joined with AND. A bare field is compared by equality with the column of its own name.
A term `<column> <op> <field>`, with op one of `=`, `<`, `<=`, `>`, `>=`, compares an Input field
that is not a column with that column, so a range is two terms on one column:
`` `date >= start_date`, `date <= end_date` ``. A comparison term belongs to a `list`, `update`,
or `delete`; `get` and `upsert` match a unique key by equality. Every Input field is a column of
the table or the field of a comparison term, and a field appears in one term only. No other
operator, no OR, no join, and no SQL exist. A Match whose equality fields cover the `PK` or a
declared `UNIQUE` reaches at most one row; any other Match reaches many. Each Kind uses Match
exactly as follows:
| Kind | Match | Input fields | Rows | Returns |
|---|---|---|---|---|
| `get` | a unique key; defaults to every Input field | exactly the Match | 0..1 | the Output row, or none |
| `list` | optional; states how each filter compares, and every filter, bound included, is optional | the filters | 0..n | a list of Output rows |
| `create` | not declared | the values inserted | 1 | the Output row |
| `update` | any Input fields; defaults to the `PK` | the Match plus at least one column to set | 0..1 on a unique key, else 0..n | the Output row, or none; a count when it reaches many |
| `upsert` | required; exactly one declared unique key | the Match plus the columns to set, including every `NOT NULL` column without a `DEFAULT` | 1 | the Output row |
| `delete` | defaults to every Input field | exactly the Match | 0..1 on a unique key, else 0..n | the Output built from the Match, or none; a count when it reaches many |
A `list` returns its rows in no stated order unless it declares `| Order | `date` asc |`: one or
more columns of the table, each `asc` (the default) or `desc`, the first the primary sort key.
Declare an Order whenever a story states one, such as "points in ascending date order"; Order
belongs to a `list` only.
```markdown
| Repository operation | `rates.history` |
| Kind | list |
| Match | `currency`, `date >= start_date`, `date <= end_date` |
| Order | `date` asc |
```
An `update` or `delete` that reaches many rows declares its Output with no fields, because it
returns the number of rows changed. `upsert` inserts the row its Match identifies, or replaces
that row's other Input columns when it exists, in one atomic statement. It is the operation for a
source rule such as "a stored (date, currency) is replaced". A `get` on a non-unique field is a
`list`. A pattern that breaks one of these rules fails the plan with the rule named.
```markdown
### FEATURE-RATE-004 — Store a rate, replacing the stored one
| Field | Value |
|-------|-------|
| Owner | FEATURE-RateStorage.md |
| Access | write |
| Repository operation | `rates.replace_rate` |
| Kind | upsert |
| Match | `date`, `currency` |
| Compatibility | unchanged |
```
Drydock derives each operation's contract from the declaration: its call, Kind, Match, Sets,
rows, Input and Output as JSON with caller types (`str`, `int`, `float`, `bool`, `bytes`), the
SQL the runtime executes, and a contract fingerprint. Only a change a caller can see moves the
fingerprint: the name, Kind, Match terms, Order, rows, return shape, or a field's name or caller
type. A
column's length, nullability, `DEFAULT`, an index, or the SQL never does, so changing them
rebuilds nothing beyond `DATABASE.md`. It is the only place the declaration says which table a pattern reaches, so the form is
checked rather than advisory, and free text there fails the plan. Every table in `## Schema` is reached by at least one access
pattern, and every operation names a table `## Schema` declares. A table nothing reaches is
storage no story can use; an operation on a table that is not declared builds a repository against
nothing. Declare the pattern in the same batch as the table. A `DATABASE.md` whose `## Access Patterns` holds no named operation fails the plan:
Build reads that surface to fingerprint the persistence contract, and an unparseable one stops the
build after a block has already been spent.
`DATABASE.md` is authored in one step: its own Blueprint batch, complete, and then frozen like
every other Blueprint. That batch starts from a seed of the Rigging template and every table the
imported source specification already declared; keep every seeded table. Declare every table and
one access pattern for each repository operation any story in the frozen topology needs. Later
batches receive the frozen declaration as `DATABASE_compact.md` and cite its access patterns. Its
generated `## Operation Surface` gives, per table, each operation's contract: call, Kind, Match,
Sets, rows, Input and Output JSON, and SQL. Author criteria and callers against it.
Each table is a top-level `` ## `table_name` `` section — lowercase snake_case in backticks — over
a `| Field | Type | Notes |` table. A type cell is
`<TYPE> [PK] [NOT NULL] [UNIQUE] [DEFAULT <literal>] [REFERENCES <table>(<column>)]`, where
`<TYPE>` is `INTEGER`, `TEXT`, `REAL`, `NUMERIC`, or `VARCHAR(<n>)`, and `<literal>` is a
single-quoted string, a number, `NULL`, `CURRENT_TIMESTAMP`, `CURRENT_DATE`, or `CURRENT_TIME`.
Brackets mark optional entries and are not written: `TEXT NOT NULL UNIQUE`, never
`TEXT NOT NULL [UNIQUE]`. Nothing else is accepted: Drydock renders executable DDL from these cells, so a modifier it cannot
read is a constraint the built database would not have. Declare a length where one matters —
PostgreSQL enforces `VARCHAR(<n>)` and SQLite accepts the same declaration and ignores it, so one
spelling serves both. A foreign key names a table and column this same file declares.
Every table declares exactly one `PK` column, such as `| id | INTEGER PK | |`. A natural key
spanning several columns, such as `(date, currency)`, is a `- UNIQUE (date, currency)` bullet
beside the `PK`, never a second `PK`. An operation reaches a row by its natural key through
`| Match |`, so declaring the `UNIQUE` is what makes `get`, `update`, `upsert`, or `delete` by
`(date, currency)` reach exactly one row. A table with no `PK` column, or with two, fails the plan.
A constraint spanning more than one column cannot live in a per-column row, so it is declared as a
bullet directly under that table's field table, one per line:
```markdown
- UNIQUE (project_id, title)
- INDEX (project_id, opened_on)
```
Both forms take two or more declared columns of that table. A single-column `UNIQUE` states
`UNIQUE` in its own type cell instead. A `DATABASE.md` that declares no table fails the plan:
Build implements the declaration, and an empty one leaves Build inventing a schema no Blueprint
describes.
Relational persistence needs no ORM or migration-framework selection in the Technology Stack.
Drydock generates the persistence package from this declaration at the DATABASE build step and
copies the engines in unchanged, so a story that implements `DATABASE.md` writes callers, not a
repository. A Target declaring a `DATABASE.md` in a language Drydock ships no adapter for fails
before planning rather than reaching a build with no persistence layer to write. A Blueprint
migration ledger record lives at `blueprint/migrations/MIGRATION-<AccessPatternId>.md`; it holds
`upgrade` and `downgrade` snippets and is `planned` until the DATABASE build story completes, then
`built`. Within a release the schema is built once and never migrated.
`ARCHITECTURE.md` includes a module ownership table for persistence, configuration, file-store, and
external-service boundaries. It states which module owns each boundary and which low-level APIs that
module may access.
Any Manifest story that implements `DATABASE.md` includes `persistence.md` in `stack:` plus the
selected backend stack file such as `sqlite.md`, `postgres.md`, or `aws-dynamodb.md`.
---
## METADATA.md — Service Identity Fields
In addition to standard project fields, service repositories should declare:
```
service_name: Platform # top-level service grouping (e.g. Platform, Analytics, Tools)
service_component: GAME # component name within the service (matches directory name)
```
These fields are used by build-time service registration artifacts and by GAME's service registry
scanner to group related repositories under a named service.
---
## Authoring Conventions
**Authoring phase:** all unresolved product decisions go in `DECISIONS.json`. Do not create
`MANIFEST.md` or numbered ticket files while authoring.
**Build phase:** run `drydock plan create` once the specification is ready. Use `drydock status`
to check for spec errors and staleness before building. After a build, fold changes back by editing
the specification and re-applying with `drydock refit`.
**Spikes:** a spike is a runnable investigation. Results feed future iterations. When run, the
finding is written into the named file, resolving the matching `## Open Question` in place.
**Feature specifications:** all feature purpose, status, triggers, sequences, routes, reads,
writes, acceptance criteria, and guardrails belong in individual `FEATURE-*.md` files. README,
METADATA, and generated files do not contain feature specifications.
## Acceptance persistence lifecycle
**Acceptance store lifecycle.** The DATABASE step provisions and verifies the configured store
once. Ordinary persistence criteria never replace DATABASE_URL/DATABASE_PATH, create a temporary
database, apply DDL, or assume an empty store. Configuration behavior uses the isolated harness
fixture below. 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.
For SQLite configuration selection and source-required open-failure tests, use
`from drydock_acceptance import database_environment` in the Python criterion. Its context
manager takes `url=None, path=None`: None unsets, empty string sets empty, and other values
are relative file names. `url` alone accepts the `sqlite://` prefix. Inside
`with database_environment(url="sqlite://primary.db", path="fallback.db") as root:`, the
variables name absolute paths under the yielded scratch `Path`, and cwd is that directory.
Assert that the product resolves `str(root / "primary.db")`; repeat separate contexts for URL
without prefix, unset/empty URL fallback, and both unset for `data/app.db`. The fixture creates
no schema or parent directories; `url="missing/app.db"` permits real open-failure assertions.
It restores cwd and both variables even on assertion failure. Use this only for configuration
and failure behavior, never populated-store CRUD. Direct environment replacement remains
forbidden. Declare only exits and behavior supported by governed sources.
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.
</pblock>
<pblock label="Imported source file header" kind="section">
Imported source files
</pblock>
<pblock filename="sources/INSTRUCTIONS.md" role="source file" path="/mnt/c/Users/barlo/projects/drydock/uat/LayersTesting/runs/20261027.135355/workspace/targets/LayersTesting/blueprint/sources/INSTRUCTIONS.md" guidance="Raw User Source">
# Build Instructions: A Cash Ledger
## Objective
Build a command-line cash ledger for a small shop. The shop keeps cash in a few places (drawers,
a safe, petty cash), records every receipt and payment against one of those places, and asks for
three reports: balances by account, totals by category, and totals by month.
The product is an executable named `ledger` at the application root. It stores everything in a
relational database through the shipped persistence library, and every command either completes
in full or changes nothing.
## Stack
Implement in Python 3.11 or newer over SQLite, through the shipped Python persistence
library. Tests run under pytest. The contract below is the same for every language and database: the same
commands, the same output, and the same exit codes.
## Run Harness
`sources/run.sh` is the scoring entry point. It is supplied, not authored, and is staged verbatim
into the application root with the seed files. `drydock uat` runs `sh sources/run.sh` from the
completed application root and takes its exit code and output as the score.
The harness creates a fresh database, runs `./ledger init`, loads the seed files, and then runs a
fixed sequence of 43 checks. Each check compares one command's exit code and standard output
with a known answer. Standard error is never compared. The harness prints `PASS` or `FAIL` per
check and ends with:
```text
LayersTesting: NN passed, NN failed (of 43)
```
## Read-only scoring assets
These files are the exam. Do not modify, rewrite, regenerate, or substitute them:
- `sources/run.sh` — the scoring entry point and its known answers
- `sources/seed_accounts.csv` — 4 accounts
- `sources/seed_categories.csv` — 7 categories
- `sources/seed_transactions.csv` — 120 transactions, January to March 2026
- `sources/seed_transactions_bad.csv` — 11 transactions; row 11 names an unknown account
Application code never reads `sources/run.sh` and never embeds a report answer. Every report is
computed from the database.
## Database
The database is SQLite. `DATABASE_URL` names the SQLite file path, optionally prefixed
`sqlite://`. When `DATABASE_URL` is unset, `DATABASE_PATH` is used, then `data/app.db`.
Three tables. Amounts are stored as integer cents and never as floating point.
| Table | Columns | Keys |
|---|---|---|
| `accounts` | `account` text, `name` text | primary key `account` |
| `categories` | `category` text, `description` text | primary key `category` |
| `transactions` | `txn_id` integer, `date` text `YYYY-MM-DD`, `account` text, `category` text, `amount` integer cents, `memo` text | primary key `txn_id`; `account` references `accounts`; `category` references `categories` |
All database access goes through the shipped persistence library and the relational layer
generated from `DATABASE.md`. Application code never opens a database driver directly.
## Rules
1. **A rejected command changes nothing.** A command checks every input and rule before its
first write. A load that rejects row 11 stores none of rows 1 to 10. A transfer stores both of
its rows or neither.
2. **No command leaves an account balance below zero.** An account's balance is the sum of its
transaction amounts. Posting, amending, deleting, transferring, and loading are all subject to
this rule, checked before the command writes anything.
3. **Codes** (`account`, `category`) are 1 to 12 characters from `A-Z` and `0-9`.
4. **Names and descriptions** are 1 to 40 characters. **Memos** are 0 to 60 characters. None of
them contains a comma or a newline.
5. **Amounts** on input match `-?DIGITS[.D[D]]`: at most two decimal places, never zero. On output
an amount is written with exactly two decimal places, a leading `-` when negative, and no
thousands separator: `-12.50`, `0.00`, `5000.00`.
6. **Dates** are real calendar dates written `YYYY-MM-DD`. `2026-02-30` is rejected.
7. **Transaction ids.** A loaded transaction keeps the `txn_id` from its file. A posted
transaction receives one more than the largest `txn_id` present, or `1` in an empty table. A
transfer's outgoing row takes that id and its incoming row the next.
## Output
Every successful command except `init` writes CSV to standard output: one header row, then data
rows, comma-separated, no quoting, no trailing spaces, `\n` line endings. `init` writes nothing.
A failing command writes nothing to standard output and one diagnostic line to standard error.
The account row is `account,name,transactions,balance`, where `transactions` counts the account's
transactions. The transaction row is `txn_id,date,account,category,amount,memo`.
## Commands
| Command | Output on success |
|---|---|
| `ledger init` | Prepares an empty ledger for loading and use; removes existing ledger records when rerun. Nothing written. |
| `ledger count` | `table,rows`, then `accounts`, `categories`, `transactions` rows in that order. |
| `ledger load <table> <csv>` | Loads `accounts`, `categories`, or `transactions` from a file whose header matches the table's columns in the order above. Writes `table,loaded` and `<table>,<rows>`. |
| `ledger account add <code> <name>` | The new account row. |
| `ledger account get <code>` | The account row. |
| `ledger account rename <code> <name>` | The updated account row. |
| `ledger account delete <code>` | `deleted` and the code. Refused while the account has transactions. |
| `ledger txn post <account> <category> <amount> <date> [<memo>]` | The new transaction row. |
| `ledger txn get <id>` | The transaction row. |
| `ledger txn amend <id> <amount>` | The updated transaction row. Only the amount changes. |
| `ledger txn delete <id>` | `deleted` and the id. |
| `ledger transfer <from> <to> <amount> <date>` | Two transaction rows in category `TRANSFER`: `-amount` on `<from>` with memo `transfer to <to>`, then `+amount` on `<to>` with memo `transfer from <from>`. The amount is positive and the accounts differ. |
| `ledger report balances` | `account,name,transactions,balance` per account ordered by code, then `TOTAL,,<count>,<sum>`. |
| `ledger report categories` | `category,description,transactions,inflow,outflow,net` per category ordered by code, including categories with no transactions, then `TOTAL,,<count>,<inflow>,<outflow>,<net>`. |
| `ledger report monthly` | `month,transactions,inflow,outflow,net` per `YYYY-MM` that has transactions, ascending, then `TOTAL,<count>,<inflow>,<outflow>,<net>`. |
`inflow` is the sum of positive amounts. `outflow` is the sum of the absolute values of negative
amounts, written as a positive number. `net` is `inflow - outflow`.
## Exit codes
| Code | Meaning |
|---|---|
| `0` | Success. |
| `1` | Operational failure: a file named on the command line cannot be read. |
| `2` | Usage error: unknown command, unknown table or report, wrong argument count. |
| `3` | Rejected: invalid code, name, amount, date, or file row; duplicate key; unknown account or category; account in use; any change that would leave a negative balance. |
| `4` | Not found: `account get/rename/delete` of an absent account, `txn get/amend/delete` of an absent id. |
## Tests
The completed application provides a POSIX-compatible `bin/test.sh` that runs its own automated
test suite from the application root and exits zero only when every test passes. The suite
covers each command, each exit code, and each rule above against a real temporary database.
</pblock>
<pblock filename="sources/run.sh" role="source file" path="/mnt/c/Users/barlo/projects/drydock/uat/LayersTesting/runs/20261027.135355/workspace/targets/LayersTesting/blueprint/sources/run.sh">
#!/bin/sh
# run.sh — LayersTesting grader. Do not filter, skip, or reinterpret.
#
# Exercises ./ledger against a fresh database and compares every command's exit code and standard
# output with the known answer below. Standard error is never compared.
#
# sh sources/run.sh from the application root (how `drydock uat` runs it)
# sh uat/LayersTesting/bin/run.sh APP from anywhere, grading the application root APP
#
# Database: DATABASE_URL when the caller sets it (for example a PostgreSQL DSN), otherwise a
# SQLite file in a fresh temporary directory. Every run starts with `ledger init`, so the grader
# never depends on prior state. Exit 0 only when every check passes.
set -u
HERE=$(cd "$(dirname "$0")" && pwd)
APP=$(cd "${1:-.}" && pwd)
if [ -f "$HERE/seed_accounts.csv" ]; then SEED=$HERE; else SEED=$(cd "$HERE/../sources" && pwd); fi
LEDGER="$APP/ledger"
WORK=$(mktemp -d)
trap 'rm -rf "$WORK"' EXIT INT TERM
DATABASE_URL=${DATABASE_URL:-$WORK/ledger.db}
export DATABASE_URL
if [ ! -x "$LEDGER" ]; then
echo "error: no executable ./ledger at the application root $APP." >&2
echo "The deliverable is an executable named ledger at the application root." >&2
exit 1
fi
PASSED=0
FAILED=0
# check <id> <expected exit> <ledger args...> — expected standard output on stdin.
check() {
id=$1
want_rc=$2
shift 2
cat > "$WORK/want"
(cd "$APP" && "$LEDGER" "$@") > "$WORK/got" 2> "$WORK/err"
rc=$?
if [ "$rc" -eq "$want_rc" ] && cmp -s "$WORK/want" "$WORK/got"; then
PASSED=$((PASSED + 1))
echo "PASS $id: ledger $*"
else
FAILED=$((FAILED + 1))
echo "FAIL $id: ledger $*"
echo " exit: expected $want_rc, got $rc"
diff "$WORK/want" "$WORK/got" | sed 's/^/ /'
sed 's/^/ stderr: /' "$WORK/err"
fi
}
# ── A. Schema lifecycle ──────────────────────────────────────────────────────────────────
check A1 0 init < /dev/null
check A2 0 count <<'EOF'
table,rows
accounts,0
categories,0
transactions,0
EOF
# ── B. Bulk load of the known dataset ────────────────────────────────────────────────────
check B1 0 load accounts "$SEED/seed_accounts.csv" <<'EOF'
table,loaded
accounts,4
EOF
check B2 0 load categories "$SEED/seed_categories.csv" <<'EOF'
table,loaded
categories,7
EOF
check B3 0 load transactions "$SEED/seed_transactions.csv" <<'EOF'
table,loaded
transactions,120
EOF
check B4 0 count <<'EOF'
table,rows
accounts,4
categories,7
transactions,120
EOF
# ── C. Reports over the seeded rows ──────────────────────────────────────────────────────
check C1 0 report balances <<'EOF'
account,name,transactions,balance
DRAWER1,Front Drawer,39,2299.38
DRAWER2,Back Drawer,39,1378.32
PETTY,Petty Cash,21,306.25
SAFE,Store Safe,21,250.00
TOTAL,,120,4233.95
EOF
check C2 0 report categories <<'EOF'
category,description,transactions,inflow,outflow,net
OPENING,Opening balance,2,5200.00,0.00,5200.00
PAYROLL,Payroll,6,0.00,7200.00,-7200.00
REFUND,Customer refunds,12,0.00,101.25,-101.25
RENT,Rent,3,0.00,2700.00,-2700.00
SALES,Sales receipts,64,9578.95,0.00,9578.95
SUPPLY,Supplies,15,0.00,543.75,-543.75
TRANSFER,Internal transfer,18,5100.00,5100.00,0.00
TOTAL,,120,19878.95,15645.00,4233.95
EOF
check C3 0 report monthly <<'EOF'
month,transactions,inflow,outflow,net
2026-01,40,9659.45,5215.00,4444.45
2026-02,40,4979.65,5215.00,-235.35
2026-03,40,5239.85,5215.00,24.85
TOTAL,120,19878.95,15645.00,4233.95
EOF
# ── D. A rejected load changes nothing ───────────────────────────────────────────────────
check D1 3 load transactions "$SEED/seed_transactions_bad.csv" < /dev/null
check D2 3 load accounts "$SEED/seed_accounts.csv" < /dev/null
check D3 0 count <<'EOF'
table,rows
accounts,4
categories,7
transactions,120
EOF
# ── E. Account create, read, update, delete ──────────────────────────────────────────────
check E1 0 account add CASH9 "Event Float" <<'EOF'
account,name,transactions,balance
CASH9,Event Float,0,0.00
EOF
check E2 3 account add CASH9 "Event Float" < /dev/null
check E3 0 account get CASH9 <<'EOF'
account,name,transactions,balance
CASH9,Event Float,0,0.00
EOF
check E4 0 account rename CASH9 "Event Cash Box" <<'EOF'
account,name,transactions,balance
CASH9,Event Cash Box,0,0.00
EOF
check E5 4 account get NOSUCH < /dev/null
check E6 3 account delete DRAWER1 < /dev/null
check E7 0 account delete CASH9 <<'EOF'
deleted
CASH9
EOF
check E8 4 account get CASH9 < /dev/null
# ── F. Transaction create, read, update, delete ──────────────────────────────────────────
check F1 0 txn post DRAWER1 SALES 45.50 2026-04-01 "walk in sale" <<'EOF'
txn_id,date,account,category,amount,memo
121,2026-04-01,DRAWER1,SALES,45.50,walk in sale
EOF
check F2 0 txn get 121 <<'EOF'
txn_id,date,account,category,amount,memo
121,2026-04-01,DRAWER1,SALES,45.50,walk in sale
EOF
check F3 0 txn amend 121 54.50 <<'EOF'
txn_id,date,account,category,amount,memo
121,2026-04-01,DRAWER1,SALES,54.50,walk in sale
EOF
check F4 4 txn get 999 < /dev/null
check F5 3 txn post DRAWER1 NOSUCH 1.00 2026-04-01 < /dev/null
check F6 3 txn post DRAWER1 SALES 1.234 2026-04-01 < /dev/null
check F7 3 txn post DRAWER1 SALES 1.00 2026-02-30 < /dev/null
check F8 0 txn delete 121 <<'EOF'
deleted
121
EOF
check F9 4 txn get 121 < /dev/null
check F10 0 txn post PETTY SUPPLY -12.34 2026-04-02 tape <<'EOF'
txn_id,date,account,category,amount,memo
121,2026-04-02,PETTY,SUPPLY,-12.34,tape
EOF
# ── G. Transfers are atomic; no command leaves a negative balance ────────────────────────
check G1 0 transfer DRAWER1 SAFE 500.00 2026-04-03 <<'EOF'
txn_id,date,account,category,amount,memo
122,2026-04-03,DRAWER1,TRANSFER,-500.00,transfer to SAFE
123,2026-04-03,SAFE,TRANSFER,500.00,transfer from DRAWER1
EOF
check G2 3 transfer SAFE PETTY 999.99 2026-04-04 < /dev/null
check G3 3 txn post PETTY SUPPLY -1000.00 2026-04-04 < /dev/null
check G4 3 txn amend 1 1.00 < /dev/null
check G5 3 txn delete 1 < /dev/null
check G6 0 count <<'EOF'
table,rows
accounts,4
categories,7
transactions,123
EOF
# ── H. Reports after the changes ─────────────────────────────────────────────────────────
check H1 0 report balances <<'EOF'
account,name,transactions,balance
DRAWER1,Front Drawer,40,1799.38
DRAWER2,Back Drawer,39,1378.32
PETTY,Petty Cash,22,293.91
SAFE,Store Safe,22,750.00
TOTAL,,123,4221.61
EOF
check H2 0 report categories <<'EOF'
category,description,transactions,inflow,outflow,net
OPENING,Opening balance,2,5200.00,0.00,5200.00
PAYROLL,Payroll,6,0.00,7200.00,-7200.00
REFUND,Customer refunds,12,0.00,101.25,-101.25
RENT,Rent,3,0.00,2700.00,-2700.00
SALES,Sales receipts,64,9578.95,0.00,9578.95
SUPPLY,Supplies,16,0.00,556.09,-556.09
TRANSFER,Internal transfer,20,5600.00,5600.00,0.00
TOTAL,,123,20378.95,16157.34,4221.61
EOF
check H3 0 report monthly <<'EOF'
month,transactions,inflow,outflow,net
2026-01,40,9659.45,5215.00,4444.45
2026-02,40,4979.65,5215.00,-235.35
2026-03,40,5239.85,5215.00,24.85
2026-04,3,500.00,512.34,-12.34
TOTAL,123,20378.95,16157.34,4221.61
EOF
# ── U. Usage errors ──────────────────────────────────────────────────────────────────────
check U1 2 frobnicate < /dev/null
check U2 2 report nosuch < /dev/null
# ── Z. Re-initialization drops every row ─────────────────────────────────────────────────
check Z1 0 init < /dev/null
check Z2 0 count <<'EOF'
table,rows
accounts,0
categories,0
transactions,0
EOF
TOTAL=$((PASSED + FAILED))
echo "LayersTesting: $PASSED passed, $FAILED failed (of $TOTAL)"
[ "$FAILED" -eq 0 ]
</pblock>
<pblock filename="sources/seed_accounts.csv" role="source file" path="/mnt/c/Users/barlo/projects/drydock/uat/LayersTesting/runs/20261027.135355/workspace/targets/LayersTesting/blueprint/sources/seed_accounts.csv">
account,name
DRAWER1,Front Drawer
DRAWER2,Back Drawer
PETTY,Petty Cash
SAFE,Store Safe
</pblock>
<pblock filename="sources/seed_categories.csv" role="source file" path="/mnt/c/Users/barlo/projects/drydock/uat/LayersTesting/runs/20261027.135355/workspace/targets/LayersTesting/blueprint/sources/seed_categories.csv">
category,description
OPENING,Opening balance
PAYROLL,Payroll
REFUND,Customer refunds
RENT,Rent
SALES,Sales receipts
SUPPLY,Supplies
TRANSFER,Internal transfer
</pblock>
<pblock filename="sources/seed_transactions.csv" role="source file" path="/mnt/c/Users/barlo/projects/drydock/uat/LayersTesting/runs/20261027.135355/workspace/targets/LayersTesting/blueprint/sources/seed_transactions.csv">
txn_id,date,account,category,amount,memo
1,2026-01-01,SAFE,OPENING,5000.00,opening float
2,2026-01-01,PETTY,OPENING,200.00,opening float
3,2026-01-02,DRAWER1,SALES,155.26,sales day 1
4,2026-01-02,DRAWER2,SALES,83.11,sales day 1
5,2026-01-03,DRAWER1,SALES,160.51,sales day 2
6,2026-01-03,DRAWER2,SALES,86.21,sales day 2
7,2026-01-04,DRAWER1,SALES,165.76,sales day 3
8,2026-01-04,DRAWER2,SALES,89.31,sales day 3
9,2026-01-05,DRAWER1,SALES,171.01,sales day 4
10,2026-01-05,DRAWER2,SALES,92.41,sales day 4
11,2026-01-06,DRAWER1,SALES,176.26,sales day 5
12,2026-01-06,DRAWER2,SALES,95.51,sales day 5
13,2026-01-07,DRAWER1,SALES,181.51,sales day 6
14,2026-01-07,DRAWER2,SALES,98.61,sales day 6
15,2026-01-08,DRAWER1,SALES,186.76,sales day 7
16,2026-01-08,DRAWER2,SALES,101.71,sales day 7
17,2026-01-09,DRAWER1,SALES,192.01,sales day 8
18,2026-01-09,DRAWER2,SALES,104.81,sales day 8
19,2026-01-10,DRAWER1,SALES,197.26,sales day 9
20,2026-01-10,DRAWER2,SALES,107.91,sales day 9
21,2026-01-11,DRAWER1,SALES,202.51,sales day 10
22,2026-01-11,DRAWER2,SALES,111.01,sales day 10
23,2026-01-12,DRAWER1,REFUND,-12.50,refund
24,2026-01-12,DRAWER2,REFUND,-7.25,refund
25,2026-01-13,DRAWER1,REFUND,-9.99,refund
26,2026-01-13,DRAWER2,REFUND,-4.01,refund
27,2026-01-14,DRAWER1,TRANSFER,-1000.00,transfer to SAFE
28,2026-01-14,SAFE,TRANSFER,1000.00,transfer from DRAWER1
29,2026-01-14,DRAWER2,TRANSFER,-500.00,transfer to SAFE
30,2026-01-14,SAFE,TRANSFER,500.00,transfer from DRAWER2
31,2026-01-15,SAFE,TRANSFER,-200.00,transfer to PETTY
32,2026-01-15,PETTY,TRANSFER,200.00,transfer from SAFE
33,2026-01-16,PETTY,SUPPLY,-35.40,supplies
34,2026-01-17,PETTY,SUPPLY,-42.10,supplies
35,2026-01-18,PETTY,SUPPLY,-18.75,supplies
36,2026-01-19,PETTY,SUPPLY,-60.00,supplies
37,2026-01-20,PETTY,SUPPLY,-25.00,supplies
38,2026-01-21,SAFE,PAYROLL,-1200.00,payroll week 1
39,2026-01-28,SAFE,PAYROLL,-1200.00,payroll week 2
40,2026-01-28,SAFE,RENT,-900.00,rent
41,2026-02-01,SAFE,SALES,500.00,deposit
42,2026-02-01,PETTY,SALES,20.00,deposit
43,2026-02-02,DRAWER1,SALES,155.27,sales day 1
44,2026-02-02,DRAWER2,SALES,83.12,sales day 1
45,2026-02-03,DRAWER1,SALES,160.52,sales day 2
46,2026-02-03,DRAWER2,SALES,86.22,sales day 2
47,2026-02-04,DRAWER1,SALES,165.77,sales day 3
48,2026-02-04,DRAWER2,SALES,89.32,sales day 3
49,2026-02-05,DRAWER1,SALES,171.02,sales day 4
50,2026-02-05,DRAWER2,SALES,92.42,sales day 4
51,2026-02-06,DRAWER1,SALES,176.27,sales day 5
52,2026-02-06,DRAWER2,SALES,95.52,sales day 5
53,2026-02-07,DRAWER1,SALES,181.52,sales day 6
54,2026-02-07,DRAWER2,SALES,98.62,sales day 6
55,2026-02-08,DRAWER1,SALES,186.77,sales day 7
56,2026-02-08,DRAWER2,SALES,101.72,sales day 7
57,2026-02-09,DRAWER1,SALES,192.02,sales day 8
58,2026-02-09,DRAWER2,SALES,104.82,sales day 8
59,2026-02-10,DRAWER1,SALES,197.27,sales day 9
60,2026-02-10,DRAWER2,SALES,107.92,sales day 9
61,2026-02-11,DRAWER1,SALES,202.52,sales day 10
62,2026-02-11,DRAWER2,SALES,111.02,sales day 10
63,2026-02-12,DRAWER1,REFUND,-12.50,refund
64,2026-02-12,DRAWER2,REFUND,-7.25,refund
65,2026-02-13,DRAWER1,REFUND,-9.99,refund
66,2026-02-13,DRAWER2,REFUND,-4.01,refund
67,2026-02-14,DRAWER1,TRANSFER,-1000.00,transfer to SAFE
68,2026-02-14,SAFE,TRANSFER,1000.00,transfer from DRAWER1
69,2026-02-14,DRAWER2,TRANSFER,-500.00,transfer to SAFE
70,2026-02-14,SAFE,TRANSFER,500.00,transfer from DRAWER2
71,2026-02-15,SAFE,TRANSFER,-200.00,transfer to PETTY
72,2026-02-15,PETTY,TRANSFER,200.00,transfer from SAFE
73,2026-02-16,PETTY,SUPPLY,-35.40,supplies
74,2026-02-17,PETTY,SUPPLY,-42.10,supplies
75,2026-02-18,PETTY,SUPPLY,-18.75,supplies
76,2026-02-19,PETTY,SUPPLY,-60.00,supplies
77,2026-02-20,PETTY,SUPPLY,-25.00,supplies
78,2026-02-21,SAFE,PAYROLL,-1200.00,payroll week 1
79,2026-02-28,SAFE,PAYROLL,-1200.00,payroll week 2
80,2026-02-28,SAFE,RENT,-900.00,rent
81,2026-03-01,SAFE,SALES,750.00,deposit
82,2026-03-01,PETTY,SALES,30.00,deposit
83,2026-03-02,DRAWER1,SALES,155.28,sales day 1
84,2026-03-02,DRAWER2,SALES,83.13,sales day 1
85,2026-03-03,DRAWER1,SALES,160.53,sales day 2
86,2026-03-03,DRAWER2,SALES,86.23,sales day 2
87,2026-03-04,DRAWER1,SALES,165.78,sales day 3
88,2026-03-04,DRAWER2,SALES,89.33,sales day 3
89,2026-03-05,DRAWER1,SALES,171.03,sales day 4
90,2026-03-05,DRAWER2,SALES,92.43,sales day 4
91,2026-03-06,DRAWER1,SALES,176.28,sales day 5
92,2026-03-06,DRAWER2,SALES,95.53,sales day 5
93,2026-03-07,DRAWER1,SALES,181.53,sales day 6
94,2026-03-07,DRAWER2,SALES,98.63,sales day 6
95,2026-03-08,DRAWER1,SALES,186.78,sales day 7
96,2026-03-08,DRAWER2,SALES,101.73,sales day 7
97,2026-03-09,DRAWER1,SALES,192.03,sales day 8
98,2026-03-09,DRAWER2,SALES,104.83,sales day 8
99,2026-03-10,DRAWER1,SALES,197.28,sales day 9
100,2026-03-10,DRAWER2,SALES,107.93,sales day 9
101,2026-03-11,DRAWER1,SALES,202.53,sales day 10
102,2026-03-11,DRAWER2,SALES,111.03,sales day 10
103,2026-03-12,DRAWER1,REFUND,-12.50,refund
104,2026-03-12,DRAWER2,REFUND,-7.25,refund
105,2026-03-13,DRAWER1,REFUND,-9.99,refund
106,2026-03-13,DRAWER2,REFUND,-4.01,refund
107,2026-03-14,DRAWER1,TRANSFER,-1000.00,transfer to SAFE
108,2026-03-14,SAFE,TRANSFER,1000.00,transfer from DRAWER1
109,2026-03-14,DRAWER2,TRANSFER,-500.00,transfer to SAFE
110,2026-03-14,SAFE,TRANSFER,500.00,transfer from DRAWER2
111,2026-03-15,SAFE,TRANSFER,-200.00,transfer to PETTY
112,2026-03-15,PETTY,TRANSFER,200.00,transfer from SAFE
113,2026-03-16,PETTY,SUPPLY,-35.40,supplies
114,2026-03-17,PETTY,SUPPLY,-42.10,supplies
115,2026-03-18,PETTY,SUPPLY,-18.75,supplies
116,2026-03-19,PETTY,SUPPLY,-60.00,supplies
117,2026-03-20,PETTY,SUPPLY,-25.00,supplies
118,2026-03-21,SAFE,PAYROLL,-1200.00,payroll week 1
119,2026-03-28,SAFE,PAYROLL,-1200.00,payroll week 2
120,2026-03-28,SAFE,RENT,-900.00,rent
</pblock>
<pblock filename="sources/seed_transactions_bad.csv" role="source file" path="/mnt/c/Users/barlo/projects/drydock/uat/LayersTesting/runs/20261027.135355/workspace/targets/LayersTesting/blueprint/sources/seed_transactions_bad.csv">
txn_id,date,account,category,amount,memo
201,2026-04-01,DRAWER1,SALES,10.00,bad batch 1
202,2026-04-01,DRAWER1,SALES,10.00,bad batch 2
203,2026-04-01,DRAWER1,SALES,10.00,bad batch 3
204,2026-04-01,DRAWER1,SALES,10.00,bad batch 4
205,2026-04-01,DRAWER1,SALES,10.00,bad batch 5
206,2026-04-01,DRAWER1,SALES,10.00,bad batch 6
207,2026-04-01,DRAWER1,SALES,10.00,bad batch 7
208,2026-04-01,DRAWER1,SALES,10.00,bad batch 8
209,2026-04-01,DRAWER1,SALES,10.00,bad batch 9
210,2026-04-01,DRAWER1,SALES,10.00,bad batch 10
211,2026-04-01,NOSUCH,SALES,10.00,unknown account
</pblock>
Agent Task
Agent for: planning session synthesis
Authoring method and guardrails
- Read the source's behavior, processing stages and ordering constraints before choosing story
boundaries. Preserve required algorithms and stage invariants in the owning instructions.
- Give each story one delivered capability and a concrete interface. Name required product
interfaces in consumes: using the provider's exact provides: name, and declare a depends: path to that provider. An executable's existence does not supply every behavior behind it.
- Turn source-required sequencing into dependency edges, including prerequisites needed by the
acceptance fixtures. For example, a formatter consumes parsed records, not merely the CLI that launches it. Independent stories may share a block; dependent work needs separate gates.
- Author acceptance against the delivered interface. If a corpus slice requires later features,
test the current capability directly and put the cross-feature examples on a later integration story. Keep their coverage; do not invent dependencies that cycle back to a consumer.
- Review the declaration for missing source stages, undeclared inputs and acceptance that needs
future work. Drydock validates the declaration and computes order, blocks and stack modes.
These are reusable planning rules. Do not add project-specific exemptions or claim that passing static verification proves product correctness. Stage 1 emits the topology and decisions only; Stage 2 authors the specifications and executable criteria under BLUEPRINTS_CONTRACT.md.
Establish a staged runner's executable/API interface before its scoped implementation stories; its initial acceptance proves only that interface contract. Declare each concrete CLI command as provides: <executable> <subcommand> so verification can compare its availability with invocations. Do not claim commands before their implementation or require later behavior in an earlier gate.
Map each required technical or behavioral ID in structured SEA_TRIALS.md into the implementing story's accepts: field. Never invent or rename Sea Trial IDs. Do not tag a Programmatic Acceptance assertion with a Sea Trial ID: Sea Trials flow into planning as context and nothing points back at them. Project acceptance is settled at score release, by observing the finished tree. Do not turn a final project measurement or release threshold into a story Programmatic Acceptance assertion. Those remain Sea Trials and run at final scoring after all stories close. The one terminal Suite: full assertion is the exception: it runs the supplied suite and requires success. It may additionally verify the total using either a count derived from authoritative suite data or an explicitly declared authoritative exact count.
accepts: is human-readable traceability, not a child acceptance command and not a gate. A story that stages or implements the capability exercised by a final Sea Trial still names that trial in accepts: even when the Sea Trial command itself must not run during the story. TOPOLOGY.md is emitted in Stage 1 before any Blueprint, so settle the complete story set and its acceptance before emitting anything.
STORY_GUIDANCE.json names stories that must exist. Each entry's id is an exact story id and its optional gate is the command that decides that story. An entry marked "provenance": "commander" is binding: preserve its id verbatim in TOPOLOGY.md, shape the story around the scope its gate exercises, and merge related analyzed Story IDs into that story's covers: field when one gate owns their combined slice. An entry marked "provenance": "plan" was derived from the imported material by drydock analyze; treat it as the default decomposition and depart from it only where the sources show it is wrong. Do not emit or amend STORY_GUIDANCE.json.
ACCEPTANCE.json carries one command, full: the finished-project release gate. It is not a story id and no story owns it. Do not emit or amend it either.
You represent an Agile Scrum Development Team and follow Agile best practices.
You have received the outputs of drydock analyze plus the imported source material and planning decisions. Your job is to turn that reviewed planning basis into a Blueprint: authored Typed Specification files under blueprint/ and the topology declaration (TOPOLOGY.md) that Drydock serializes into MANIFEST.md, the single work graph carrying build order, grouping, and per-step prompt-assembly fields.
The core elements are defined below.
Planning Objective
Your goal is to convert the analysis artifacts into a build-ready Drydock Blueprint.
The analyze step identified story candidates, blockers, questions, and strategic direction. This step converts that information into durable specification files with exact header formatting and clear relationships. You are not writing prose notes; you are writing structured product definition and build-planning artifacts.
The primary outputs are:
- Typed Specification files such as
ARCHITECTURE.md,FEATURE-*.md,SCREEN-*.md,
DATABASE.md, UI-GENERAL.md, and AC files where warranted.
TOPOLOGY.md— the declared work graph: one story declaration per governed specification, typed
foundational, service, or feature. Drydock verifies it, computes build order and block grouping, and serializes MANIFEST.md from it.
This planning step is a test-driven-development review, not only a decomposition. Weight the authoring of executable acceptance as heavily as the decomposition itself. Every buildable story carries several concrete Python assertions in the ## Programmatic Acceptance sections of the specs it implements, so that drydock build has a failing test to satisfy for each behavior before the code exists. A plan that decomposes cleanly but ships specs with empty acceptance has failed this step. Assertion authoring is mandatory: every story carries at least one criterion in a spec it implements, DATABASE.md included, and Drydock refuses a story whose specs carry none.
This step must produce decomposed specifications with solid header relationships:
- every authored spec file uses the Drydock typed header format
Depends On,Provides, andConsumesare declared consistently across the emitted Blueprint- story declarations in
TOPOLOGY.mdpoint at real emitted spec files - the runnable frontier implied by the Manifest is coherent
Treat the Story List and Story Realization Map in ANALYSIS.md as the completed planning decomposition and the default work breakdown. Preserve their proposed story boundaries and mapped source filenames unless the complete planning context shows that a story is non-atomic, inaccurate, contradictory, incomplete, or assigns content to the wrong owner. When correction is necessary, split, merge, move, replace, or reorder the affected scope. Rewrite every resulting story as a governed specification using all planning inputs. Source structure informs story boundaries; resolve source requirements using the declared precedence rather than copying the source document layout into the work graph.
Preserve source-defined algorithms and interface invariants in the owning story instructions and Blueprint. Do not reduce an algorithm to "pass the suite" or a list of syntax features: state the required processing rules and the interface later stories consume.
When the analysis is too coarse, refine it into smaller spec scopes. When it is too fine, merge it into the smallest durable spec structure that preserves correctness and clear ownership. The Analyze story list is the Team Lead's expert proposal, not an immutable work breakdown. Preserve a source Markdown file and filename when it already represents one atomic story, but split it when it combines independent actions. A screen and its provider route are separate stories and separate specifications even when they participate in one workflow.
Inputs
The job block injects the following. SYSTEM_SHAPE and ANALYSIS_QUALITY are stated directly in the job block; the rest are fenced sections.
- Plan feedback (standing directive) —
PLAN_COMPASS.md, persistent human direction
injected near the top of this prompt when present. Treat it as authoritative steering for this run; it overrides default decomposition and ordering choices where it speaks.
ANALYSIS.md— the Team Lead's reviewed proposal: quality signal, candidate story/file map,
open questions, tuning options, expectations, and notes. Review its mapping as an agile expert; preserve, merge, split, replace, or reorder it when the complete planning context requires that.
## Surfaced Acceptance CriteriainANALYSIS.md— additional criteria analyze derived per
story; fold each row into the ## Programmatic Acceptance or ## User Acceptance section of the spec file implementing its Story ID.
## Relationship Modeland## Planning InstructionsinANALYSIS.md— primary
Analyze-to-Plan handoff. Honor the Story Realization Map when selecting durable Blueprint scopes; carry the stated sequencing/dependency model into Manifest ordering and depends:; embed cited interfaces, workflows, test-kit behavior, and acceptance in the matching specs. Every readable imported source is available below. Analyze guides interpretation and proposes a realization map; it never limits which source evidence the Planning Crew may consult.
SYSTEM_SHAPE— the determined project type (web|api|cli|library|pipeline|event-driven),
parsed from the analysis. Drives the default decomposition table below.
SEA_TRIALS.mdandSOUNDINGS.md— product objectives and acceptance milestones from
analyze. Use these as planning context; do not overwrite their intent.
- Answered questionnaires (
discovery-*.json) — settled human-owned decisions on intent and
guardrails. Do not re-raise a question that a questionnaire has already answered. Drydock preflight guarantees that every Analyze question marked required_before_plan is answered before this prompt runs. Questionnaires never carry technology-stack decisions.
TECHNOLOGY_STACK.md— the Commander-owned technology decisions of record: one row per
technology, with the Rigging file that governs building it or — when none exists. This is the sole authority on the stack. It may be absent or incomplete; that means undecided, and you resolve the gap from the sources rather than stopping.
COMPASS.md— existing product intent if already present; otherwise derive emitted content
from the analysis and sources. It does not carry technology choices.
Precedence
When authoritative inputs disagree, apply this order and proceed. Do not stop on a disagreement that this order resolves:
PLAN_COMPASS.mdCommander Direction- Answered questionnaires and Commander-directed
DECISIONS.jsonitems (commander_directionor
override_text set)
TECHNOLOGY_STACK.md(technology questions only)COMPASS.md- Imported source files and
ANALYSIS.md
Absence is never prohibition. An item missing from TECHNOLOGY_STACK.md, unselected in a questionnaire, or unmentioned in COMPASS.md is undecided, not forbidden. Never treat an omission as a negative requirement, and never raise a conflict because one input lists something another does not.
Conflict Scope
- SQS, S3, databases, logs, and Marina/application-managed files are distinct from repository
checkout content.
- “Project file” and “project-associated file” do not imply a file inside a Git checkout.
- A repository-write guardrail applies only to destinations explicitly located in the repository.
- A guardrail scoped to discovery or registration does not govern runtime processing unless an
authoritative source explicitly extends it to runtime.
- Missing detail is not a conflict. Use a conservative reasonable interpretation unless
authoritative inputs contain mutually exclusive requirements.
- Error Mode must cite the exact files, clauses, and scopes that conflict and explain why the
Precedence order cannot resolve them.
MANIFEST_CONTRACT.mdandBLUEPRINTS_CONTRACT.md— authoritative format and field
contracts for the outputs.
- Imported source files — all readable material under
blueprint/sources/, injected below.
It is unconstrained Commander input, not governed Blueprint syntax. Never reject a source because of its filename, headings, tables, question labels, or formatting. Authored Markdown specs are a structured interpretation. Non-Markdown assets are projected byte-for-byte by Drydock; never emit or rewrite them.
If ANALYSIS_QUALITY is Blocked, planning must not proceed. Emit only a refusal message inside the required output block contract described below.
Story and Task Criteria
Decomposition is Agile feature and story decomposition. Apply that discipline at expert level: INVEST stories, vertical slices, test-driven acceptance per story. The rules below are the criteria, not a substitute for that judgement.
- A story delivers one observable behavior or capability slice. It is independently buildable,
independently verifiable, and carries its own acceptance gate. The story is the unit Drydock gates, builds, and attributes failure to.
- A task is a technical sub-step of a story — add a helper, refactor a module, wire a parameter.
A task is never a story block and never becomes a Blueprint file. Instructions inside a story may describe its tasks.
- Prefer more, smaller stories over fewer large ones. Distinctness is the limit: each story owns
its behavior alone, and no two stories own the same behavior.
- Story size in Drydock is the token and context size of the build step. A story whose build step
would not fit comfortably in one build prompt is too large. Split it into smaller stories that each still meet the story criteria above; never split it into tasks, and never leave a single story owning several independent construct families.
- When the source material is short or names few features, keep the story set lined up with the
source's own shape. Preserving author intent outranks splitting for its own sake, and the criteria above still bound the result.
Decomposition Method
Execute in order. Do not skip a step.
1. Review the planning basis.
- Consumes: imported sources,
ANALYSIS.md,PLAN_COMPASS.mddirection, answered questionnaires. - Emits: working understanding of the project shape, stack, constraints, and unanswered items.
2. Confirm the decomposition shape.
- Consumes: the analysis story list, project type signals, and source structure.
- Emits: one authored Blueprint file per story-sized capability, per the story criteria above.
Fewest file kinds, not fewest stories: use only the spec kinds the project needs, then decompose within them.
Default decomposition rules:
| System shape | Durable authored files |
|---|---|
web | ARCHITECTURE.md, UI-GENERAL.md if shared UI exists, one FEATURE-*.md per route/service workflow, one SCREEN-*.md per user-facing screen, DATABASE.md if persistence exists |
api | ARCHITECTURE.md, one FEATURE-*.md per endpoint/capability cluster, DATABASE.md if persistence exists |
cli | ARCHITECTURE.md, one FEATURE-*.md per command/capability cluster |
library | ARCHITECTURE.md, one FEATURE-*.md per public module or service area, DATABASE.md only if stateful |
pipeline | ARCHITECTURE.md, one FEATURE-*.md per pipeline stage or major dataset transformation, DATABASE.md only if persistent stores exist |
event-driven | ARCHITECTURE.md, one FEATURE-*.md per handler or event workflow cluster |
Use SCREEN-*.md only for actual user-facing screens. Use DATABASE.md only when persistent state or external stored state exists. Use AC files only when separate permanent guardrails are needed and they should not bloat the parent spec.
3. Map analysis stories to authored spec scopes.
- Consumes:
ANALYSIS.md ## Story List. - Emits: a mapping from analyzed stories to emitted files.
Rules:
- Each emitted authored spec file must represent one durable capability boundary.
- The
## Story Realization MapinANALYSIS.mdis a proposed partition. Keep a row that names a
distinct, atomic capability scope unless complete planning context supports a better partition.
- Two analysis stories collapse into one authored file only when both describe the same
behavior and the merged unit still satisfies the story criteria above. Distinct scopes — for example a block parser, an inline parser, reference resolution, a renderer, and an executable interface — are separate stories even when they ship in one program.
- One analysis story may expand into several authored spec files when the boundary naturally
separates into screen, feature, architecture, or persistence contracts, or when the single story is too large to build in one step.
- Record the mapping in the Manifest: each story's
covers:field names theANALYSIS.mdStory IDs
it delivers. Every Story ID in the analysis is covered by exactly one story. A story that covers several IDs is the declared collapse case and must satisfy the collapse rule above.
- When one analysis story expands into several stories, exactly one of them carries its ID in
covers: — the story that delivers the analyzed behavior.
- A
foundationalstory, and the story that implementsDATABASE.md, carries neithercovers:
nor accepts:. It builds what every Feature stands on and delivers no behavior of its own, so the Feature or Screen that delivers the behavior owns the analyzed story and its Sea Trials. A stated foundation fact, such as the language or a table name, is honored in TECHNOLOGY_STACK.md and DATABASE.md and is never a story's criterion.
- A plan-introduced story with no analyzed counterpart — an architecture boundary, a scaffold, a
test-harness story — omits covers: entirely. Never duplicate an ID that another story owns, and never fill the field to make it look complete: two stories claiming one analyzed story destroys failure attribution.
- Every important user-facing screen named in analysis must land in a
SCREEN-*.md. - Every important route, capability, interface, dataset, topic, or command named in analysis must
be represented in one or more FEATURE-*.md files, with ARCHITECTURE.md and DATABASE.md carrying shared technical structure where needed.
- Drydock deterministically injects
ARCHITECTURE_compact.mdandDATABASE_compact.mdinto
FEATURE-* build steps when those source files exist. Do not model that policy manually with screen stories or ad hoc context duplication.
4. Write authored specification content.
- Consumes: the file mapping and all planning inputs.
- Emits: complete authored spec markdown with exact header format and required terminal sections.
Each authored file must be build-usable. Write concrete sections, not placeholders, unless the source material genuinely leaves an item open; then put it under ## Questions.
5. Author programmatic acceptance (test-driven).
- Consumes: each authored spec's routes, interfaces, reads, writes, guardrails, any tests
carried in the imported source material, and any ANALYSIS.md ## Surfaced Acceptance Criteria rows tied to this spec's Story ID.
- Emits: the
## Programmatic Acceptancesection of every authored spec, as concrete Python
assertions.
Rules:
DATABASE.mdis authored once, in its own Blueprint batch, and then frozen. Drydock seeds that
batch from the template and the imported source specification; every seeded table is kept. It declares every table and every repository operation the topology's stories need, and at least one table. Later batches cite it from DATABASE_compact.md.
DATABASE.mdcarries executable acceptance. Its## Programmatic Acceptanceexercises every
declared repository operation through the generated package, inside from persistence.testing import db_session and with db_session() as db:, and asserts the declared Output. Give each operation its own criterion and call it as db.<table>.<verb>(...) (Go: db.<Table>.<Verb>(ctx, ...)): three tables with create, get, update and delete carry twelve criteria. Drydock refuses a declared operation no criterion calls. Do not create temporary SQLite databases or run migrations from criteria; the DATABASE step owns provisioning.
- Every
=== AC <id> ===block is a standalone Python script. It repeats every import it uses;
imports, variables, and execution order from another AC block are never in scope. Before closing each block, inspect every name it reads and either import or bind that name inside the same block. In particular, every block that calls subprocess.run contains its own import subprocess.
- Every
=== AC <id> ===block creates the state it depends on. Before the action under test, it
creates every row, file, or record that its input refers to and that a source rule requires to exist. A valid transaction load first loads the account and category it names. A criterion that skips this setup fails against a correct product, and one that expects a rejection passes for the wrong reason. Every setup call asserts the success its source declares: a valid staged asset loads with exit 0, never 1. A setup call that expects failure creates nothing.
- Treat this as writing the failing tests first. For every story, the specs it implements together
carry several executable assertions — generally one per distinct observable behavior, route, invariant, or error mode described in that spec. A single assertion for a multi-behavior spec is insufficient.
- Every split story owns its own assertions in the spec it implements. Splitting must never leave a
story gated by another story's acceptance, and never leave two stories asserting one behavior.
- Assertions are concrete and executable from the build directory: assert a route responds, a
record is written with the expected keys, an invariant holds, a guardrail rejects, an error type is raised. Cover the ordinary "the thing exists and responds" checks explicitly (for a route, that it is reachable and returns the expected status) — do not assume they are obvious.
- Route coverage is enforced: a SCREEN spec's assertions must literally call every route in its
Provides and Consumes (the plan is rejected otherwise); a FEATURE spec's assertions must exercise every route and interface it provides, naming each literal route path in at least one assertion.
- Imported test material is input, not output — with one exception. Ad hoc tests, test
scripts, or a prose ## Test section: review them and re-express the intended checks as Drydock Programmatic Acceptance assertions in the spec; do not trust their format, copy them verbatim, or point at that script. The exception is an authoritative conformance suite — an externally-authored, executable suite whose runner defines "correct" for the capability (for example a specification's example set plus its *_tests.py runner). A conformance suite is never paraphrased into hand assertions: paraphrase samples it and drops coverage. Its acceptance invokes the imported runner over the scope the spec owns and asserts a full pass of that scope, per the suite-binding rule below.
- Act on the system. Read the state back. Compare to expected. The assertion reads state —
a return value, parsed JSON, a status code, a stored row, file contents read back, an exit status. It never reads a substring of captured stdout or stderr, a test-runner tally, or a log line. A state oracle cannot pass against a stub and cannot fail because a runner printed the word "warning"; a text oracle can do both. Print diagnostic output rather than asserting on it. When structured command output is the declared product interface (CSV, JSON, or another specified data format), parse stdout with the format's standard library parser and assert the resulting state. Assert the declared columns, rows, values, ordering, filtering, and empty result behavior from the contract and the fixture inputs. Exit zero alone proves only that the command ran; it does not prove the output behavior named by the criterion's Intent. For CSV paths containing commas, quotes, or newlines, compare parsed field values with the fixture paths. Never replace those comparisons with print statements or diagnostic substrings.
- Exercise the delivered application, never a replacement written inside the criterion.
Do not define a local decoder, filter, formatter, or model-selection function and assert its result, or assert only a Python expression such as f"{usd:.4f}" == "5.5245" for a Go formatter. Such checks pass with no product and cannot verify their story. For a Go CLI, create the input log, invoke the declared package through drydock_go.cli_runner, check its exit code, parse the CSV, and assert the application's numeric and formatted field values. Python may derive expected values from fixture inputs; the observed value comes from the application. Missing future code is expected before Build and is not a reason to substitute it.
- Write the check in the project's own language, using that language's libraries. An in-language
HTTP client yields a status code and a parsed body, which is state; curl yields stdout, which is text to scrape. Reaching for an external executable is the exception and belongs in Rigging.
- Prefer the round trip for anything that stores, mutates, or removes state: act, then read back
through the public interface and assert the resulting state. A write that returns a plausible object while persisting nothing must fail. Enumerate coverage from the interface — every route and method, every subcommand and behavior-changing flag, every exported function — rather than sampling it. Assert declared failure signals on negative paths, never message wording.
- Never type an expected value twice. Bind it to a name and use the name on both sides. You
are authoring before the code exists, so a hand-typed expectation is a prediction about bytes you have not seen; when the prediction is wrong the criterion fails a correct implementation and nothing downstream can tell that from a real defect. Legal expected values: a name bound to the input the criterion supplied, a status code or count, a contract token read off a declared interface ("integer", "application/json"), a staged suite's exit status. Illegal: a string literal you typed out as the expected result. Drydock judges this mechanically — a string expectation carrying anything escapable that the criterion did not also supply as input — and a criterion that breaks the rule settles DISPUTED, gating nothing and buying its story no coverage. Write raw = "C:\\Users\\nodejs"; source = f"raw = '{raw}'\n"; ... assert decoded["raw"]["value"] == raw, never a second spelling of the same value.
- Where a transform's output cannot be derived from its input — a renderer turning
# hinto
<h1>h</h1> — do not hand-write the expectation. Bind to the authoritative suite that defines correctness for that transform. Where no such suite exists, leave the case to the project's own test suite, which the implementer writes against real output.
- Never write
- None.under## Programmatic Acceptancein a spec a story implements; Drydock
refuses a story with no criterion. A spec with no behavior of its own, such as a shared layout, asserts what it does deliver: a template renders, a module imports, a route answers.
6. Declare relationships.
- Consumes: the authored spec set as a whole.
- Emits:
Depends On,Provides, andConsumesin each Blueprint header.
Rules:
Depends Onnames the files or interface points required before this file can be implemented.Providesnames routes, commands, API symbols, datasets, queues, or event types this file
defines.
Consumeslists the interface points this file calls. A SCREEN lists the routes it calls.- A SCREEN route must be backed by a provider in some FEATURE or service definition.
- Do not leave relationship fields contradictory across files. State what each file requires and
provides; Drydock derives the rest.
7. Declare the topology.
- Consumes: the authored spec set and its declared relationships.
- Emits:
TOPOLOGY.md— one declaration per authored specification, carrying declarations only.
These seven jobs are the order you think in, not the order you emit in. Settle all seven first. Stage 1 then emits the complete TOPOLOGY.md declaration and DECISIONS.json only. Drydock freezes that declaration before starting Stage 2, which authors its Blueprint specifications in bounded batches.
You author judgment. Drydock computes everything positional. Do not emit MANIFEST.md. Do not sort the stories, do not group them, do not assign block: or stack_mode:, and do not reason about a story's position in an order you have not computed. Declare the stories in any order that is convenient; Drydock verifies the graph, orders it, packs it into blocks, and serializes MANIFEST.md itself. A contradiction in your declarations becomes a precise deterministic error, not a shape failure.
TOPOLOGY.md is a flat declaration. Begin it with the display-only heading ## Declarations, then declare one ## story <id> heading per governed specification, followed by field: value lines. There is no id: line — the heading carries the id. There is no block:, no stack_mode:, no state:, no numbering, and no ordering of any kind:
## Declarations
## story catalog-service
summary: Serve the catalog read API.
type: service
kind: capability
phase: 1
implements: FEATURE-Catalog.md
covers: CATALOG-001
context: DATABASE.md
stack: common.md, python.md, fastapi.md
provides: GET /catalog, GET /catalog/{id}
consumes: catalog_items
depends: foundation
acceptance: yes
instructions: |
Implement the catalog read endpoints against the catalog_items table.
Return 404 for an unknown id.
Declare, per story:
summary,implements(exactly one governed specification file — one filename, never a
list), instructions
type—foundational,service, orfeature, perMANIFEST_CONTRACT.mdkind—capability,integration,migration, ortest harnessphase— the high-level topology: Commander build sequencing, build Feature X then Feature Y.
It is not the tier chain: the tiers repeat inside each phase rather than running once across the project. Weigh Commander ordering direction as input when assigning it.
- Inside a phase,
dependscarries the tier chain each story'sstack:files declare —
language, platform (sub-ordered database, web server, CLI), branding, interface, screen-foundation, then application, per MANIFEST_CONTRACT.md. A story building on bootstrap5.md depends on the language, platform, and branding work and precedes every screen story; it carries no ordering claim against a service. Services and screens are tier 6 application: they are ordered against each other by depends: alone, never by tier.
depends— the actual topology: the genuine input requirements of this story, by story id. A
feature story depends on its member stories.
provides/consumes— what this story defines and calls, comma-separatedstack— the Rigging stack files this story builds withacceptance—yeswhen the story has real acceptance to honorcovers,accepts,context,rules,copy,scope,feedbackwhen applicable
A feature assembly story remains a story: it implements exactly one governed Blueprint file that Stage 2 authors. Do not emit phase, terminal, integration, or acceptance assembly stories with an empty implements: field.
instructions uses the | block form shown above: every body line is indented, and the body ends at the first unindented line. Every other field is one line.
The two topologies must agree: a story in phase 2 cannot depend on a story in phase 3. Drydock checks this and rejects the plan when they disagree.
For every injected Persistent Plan feedback decision, add one line to a planning_feedback: | block at the very top of TOPOLOGY.md, before the first ## story heading: <decision-id> applied <Blueprint path>, <decision-id> retained, or <decision-id> retired <scope-change reason>. A renamed file is never a retirement reason. Put applied decisions into normal Blueprint content and list their ids in the owning story's feedback: field.
Typed Specification Format
For every authored Blueprint file except METADATA.md and README.md, use this exact header shape:
# {FileType}: {ObjectName}
| Field | Value |
|-------------|-------|
| Version | YYYYMMDD V1 |
| Description | One sentence summary. |
| Depends On | FEATURE-SERVICE-CATALOG.md, UI-GENERAL.md |
| Provides | GET /welcome, GET /welcome/summary |
| Consumes | GET /api/welcome-summary |
Phase is not a Blueprint header field. It describes when a file is built, not the file, so it is declared in TOPOLOGY.md only.
SCREEN files may also include:
| Route | /welcome |
| Parent | Main |
| Main Menu | Welcome (1) |
| Sub Menu | Summary (1) |
| Tab Order | 1 |
Required rules:
Versionmust use the current job date and start atV1for new files.Descriptionis one sentence.- Preserve exact field names and table formatting.
- Use
COMPASS,SCREEN,FEATURE,DATABASE,UI-GENERAL,ARCHITECTURE,HOMEPAGE,
or AC as the FileType, as applicable.
- Do not invent a new typed file category.
Every authored Specification file places ## Questions immediately after the typed metadata table. Use - None. when no human-owned unknown remains. Otherwise use the exact record contract from BLUEPRINTS_CONTRACT.md. The file then ends with these sections:
## Programmatic Acceptance
- None.
## User Acceptance
- None.
## Guardrails
- None.
Use - None. only when that section is truly empty. ## Programmatic Acceptance is never empty in a spec a story implements (see below).
Additional body guidance:
COMPASS.mdbody uses## Compass,## Constraints, and## Guardrails.ARCHITECTURE.mdcaptures modules, boundaries, route groupings, interfaces, technical
decisions, and a module ownership table for persistence/config/file/service boundaries.
ARCHITECTURE.mdcarries a## Technology Stacksection derived fromTECHNOLOGY_STACK.md:
the technologies in use and where each applies. It is derived prose, not the decision of record — never contradict TECHNOLOGY_STACK.md and never introduce a technology it does not list.
DATABASE.mddefines access patterns, stores, typed persistence interfaces, schemas,
migrations, config, file stores, and external services; no raw-storage access outside the encapsulation boundary.
FEATURE-*.mddefines the workflow, trigger, routes or interface points, reads, writes, and
operational behavior.
SCREEN-*.mddefines the route, layout, controls, interactions, and user-visible behaviors.Programmatic Acceptancedefines Python assertions that Drydock runs from the build directory
after the implementing story completes. It is mandatory: every spec with a programmatic surface (any Provides entry, route, interface, read, or write) carries several concrete executable assertions covering its distinct behaviors, invariants, and error modes — including the basic reachability/existence checks. This is the test-driven contract the build must satisfy. Never substitute prose, a ## Test narrative, or an external script reference for the assertions. Never emit - None. in a spec a story implements.
- Declare every external Python package and executable used directly or indirectly by each
Programmatic Acceptance mechanism using repeated Requires: <kind>=<name>; scope=<scope> lines. Include framework test-client dependencies, such as httpx2 for FastAPI TestClient; every criterion in one Target declares the same transport. Never install or silently assume an undeclared tool. Permission-bearing tooling choices belong in the Blueprint ## Questions, not only in DECISIONS.json; Drydock projects the canonical blocking question deterministically.
- An assertion that invokes a staged asset obeys that asset's documented interface, supplies every
environment variable it declares required, and extends the inherited environment rather than replacing it. See the staged-asset invocation rules in BLUEPRINTS_CONTRACT.md.
- Where an imported source stages an authoritative test suite, exactly one story runs the whole
suite and that story is the terminal one. Every other story that owns behavior the suite covers runs its own slice of it, scoped by the runner's selector to the cases that story implements, and the slice executes those cases — a list or dry-run invocation asserts nothing about the product and is a defect outside a pure staging story. The slices together cover every case in the corpus; overlap is expected, a gap is not. Never let a scoping flag override an imported instruction that says where the suite may run. See the authoritative-suite rules in BLUEPRINTS_CONTRACT.md.
User Acceptancecontains only Commander-observed checks that cannot be honestly automated.
Manifest Construction Rules
Derive the Manifest from the authored specs, not directly from the imported source text.
Story types
- One story per governed specification:
implements:names exactly one spec file, and every
authored spec file is implemented by exactly one story. The story is the atomic build primitive.
foundational— structure and scaffolding. Standing up S3 and proving the connection is
architecture. Recognizing that something must establish the web server, and making it a node, is your judgment and determines story structure.
service— everything that does work. Much of what source material labels architecture is
service work: the web server and the database are foundation; a voice service interpreter is a service wearing an architecture filename.
feature— an assembly story. It depends on its member stories, carries acceptance criteria, and
carries assembly and intent instructions instead of implementation instructions. It is not a grouping construct and it is not a batching unit.
- There is no fourth type, and no
spikeoracstory type. A research question becomes a
questionnaire before Plan or a DECISIONS.json record after.
Story sizing
- A story is a normal Agile story: 1 to 5 story points. Never a half point — that is a task,
and a task is folded into the story it serves. Never twelve — that is split.
- A story does one thing completely, carries test criteria, and is releasable on its own. A task is
not releasable and is therefore not a story.
- Size by that judgement alone. A story has no token dimension: token cost is a property of the
block a story is built in, not of the story.
- Story count is not capped, and it is an output of correct decomposition rather than a target.
Never collapse distinct behaviors to reduce the count, and never split one behavior to raise it.
Stack
- Draw
stack:values from the Rigging column ofTECHNOLOGY_STACK.md: give each story the files
for the technologies it actually builds with, and no others. A technology whose Rigging cell is — contributes no stack: entry. When TECHNOLOGY_STACK.md is absent or silent on a technology the story needs, choose the conventional Rigging file for it.
- Never emit
stack_mode:. Drydock assigns builder/consumer from first use in the order it
computes.
- Any story that implements
DATABASE.mdmust includepersistence.mdinstack:plus the
selected backend stack file such as sqlite.md, postgres.md, or aws-dynamodb.md.
Context
- Use
context:only for genuine read-only support files. - For context files classified in
ANALYSIS.md## Source Roles, preserve their source role in
a context_roles: | mapping (<path>: <role>). Key it by the promoted Blueprint name, never a sources/... path. A test suite or harness is context, never implements.
- A file the Analysis marks
stageis present in the build directory atsources/<name>.
Reference it by that build-relative path in Programmatic Acceptance. Never reference a blueprint/ path or an absolute path, and never author, rewrite, or trim a staged asset.
Decisions
- Where the Blueprint, guardrails, or stack declaration are silent on a needed decision, decide:
pick the option that most reduces rework risk, proceed as if it were chosen, and disclose it as a DECISIONS.json item (see Significant Design Decisions below). Ordinary design choices never enter Blueprint ## Questions; permission-bearing acceptance tooling requirements do, and gate only their owning story. Assign low, material, or blocking severity. Ordinary Plan-selected choices never hard-block regardless of severity.
- Treat counts, summaries, indexes, and other derived metadata as subordinate to the detailed
records from which they are computed. When derived metadata disagrees with an unambiguous detailed enumeration, recompute it from that enumeration and continue. This is neither a product question nor Error Mode. Do not require the Commander to correct a stale derived total.
Acceptance
- Durable behavioral acceptance lives in the implemented spec's
Programmatic Acceptance: a SCREEN
spec's assertions call every route the screen provides and consumes; a FEATURE spec's assertions exercise every route, interface, read, and write it provides.
- Do not copy Sea Trial commands into ordinary story acceptance or execute them while planning.
- The terminal story is the last story in the build order — the one on which every other story
is a transitive dependency and after which no further story runs. Position in the dependency graph decides it, never the story's name, type, or kind. A story that stages the test assets runs first and is never terminal. Resolve depends and identify the terminal story before writing any suite criterion.
- When the Analysis states a terminal verification story, that one story gates on the complete
suite: its Programmatic Acceptance assertion declares Suite: full as one of the block's declaration lines, and it depends on every implementation story. Without that declaration a full-suite run is rejected. Only the terminal story runs the whole suite.
- A story that owns behavior the suite covers gates on its own slice: the runner scoped by its
selector to the cases that story implements, executing them, asserting exit 0. Declare the runner's list-mode selector as Probe: and its output format as Probe Count:; Drydock runs the selection probe during verification. Do not execute tools or invent a selected count while authoring the plan. An unbounded run of the suite from any non-terminal story, without Suite: full, is rejected.
- A pure harness staging story — one that proves the runner is staged and starts, implements none
of the behavior under test, and gates no correctness — is the single exception: it invokes the runner in its list or dry-run mode, which enumerates the suite without executing a case, and asserts the runner exits 0 and reports the expected count. Using list mode anywhere else produces a criterion that is green before the code exists. Never leave a staging story with no criterion: a story that cannot be verified closes advisory and gates nothing.
- Every invocation of a staged asset — in any story, in any mode, including list and dry-run mode —
supplies every environment variable that asset declares required, by extending the inherited environment (env={**os.environ, "NAME": value}). Read the asset's usage block for the value it names. An asset that is called without a variable it requires exits on its own usage code, which is a harness fault and never a verdict about the product, so the criterion is false under every implementation and no build can move it.
- When an authoritative conformance suite is imported (a specification's example set plus its
runner), every implementing feature story binds its acceptance to that suite over the sections it owns, never to a hand-written sample. The assertion invokes the imported runner limited to the feature's sections and asserts a full pass of that slice; it declares Suite: scoped on its own line so the check receives the suite timeout. Partition the suite's sections so each is owned by exactly one story; the union of the story slices plus the terminal Suite: full story reproduces the whole suite. One story owning every section is an under-decomposed plan. A scoped run requires runner success and zero failures/errors within its selected slice. It must not require 0 skipped: tests outside that slice are expected to be reported as skipped. Only the terminal Suite: full assertion may require zero skipped tests.
- Absent such a suite, every non-terminal story stays bounded — a hand sample proves a unit works,
never that the project is correct.
Ordering and grouping — not yours
- Do not sort the stories. Do not compute a topological order. Do not group them into batches.
- Do not emit
block:. Blocks are ephemeral context-optimization groups computed by Drydock: one
topology type per block, never crossing a phase boundary, never violating the edges, packed to amortize stack-file cost across one build pass. Context economy comes from blocks, not from feature grouping. Only stories ready before a block starts can share it; a dependent story is built and graded after its prerequisites, never in their agent call.
- Declare
depends:as genuine input requirements only. An entry that is decoration rather than a
real prerequisite corrupts the order Drydock computes from it.
Significant Design Decisions
Significant Design Decisions not specified by the Blueprint. Build must never stall on a choice Plan should have already made, and the Commander must be able to review and redirect any such choice before Build acts on it. Where the Blueprint, guardrails, or stack declaration are silent on a needed decision, you have permission and the obligation to decide: pick the option that most reduces rework risk, proceed as if it were chosen, and disclose it.
Ask the way you'd ask a colleague mid-task — state the decision, name the options you weighed, give your pick, own it. Not an exhaustive survey.
Assigning blueprint: name the one Blueprint file the decision belongs to — the service or screen it governs. If it belongs to neither, name ARCHITECTURE.md.
Emit every decision as DECISIONS.json, using the standard file delimiters. Emit [] when there are no decisions — never a silent decision with nothing recorded.
=== BEGIN ARTIFACT DECISIONS.json ===
[
{
"id": "string, e.g. Q-001",
"type": "choice | text",
"severity": "low | material | blocking",
"blueprint": "string — the Blueprint filename this decision belongs to",
"story": "string | null",
"title": "string",
"description": "string",
"options": [ { "value": "string", "label": "string" } ],
"system_choice": "string"
}
]
=== END ARTIFACT ===
type: "text" decisions set options to [] and put the resolution in system_choice. Do not include commander_direction, override_text, status, origin, or archived — those are Commander/QuarterDeck-owned and never emitted by Plan.
DECISIONS.json never gates Build regardless of severity, and it is never a Blueprint ## Questions record. It is the sole disclosure surface for ordinary Plan-selected design choices; permission-bearing acceptance tooling uses the governed Blueprint question surface.
Output Contract
Emit exactly one response mode. Nothing outside the blocks — no preamble, no explanation, no commentary. No stray text: never announce, narrate, or explain what you are about to do, before, between, or after the blocks. Any output outside a delimited block is a protocol violation and will cause the run to fail. Start your response with the first === BEGIN ARTIFACT ... === block.
The response is processed by a deterministic parser. The parser rejects the entire response if it finds any non-whitespace character before the first artifact block, between artifact blocks, or after the final artifact block. A rejected response writes no Blueprint files and no MANIFEST.md.
Do not emit transition or completion text such as Now the Manifest., Next file:, Here is the completed Blueprint., or Done. After === END ARTIFACT ===, emit only whitespace followed immediately by the next === BEGIN ARTIFACT <name> === delimiter, or end the response.
Success Mode
Use Success Mode whenever the product basis is sufficient to declare an internally consistent Blueprint and Manifest.
Stage 1 emits exactly two blocks: the complete TOPOLOGY.md first and DECISIONS.json second. Do not emit any Blueprint specification in this response. Drydock parses, verifies, and freezes the complete topology before it starts Stage 2 Blueprint authoring.
Declaring first is a hard requirement, not a stylistic one. TOPOLOGY.md is the plan; the spec files implement it. Emitting it in a separate stage commits you to the complete story set before any Blueprint prose is emitted. A response whose declaration never arrives is unrecoverable.
Every implements: filename in TOPOLOGY.md must name exactly one Blueprint file that Stage 2 will author, or an authored Blueprint spec file that already exists in the input context.
Wrap both Stage 1 files in matching open/END delimiter pairs:
=== BEGIN ARTIFACT relative/path/from/blueprint/or/target ===
{full file contents}
=== END ARTIFACT ===
The === END ARTIFACT === line is mandatory for every file, not only for TOPOLOGY.md. The closing delimiter is that constant token and nothing else: it never carries the file name, the file's title, or any heading from the file's content. The name is typed once, at the open. Never separate files with a bare opening delimiter, and never emit two consecutive === END ARTIFACT === lines. Emit each file once where possible. To correct a file within the same response, emit its complete replacement in a new block with the same filename; the last block is authoritative and receives the normal validation. Never emit a patch or partial update.
Finish and close TOPOLOGY.md before opening DECISIONS.json. Check the completed response for two opening lines and two closing lines, one matched pair per artifact; complete any unfinished body before closing it.
The complete Stage 1 response is:
=== BEGIN ARTIFACT TOPOLOGY.md ===
{the story declarations}
=== END ARTIFACT ===
=== BEGIN ARTIFACT DECISIONS.json ===
[]
=== END ARTIFACT ===
DECISIONS.json is emitted once after the topology — per §Significant Design Decisions. Emit [] when there are no decisions to disclose. Stage 2 uses a separate prompt and emits only bounded Blueprint batches.
Never emit a MANIFEST.md block. Drydock serializes the Manifest from your declaration.
Blocked Mode
Use Blocked Mode only when ANALYSIS_QUALITY is Blocked. Emit only:
=== BEGIN ARTIFACT PLAN_CREATE_BLOCKED.txt ===
Planning cannot proceed because ANALYSIS.md is Blocked.
Reason:
- {specific blocker summary}
Required action:
- Resolve blockers and rerun `drydock analyze`, then rerun `drydock plan`.
=== END ARTIFACT ===
Error Mode
Use Error Mode only for an unresolvable product question — one the Precedence order above cannot settle and no reasonable assumption can bridge. Drydock records this report as an active product decision error and does not persist model-generated Blueprint or Manifest artifacts.
A mismatch between derived summary metadata and its unambiguous detailed records is never Error Mode. Recompute the derived value from the detailed records and begin the Success Mode artifact batch.
Available response length is never Error Mode. Stage 1 emits only the complete topology and decisions. Drydock separately controls the size and retry behavior of Stage 2 Blueprint batches.
A technology-stack disagreement is never Error Mode. Resolve it by Precedence, plan on the winning choice, and record the variance as a Note: line in the Manifest preamble.
Emit only:
=== BEGIN ARTIFACT PLAN_CREATE_ERROR.txt ===
Planning output was not produced.
Error type: {format|missing-input|conflict|insufficient-specification|other}
Reason:
- {exact conflicting files, clauses, and scopes; why precedence cannot resolve them}
Required action:
- {specific product decision or source correction required}
=== END ARTIFACT ===
Hard Rules
- Nothing outside the required output blocks — no preamble, no summary, no prose, no stray text.
- Never emit
MANIFEST.md; Drydock serializes it fromTOPOLOGY.md. - In Success Mode
TOPOLOGY.mdis the first block,DECISIONS.jsonis the second block, and no
Blueprint specification is emitted during Stage 1.
- Never emit
TOPOLOGY.mdin Error Mode or Blocked Mode. - Never emit partial Blueprint files in Error Mode or Blocked Mode.
- Do not emit a file that violates
BLUEPRINTS_CONTRACT.mdorMANIFEST_CONTRACT.md. - Every
implements:entry inTOPOLOGY.mdnames a Blueprint file Stage 2 will author or an
authored spec file that already exists in the input Blueprint.
- Stories and governed specifications are one-to-one: each story's
implements:names exactly one
spec file, and every authored spec file is implemented by exactly one story.
implements:never lists files.implements: SCREEN-Orders.md, FEATURE-Pricing.mdis refused
before any Blueprint is authored: declare a feature-pricing story that implements FEATURE-Pricing.md, and add feature-pricing to the screen story's depends:. A file that two stories need is implemented by one story and depended on by the other.
- Never emit
AGENTS.md. AGENTS.md is not a Blueprint file and is distributed with rigging at build time. - Every emitted authored spec file except
METADATA.mdandREADME.mduses the exact typed header
table and ends with ## Programmatic Acceptance, ## User Acceptance, and ## Guardrails, with ## Questions immediately after the header table.
- Emit
DECISIONS.jsononce, in Success Mode only, immediately afterTOPOLOGY.md. Never
put a Plan decision in a Blueprint ## Questions section.
Phaseis never a Blueprint header field; declare it inTOPOLOGY.mdonly.- Never emit
block:orstack_mode:; both are computed by Drydock. - Every spec that declares a
Providesentry (or any route, interface, read, or write) carries
several concrete Python assertions under ## Programmatic Acceptance. Every spec a story implements, DATABASE.md included, carries at least one; - None. there is refused.
- A SCREEN spec's Programmatic Acceptance must literally call every route in its
Providesand
Consumes; a plan whose SCREEN acceptance skips a route is rejected.
- Do not invent interfaces, routes, datasets, commands, or capabilities that the sources and
analysis do not support.
- Do not leave user-facing screens without backing providers.
- Do not emit placeholder phrases like
TBD,fill later,to be determined, or
implementation details here; unresolved items belong in ## Questions.
- Do not emit empty authored files.
- Keep the Blueprint authoritative and durable; keep execution state in
MANIFEST.md.
Review the authored relationships and emit complete artifacts with exact delimiters. Do not compute the schedule or claim validation results: Drydock checks structure, graph consistency and buildability after the response. Use returned defects to correct their owning declarations or criteria without weakening source requirements.
The governing contracts, planning artifacts, and source materials follow below.
Acceptance persistence lifecycle
Acceptance store lifecycle. The DATABASE step provisions and verifies the configured store once. Ordinary persistence criteria never replace DATABASE_URL/DATABASE_PATH, create a temporary database, apply DDL, or assume an empty store. Configuration behavior is tested separately using the harness fixture below. 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.
SQLite configuration tests (Python acceptance container). The harness supplies from drydock_acceptance import database_environment. Use it only to test configuration selection, default paths, or source-required open failures, never ordinary CRUD acceptance:
import os
from drydock_acceptance import database_environment
from <declared_config_module> import database_path
with database_environment(url="sqlite://primary.db", path="fallback.db") as root:
assert str(database_path()) == str(root / "primary.db")
with database_environment(path="fallback.db") as root:
assert str(database_path()) == str(root / "fallback.db")
with database_environment() as root:
assert str(database_path()) == "data/app.db"
None (the default) unsets a variable; "" sets it empty. Other arguments are relative SQLite file names within a fresh temporary working directory; only url permits the sqlite:// prefix. The fixture maps names to absolute scratch paths, yields that directory as a Path, and restores both variables and cwd on exit, including failures. It applies no schema and creates no parent directories: url="missing/app.db" exercises an unopenable path. Invoke the declared application interface inside the context, assert the source-required outcome, and do not read or write the managed store. Import the declared configuration module, never invent a module or an exit requirement absent from the source. Do not replace environment variables directly or bypass this fixture with monkeypatches.
For acceptance-store repair of an existing configuration test, move its environment setup and restoration into this fixture. Preserve URL-prefix/precedence/unset/empty conditions, command arguments, error behavior and expected results. Replace arbitrary fixture paths with relative names and derive asserted absolute paths from root; this is a mechanical fixture relocation, not permission to change which configured value wins or weaken any assertion. If the criterion needs a populated replacement store, report REPAIR_IMPOSSIBLE instead.
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.
<pblock label="Frozen Stage 1 output" kind="frozen-stage">
Frozen Stage 1 Output
The following topology and decisions are the exact accepted Stage 1 output. Author the current Blueprint batch from them; do not reconstruct or amend them.
TOPOLOGY.md
Declarations
story foundation-python
summary: Stand up the Python project tree, environment, dependency manifest, pytest runner, and bin/test.sh. type: foundational kind: capability phase: 1 implements: ARCHITECTURE.md stack: common.md, python.md provides: project tree, bin/test.sh acceptance: yes instructions: | Build the Python 3.11+ project root: pyproject.toml, committed uv.lock, .venv launchers in bin/, conftest.py, and a POSIX bin/test.sh that runs pytest -q from the application root and exits zero only when every test passes.
Create the ledger_core package that later stories fill (validation, money, balances, csvio, accounts, transactions, reports). State the module ownership table: only the generated persistence package touches the database; no driver is imported elsewhere. Money is integer cents at every layer; no floating point.
Configuration resolves DATABASE_URL (optional sqlite:// prefix), then DATABASE_PATH, then data/app.db. An unopenable database path is an operational failure, exit 1, with no writes.
story foundation-database
summary: Declare the accounts, categories, and transactions tables and every repository operation the stories need. type: foundational kind: capability phase: 1 implements: DATABASE.md stack: common.md, python.md, persistence.md, sqlite.md provides: persistence.accounts, persistence.categories, persistence.transactions depends: foundation-python acceptance: yes instructions: | Author DATABASE.md as the complete persistence declaration. Tables: accounts(account PK, name), categories(category PK, description), transactions(txn_id INTEGER PK, date, account REFERENCES accounts, category REFERENCES categories, amount INTEGER cents, memo).
Declare one access pattern per operation any story needs: create/get/update/delete/list for each table; transactions listing by account and by month; count per table; max txn_id; per-account transaction count and balance sum; delete-all per table for init; and atomic multi-row create where the persistence library allows it. Every operation carries a criterion that calls it. The builder writes no persistence code; Drydock generates it.
story foundation-cli
summary: Provide the ledger executable at the application root with a command registry, usage-error handling, and the stdout/stderr contract. type: foundational kind: capability phase: 1 implements: FEATURE-CliEntry.md stack: common.md, python.md, cli.md provides: ledger, cli.registry consumes: persistence.accounts, persistence.categories, persistence.transactions depends: foundation-database acceptance: yes instructions: | Create the executable ledger (POSIX launcher that activates .venv and calls cli.main), the cli package with main(argv) -> int and cli/testing.py with cli_runner.
Commands are discovered from modules in cli/commands/; each module exposes a COMMANDS mapping from a word tuple such as ("account", "add") to a handler. Dispatch rules: unknown first word, a known group word with an unknown sub-word (unknown table or report), or a wrong argument count exit 2 with one stderr line and no stdout. A handler returns the rows to print; stdout is written only after the handler succeeds, so a failing command never prints. Domain errors map to exit codes: Rejected 3, NotFound 4, Operational 1. Output is CSV with \n endings, no quoting, no trailing spaces.
story feature-validation
summary: Validate codes, names, memos, amounts, and dates, and format integer cents as two-decimal text. type: service kind: capability phase: 1 implements: FEATURE-Validation.md stack: common.md, python.md provides: ledger_core.validation, ledger_core.money depends: foundation-python acceptance: yes instructions: | Implement pure functions. Codes: 1 to 12 chars of A-Z0-9. Names/descriptions: 1 to 40 chars; memos 0 to 60; none contains a comma or newline. Amounts on input match -?DIGITS[.D[D]], parse to integer cents with Decimal-free integer arithmetic or Decimal, never float, and reject zero and three or more decimals. Dates are real calendar dates YYYY-MM-DD (reject 2026-02-30). format_cents writes exactly two decimals, leading - when negative, no thousands separator. Violations raise Rejected (exit 3).
story feature-balance-rule
summary: Check that a proposed set of transaction changes leaves no account balance below zero before any write. type: service kind: capability phase: 1 implements: FEATURE-BalanceRule.md stack: common.md, python.md provides: ledger_core.balances consumes: persistence.transactions depends: foundation-database acceptance: yes instructions: | Provide check_no_negative(db, changes) where changes are inserts, amount edits, and deletions of transaction rows. It computes each affected account's resulting balance as the stored sum plus the net delta, and raises Rejected if any resulting balance is below zero. An account's balance is the sum of its amounts. It writes nothing. Used by load, post, amend, delete, and transfer.
story feature-init-count
summary: Implement ledger init and ledger count. type: service kind: capability phase: 2 implements: FEATURE-InitCount.md covers: LEDGER-SCHEMA-001 stack: common.md, python.md, cli.md provides: ledger init, ledger count consumes: ledger, cli.registry depends: foundation-cli acceptance: yes instructions: | init creates the database file if absent, removes all rows from transactions, then categories, then accounts (foreign-key order), writes nothing, exits 0. count prints table,rows then accounts, categories, transactions counts read from the database.
story feature-load-csv-reader
summary: Read and header-check a CSV file named on the command line, exiting 1 when it cannot be read. type: service kind: capability phase: 2 implements: FEATURE-LoadCsvReader.md covers: LEDGER-LOAD-004 stack: common.md, python.md, cli.md provides: ledger_core.csvio consumes: ledger, cli.registry depends: foundation-cli acceptance: yes instructions: | Provide read_rows(path, header) using the csv module. An unreadable or missing file raises Operational (exit 1) with no writes. A header differing from the table's columns in order, or a row with the wrong field count, raises Rejected (exit 3). It returns parsed rows with their line numbers for diagnostics and writes nothing.
story feature-load-accounts
summary: Implement ledger load accounts <csv> as an all-or-nothing load. type: service kind: capability phase: 2 implements: FEATURE-LoadAccounts.md covers: LEDGER-LOAD-001 stack: common.md, python.md, cli.md provides: ledger load accounts consumes: ledger_core.csvio, ledger_core.validation, cli.registry depends: feature-load-csv-reader, feature-validation acceptance: yes instructions: | Header account,name. Validate every row (code, name, duplicate key within the file and against stored accounts) before the first write, then insert all rows atomically. On success print table,loaded and accounts,<rows>. Any invalid row exits 3 and stores none of the rows.
story feature-load-categories
summary: Implement ledger load categories <csv> as an all-or-nothing load. type: service kind: capability phase: 2 implements: FEATURE-LoadCategories.md covers: LEDGER-LOAD-002 stack: common.md, python.md, cli.md provides: ledger load categories consumes: ledger_core.csvio, ledger_core.validation, cli.registry depends: feature-load-csv-reader, feature-validation acceptance: yes instructions: | Header category,description. Same validate-everything-then-write rule as accounts. On success print table,loaded and categories,<rows>; any invalid row or duplicate key exits 3 with no rows stored.
story feature-load-transactions
summary: Implement ledger load transactions <csv> with foreign-key, date, amount, and balance validation before any write. type: service kind: capability phase: 2 implements: FEATURE-LoadTransactions.md covers: LEDGER-LOAD-003 accepts: st-004 stack: common.md, python.md, cli.md provides: ledger load transactions consumes: ledger_core.csvio, ledger_core.validation, ledger_core.balances, cli.registry depends: feature-load-csv-reader, feature-validation, feature-balance-rule, feature-load-accounts, feature-load-categories acceptance: yes instructions: | Header txn_id,date,account,category,amount,memo. Keep each file txn_id. Reject, before any write, a duplicate txn_id (in file or stored), an unknown account or category (stored or none), a bad date, amount, or memo, and any file whose combined effect leaves an account balance below zero. The balance check considers all rows together. Insert all rows atomically; print table,loaded and transactions,<rows>. A rejection at row 11 stores none of rows 1 to 10.
story feature-account-add
summary: Implement ledger account add <code> <name>. type: service kind: capability phase: 2 implements: FEATURE-AccountAdd.md covers: LEDGER-ACCT-001 stack: common.md, python.md, cli.md provides: ledger account add, ledger_core.accounts consumes: ledger_core.validation, ledger_core.money, cli.registry depends: foundation-cli, feature-validation acceptance: yes instructions: | Validate code and name, reject a duplicate with exit 3, insert, and print the row account,name,transactions,balance with 0 transactions and 0.00. Export an account_row helper computing the transaction count and balance from the database for the other account commands.
story feature-account-get
summary: Implement ledger account get <code>. type: service kind: capability phase: 2 implements: FEATURE-AccountGet.md covers: LEDGER-ACCT-002 stack: common.md, python.md, cli.md provides: ledger account get consumes: ledger_core.accounts, cli.registry depends: feature-account-add acceptance: yes instructions: | Print the current account row with live transaction count and balance. An absent code exits 4.
story feature-account-rename
summary: Implement ledger account rename <code> <name>. type: service kind: capability phase: 2 implements: FEATURE-AccountRename.md covers: LEDGER-ACCT-003 stack: common.md, python.md, cli.md provides: ledger account rename consumes: ledger_core.accounts, ledger_core.validation, cli.registry depends: feature-account-add acceptance: yes instructions: | Validate the new name, update only the name, and print the updated row. An absent code exits 4; an invalid name exits 3 and changes nothing.
story feature-account-delete
summary: Implement ledger account delete <code>. type: service kind: capability phase: 2 implements: FEATURE-AccountDelete.md covers: LEDGER-ACCT-004 accepts: st-006 stack: common.md, python.md, cli.md provides: ledger account delete consumes: ledger_core.accounts, cli.registry depends: feature-account-add acceptance: yes instructions: | Check existence (absent exits 4), then check the account has no transactions (otherwise exit 3), then delete and print deleted and the code.
story feature-txn-post
summary: Implement ledger txn post <account> <category> <amount> <date> [<memo>]. type: service kind: capability phase: 2 implements: FEATURE-TxnPost.md covers: LEDGER-TXN-001 stack: common.md, python.md, cli.md provides: ledger txn post, ledger_core.transactions consumes: ledger_core.validation, ledger_core.money, ledger_core.balances, cli.registry depends: foundation-cli, feature-validation, feature-balance-rule acceptance: yes instructions: | Validate every input and rule first: account and category exist, amount, date, memo, and the no-negative-balance rule. Assign txn_id as max(txn_id)+1, or 1 when empty, insert, and print the row txn_id,date,account,category,amount,memo. Export txn_row and next_txn_id helpers. Any violation exits 3 and writes nothing.
story feature-txn-get
summary: Implement ledger txn get <id>. type: service kind: capability phase: 2 implements: FEATURE-TxnGet.md covers: LEDGER-TXN-002 stack: common.md, python.md, cli.md provides: ledger txn get consumes: ledger_core.transactions, cli.registry depends: feature-txn-post acceptance: yes instructions: | Print the transaction row; an absent id exits 4 and a non-integer id exits 3.
story feature-txn-amend
summary: Implement ledger txn amend <id> <amount>. type: service kind: capability phase: 2 implements: FEATURE-TxnAmend.md covers: LEDGER-TXN-003 accepts: st-006 stack: common.md, python.md, cli.md provides: ledger txn amend consumes: ledger_core.transactions, ledger_core.validation, ledger_core.balances, cli.registry depends: feature-txn-post acceptance: yes instructions: | Absent id exits 4. Validate the amount, check the resulting balance of the transaction's account (stored sum minus old amount plus new) is non-negative, then update only the amount and print the row. A rejection exits 3 and leaves the original amount.
story feature-txn-delete
summary: Implement ledger txn delete <id>. type: service kind: capability phase: 2 implements: FEATURE-TxnDelete.md covers: LEDGER-TXN-004 stack: common.md, python.md, cli.md provides: ledger txn delete consumes: ledger_core.transactions, ledger_core.balances, cli.registry depends: feature-txn-post acceptance: yes instructions: | Absent id exits 4. Check that removing the row leaves its account balance non-negative (else exit 3, row kept), then delete and print deleted and the id.
story feature-transfer
summary: Implement ledger transfer <from> <to> <amount> <date> as an atomic two-row write. type: service kind: capability phase: 2 implements: FEATURE-Transfer.md covers: LEDGER-XFER-001 accepts: st-010 stack: common.md, python.md, cli.md provides: ledger transfer consumes: ledger_core.transactions, ledger_core.validation, ledger_core.balances, cli.registry depends: feature-txn-post acceptance: yes instructions: | Both accounts must exist and differ; the amount is positive; the date is valid; the TRANSFER category must exist. Check the source balance after the debit before any write. Insert the outgoing row (-amount, memo transfer to <to>) with id max+1 and the incoming row (+amount, memo transfer from <from>) with the next id, atomically, and print both rows. A rejection stores neither.
story feature-report-balances
summary: Implement ledger report balances. type: service kind: capability phase: 3 implements: FEATURE-ReportBalances.md covers: LEDGER-RPT-001 stack: common.md, python.md, cli.md provides: ledger report balances consumes: ledger_core.money, cli.registry depends: foundation-cli, feature-validation acceptance: yes instructions: | Header account,name,transactions,balance; one row per account ordered by code, then TOTAL,,<count>,<sum>. All values computed from queries; amounts formatted from integer cents.
story feature-report-categories
summary: Implement ledger report categories. type: service kind: capability phase: 3 implements: FEATURE-ReportCategories.md covers: LEDGER-RPT-002 stack: common.md, python.md, cli.md provides: ledger report categories consumes: ledger_core.money, cli.registry depends: foundation-cli, feature-validation acceptance: yes instructions: | Header category,description,transactions,inflow,outflow,net; every category ordered by code, including those with no transactions (zero values), then the TOTAL row. inflow is the sum of positive amounts, outflow the sum of absolute negative amounts, net inflow minus outflow.
story feature-report-monthly
summary: Implement ledger report monthly. type: service kind: capability phase: 3 implements: FEATURE-ReportMonthly.md covers: LEDGER-RPT-003 stack: common.md, python.md, cli.md provides: ledger report monthly consumes: ledger_core.money, cli.registry depends: foundation-cli, feature-validation acceptance: yes instructions: | Header month,transactions,inflow,outflow,net; one row per YYYY-MM that has transactions, ascending, then TOTAL,<count>,<inflow>,<outflow>,<net>. Month is the first seven characters of the stored date.
story feature-command-contract
summary: Assemble and verify the CSV output contract and exit codes across every command. type: feature kind: integration phase: 4 implements: FEATURE-CommandContract.md covers: LEDGER-CLI-001 accepts: st-007, st-011 stack: common.md, python.md, cli.md consumes: ledger init, ledger count, ledger load accounts, ledger load categories, ledger load transactions, ledger account add, ledger account get, ledger account rename, ledger account delete, ledger txn post, ledger txn get, ledger txn amend, ledger txn delete, ledger transfer, ledger report balances, ledger report categories, ledger report monthly depends: feature-init-count, feature-load-accounts, feature-load-categories, feature-load-transactions, feature-account-add, feature-account-get, feature-account-rename, feature-account-delete, feature-txn-post, feature-txn-get, feature-txn-amend, feature-txn-delete, feature-transfer, feature-report-balances, feature-report-categories, feature-report-monthly acceptance: yes instructions: | Assembly and intent only. Verify across the delivered commands that successful output is CSV with the specified headers, \n endings, two-decimal amounts and no trailing spaces; that a failing command writes nothing to stdout; that exit 2 results from unknown commands, tables, reports, and wrong argument counts; and that every rejected writing command leaves counts unchanged. Fix seams in the owning modules rather than adding new behavior.
story feature-no-negative-balance
summary: Assemble and verify that every writing command enforces the no-negative-balance rule atomically. type: feature kind: integration phase: 4 implements: FEATURE-NoNegativeBalance.md covers: LEDGER-CLI-002 accepts: st-008 stack: common.md, python.md, cli.md consumes: ledger load transactions, ledger txn post, ledger txn amend, ledger txn delete, ledger transfer depends: feature-load-transactions, feature-txn-post, feature-txn-amend, feature-txn-delete, feature-transfer acceptance: yes instructions: | Assembly and intent only. For each of load, post, amend, delete, and transfer, drive a case that would leave a balance below zero, assert exit 3, and read back that balances and row counts are unchanged. Include a load file whose later rows make an earlier-valid balance negative.
story feature-verification
summary: Terminal gate: run the supplied grader and the full project test suite. type: feature kind: test harness phase: 4 implements: FEATURE-Verification.md accepts: st-001, st-005 stack: common.md, python.md, cli.md depends: foundation-python, foundation-database, foundation-cli, feature-validation, feature-balance-rule, feature-init-count, feature-load-csv-reader, feature-load-accounts, feature-load-categories, feature-load-transactions, feature-account-add, feature-account-get, feature-account-rename, feature-account-delete, feature-txn-post, feature-txn-get, feature-txn-amend, feature-txn-delete, feature-transfer, feature-report-balances, feature-report-categories, feature-report-monthly, feature-command-contract, feature-no-negative-balance acceptance: yes instructions: | Terminal story. Its acceptance declares Suite: full, runs sh sources/run.sh and requires exit status 0, and runs sh bin/test.sh requiring exit 0. Print captured output before asserting. Supply the inherited environment when invoking. Do not modify anything under sources/.
DECISIONS.json
[ { "id": "Q-001", "type": "choice", "severity": "low", "blueprint": "ARCHITECTURE.md", "story": "foundation-python", "title": "Exit code for an unopenable database location", "description": "Sources give no exit code when DATABASE_URL names a path that cannot be opened. Options weighed: 1 (operational failure) or 3 (rejected). Operational failure fits the exit-code table.", "options": [ { "value": "1", "label": "Exit 1, operational failure" }, { "value": "3", "label": "Exit 3, rejected" } ], "system_choice": "1" }, { "id": "Q-002", "type": "choice", "severity": "low", "blueprint": "FEATURE-CliEntry.md", "story": "foundation-cli", "title": "Precedence between usage, not-found, and rejection errors", "description": "When a command has several problems, the order matters. Chosen order: argument count and unknown command (2), then input validation (3), then existence lookups (4 for get/rename/delete/amend), then business rules (3).", "options": [ { "value": "usage-validation-notfound-rules", "label": "2, then 3 validation, then 4, then 3 rules" }, { "value": "usage-notfound-validation-rules", "label": "2, then 4, then 3" } ], "system_choice": "usage-validation-notfound-rules" }, { "id": "Q-003", "type": "choice", "severity": "low", "blueprint": "FEATURE-LoadTransactions.md", "story": "feature-load-transactions", "title": "Duplicate txn_id in a load file", "description": "Sources say duplicate keys are rejected (exit 3) but do not name txn_id loads explicitly. The load rejects a txn_id repeated in the file or already stored, before any write.", "options": [ { "value": "reject", "label": "Reject with exit 3" }, { "value": "replace", "label": "Replace the stored row" } ], "system_choice": "reject" } ] </pblock>
<pblock filename="DATABASE_compact.md" role="frozen persistence declaration; cite its access patterns">
# DATABASE: LayersTesting
| Field | Value |
|-------|-------|
| Version | 20261027 V1 |
| Description | Persistence stores and typed interfaces for the LayersTesting cash ledger. |
| Depends On | ARCHITECTURE.md |
| Provides | persistence.accounts, persistence.categories, persistence.transactions |
| Build Order | 1 |
## Questions
- None.
## Persistence Boundary
| Boundary | Rule |
|----------|------|
| Raw storage access | Only the generated `persistence/` package reaches the store. |
| Caller dependency | Features depend on declared access patterns and their DTOs, not on schemas. |
| Implementation | Generated from this file at the DATABASE build step; never written by hand. |
| Money | Amounts are stored as integer cents; no floating point at any layer. |
| Aggregates | Counts, sums, and the largest `txn_id` are computed by callers from `list` results; no aggregate operation is declared. |
## Access Patterns
### FEATURE-ACCOUNT-001 — Create an account
| Field | Value |
|-------|-------|
| Owner | DATABASE.md |
| Access | write |
| Repository operation | `accounts.create` |
| Compatibility | unchanged |
Input: AccountsCreateInput
| Field | Type | Notes |
|-------|------|-------|
| account | TEXT | Account code |
| name | TEXT | Account name |
Output: AccountsCreateOutput
| Field | Type | Notes |
|-------|------|-------|
| account | TEXT | Account code |
| name | TEXT | Account name |
### FEATURE-ACCOUNT-002 — Get an account by code
| Field | Value |
|-------|-------|
| Owner | DATABASE.md |
| Access | read |
| Repository operation | `accounts.get` |
| Compatibility | unchanged |
Input: AccountsGetInput
| Field | Type | Notes |
|-------|------|-------|
| account | TEXT | Account code |
Output: AccountsGetOutput
| Field | Type | Notes |
|-------|------|-------|
| account | TEXT | Account code |
| name | TEXT | Account name |
### FEATURE-ACCOUNT-003 — Rename an account
| Field | Value |
|-------|-------|
| Owner | DATABASE.md |
| Access | write |
| Repository operation | `accounts.update` |
| Match | `account` |
| Compatibility | unchanged |
Input: AccountsUpdateInput
| Field | Type | Notes |
|-------|------|-------|
| account | TEXT | Account code (match) |
| name | TEXT | New name |
Output: AccountsUpdateOutput
| Field | Type | Notes |
|-------|------|-------|
| account | TEXT | Account code |
| name | TEXT | Account name |
### FEATURE-ACCOUNT-004 — Delete an account
| Field | Value |
|-------|-------|
| Owner | DATABASE.md |
| Access | write |
| Repository operation | `accounts.delete` |
| Match | `account` |
| Compatibility | unchanged |
Input: AccountsDeleteInput
| Field | Type | Notes |
|-------|------|-------|
| account | TEXT | Account code |
Output: AccountsDeleteOutput
| Field | Type | Notes |
|-------|------|-------|
| account | TEXT | Account code |
### FEATURE-ACCOUNT-005 — List accounts by code
| Field | Value |
|-------|-------|
| Owner | DATABASE.md |
| Access | read |
| Repository operation | `accounts.list` |
| Kind | list |
| Order | `account` asc |
| Compatibility | unchanged |
Input: AccountsListInput
| Field | Type | Notes |
|-------|------|-------|
Output: AccountsListOutput
| Field | Type | Notes |
|-------|------|-------|
| account | TEXT | Account code |
| name | TEXT | Account name |
### FEATURE-ACCOUNT-006 — Remove accounts from a code onward
| Field | Value |
|-------|-------|
| Owner | DATABASE.md |
| Access | write |
| Repository operation | `accounts.clear` |
| Kind | delete |
| Match | `account >= min_account` |
| Compatibility | unchanged |
Input: AccountsClearInput
| Field | Type | Notes |
|-------|------|-------|
| min_account | TEXT | Lowest code removed; an empty string removes every account |
Output: AccountsClearOutput
| Field | Type | Notes |
|-------|------|-------|
### FEATURE-CATEGORY-001 — Create a category
| Field | Value |
|-------|-------|
| Owner | DATABASE.md |
| Access | write |
| Repository operation | `categories.create` |
| Compatibility | unchanged |
Input: CategoriesCreateInput
| Field | Type | Notes |
|-------|------|-------|
| category | TEXT | Category code |
| description | TEXT | Description |
Output: CategoriesCreateOutput
| Field | Type | Notes |
|-------|------|-------|
| category | TEXT | Category code |
| description | TEXT | Description |
### FEATURE-CATEGORY-002 — Get a category by code
| Field | Value |
|-------|-------|
| Owner | DATABASE.md |
| Access | read |
| Repository operation | `categories.get` |
| Compatibility | unchanged |
Input: CategoriesGetInput
| Field | Type | Notes |
|-------|------|-------|
| category | TEXT | Category code |
Output: CategoriesGetOutput
| Field | Type | Notes |
|-------|------|-------|
| category | TEXT | Category code |
| description | TEXT | Description |
### FEATURE-CATEGORY-003 — Change a category description
| Field | Value |
|-------|-------|
| Owner | DATABASE.md |
| Access | write |
| Repository operation | `categories.update` |
| Match | `category` |
| Compatibility | unchanged |
Input: CategoriesUpdateInput
| Field | Type | Notes |
|-------|------|-------|
| category | TEXT | Category code (match) |
| description | TEXT | New description |
Output: CategoriesUpdateOutput
| Field | Type | Notes |
|-------|------|-------|
| category | TEXT | Category code |
| description | TEXT | Description |
### FEATURE-CATEGORY-004 — Delete a category
| Field | Value |
|-------|-------|
| Owner | DATABASE.md |
| Access | write |
| Repository operation | `categories.delete` |
| Match | `category` |
| Compatibility | unchanged |
Input: CategoriesDeleteInput
| Field | Type | Notes |
|-------|------|-------|
| category | TEXT | Category code |
Output: CategoriesDeleteOutput
| Field | Type | Notes |
|-------|------|-------|
| category | TEXT | Category code |
### FEATURE-CATEGORY-005 — List categories by code
| Field | Value |
|-------|-------|
| Owner | DATABASE.md |
| Access | read |
| Repository operation | `categories.list` |
| Kind | list |
| Order | `category` asc |
| Compatibility | unchanged |
Input: CategoriesListInput
| Field | Type | Notes |
|-------|------|-------|
Output: CategoriesListOutput
| Field | Type | Notes |
|-------|------|-------|
| category | TEXT | Category code |
| description | TEXT | Description |
### FEATURE-CATEGORY-006 — Remove categories from a code onward
| Field | Value |
|-------|-------|
| Owner | DATABASE.md |
| Access | write |
| Repository operation | `categories.clear` |
| Kind | delete |
| Match | `category >= min_category` |
| Compatibility | unchanged |
Input: CategoriesClearInput
| Field | Type | Notes |
|-------|------|-------|
| min_category | TEXT | Lowest code removed; an empty string removes every category |
Output: CategoriesClearOutput
| Field | Type | Notes |
|-------|------|-------|
### FEATURE-TXN-001 — Create a transaction
| Field | Value |
|-------|-------|
| Owner | DATABASE.md |
| Access | write |
| Repository operation | `transactions.create` |
| Compatibility | unchanged |
Input: TransactionsCreateInput
| Field | Type | Notes |
|-------|------|-------|
| txn_id | INTEGER | Caller-assigned id (loaded id, or largest id plus one) |
| date | TEXT | YYYY-MM-DD |
| account | TEXT | Existing account code |
| category | TEXT | Existing category code |
| amount | INTEGER | Cents, signed |
| memo | TEXT | Memo, possibly empty |
Output: TransactionsCreateOutput
| Field | Type | Notes |
|-------|------|-------|
| txn_id | INTEGER | Transaction id |
| date | TEXT | YYYY-MM-DD |
| account | TEXT | Account code |
| category | TEXT | Category code |
| amount | INTEGER | Cents, signed |
| memo | TEXT | Memo |
### FEATURE-TXN-002 — Get a transaction by id
| Field | Value |
|-------|-------|
| Owner | DATABASE.md |
| Access | read |
| Repository operation | `transactions.get` |
| Compatibility | unchanged |
Input: TransactionsGetInput
| Field | Type | Notes |
|-------|------|-------|
| txn_id | INTEGER | Transaction id |
Output: TransactionsGetOutput
| Field | Type | Notes |
|-------|------|-------|
| txn_id | INTEGER | Transaction id |
| date | TEXT | YYYY-MM-DD |
| account | TEXT | Account code |
| category | TEXT | Category code |
| amount | INTEGER | Cents, signed |
| memo | TEXT | Memo |
### FEATURE-TXN-003 — Amend a transaction amount
| Field | Value |
|-------|-------|
| Owner | DATABASE.md |
| Access | write |
| Repository operation | `transactions.update` |
| Match | `txn_id` |
| Compatibility | unchanged |
Input: TransactionsUpdateInput
| Field | Type | Notes |
|-------|------|-------|
| txn_id | INTEGER | Transaction id (match) |
| amount | INTEGER | New amount in cents |
Output: TransactionsUpdateOutput
| Field | Type | Notes |
|-------|------|-------|
| txn_id | INTEGER | Transaction id |
| date | TEXT | YYYY-MM-DD |
| account | TEXT | Account code |
| category | TEXT | Category code |
| amount | INTEGER | Cents, signed |
| memo | TEXT | Memo |
### FEATURE-TXN-004 — Delete a transaction
| Field | Value |
|-------|-------|
| Owner | DATABASE.md |
| Access | write |
| Repository operation | `transactions.delete` |
| Match | `txn_id` |
| Compatibility | unchanged |
Input: TransactionsDeleteInput
| Field | Type | Notes |
|-------|------|-------|
| txn_id | INTEGER | Transaction id |
Output: TransactionsDeleteOutput
| Field | Type | Notes |
|-------|------|-------|
| txn_id | INTEGER | Transaction id |
### FEATURE-TXN-005 — List transactions by account, category, or date range
| Field | Value |
|-------|-------|
| Owner | DATABASE.md |
| Access | read |
| Repository operation | `transactions.list` |
| Kind | list |
| Match | `account`, `category`, `date >= start_date`, `date <= end_date` |
| Order | `txn_id` asc |
| Compatibility | unchanged |
Input: TransactionsListInput
| Field | Type | Notes |
|-------|------|-------|
| account | TEXT | Optional filter |
| category | TEXT | Optional filter |
| start_date | TEXT | Optional lower bound, inclusive |
| end_date | TEXT | Optional upper bound, inclusive |
Output: TransactionsListOutput
| Field | Type | Notes |
|-------|------|-------|
| txn_id | INTEGER | Transaction id |
| date | TEXT | YYYY-MM-DD |
| account | TEXT | Account code |
| category | TEXT | Category code |
| amount | INTEGER | Cents, signed |
| memo | TEXT | Memo |
### FEATURE-TXN-006 — Remove transactions from an id onward
| Field | Value |
|-------|-------|
| Owner | DATABASE.md |
| Access | write |
| Repository operation | `transactions.clear` |
| Kind | delete |
| Match | `txn_id >= min_txn_id` |
| Compatibility | unchanged |
Input: TransactionsClearInput
| Field | Type | Notes |
|-------|------|-------|
| min_txn_id | INTEGER | Lowest id removed; 0 removes every transaction |
Output: TransactionsClearOutput
| Field | Type | Notes |
|-------|------|-------|
## Schemas
## `accounts`
| Field | Type | Notes |
|-------|------|-------|
| account | TEXT PK | Code, 1 to 12 characters of A-Z and 0-9 |
| name | TEXT NOT NULL | 1 to 40 characters |
## `categories`
| Field | Type | Notes |
|-------|------|-------|
| category | TEXT PK | Code, 1 to 12 characters of A-Z and 0-9 |
| description | TEXT NOT NULL | 1 to 40 characters |
## `transactions`
| Field | Type | Notes |
|-------|------|-------|
| txn_id | INTEGER PK | Transaction id |
| date | TEXT NOT NULL | YYYY-MM-DD |
| account | TEXT NOT NULL REFERENCES accounts(account) | Owning account |
| category | TEXT NOT NULL REFERENCES categories(category) | Category |
| amount | INTEGER NOT NULL | Integer cents, signed, never zero |
| memo | TEXT NOT NULL DEFAULT '' | 0 to 60 characters |
- INDEX (account, date)
## Migrations
Each relational change has one staged record in `migrations/MIGRATION-<AccessPatternId>.md`.
The record carries Alembic `upgrade`/`downgrade` snippets and progresses from `planned` to `built`
only when its DATABASE build story completes. Alembic records deployment application separately.
| Access Pattern | Revision | State |
|----------------|----------|-------|
## Config (.env)
| Key | Type | Required | Notes |
|-----|------|----------|-------|
| DATABASE_URL | string | No | SQLite file path, optionally prefixed `sqlite://`; consulted first |
| DATABASE_PATH | string | No | SQLite file path; consulted when DATABASE_URL is unset; default `data/app.db` |
## File Stores
| Store | Root dir | Notes |
|-------|----------|-------|
## External Services
| Service | Wrapper | Notes |
|---------|---------|-------|
## External Libraries
| Library | Ownership | Distribution | Consumer Contract |
|---------|-----------|--------------|-------------------|
## Programmatic Acceptance
=== AC accounts-create ===
Intent: accounts.create stores a row and returns the declared Output, which a separate get reads back.
from persistence.testing import db_session
def f(row, name):
return row[name] if isinstance(row, dict) else getattr(row, name)
code = "ZZCR1"
label = "Create Probe"
with db_session() as db:
out = db.accounts.create(account=code, name=label)
assert f(out, "account") == code
assert f(out, "name") == label
back = db.accounts.get(account=code)
assert back is not None
assert f(back, "name") == label
=== END AC accounts-create ===
=== AC accounts-get ===
Intent: accounts.get returns the stored row for an existing code and None for an absent one.
from persistence.testing import db_session
def f(row, name):
return row[name] if isinstance(row, dict) else getattr(row, name)
code = "ZZGET1"
label = "Get Probe"
with db_session() as db:
db.accounts.create(account=code, name=label)
row = db.accounts.get(account=code)
assert row is not None
assert f(row, "account") == code
assert f(row, "name") == label
assert db.accounts.get(account="ZZGETNONE") is None
=== END AC accounts-get ===
=== AC accounts-update ===
Intent: accounts.update changes only the name and the change is visible on a separate read.
from persistence.testing import db_session
def f(row, name):
return row[name] if isinstance(row, dict) else getattr(row, name)
code = "ZZUPD1"
before = "Before Name"
after = "After Name"
with db_session() as db:
db.accounts.create(account=code, name=before)
out = db.accounts.update(account=code, name=after)
assert out is not None
assert f(out, "name") == after
back = db.accounts.get(account=code)
assert f(back, "name") == after
assert f(back, "account") == code
=== END AC accounts-update ===
=== AC accounts-delete ===
Intent: accounts.delete removes the row so a later get finds nothing.
from persistence.testing import db_session
def f(row, name):
return row[name] if isinstance(row, dict) else getattr(row, name)
code = "ZZDEL1"
with db_session() as db:
db.accounts.create(account=code, name="Delete Probe")
out = db.accounts.delete(account=code)
assert out is not None
assert f(out, "account") == code
assert db.accounts.get(account=code) is None
=== END AC accounts-delete ===
=== AC accounts-list ===
Intent: accounts.list returns rows ordered by account code ascending; two codes created in reverse order appear in sorted order.
from persistence.testing import db_session
def f(row, name):
return row[name] if isinstance(row, dict) else getattr(row, name)
codes = ["ZZLA2", "ZZLA1"]
with db_session() as db:
for c in codes:
db.accounts.create(account=c, name="List " + c)
rows = db.accounts.list()
seen = [f(r, "account") for r in rows if f(r, "account") in codes]
assert seen == sorted(codes)
allcodes = [f(r, "account") for r in rows]
assert allcodes == sorted(allcodes)
=== END AC accounts-list ===
=== AC accounts-clear ===
Intent: accounts.clear removes accounts whose code is at or above the bound, reports a positive count, and leaves none readable.
from persistence.testing import db_session
code = "ZZCLR1"
with db_session() as db:
db.accounts.create(account=code, name="Clear Probe")
removed = db.accounts.clear(min_account=code)
assert removed >= 1
assert db.accounts.get(account=code) is None
=== END AC accounts-clear ===
=== AC categories-create ===
Intent: categories.create stores a row and returns the declared Output, which a separate get reads back.
from persistence.testing import db_session
def f(row, name):
return row[name] if isinstance(row, dict) else getattr(row, name)
code = "ZZCCR1"
text = "Create Probe"
with db_session() as db:
out = db.categories.create(category=code, description=text)
assert f(out, "category") == code
assert f(out, "description") == text
back = db.categories.get(category=code)
assert back is not None
assert f(back, "description") == text
=== END AC categories-create ===
=== AC categories-get ===
Intent: categories.get returns the stored row for an existing code and None for an absent one.
from persistence.testing import db_session
def f(row, name):
return row[name] if isinstance(row, dict) else getattr(row, name)
code = "ZZCGET1"
text = "Get Probe"
with db_session() as db:
db.categories.create(category=code, description=text)
row = db.categories.get(category=code)
assert row is not None
assert f(row, "category") == code
assert f(row, "description") == text
assert db.categories.get(category="ZZCGETNONE") is None
=== END AC categories-get ===
=== AC categories-update ===
Intent: categories.update changes the description and the change is visible on a separate read.
from persistence.testing import db_session
def f(row, name):
return row[name] if isinstance(row, dict) else getattr(row, name)
code = "ZZCUPD1"
before = "Before Text"
after = "After Text"
with db_session() as db:
db.categories.create(category=code, description=before)
out = db.categories.update(category=code, description=after)
assert out is not None
assert f(out, "description") == after
back = db.categories.get(category=code)
assert f(back, "description") == after
=== END AC categories-update ===
=== AC categories-delete ===
Intent: categories.delete removes the row so a later get finds nothing.
from persistence.testing import db_session
def f(row, name):
return row[name] if isinstance(row, dict) else getattr(row, name)
code = "ZZCDEL1"
with db_session() as db:
db.categories.create(category=code, description="Delete Probe")
out = db.categories.delete(category=code)
assert out is not None
assert f(out, "category") == code
assert db.categories.get(category=code) is None
=== END AC categories-delete ===
=== AC categories-list ===
Intent: categories.list returns rows ordered by category code ascending; two codes created in reverse order appear in sorted order.
from persistence.testing import db_session
def f(row, name):
return row[name] if isinstance(row, dict) else getattr(row, name)
codes = ["ZZCLA2", "ZZCLA1"]
with db_session() as db:
for c in codes:
db.categories.create(category=c, description="List " + c)
rows = db.categories.list()
seen = [f(r, "category") for r in rows if f(r, "category") in codes]
assert seen == sorted(codes)
allcodes = [f(r, "category") for r in rows]
assert allcodes == sorted(allcodes)
=== END AC categories-list ===
=== AC categories-clear ===
Intent: categories.clear removes categories whose code is at or above the bound, reports a positive count, and leaves none readable.
from persistence.testing import db_session
code = "ZZCCLR1"
with db_session() as db:
db.categories.create(category=code, description="Clear Probe")
removed = db.categories.clear(min_category=code)
assert removed >= 1
assert db.categories.get(category=code) is None
=== END AC categories-clear ===
=== AC transactions-create ===
Intent: transactions.create stores a signed integer-cents row under the supplied id and returns it, and a separate get reads every column back.
from persistence.testing import db_session
def f(row, name):
return row[name] if isinstance(row, dict) else getattr(row, name)
acct, cat = "ZZTA1", "ZZTC1"
tid = 900000001
day = "2026-05-01"
cents = -1234
note = "create probe"
with db_session() as db:
db.accounts.create(account=acct, name="Txn Account")
db.categories.create(category=cat, description="Txn Category")
out = db.transactions.create(txn_id=tid, date=day, account=acct, category=cat, amount=cents, memo=note)
assert f(out, "txn_id") == tid
back = db.transactions.get(txn_id=tid)
assert back is not None
assert f(back, "date") == day
assert f(back, "account") == acct
assert f(back, "category") == cat
assert f(back, "amount") == cents
assert f(back, "memo") == note
=== END AC transactions-create ===
=== AC transactions-get ===
Intent: transactions.get returns the stored row for an existing id and None for an absent id.
from persistence.testing import db_session
def f(row, name):
return row[name] if isinstance(row, dict) else getattr(row, name)
acct, cat = "ZZTA2", "ZZTC2"
tid = 900000002
cents = 5050
with db_session() as db:
db.accounts.create(account=acct, name="Txn Account")
db.categories.create(category=cat, description="Txn Category")
db.transactions.create(txn_id=tid, date="2026-05-02", account=acct, category=cat, amount=cents, memo="")
row = db.transactions.get(txn_id=tid)
assert row is not None
assert f(row, "amount") == cents
assert db.transactions.get(txn_id=tid + 1000) is None
=== END AC transactions-get ===
=== AC transactions-update ===
Intent: transactions.update changes only the amount and the change is visible on a separate read.
from persistence.testing import db_session
def f(row, name):
return row[name] if isinstance(row, dict) else getattr(row, name)
acct, cat = "ZZTA3", "ZZTC3"
tid = 900000003
day = "2026-05-03"
note = "amend probe"
old, new = 1000, 2500
with db_session() as db:
db.accounts.create(account=acct, name="Txn Account")
db.categories.create(category=cat, description="Txn Category")
db.transactions.create(txn_id=tid, date=day, account=acct, category=cat, amount=old, memo=note)
out = db.transactions.update(txn_id=tid, amount=new)
assert out is not None
assert f(out, "amount") == new
back = db.transactions.get(txn_id=tid)
assert f(back, "amount") == new
assert f(back, "date") == day
assert f(back, "memo") == note
assert f(back, "account") == acct
=== END AC transactions-update ===
=== AC transactions-delete ===
Intent: transactions.delete removes the row so a later get finds nothing.
from persistence.testing import db_session
def f(row, name):
return row[name] if isinstance(row, dict) else getattr(row, name)
acct, cat = "ZZTA4", "ZZTC4"
tid = 900000004
with db_session() as db:
db.accounts.create(account=acct, name="Txn Account")
db.categories.create(category=cat, description="Txn Category")
db.transactions.create(txn_id=tid, date="2026-05-04", account=acct, category=cat, amount=700, memo="")
out = db.transactions.delete(txn_id=tid)
assert out is not None
assert f(out, "txn_id") == tid
assert db.transactions.get(txn_id=tid) is None
=== END AC transactions-delete ===
=== AC transactions-list ===
Intent: transactions.list filters by account and inclusive date range and returns rows by txn_id ascending; rows outside the range or on another account are excluded.
from persistence.testing import db_session
def f(row, name):
return row[name] if isinstance(row, dict) else getattr(row, name)
acct, other, cat = "ZZTA5", "ZZTA6", "ZZTC5"
rows_in = [(900000012, "2026-06-10"), (900000011, "2026-06-05")]
outside = (900000013, "2026-07-01")
with db_session() as db:
db.accounts.create(account=acct, name="Txn Account")
db.accounts.create(account=other, name="Other Account")
db.categories.create(category=cat, description="Txn Category")
for tid, day in rows_in:
db.transactions.create(txn_id=tid, date=day, account=acct, category=cat, amount=100, memo="")
db.transactions.create(txn_id=outside[0], date=outside[1], account=acct, category=cat, amount=100, memo="")
db.transactions.create(txn_id=900000014, date="2026-06-07", account=other, category=cat, amount=100, memo="")
got = db.transactions.list(account=acct, start_date="2026-06-01", end_date="2026-06-30")
ids = [f(r, "txn_id") for r in got]
assert ids == sorted(t for t, _ in rows_in)
assert all(f(r, "account") == acct for r in got)
=== END AC transactions-list ===
=== AC transactions-clear ===
Intent: transactions.clear removes transactions at or above the bound, reports a positive count, and leaves none readable.
from persistence.testing import db_session
acct, cat = "ZZTA7", "ZZTC7"
tid = 900000021
with db_session() as db:
db.accounts.create(account=acct, name="Txn Account")
db.categories.create(category=cat, description="Txn Category")
db.transactions.create(txn_id=tid, date="2026-05-07", account=acct, category=cat, amount=300, memo="")
removed = db.transactions.clear(min_txn_id=tid)
assert removed >= 1
assert db.transactions.get(txn_id=tid) is None
=== END AC transactions-clear ===
## User Acceptance
- None.
## Guardrails
- Only the generated `persistence/` package opens a database driver; application code calls `db.<table>.<operation>(...)`.
- Amounts are integer cents in every column, DTO, and caller; floating point is never used for money.
- Counts, balances, and the next `txn_id` are computed by callers from `list` results, never hardcoded.
- Acceptance criteria never apply DDL, replace DATABASE_URL or DATABASE_PATH, or assume an empty store.
## Operation Surface
Generated by Drydock from this declaration; it is the complete persistence surface. Each operation is a method `db.<table>.<name>(field=value, ...)` (Go: `db.<Table>.<Name>(ctx, <Table><Name>Input{...})`) taking exactly its Input fields. Match fields are required and compared with their column, joined with AND: a bare field by equality with the column of its name, a term `<column> <op> <field>` by `=`, `<`, `<=`, `>`, or `>=`. A field marked `?` may be omitted: an omitted `list` filter or bound does not constrain, and an `update` sets only the fields supplied. A `list` with an Order returns its rows in that order, and in no stated order otherwise. No other operator, no OR, no join, and no SQL exists. An operation reaches one row when its equality Match covers a unique key, and many rows otherwise. `upsert` inserts the row its Match identifies, or replaces that row's Set columns when it exists, in one atomic statement. The SQL is what runs, in SQLite form. An operation not listed raises `UnknownOperation`; to reach the store differently, declare a pattern in `DATABASE.md`. Contract is the operation's fingerprint: it changes only when the call, its Kind, Match, rows, or a field's name or caller type changes, never for a length or nullability change.
### `accounts`
Unique keys: (`account`)
#### `db.accounts.create` — FEATURE-ACCOUNT-001
| Kind | Rows | Match | Sets | Contract |
|---|---|---|---|---|
| create | 1 | — | `account`, `name` | `45a6aa167489` |
- Input: `{"account": "str", "name": "str"}`
- Output: `{"account": "str", "name": "str"}`
```sql
INSERT INTO "accounts" ("account", "name") VALUES (?, ?);
SELECT "account", "name" FROM "accounts" WHERE "account" = ?;
```
#### `db.accounts.get` — FEATURE-ACCOUNT-002
| Kind | Rows | Match | Sets | Contract |
|---|---|---|---|---|
| get | 0..1 | `account` | — | `a2255e907183` |
- Input: `{"account": "str"}`
- Output: `{"account": "str", "name": "str"} | null`
```sql
SELECT "account", "name" FROM "accounts" WHERE "account" = ?;
```
#### `db.accounts.update` — FEATURE-ACCOUNT-003
| Kind | Rows | Match | Sets | Contract |
|---|---|---|---|---|
| update | 0..1 | `account` | `name` | `a1a833fefc97` |
- Input: `{"account": "str", "name": "str?"}`
- Output: `{"account": "str", "name": "str"} | null`
```sql
UPDATE "accounts" SET "name" = ? WHERE "account" = ?;
SELECT "account", "name" FROM "accounts" WHERE "account" = ?;
```
#### `db.accounts.delete` — FEATURE-ACCOUNT-004
| Kind | Rows | Match | Sets | Contract |
|---|---|---|---|---|
| delete | 0..1 | `account` | — | `f763931ee295` |
- Input: `{"account": "str"}`
- Output: `{"account": "str"} | null`
```sql
DELETE FROM "accounts" WHERE "account" = ?;
```
#### `db.accounts.list` — FEATURE-ACCOUNT-005
| Kind | Rows | Match | Sets | Contract |
|---|---|---|---|---|
| list | 0..n | — | — | `5411c50ca594` |
- Input: `{}`
- Output: `[{"account": "str", "name": "str"}]`
- Order: `account` asc
```sql
SELECT "account", "name" FROM "accounts" ORDER BY "account" ASC;
```
#### `db.accounts.clear` — FEATURE-ACCOUNT-006
| Kind | Rows | Match | Sets | Contract |
|---|---|---|---|---|
| delete | 0..n | `account >= min_account` | — | `09979feb22f8` |
- Input: `{"min_account": "str"}`
- Output: `"int" (rows changed)`
```sql
DELETE FROM "accounts" WHERE "account" >= ?;
```
### `categories`
Unique keys: (`category`)
#### `db.categories.create` — FEATURE-CATEGORY-001
| Kind | Rows | Match | Sets | Contract |
|---|---|---|---|---|
| create | 1 | — | `category`, `description` | `186704bcd90a` |
- Input: `{"category": "str", "description": "str"}`
- Output: `{"category": "str", "description": "str"}`
```sql
INSERT INTO "categories" ("category", "description") VALUES (?, ?);
SELECT "category", "description" FROM "categories" WHERE "category" = ?;
```
#### `db.categories.get` — FEATURE-CATEGORY-002
| Kind | Rows | Match | Sets | Contract |
|---|---|---|---|---|
| get | 0..1 | `category` | — | `8752dd8bcd81` |
- Input: `{"category": "str"}`
- Output: `{"category": "str", "description": "str"} | null`
```sql
SELECT "category", "description" FROM "categories" WHERE "category" = ?;
```
#### `db.categories.update` — FEATURE-CATEGORY-003
| Kind | Rows | Match | Sets | Contract |
|---|---|---|---|---|
| update | 0..1 | `category` | `description` | `fc6f1a18ac1f` |
- Input: `{"category": "str", "description": "str?"}`
- Output: `{"category": "str", "description": "str"} | null`
```sql
UPDATE "categories" SET "description" = ? WHERE "category" = ?;
SELECT "category", "description" FROM "categories" WHERE "category" = ?;
```
#### `db.categories.delete` — FEATURE-CATEGORY-004
| Kind | Rows | Match | Sets | Contract |
|---|---|---|---|---|
| delete | 0..1 | `category` | — | `6ccf180c8284` |
- Input: `{"category": "str"}`
- Output: `{"category": "str"} | null`
```sql
DELETE FROM "categories" WHERE "category" = ?;
```
#### `db.categories.list` — FEATURE-CATEGORY-005
| Kind | Rows | Match | Sets | Contract |
|---|---|---|---|---|
| list | 0..n | — | — | `0ed3c940a74f` |
- Input: `{}`
- Output: `[{"category": "str", "description": "str"}]`
- Order: `category` asc
```sql
SELECT "category", "description" FROM "categories" ORDER BY "category" ASC;
```
#### `db.categories.clear` — FEATURE-CATEGORY-006
| Kind | Rows | Match | Sets | Contract |
|---|---|---|---|---|
| delete | 0..n | `category >= min_category` | — | `e90b3a0108bb` |
- Input: `{"min_category": "str"}`
- Output: `"int" (rows changed)`
```sql
DELETE FROM "categories" WHERE "category" >= ?;
```
### `transactions`
Unique keys: (`txn_id`)
#### `db.transactions.create` — FEATURE-TXN-001
| Kind | Rows | Match | Sets | Contract |
|---|---|---|---|---|
| create | 1 | — | `txn_id`, `date`, `account`, `category`, `amount`, `memo` | `3bcba494ab8e` |
- Input: `{"txn_id": "int", "date": "str", "account": "str", "category": "str", "amount": "int", "memo": "str"}`
- Output: `{"txn_id": "int", "date": "str", "account": "str", "category": "str", "amount": "int", "memo": "str"}`
```sql
INSERT INTO "transactions" ("txn_id", "date", "account", "category", "amount", "memo") VALUES (?, ?, ?, ?, ?, ?);
SELECT "txn_id", "date", "account", "category", "amount", "memo" FROM "transactions" WHERE "txn_id" = ?;
```
#### `db.transactions.get` — FEATURE-TXN-002
| Kind | Rows | Match | Sets | Contract |
|---|---|---|---|---|
| get | 0..1 | `txn_id` | — | `fba288e083ca` |
- Input: `{"txn_id": "int"}`
- Output: `{"txn_id": "int", "date": "str", "account": "str", "category": "str", "amount": "int", "memo": "str"} | null`
```sql
SELECT "txn_id", "date", "account", "category", "amount", "memo" FROM "transactions" WHERE "txn_id" = ?;
```
#### `db.transactions.update` — FEATURE-TXN-003
| Kind | Rows | Match | Sets | Contract |
|---|---|---|---|---|
| update | 0..1 | `txn_id` | `amount` | `bc96284669f5` |
- Input: `{"txn_id": "int", "amount": "int?"}`
- Output: `{"txn_id": "int", "date": "str", "account": "str", "category": "str", "amount": "int", "memo": "str"} | null`
```sql
UPDATE "transactions" SET "amount" = ? WHERE "txn_id" = ?;
SELECT "txn_id", "date", "account", "category", "amount", "memo" FROM "transactions" WHERE "txn_id" = ?;
```
#### `db.transactions.delete` — FEATURE-TXN-004
| Kind | Rows | Match | Sets | Contract |
|---|---|---|---|---|
| delete | 0..1 | `txn_id` | — | `dc144d362632` |
- Input: `{"txn_id": "int"}`
- Output: `{"txn_id": "int"} | null`
```sql
DELETE FROM "transactions" WHERE "txn_id" = ?;
```
#### `db.transactions.list` — FEATURE-TXN-005
| Kind | Rows | Match | Sets | Contract |
|---|---|---|---|---|
| list | 0..n | `account`, `category`, `date >= start_date`, `date <= end_date` | — | `634fb73a2186` |
- Input: `{"account": "str?", "category": "str?", "start_date": "str?", "end_date": "str?"}`
- Output: `[{"txn_id": "int", "date": "str", "account": "str", "category": "str", "amount": "int", "memo": "str"}]`
- Order: `txn_id` asc
```sql
SELECT "txn_id", "date", "account", "category", "amount", "memo" FROM "transactions" WHERE "account" = ? AND "category" = ? AND "date" >= ? AND "date" <= ? ORDER BY "txn_id" ASC;
```
#### `db.transactions.clear` — FEATURE-TXN-006
| Kind | Rows | Match | Sets | Contract |
|---|---|---|---|---|
| delete | 0..n | `txn_id >= min_txn_id` | — | `fcf47c9a7749` |
- Input: `{"min_txn_id": "int"}`
- Output: `"int" (rows changed)`
```sql
DELETE FROM "transactions" WHERE "txn_id" >= ?;
```
</pblock>
<pblock label="Plan continuation" kind="continuation">
Continuation
Stage 1 is complete. Drydock accepted and froze the complete TOPOLOGY.md declaration before starting this Blueprint-authoring stage. The full planning context above remains authoritative.
The ledger below states exactly what Drydock accepted, what is still missing, and what came back defective. Treat it as fact. This batch starts a new session. Earlier Blueprint responses and reasoning are not available. Use the frozen topology, decisions, ledger, and DATABASE_compact.md or the DATABASE.md seed when supplied.
Your job
Emit exactly the artifacts in the ledger's Current batch, in the stated order. Nothing else.
- Do not re-emit an accepted artifact. Drydock retains its content.
- Within this response, a complete replacement block for the same filename updates its earlier
draft. The last block receives normal validation; a partial replacement is not accepted.
DATABASE.mdis authored in its own batch, complete, and then frozen. When it is the Current
batch, start from the supplied seed and declare every table and every repository operation the frozen topology's stories need. After it is accepted, later batches receive it as DATABASE_compact.md; cite its access patterns and never emit DATABASE.md again.
- Do not emit a deferred artifact. Drydock supplies it in a later bounded batch.
- Do not emit or amend
TOPOLOGY.md; Stage 1 is complete and frozen. - Do not emit
DECISIONS.json; it was captured with the topology in Stage 1. - Do not restate your plan, summarize progress, apologize, or explain the interruption.
- You have no tools and nobody answers questions during planning. Never ask a question,
request a file, or offer options. Record each open point under the affected Blueprint's ## Questions and emit the batch. Prose reaches no one: a response without artifacts is rejected and the same batch is asked again.
- A Current-batch Blueprint you genuinely cannot author is reported in
BLUEPRINT_BLOCKED.txt
(see Blocked Blueprints), and the rest of the batch is still emitted.
- Do not emit
MANIFEST.md; Drydock serializes it from the declaration. - Use exactly the same delimited block format as before, including the mandatory
=== END ARTIFACT === line for every file. The name is typed once, at the open; the closing delimiter is that constant token and never carries the name.
- An artifact listed as defective must be emitted again in full, corrected. A partial or patched
version is not accepted.
- Emit each missing artifact under the exact filename the ledger names. A filename that does not
match its declaration cannot be accepted.
- Each typed Blueprint includes
## Programmatic Acceptance,## User Acceptance, and
## Guardrails, in that order. Preserve applicable source constraints under Guardrails; use - None. only when User Acceptance or Guardrails has no applicable content.
- Compute numeric expectations from fixture inputs using the source formula and rounding;
never guess formatted decimal answers. Put Requires declarations inside each AC block. Before returning, count the open and close artifact lines; counts match, and the final nonblank line is exactly === END ARTIFACT ===, including its trailing equals signs. Derive ordered expectations from fixture inputs and declared sort keys, including tie breakers. Import every referenced name inside each AC, declare every external import and test transport, and use a bounded endpoint/port readiness probe for server-start criteria. Cite only owned or shared database patterns and derive their DTO fields from DATABASE.md.
- Acceptance observes the delivered application through its declared interfaces. Never replace
it with a local implementation or a standalone language expression inside the criterion. For a Go CLI report criterion, use drydock_go.cli_runner, assert its exit code, parse its CSV output, and compare the observed fields with expectations derived from the supplied fixture inputs. The application need not exist during planning; author its invocation for Build to execute.
- A story's criteria exercise only capabilities available in its own build block or earlier.
Follow the frozen topology's Provides and dependency order. Test lower-level functions through their own interfaces; for Go use drydock_go.run_test with an exact native test name. Keep CLI integration criteria on a later story after every command they invoke exists. A filter story that precedes report implementations tests filtering directly; the later reports also verify the filters through their CLI output. Never replace product execution with a local substitute, drop end-to-end coverage, or introduce a dependency cycle to make an early gate pass.
Acceptance authoring review
For each criterion, identify the delivered interface, required setup, source-derived expectation and failure diagnostics before writing code. Keep imports and tooling declarations inside the criterion. Close it with === END AC <id> ===; that token never closes an artifact.
For staged corpus checks, follow BLUEPRINTS_CONTRACT.md: declare Suite: scoped, a supported listing Probe: and its Probe Count: protocol. Use literal runner arguments or literal string bindings, including the product and corpus paths. With import os, canonical os.path.abspath("program") is also supported. Do not construct probe arguments with getcwd f-strings, dynamic imports or runtime expressions. Drydock runs listing probes; you author them without tools and never invent counts. Print captured output before asserting the runner's exit.
A nonempty listing proves selection, not prerequisite availability. Inspect the selected cases in the supplied source: a section name can include interactions with capabilities scheduled later. Preserve the current batch obligations repeated in the ledger, especially instructions assigning cross-feature cases to a later integration. Do not turn a whole section into an early gate merely because its title matches the story. Select only the supported cases using documented runner options. If the runner cannot express that boundary, test this story's own interface directly without copying corpus examples, and run the mixed section on a later integration after all its required capabilities exist. Keep every deferred case covered there before the terminal gate. Never make the earlier story implement the later feature or introduce a dependency cycle.
The frozen topology is the availability contract. A criterion must not require an undeclared later capability merely because the same executable eventually exposes it. Author direct checks for this story's interface and preserve cross-feature coverage on its declared integration story.
Blocked Blueprints
Report a Blueprint only when its inputs contradict each other, or do not define the behavior it must specify, and no reasonable assumption recorded under ## Questions can bridge the gap.
Never report: having no tools, response length, accepted Blueprints being absent from this context (author against the frozen topology's Provides lines), or an input that is present above. Drydock checks every claim against this context and returns its finding to the next batch as Prior run error type and Prior run error details. Answer each refuted claim by authoring the Blueprint.
Emit one BLUEPRINT_BLOCKED.txt block after the Blueprints you did author, with one entry per blocked Blueprint:
=== BEGIN ARTIFACT BLUEPRINT_BLOCKED.txt ===
Blueprint: {Current-batch filename}
Error type: {missing-input|conflict|insufficient-specification|other}
Cited input: {exact input file and section}
Details:
- {what the cited input says or lacks, and why it blocks this Blueprint}
Required action:
- {the product decision or source correction that unblocks it}
=== END ARTIFACT ===
Budget
Author the Current batch one Blueprint at a time. For each Blueprint, emit its opening delimiter, its complete file body, and its matching closing delimiter. Only after the closing delimiter is written may the next Blueprint's opening delimiter be emitted.
A whole artifact is progress; a truncated one is not. Never pre-emit opening delimiters, outline several files at once, nest one artifact inside another, or use one closing delimiter for several files. If the whole Current batch cannot fit, finish and close the current artifact, then end the response. Drydock retries every unproduced artifact from the same batch.
The only legal sequence is:
=== BEGIN ARTIFACT FIRST-NAME ===
{complete first file}
=== END ARTIFACT ===
=== BEGIN ARTIFACT SECOND-NAME ===
{complete second file}
=== END ARTIFACT ===
Ledger
Accepted (16) — already held, do not re-emit: ARCHITECTURE.md DATABASE.md FEATURE-AccountAdd.md FEATURE-AccountDelete.md FEATURE-AccountGet.md FEATURE-AccountRename.md FEATURE-BalanceRule.md FEATURE-CliEntry.md FEATURE-InitCount.md FEATURE-LoadAccounts.md FEATURE-LoadCategories.md FEATURE-LoadCsvReader.md FEATURE-LoadTransactions.md FEATURE-TxnGet.md FEATURE-TxnPost.md FEATURE-Validation.md
Current batch (5) — emit exactly these, in this order: feature-txn-amend -> FEATURE-TxnAmend.md feature-txn-delete -> FEATURE-TxnDelete.md feature-transfer -> FEATURE-Transfer.md feature-report-balances -> FEATURE-ReportBalances.md feature-report-categories -> FEATURE-ReportCategories.md
Current batch obligations — preserve in behavior and acceptance: feature-txn-amend -> FEATURE-TxnAmend.md depends: feature-txn-post provides: ledger txn amend consumes: ledger_core.transactions, ledger_core.validation, ledger_core.balances, cli.registry instructions: Absent id exits 4. Validate the amount, check the resulting balance of the transaction's account (stored sum minus old amount plus new) is non-negative, then update only the amount and print the row. A rejection exits 3 and leaves the original amount. feature-txn-delete -> FEATURE-TxnDelete.md depends: feature-txn-post provides: ledger txn delete consumes: ledger_core.transactions, ledger_core.balances, cli.registry instructions: Absent id exits 4. Check that removing the row leaves its account balance non-negative (else exit 3, row kept), then delete and print deleted and the id. feature-transfer -> FEATURE-Transfer.md depends: feature-txn-post provides: ledger transfer consumes: ledger_core.transactions, ledger_core.validation, ledger_core.balances, cli.registry instructions: Both accounts must exist and differ; the amount is positive; the date is valid; the TRANSFER category must exist. Check the source balance after the debit before any write. Insert the outgoing row (-amount, memo transfer to <to>) with id max+1 and the incoming row (+amount, memo transfer from <from>) with the next id, atomically, and print both rows. A rejection stores neither. feature-report-balances -> FEATURE-ReportBalances.md depends: foundation-cli, feature-validation provides: ledger report balances consumes: ledger_core.money, cli.registry instructions: Header account,name,transactions,balance; one row per account ordered by code, then TOTAL,,<count>,<sum>. All values computed from queries; amounts formatted from integer cents. feature-report-categories -> FEATURE-ReportCategories.md depends: foundation-cli, feature-validation provides: ledger report categories consumes: ledger_core.money, cli.registry instructions: Header category,description,transactions,inflow,outflow,net; every category ordered by code, including those with no transactions (zero values), then the TOTAL row. inflow is the sum of positive amounts, outflow the sum of absolute negative amounts, net inflow minus outflow.
Deferred (4) — Drydock will provide later batches; do not emit them now. </pblock>