Run artifact

evidence/prompts/20261020.193838.057Z_layerstesting_build_codex.prompt.md

System Instructions

This prompt is divided into three sections:

  1. System Instructions (this section) — structural orientation only. Do not treat this

section as task input.

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

<pblock> tags. Two block types:

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

rules, instructions, or group headers.

  1. Agent Task — begins with the heading # Agent Task. Defines your persona, constraints,

and required outputs. Read all input context before acting on this section.

Input Context

<pblock label="Build block job" kind="job">

Build block job

</pblock>

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

Stories in this block

</pblock>

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

Files on disk in the build directory

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

</pblock>

<pblock label="Missing context files" kind="section"> Missing context files (named by the plan but not found):

</pblock>

COMPASS - Target Orientation

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

# COMPASS: LayersTesting

## Compass

Build a command-line cash ledger, an executable named `ledger` at the application root, as
described in `sources/INSTRUCTIONS.md`. It keeps accounts, categories, and cash transactions in a
relational database reached only through the shipped persistence library, rejects a failing command
before it writes, enforces non-negative balances, and reports balances, category totals, and monthly totals.

Correctness is measured by `sources/run.sh`: 43 checks of exit code and standard output against
known answers computed from the seed files. The goal is every check passing.

## Constraints

- Implement in the language and database named under `## Stack` in `sources/INSTRUCTIONS.md`.
- Provide an executable named `ledger` at the application root, invoked as `./ledger <command>`.
- Read the database location from `DATABASE_URL`, then `DATABASE_PATH`, then `data/app.db`.
- Store amounts as integer cents.
- Check every command in full before its first write.
- Run without network access other than to a PostgreSQL server named by `DATABASE_URL`.
- Diagnostics go to standard error and are never compared.

## Guardrails

- Do not modify, rewrite, regenerate, or substitute any file under `sources/`.
- Do not read `sources/run.sh` or any seed file from application code. Seed files reach the
  database only through `ledger load`.
- Do not hardcode a report row, a count, or a total. Every value comes from a query.
- Do not open a database driver outside the shipped persistence library.
- Do not use floating point for money at any layer.

## Verification Protocol

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

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

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

</pblock>

STACK - Technology HOW

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

<!-- Compacted from Rigging/languages/python/python.md sha256=fe344456a351e3237cfe3bae2408a69758d401430b935f60c15f91b9a97e8016 on 2026-10-18 by Rigging maintenance -->

## Foundation Contract

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

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

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

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

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

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

## Consumer Rules

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

</pblock>

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

# Command-Line Application

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

Technology reference. This file does not change between projects.

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

---

## Foundation Contract

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

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

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

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

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

# conftest.py
import pytest
from cli import testing

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

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

---

## 1. Directory Layout

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

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

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

---

## 2. Entry Point and Exit Codes

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

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

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

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

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

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

---

## 3. Parsing Is Separate From Behavior

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

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

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

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

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

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

---

## 4. Cross-Platform Launchers

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

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

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

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

sys.exit(main())
```

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

---

## 5. Output and Streams

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

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

---

## 6. Testing Without a Process

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

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

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

---

## Checklist

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

</pblock>

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

<!-- Compacted from Rigging/stack/persistence.md sha256=faaae951cc9641b1a3799eb0a46030514bc49afa4ba8f9ca71949fa3861addbd on 2026-10-20 by drydock rigging compact — regenerate with: drydock rigging compact --include-file {rel_source} -->

# Persistence & Service Encapsulation — Contract Surface

## Persistence

### Rule: typed-persistence-boundary

All persistence and external-service access goes through typed encapsulation classes.

Constraints: Route, feature, and business-logic code must not execute raw SQL, read `os.environ`, open application files, or import cloud SDKs.

### function_name

`open_database(dsn)` opens the generated database abstraction selected by the DSN.

| Input | Type |
|---|---|
| `dsn` | `str` |

Returns a `Database` with one attribute per declared table.

Constraints: The generated persistence package is derived from `DATABASE.md`; callers must not create repositories, DAOs, ORM models, session factories, migrations, or alternate storage paths.

### Database.table.get

Retrieves one row by identifier.

| Input | Type |
|---|---|
| `id` | declared identifier type |

Returns a frozen dataclass or `None`.

### Database.table.list

Lists rows matching declared access-pattern fields.

Returns a list of frozen row dataclasses.

### Database.table.create

Creates a row using exactly the declared operation input fields.

Returns the new record identifier.

### Database.table.update

Updates a row using exactly the declared operation input fields.

Returns no specified value.

### Database.table.delete

Deletes a row by the declared operation input fields.

Returns no specified value.

### Rule: declared-operation-surface

Each declared table exposes only the methods specified by its `DATABASE.md` access patterns. Unsupported verbs raise `UnknownOperation` naming the granted operations.

### Rule: database-lifecycle

Callers construct one `Database`, share it, and call methods synchronously. Returned rows contain no connection state.

Constraints: `schema.sql` is applied once during the DATABASE build step. Application startup must not create or alter schema.

### Rule: generated-engine-access

Both SQLite and PostgreSQL engines are available at runtime and selected from the DSN.

Constraints: Code outside `persistence/` must not import `sqlite3` or `psycopg`, and nothing under `persistence/` is edited by hand.

## Configuration

### Config.load

Loads and validates environment configuration once at startup.

Returns a frozen `Config`.

| Field | Type | Source | Default |
|---|---|---|---|
| `secret_key` | `str` | `SECRET_KEY` | required |
| `database_path` | `str` | `DATABASE_PATH` | `data/app.db` |
| `port` | `int` | `APP_PORT` | `5001` |
| `debug` | `bool` | `APP_DEBUG == "1"` | `False` |

Constraints: Missing required environment variables raise `RuntimeError`. Malformed typed values fail during startup. No code other than `Config` reads `os.environ`; no Dev/Prod/Test subclasses are permitted.

## File Storage

### FileStore.__init__

Creates a file store rooted at the supplied directory.

| Input | Type |
|---|---|
| `root` | `str` |

### FileStore.read

Reads a UTF-8 application file by name.

| Input | Type |
|---|---|
| `name` | `str` |

Returns `str`.

### FileStore.write

Writes UTF-8 application data by name.

| Input | Type |
|---|---|
| `name` | `str` |
| `data` | `str` |

Returns `None`.

### FileStore.list

Lists application files matching a glob pattern.

| Input | Type | Default |
|---|---|---|
| `pattern` | `str` | `"*"` |

Returns `list[str]`.

### Rule: file-access-boundary

Only `FileStore` opens application files or uses file utilities.

Constraints: Callers must not construct application paths or call `open()` or `shutil` directly. Path-traversal validation and atomic writes are required in `FileStore`.

## External Services

### ServiceClient.__init__

Initializes a service wrapper with a backend handle and optional logger name.

| Input | Type |
|---|---|
| `backend` | backend object |
| `name` | `str \| None` |

### ServiceClient._guard

Executes a backend operation, logs failures, and re-raises exceptions.

| Input | Type |
|---|---|
| `op` | callable |
| `*args` | operation arguments |
| `**kwargs` | operation keyword arguments |

Returns the operation result.

### MessageBus.publish

Publishes a payload to a topic through the wrapped backend.

| Input | Type |
|---|---|
| `topic` | `str` |
| `payload` | `dict` |

Returns `str`.

### MessageBus.subscribe

Registers a handler for a topic through the wrapped backend.

| Input | Type |
|---|---|
| `topic` | `str` |
| `handler` | callable |

Returns `None`.

### Rule: service-wrapper-boundary

Every external-service wrapper extends `ServiceClient`, exposes typed methods, and does not expose the SDK client.

Constraints: Cloud SDK imports must remain inside their service wrappers.

</pblock>

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

# SQLite

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

Technology reference. This file does not change between projects.

Prerequisite: `stack/persistence.md`

---

## Foundation Contract

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

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

### How is this engine configured and initialized?

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

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

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

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

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

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

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

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

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

# application code
from persistence import open_database

db = open_database(config.database_path)

# a criterion
from persistence.testing import db_session

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

# conftest.py
import pytest
from persistence import testing

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

`db_session()` opens `dsn`, or a fresh temporary SQLite store, with `schema.sql` applied. A
criterion imports it from `persistence.testing` and uses it as a context manager —
`with db_session() as db:` — against the built database layer, without pytest. The pytest suite
receives the same store through the `conftest.py` fixture. Neither opens a connection of its
own, and a criterion never imports `sqlite3`.

---

## You do not write the access layer

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

**By language**

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

## Role

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

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

## What it enforces

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

## What it ignores

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

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

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

## Guardrails

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

</pblock>

CONTEXT - Read-Only Support

<pblock filename="ARCHITECTURE_compact.md" role="context" path="/mnt/c/Users/barlo/projects/drydock/uat/LayersTesting/runs/20261020.191708/workspace/targets/LayersTesting/blueprint/ARCHITECTURE_compact.md">

<!-- Compacted from ARCHITECTURE.md sha256=720369e5d325d4742ec589bc3a3c05da95245579b7fb57132fcecddad782b7e6 on 2026-10-20 by drydock build agent -->

Expose `cli.main(argv)` and `persistence.open_database(dsn)`. Use boundaries for configuration, validation/services, persistence callers, reporting, and CLI dispatch. Resolve databases via `DATABASE_URL`, `DATABASE_PATH`, then `data/app.db`. Keep all monetary values as integer cents; application code must not access database drivers directly. CLI exit codes: 0 success, 1 operational failure, 2 usage error, 3 rejected input/invariant violation, 4 absent record.

</pblock>

<pblock filename="DATABASE_compact.md" role="context" path="/mnt/c/Users/barlo/projects/drydock/uat/LayersTesting/runs/20261020.191708/workspace/targets/LayersTesting/blueprint/DATABASE_compact.md">

<!-- Compacted from DATABASE.md sha256=fce590c2ef857d4ed0e9d1ba21fdfcbe1ec8cde7fea03986bcae3670b48a70f3 on 2026-10-20 by drydock build agent -->

Relational ledger persistence uses `DATABASE_URL`, then `DATABASE_PATH`, then `data/app.db`. Tables: `accounts(account VARCHAR(12) PK, name VARCHAR(40))`; `categories(category VARCHAR(12) PK, description VARCHAR(40))`; `transactions(txn_id INTEGER PK, date VARCHAR(10), account/category foreign keys, amount INTEGER cents, memo VARCHAR(60))`. Foreign keys are enforced; initialization recreates all tables empty; rejected operations preserve existing rows; callers use only `persistence.open_database`.

</pblock>

IMPLEMENTS - Authoritative Step Specifications

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

</pblock>

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

# FEATURE: Account Transfers

| Field       | Value |
|-------------|-------|
| Version     | 20261020 V1 |
| Description | Execute atomic two-row transfers between ledger accounts. |
| Depends On  | FEATURE-Balance-Invariant.md, FEATURE-Transaction-Management.md |
| Provides    | transfer |
| Consumes    | command dispatch, transactions.create, accounts.get, categories.get, prospective balance validation |

## Purpose

A transfer moves a positive amount from one existing account to another by creating two consecutive transactions in category `TRANSFER`.

## Workflow

1. Validate both account codes, account existence, distinctness, positive amount, date, and the `TRANSFER` category.
2. Calculate both prospective balances before writing.
3. Create the outgoing row, then the incoming row, in one transaction.
4. Emit both transaction rows in identifier order.
5. Roll back completely on any rejection.

The outgoing memo is `transfer to <destination>` and the incoming memo is `transfer from <source>`.

## Programmatic Acceptance

=== AC transfers-success ===
Intent: A valid transfer creates two persisted transaction rows and succeeds.
from cli.testing import cli_runner
from persistence.testing import db_session
import csv
import io
import os
import tempfile

with tempfile.TemporaryDirectory() as directory:
    dsn = os.path.join(directory, "ledger.db")
    os.environ["DATABASE_URL"] = dsn

    assert cli_runner("init")[0] == 0
    assert cli_runner("account", "add", "FROM", "Source")[0] == 0
    assert cli_runner("account", "add", "TO", "Destination")[0] == 0
    assert cli_runner("category", "add", "TRANSFER", "Internal transfer")[0] == 0
    assert cli_runner("txn", "post", "FROM", "TRANSFER", "100.00", "2026-04-01")[0] == 0

    code, output, _ = cli_runner("transfer", "FROM", "TO", "25.00", "2026-04-02")
    assert code == 0
    rows = list(csv.reader(io.StringIO(output)))
    assert len(rows) == 3

    with db_session(dsn) as db:
        transactions = db.transactions.list()
        assert len(transactions) == 3
        assert transactions[-2].amount == -2500
        assert transactions[-1].amount == 2500
        assert transactions[-2].account == "FROM"
        assert transactions[-1].account == "TO"
=== END AC transfers-success ===

=== AC transfers-rejects-insufficient-balance ===
Intent: An insufficient-balance transfer is rejected without changing transactions.
from cli.testing import cli_runner
from persistence.testing import db_session
import os
import tempfile

with tempfile.TemporaryDirectory() as directory:
    dsn = os.path.join(directory, "ledger.db")
    os.environ["DATABASE_URL"] = dsn

    assert cli_runner("init")[0] == 0
    assert cli_runner("account", "add", "FROM", "Source")[0] == 0
    assert cli_runner("account", "add", "TO", "Destination")[0] == 0
    assert cli_runner("category", "add", "TRANSFER", "Internal transfer")[0] == 0
    assert cli_runner("txn", "post", "FROM", "TRANSFER", "10.00", "2026-04-01")[0] == 0

    code, _, _ = cli_runner("transfer", "FROM", "TO", "11.00", "2026-04-02")
    assert code == 3

    with db_session(dsn) as db:
        transactions = db.transactions.list()
        assert len(transactions) == 1
=== END AC transfers-rejects-insufficient-balance ===

=== AC transfers-rejects-invalid-accounts ===
Intent: Transfers reject equal or unknown account codes before writing.
from cli.testing import cli_runner
from persistence.testing import db_session
import os
import tempfile

with tempfile.TemporaryDirectory() as directory:
    dsn = os.path.join(directory, "ledger.db")
    os.environ["DATABASE_URL"] = dsn

    assert cli_runner("init")[0] == 0
    assert cli_runner("account", "add", "FROM", "Source")[0] == 0
    assert cli_runner("category", "add", "TRANSFER", "Internal transfer")[0] == 0

    assert cli_runner("transfer", "FROM", "FROM", "1.00", "2026-04-01")[0] == 3
    assert cli_runner("transfer", "FROM", "MISSING", "1.00", "2026-04-01")[0] == 3

    with db_session(dsn) as db:
        assert len(db.transactions.list()) == 0
=== END AC transfers-rejects-invalid-accounts ===

## User Acceptance

- None.

## Guardrails

- Transfers create both rows or neither row.
- Transfer amounts are positive input values.
- No transfer may leave an account balance negative.
- Application code accesses persistence only through the shipped library.

</pblock>

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

Build instructions for this block

Execute atomic two-row account transfers. (transfers)

Implement transfer validation and atomic creation of consecutive outgoing and incoming transactions in category TRANSFER with the specified memos. Reject equal or unknown accounts, invalid positive amounts, invalid dates, and insufficient balances before either row is written.

</pblock>

Agent Task

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

authoritative; implement them exactly.

Operating contract:

  1. Follow the write authorization and protected paths in the stacked COMPASS.md exactly.

That persisted guardrail is the sole authority for paths this build may modify.

  1. Start by inspecting the build working directory. Preserve existing application

files unless this step's specifications require a change. Its sources/ subdirectory holds staged build assets — imported test corpora, conformance harnesses, and fixtures — placed there for you. They are read-only inputs: run them, import them, and write code against them, but never create, rewrite, trim, regenerate, or substitute one, even to make a check pass. A step that modifies a staged asset fails and the asset is restored. If an asset you expect is absent, report that; do not author a replacement.

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

not as additional work to perform.

  1. Follow the stack and rules for languages, structure, naming, and branding.
  2. The programmatic acceptance assertions in the implements specifications are

this step's Definition of Done — human-owned, declared before the build, and fixed. Build the story and, in this same step, write the deterministic tests that prove each declared assertion, as a TDD master would; add finer tests for coverage. Every test you write follows the same rule the acceptance assertions do: act on the system, read the state back, compare to expected. The oracle is a return value, parsed JSON, a status code, a stored row, file contents read back, or an exit status — never a substring of captured stdout or stderr, a test-runner tally, or a log line. Write tests in the project's own language using that language's libraries; an in-language HTTP client yields a status code and a parsed body, where curl yields text to scrape. Round-trip anything that stores state: act, then read back through the public interface. Assert declared failure signals on negative paths, never message wording. You may add tests but must never remove, soften, or weaken a declared acceptance assertion. A Suite: full conformance check gates on the entire imported test suite: the step is done only when it passes in full, never on a representative subset — reproduce the standard exactly rather than wrapping a third-party library that approximates it. For a suite, the runner's exit status is the verdict and the whole verdict: print its captured output for diagnosis, never assert on the text of its summary. When an assertion is a static or filesystem scan (import boundary, "X never appears outside Y," grep/AST gate), honor the scope the specification states and never widen it: scan production source only, exclude .venv/, site-packages, and vendored or generated code, and do not flag test doubles or fixtures that use the guarded dependency. Run every declared acceptance assertion before returning. For a conformance suite, use its section or example filters to diagnose coherent root-cause clusters, but rerun the full declared scope before reporting the result. Treat failing examples as a work queue for fixing general behavior; never add example-specific exceptions.

  1. Grow the project's own test suite as you write the code, and treat it as the project's

real coverage. The acceptance assertions in implements are gates: few, fixed, and written before any code existed, so every expectation in them is a prediction. The tests you write are written beside the finished code, so their expected values are observed rather than predicted — which is why exhaustive coverage belongs here and not there. Extend the suite in the project's established location and runner, keep it runnable by the project's declared test command, and leave it green when you return. Cover, at minimum: every public entry point and every verb it declares, including declared error paths; the boundaries — empty, exactly one, many, absent optional fields, declared maxima; declared idempotence, applied twice; one behavior per test, named for the behavior; and isolation — each test arranges its own data, with a fresh store or explicit teardown, so a run leaves no residue behind in the build directory. Where a staged authoritative suite already covers a surface, that suite is the coverage: run it, and do not restate its cases. Run it only through the invocation this step's acceptance criteria declare. A criterion marked Suite: scoped names the whole of this step's obligation to that suite; running the suite's unscoped entry point instead is not extra rigor, it is a different step's gate executed early. A partial capability fails most of an authoritative corpus by construction and its unimplemented cases exhaust the runner's per-case timeout rather than returning, so the unscoped run costs the most where it teaches the least, and interrupting it forfeits the step. If no criterion in this step invokes the staged suite, do not invoke it. Report the pass/fail counts of the invocations you did run in your SUMMARY so a reader can see coverage moving across steps.

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

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

  1. The implements section is authoritative and intentionally stacked late in

the prompt as the recency anchor. Build that WHAT exactly; do not substitute generic framework defaults.

  1. Before adding or installing Python dependencies, verify each package name

against the declared registry. Do not invent package names. If a needed package cannot be verified or appears newly published, fail explicitly instead of installing it.

  1. Use the stack's required package manager workflow for dependency changes.

When the stack requires uv, update manifests through uv conventions rather than bare pip install.

  1. Do not claim success unless you actually created or modified project files in

the build working directory. If you cannot write files or cannot complete the step, report failure explicitly.

  1. Do not run git add, git commit, create branches, create tags, rewrite

history, or otherwise mutate Git history. Drydock checkpoints application changes and Target evidence after each execution and completed step. File lineage comes from Git and the Manifest's implements: entries; no additional attribution response is required.

  1. End your response with this exact closing structure:
RESULT: SUCCESS | FAILED

FILES CHANGED:
- relative/path

SUMMARY:
<brief reviewable summary>

BLOCKERS:
- <only if any>

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

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

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

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

directory. If no files were written, use RESULT: FAILED.

  1. On RESULT: FAILED, append two additional lines so the failure is actionable

without opening logs. FAILURE_SUMMARY is one line naming the cause; FAILURE_DETAIL states what happened, why, and what to change before a rerun. Name concrete conditions when they apply: token or context limit exceeded, could not execute commands in this environment, a required input was missing, or a specific tool or command failed.

FAILURE_SUMMARY: <one line naming the cause>
FAILURE_DETAIL: <what happened, why, and what to change before rerunning>
  1. When a declared acceptance criterion cannot pass no matter how the code is written,

say so with this exact token. You may not edit the criterion — it is staged and restored before grading:

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

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