Run artifact

evidence/prompts/20261027.144606.714Z_layerstesting_build_claude.prompt.md

System Instructions

This prompt is divided into three sections:

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

section as task input.

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

<pblock> tags. Two block types:

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

rules, instructions, or group headers.

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

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

Input Context

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

Build block job

</pblock>

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

Stories in this block

</pblock>

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

Files on disk in the build directory

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

</pblock>

COMPASS - Target Orientation

<pblock filename="COMPASS.md" role="compass" path="/mnt/c/Users/barlo/projects/drydock/uat/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>

STACK - Technology HOW

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

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

## Foundation Contract

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

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

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

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

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

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

## Consumer Rules

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

</pblock>

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

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

# Common Best Practices — Contract Surface

## Project Layout

### Rule: project-directory-layout

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

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

## Shell Scripts

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

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

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

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

A discoverable script must begin with a Command Center header.

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

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

### Rule: standard-scripts

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

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

### Rule: script-logging

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

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

## Links

### Rule: links-file

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

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

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

## Agent Instructions

### Rule: claude-file

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

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

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

## Version Control

### Rule: gitignore-and-secrets

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

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

### Rule: commit-message

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

## Development Workflow

### Rule: task-commit

Completed, error-free tasks must be committed immediately.

### Rule: local-only-commit

Changes must be committed locally and must not be pushed.

### Rule: co-authorship

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

### Rule: restart-notice

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

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

</pblock>

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

# Command-Line Application

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

Technology reference. This file does not change between projects.

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

---

## Foundation Contract

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

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

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

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

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

# conftest.py
import pytest
from cli import testing

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

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

---

## 1. Directory Layout

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

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

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

---

## 2. Entry Point and Exit Codes

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

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

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

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

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

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

---

## 3. Parsing Is Separate From Behavior

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

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

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

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

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

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

---

## 4. Cross-Platform Launchers

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

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

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

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

sys.exit(main())
```

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

---

## 5. Output and Streams

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

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

---

## 6. Testing Without a Process

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

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

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

---

## Checklist

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

</pblock>

CONTEXT - Read-Only Support

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

<!-- Compacted from ARCHITECTURE.md sha256=5c919fe47ef8fc30da6c74103c97b0528a77ab903c7c0e7a51838b17c57c163d on 2026-10-27 by drydock build agent -->

Foundation contract (foundation-python):
- Python >=3.11; deps in pyproject.toml; uv.lock committed; .venv local (gitignored).
- bin/test.sh (POSIX sh): runs `pytest -q` from root; exit status = verdict.
- conftest.py fixtures: db_session (delegates to persistence.testing.db_session), cli_runner (delegates to cli.testing.cli_runner).
- ledger_core.config.database_path() -> str: DATABASE_URL (strip leading "sqlite://"), else DATABASE_PATH, else "data/app.db"; empty = unset.
- ledger_core.errors: LedgerError(Exception) with exit_code:int; Rejected=3, NotFound=4, Operational=1.
- Boundary: no module under ledger_core/ or cli/ imports sqlite3/psycopg/psycopg2; no float calls or float literals in ledger_core/.

</pblock>

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

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

Database: LayersTesting (version 20261027 V1). Build order 1. Provides persistence.accounts, persistence.categories, persistence.transactions.

Access: `open_database(dsn)` returns `Database`; `db.<table>.<op>(...)`. Money: integer cents everywhere. No aggregate operations; callers compute counts, sums, next txn_id from list results.

Operations (input -> output; * = match key):
- accounts.create(account, name) -> (account, name)
- accounts.get(account*) -> (account, name) | None
- accounts.update(account*, name) -> (account, name)
- accounts.delete(account*) -> (account)
- accounts.list() -> [(account, name)] order account asc
- accounts.clear(min_account) -> count; removes account >= min_account; "" removes all
- categories.create(category, description) -> (category, description)
- categories.get(category*) -> (category, description) | None
- categories.update(category*, description) -> (category, description)
- categories.delete(category*) -> (category)
- categories.list() -> [(category, description)] order category asc
- categories.clear(min_category) -> count; "" removes all
- transactions.create(txn_id, date, account, category, amount, memo) -> (txn_id, date, account, category, amount, memo)
- transactions.get(txn_id*) -> row | None
- transactions.update(txn_id*, amount) -> row
- transactions.delete(txn_id*) -> (txn_id)
- transactions.list(account?, category?, start_date?, end_date?) -> [row] filters account, category, date>=start_date, date<=end_date; order txn_id asc
- transactions.clear(min_txn_id) -> count; 0 removes all

Schema:
- accounts(account TEXT PK, 1-12 chars A-Z0-9; name TEXT NOT NULL, 1-40 chars)
- categories(category TEXT PK, 1-12 chars A-Z0-9; description TEXT NOT NULL, 1-40 chars)
- transactions(txn_id INTEGER PK; date TEXT YYYY-MM-DD; account FK accounts; category FK categories; amount INTEGER cents signed, never zero; memo TEXT 0-60 chars default ''); INDEX(account, date)

Config: DATABASE_URL (SQLite path, optional sqlite:// prefix, wins), DATABASE_PATH (fallback), default data/app.db.

Guardrails: only the persistence package opens a driver; amounts never float; counts/balances never hardcoded.

</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-LoadAccounts.md" role="implements" path="/mnt/c/Users/barlo/projects/drydock/uat/LayersTesting/runs/20261027.135355/workspace/targets/LayersTesting/blueprint/FEATURE-LoadAccounts.md" guidance="Feature Specification">

# FEATURE: Load Accounts

| Field | Value |
|-------|-------|
| Version | 20261027 V1 |
| Description | Implements `ledger load accounts <csv>` as an all-or-nothing bulk load. |
| Depends On | FEATURE-LoadCsvReader.md, FEATURE-Validation.md, DATABASE.md |
| Provides | ledger load accounts |
| Consumes | ledger_core.csvio, ledger_core.validation, cli.registry |

## Purpose

Load accounts from a CSV file whose header is `account,name`. Every row is validated before the
first write; the rows are then written together or not at all.

## Behavior

1. `ledger load accounts <csv>` takes exactly one file argument; other counts exit 2.
2. Read the file with `ledger_core.csvio.read_rows(path, ("account", "name"))`. An unreadable file
   exits 1; a wrong header or wrong field count exits 3.
3. Validate every row before any write: the code is 1 to 12 characters of `A-Z0-9`, the name is 1
   to 40 characters with no comma or newline, the code does not repeat within the file, and the code
   is not already stored.
4. Insert every row in one atomic unit. A failure at any row leaves every earlier row unstored.
5. Print `table,loaded` then `accounts,<rows>`, where `<rows>` is the number of rows inserted.
6. Any rejection exits 3 with nothing on standard output and one diagnostic line on standard error.
   A header-only file loads zero rows and prints `accounts,0`.

## Database Interface

- `FEATURE-ACCOUNT-005` — read: list stored accounts to detect duplicate keys - supplies: — - returns: `account`, `name`
- `FEATURE-ACCOUNT-001` — write: create an account - supplies: `account`, `name` - returns: `account`, `name`

## Programmatic Acceptance

=== AC load-accounts-success ===
Intent: a valid accounts file loads every row, prints the declared two CSV rows with the loaded count, and the rows are readable afterward.
Requires: executable=python3; scope=test

import csv
import io
import os
import tempfile
from cli.testing import cli_runner
from persistence.testing import db_session

rows = [["ZZLAA1", "Load One"], ["ZZLAA2", "Load Two"], ["ZZLAA3", "Load Three"]]
with tempfile.TemporaryDirectory() as d:
    path = os.path.join(d, "accounts.csv")
    with open(path, "w", newline="") as fh:
        w = csv.writer(fh, lineterminator="\n")
        w.writerow(["account", "name"])
        w.writerows(rows)
    with db_session() as db:
        code, out, err = cli_runner("load", "accounts", path)
        print(out, err)
        assert code == 0
        parsed = list(csv.reader(io.StringIO(out)))
        assert parsed == [["table", "loaded"], ["accounts", str(len(rows))]]
        for acct, name in rows:
            row = db.accounts.get(account=acct)
            assert row is not None
            got = row["name"] if isinstance(row, dict) else row.name
            assert got == name
=== END AC load-accounts-success ===

=== AC load-accounts-rejected-row-stores-nothing ===
Intent: when the last row is invalid, exit 3 is returned, stdout is empty, and none of the earlier valid rows is stored.
Requires: executable=python3; scope=test

import csv
import os
import tempfile
from cli.testing import cli_runner
from persistence.testing import db_session

good = [["ZZLB%d" % i, "Good %d" % i] for i in range(1, 11)]
bad = ["zzlbbad", "Lowercase Code"]
with tempfile.TemporaryDirectory() as d:
    path = os.path.join(d, "accounts.csv")
    with open(path, "w", newline="") as fh:
        w = csv.writer(fh, lineterminator="\n")
        w.writerow(["account", "name"])
        w.writerows(good)
        w.writerow(bad)
    with db_session() as db:
        before = len(db.accounts.list())
        code, out, err = cli_runner("load", "accounts", path)
        assert code == 3
        assert out == ""
        assert len(db.accounts.list()) == before
        for acct, _ in good:
            assert db.accounts.get(account=acct) is None
=== END AC load-accounts-rejected-row-stores-nothing ===

=== AC load-accounts-invalid-fields ===
Intent: each invalid code or name (too long, empty, bad characters, comma in name) rejects the whole file with exit 3 and stores neither it nor the valid row before it.
Requires: executable=python3; scope=test

import csv
import os
import tempfile
from cli.testing import cli_runner
from persistence.testing import db_session

first = ["ZZLCOK", "Valid First"]
bad_rows = [
    ["ABCDEFGHIJKLM", "Code Too Long"],
    ["ZZLC-1", "Bad Char Code"],
    ["", "Empty Code"],
    ["ZZLC2", ""],
    ["ZZLC3", "x" * 41],
    ["ZZLC4", "has,comma"],
]
with tempfile.TemporaryDirectory() as d:
    with db_session() as db:
        for i, bad in enumerate(bad_rows):
            path = os.path.join(d, "a%d.csv" % i)
            with open(path, "w", newline="") as fh:
                w = csv.writer(fh, lineterminator="\n")
                w.writerow(["account", "name"])
                w.writerow(first)
                w.writerow(bad)
            code, out, err = cli_runner("load", "accounts", path)
            assert code == 3, bad
            assert out == ""
            assert db.accounts.get(account=first[0]) is None
=== END AC load-accounts-invalid-fields ===

=== AC load-accounts-duplicates-rejected ===
Intent: a code repeated inside the file, and a code already stored, each reject the whole file with exit 3 and leave the other rows unstored.
Requires: executable=python3; scope=test

import csv
import os
import tempfile
from cli.testing import cli_runner
from persistence.testing import db_session

def write(path, rows):
    with open(path, "w", newline="") as fh:
        w = csv.writer(fh, lineterminator="\n")
        w.writerow(["account", "name"])
        w.writerows(rows)

with tempfile.TemporaryDirectory() as d:
    with db_session() as db:
        p1 = os.path.join(d, "dup_in_file.csv")
        write(p1, [["ZZLD1", "One"], ["ZZLD2", "Two"], ["ZZLD1", "One Again"]])
        code, out, err = cli_runner("load", "accounts", p1)
        assert code == 3
        assert out == ""
        assert db.accounts.get(account="ZZLD1") is None
        assert db.accounts.get(account="ZZLD2") is None

        stored = "ZZLD3"
        stored_name = "Already Stored"
        db.accounts.create(account=stored, name=stored_name)
        p2 = os.path.join(d, "dup_stored.csv")
        write(p2, [["ZZLD4", "Fresh"], [stored, "Replacement"]])
        code, out, err = cli_runner("load", "accounts", p2)
        assert code == 3
        assert out == ""
        assert db.accounts.get(account="ZZLD4") is None
        row = db.accounts.get(account=stored)
        got = row["name"] if isinstance(row, dict) else row.name
        assert got == stored_name
=== END AC load-accounts-duplicates-rejected ===

=== AC load-accounts-header-and-usage ===
Intent: a wrong header exits 3 with nothing stored, and a missing file argument is a usage error with exit 2.
Requires: executable=python3; scope=test

import csv
import os
import tempfile
from cli.testing import cli_runner
from persistence.testing import db_session

with tempfile.TemporaryDirectory() as d:
    path = os.path.join(d, "wrong_header.csv")
    with open(path, "w", newline="") as fh:
        w = csv.writer(fh, lineterminator="\n")
        w.writerow(["code", "name"])
        w.writerow(["ZZLE1", "Wrong Header"])
    with db_session() as db:
        code, out, err = cli_runner("load", "accounts", path)
        assert code == 3
        assert out == ""
        assert db.accounts.get(account="ZZLE1") is None
        code, out, err = cli_runner("load", "accounts")
        assert code == 2
        assert out == ""
=== END AC load-accounts-header-and-usage ===

## User Acceptance

- None.

## Guardrails

- No row is written until every row in the file has been validated.
- Seed files are never read by application code; the file path comes only from the command line.
- A failing command writes nothing to standard output.

</pblock>

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

# FEATURE: Account Delete

| Field | Value |
|-------|-------|
| Version | 20261027 V1 |
| Description | Implements `ledger account delete <code>`, removing an account that has no transactions. |
| Depends On | FEATURE-AccountAdd.md, FEATURE-CliEntry.md, DATABASE.md |
| Provides | ledger account delete |
| Consumes | ledger_core.accounts, cli.registry |

## Purpose

`ledger account delete <code>` removes an account and prints `deleted` then the code, one per line. An account that still has transactions is refused.

## Behavior

- Exactly one argument is required; otherwise exit 2.
- An absent code exits 4.
- An account with at least one transaction exits 3 and stays stored.
- Otherwise the account is deleted and the command exits 0.

## Database Interface

- `FEATURE-ACCOUNT-002` — read: check the account exists - supplies: `account` - returns: `account`
- `FEATURE-TXN-005` — read: check the account has transactions - supplies: `account` - returns: `txn_id`
- `FEATURE-ACCOUNT-004` — write: delete the account - supplies: `account` - returns: `account`

## Programmatic Acceptance

=== AC account-delete-success ===
Intent: Deleting an account without transactions prints the confirmation and a later read finds nothing.
Requires: executable=python3; scope=test

import csv
import io
from persistence.testing import db_session
from cli.testing import cli_runner

code = "ZZAD1"
with db_session() as db:
    db.accounts.create(account=code, name="Delete Probe")
    rc, out, err = cli_runner("account", "delete", code)
    print(out)
    print(err)
    assert rc == 0
    rows = list(csv.reader(io.StringIO(out)))
    assert rows == [["deleted"], [code]]
    assert db.accounts.get(account=code) is None
=== END AC account-delete-success ===

=== AC account-delete-in-use ===
Intent: An account with a transaction is refused with exit 3 and both the account and the transaction remain.
Requires: executable=python3; scope=test

from persistence.testing import db_session
from cli.testing import cli_runner

code, cat, tid = "ZZAD2", "ZZADC2", 900001201
with db_session() as db:
    db.accounts.create(account=code, name="In Use")
    db.categories.create(category=cat, description="Delete Category")
    db.transactions.create(txn_id=tid, date="2026-04-01", account=code, category=cat, amount=500, memo="")
    rc, out, err = cli_runner("account", "delete", code)
    print(err)
    assert rc == 3
    assert out == ""
    assert db.accounts.get(account=code) is not None
    assert db.transactions.get(txn_id=tid) is not None
=== END AC account-delete-in-use ===

=== AC account-delete-absent ===
Intent: Deleting an absent account exits 4 with no standard output.
Requires: executable=python3; scope=test

from persistence.testing import db_session
from cli.testing import cli_runner

code = "ZZADNONE"
with db_session() as db:
    assert db.accounts.get(account=code) is None
    rc, out, err = cli_runner("account", "delete", code)
    print(err)
    assert rc == 4
    assert out == ""
=== END AC account-delete-absent ===

=== AC account-delete-usage ===
Intent: A missing argument is a usage error with exit 2 and no standard output.
Requires: executable=python3; scope=test

from persistence.testing import db_session
from cli.testing import cli_runner

with db_session() as db:
    rc, out, err = cli_runner("account", "delete")
    assert rc == 2
    assert out == ""
=== END AC account-delete-usage ===

## User Acceptance

- None.

## Guardrails

- Existence and in-use checks both complete before the delete is issued.
- A refused or failed delete leaves every stored record unchanged.
- Failures write nothing to standard output.

</pblock>

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

# FEATURE: Transaction Get

| Field | Value |
|-------|-------|
| Version | 20261027 V1 |
| Description | Implements `ledger txn get <id>`, printing one stored transaction row. |
| Depends On | FEATURE-TxnPost.md, FEATURE-CliEntry.md, DATABASE.md |
| Provides | ledger txn get |
| Consumes | ledger_core.transactions, cli.registry |

## Purpose

`ledger txn get <id>` prints the header row `txn_id,date,account,category,amount,memo` and the stored transaction, formatted with `txn_row` from `ledger_core.transactions`, with the amount shown in two decimals.

## Behavior

- Exactly one argument is required; otherwise exit 2.
- A non-integer id exits 3.
- An absent id exits 4.
- The command never writes to the database.

## Database Interface

- `FEATURE-TXN-002` — read: get a transaction by id - supplies: `txn_id` - returns: `txn_id`, `date`, `account`, `category`, `amount`, `memo`

## Programmatic Acceptance

=== AC txn-get-existing ===
Intent: A stored transaction prints with every column and the cents shown as a two-decimal amount.
Requires: executable=python3; scope=test

import csv
import io
from persistence.testing import db_session
from cli.testing import cli_runner

acct, cat, tid = "ZZTG1", "ZZTGC1", 900001601
day, memo = "2026-04-05", "get probe"
with db_session() as db:
    db.accounts.create(account=acct, name="Get Probe")
    db.categories.create(category=cat, description="Get Category")
    db.transactions.create(txn_id=tid, date=day, account=acct, category=cat, amount=1234, memo=memo)
    rc, out, err = cli_runner("txn", "get", str(tid))
    print(out)
    print(err)
    assert rc == 0
    rows = list(csv.reader(io.StringIO(out)))
    assert rows[0] == ["txn_id", "date", "account", "category", "amount", "memo"]
    assert rows[1] == [str(tid), day, acct, cat, "12.34", memo]
=== END AC txn-get-existing ===

=== AC txn-get-negative-amount ===
Intent: A negative stored amount prints with a leading minus and two decimals.
Requires: executable=python3; scope=test

import csv
import io
from persistence.testing import db_session
from cli.testing import cli_runner

acct, cat, tid = "ZZTG2", "ZZTGC2", 900001602
with db_session() as db:
    db.accounts.create(account=acct, name="Get Probe")
    db.categories.create(category=cat, description="Get Category")
    db.transactions.create(txn_id=tid, date="2026-04-06", account=acct, category=cat, amount=2000, memo="")
    db.transactions.create(txn_id=tid + 1, date="2026-04-06", account=acct, category=cat, amount=-1250, memo="")
    rc, out, err = cli_runner("txn", "get", str(tid + 1))
    print(out)
    print(err)
    assert rc == 0
    rows = list(csv.reader(io.StringIO(out)))
    assert rows[1][4] == "-12.50"
=== END AC txn-get-negative-amount ===

=== AC txn-get-absent ===
Intent: An absent transaction id exits 4 with no standard output.
Requires: executable=python3; scope=test

from persistence.testing import db_session
from cli.testing import cli_runner

tid = 999999999
with db_session() as db:
    assert db.transactions.get(txn_id=tid) is None
    rc, out, err = cli_runner("txn", "get", str(tid))
    print(err)
    assert rc == 4
    assert out == ""
=== END AC txn-get-absent ===

=== AC txn-get-bad-id ===
Intent: A non-integer id is rejected with exit 3 and a wrong argument count is a usage error with exit 2.
Requires: executable=python3; scope=test

from persistence.testing import db_session
from cli.testing import cli_runner

with db_session() as db:
    rc, out, err = cli_runner("txn", "get", "abc")
    assert rc == 3
    assert out == ""
    rc, out, err = cli_runner("txn", "get")
    assert rc == 2
    assert out == ""
=== END AC txn-get-bad-id ===

## User Acceptance

- None.

## Guardrails

- The command is read-only and never writes to the database.
- Amounts are displayed from integer cents with exactly two decimals; floating point is never used.
- Failures write nothing to standard output.

</pblock>

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

# FEATURE: Account Rename

| Field | Value |
|-------|-------|
| Version | 20261027 V1 |
| Description | Implements `ledger account rename <code> <name>`, changing only an account's name and printing the updated row. |
| Depends On | FEATURE-AccountAdd.md, FEATURE-CliEntry.md, FEATURE-Validation.md, DATABASE.md |
| Provides | ledger account rename |
| Consumes | ledger_core.accounts, ledger_core.validation, cli.registry |

## Purpose

`ledger account rename <code> <name>` validates the new name, updates only the name column, and prints the header row and the updated account row `account,name,transactions,balance`.

## Behavior

- Exactly two arguments are required; otherwise exit 2.
- Name validation (1 to 40 characters, no comma, no newline) happens first; a violation exits 3 and changes nothing.
- An absent code exits 4 and changes nothing.
- On success only `name` changes; the transaction count and balance in the output are computed live.

## Database Interface

- `FEATURE-ACCOUNT-002` — read: check the account exists - supplies: `account` - returns: `account`, `name`
- `FEATURE-ACCOUNT-003` — write: rename an account - supplies: `account`, `name` - returns: `account`, `name`

## Programmatic Acceptance

=== AC account-rename-success ===
Intent: Renaming prints the updated row and a separate read shows the new name persisted.
Requires: executable=python3; scope=test

import csv
import io
from persistence.testing import db_session
from cli.testing import cli_runner

code, before, after = "ZZAR1", "Old Name", "New Name"
with db_session() as db:
    db.accounts.create(account=code, name=before)
    rc, out, err = cli_runner("account", "rename", code, after)
    print(out)
    print(err)
    assert rc == 0
    rows = list(csv.reader(io.StringIO(out)))
    assert rows[0] == ["account", "name", "transactions", "balance"]
    assert rows[1] == [code, after, str(0), "0.00"]
    back = db.accounts.get(account=code)
    assert back is not None
    name = back["name"] if isinstance(back, dict) else back.name
    assert name == after
=== END AC account-rename-success ===

=== AC account-rename-absent ===
Intent: Renaming an absent account exits 4 with no standard output and creates nothing.
Requires: executable=python3; scope=test

from persistence.testing import db_session
from cli.testing import cli_runner

code = "ZZARNONE"
with db_session() as db:
    rc, out, err = cli_runner("account", "rename", code, "Any Name")
    print(err)
    assert rc == 4
    assert out == ""
    assert db.accounts.get(account=code) is None
=== END AC account-rename-absent ===

=== AC account-rename-invalid-name ===
Intent: A name containing a comma, an empty name, and an over-length name each exit 3 and leave the stored name unchanged.
Requires: executable=python3; scope=test

from persistence.testing import db_session
from cli.testing import cli_runner

code, original = "ZZAR2", "Keep Me"
bad_names = ["has,comma", "", "x" * 41]
with db_session() as db:
    db.accounts.create(account=code, name=original)
    for bad in bad_names:
        rc, out, err = cli_runner("account", "rename", code, bad)
        print(err)
        assert rc == 3
        assert out == ""
        back = db.accounts.get(account=code)
        name = back["name"] if isinstance(back, dict) else back.name
        assert name == original
=== END AC account-rename-invalid-name ===

=== AC account-rename-usage ===
Intent: A wrong argument count is a usage error with exit 2 and no standard output.
Requires: executable=python3; scope=test

from persistence.testing import db_session
from cli.testing import cli_runner

with db_session() as db:
    rc, out, err = cli_runner("account", "rename", "ZZAR3")
    assert rc == 2
    assert out == ""
=== END AC account-rename-usage ===

## User Acceptance

- None.

## Guardrails

- Only the name column changes; the code, transactions, and balance are untouched.
- Every input is validated before the first write.
- Failures write nothing to standard output.

</pblock>

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

# FEATURE: Account Get

| Field | Value |
|-------|-------|
| Version | 20261027 V1 |
| Description | Implements `ledger account get <code>`, printing the current account row with live transaction count and balance. |
| Depends On | FEATURE-AccountAdd.md, FEATURE-CliEntry.md, DATABASE.md |
| Provides | ledger account get |
| Consumes | ledger_core.accounts, cli.registry |

## Purpose

`ledger account get <code>` prints the account's header row and data row `account,name,transactions,balance`. The transaction count and balance are computed from the account's stored transactions using the `account_row` helper exported by `ledger_core.accounts`. The balance is the sum of integer cents, formatted with exactly two decimals.

## Behavior

- Exactly one argument is required; any other count is a usage error, exit 2.
- An absent code exits 4 with one stderr line and nothing on stdout.
- Success exits 0 and writes the CSV with `\n` line endings.
- The command never writes to the database.

## Database Interface

- `FEATURE-ACCOUNT-002` — read: get an account by code - supplies: `account` - returns: `account`, `name`
- `FEATURE-TXN-005` — read: list an account's transactions - supplies: `account` - returns: `amount`

## Programmatic Acceptance

=== AC account-get-existing ===
Intent: An account with two stored transactions is printed with its live count and its balance, both derived from the fixture amounts.
Requires: executable=python3; scope=test

import csv
import io
from persistence.testing import db_session
from cli.testing import cli_runner

def money(c):
    sign = "-" if c < 0 else ""
    q, r = divmod(abs(c), 100)
    return f"{sign}{q}.{r:02d}"

code, label, cat = "ZZAG1", "Get Probe", "ZZAGC1"
amounts = [1000, -250]
with db_session() as db:
    db.accounts.create(account=code, name=label)
    db.categories.create(category=cat, description="Get Category")
    base = 900001001
    for i, cents in enumerate(amounts):
        db.transactions.create(txn_id=base + i, date="2026-04-01", account=code, category=cat, amount=cents, memo="")
    rc, out, err = cli_runner("account", "get", code)
    print(out)
    print(err)
    assert rc == 0
    rows = list(csv.reader(io.StringIO(out)))
    assert rows[0] == ["account", "name", "transactions", "balance"]
    assert rows[1] == [code, label, str(len(amounts)), money(sum(amounts))]
    assert len(rows) == 2
=== END AC account-get-existing ===

=== AC account-get-empty-account ===
Intent: An account with no transactions prints a zero count and a zero balance.
Requires: executable=python3; scope=test

import csv
import io
from persistence.testing import db_session
from cli.testing import cli_runner

code, label = "ZZAG2", "Empty Probe"
with db_session() as db:
    db.accounts.create(account=code, name=label)
    rc, out, err = cli_runner("account", "get", code)
    print(out)
    print(err)
    assert rc == 0
    rows = list(csv.reader(io.StringIO(out)))
    assert rows[1] == [code, label, str(0), "0.00"]
=== END AC account-get-empty-account ===

=== AC account-get-absent ===
Intent: An absent account code exits 4 and writes nothing to standard output.
Requires: executable=python3; scope=test

from persistence.testing import db_session
from cli.testing import cli_runner

code = "ZZAGNONE"
with db_session() as db:
    assert db.accounts.get(account=code) is None
    rc, out, err = cli_runner("account", "get", code)
    print(out)
    print(err)
    assert rc == 4
    assert out == ""
=== END AC account-get-absent ===

=== AC account-get-usage ===
Intent: A missing or surplus argument is a usage error with exit 2 and no standard output.
Requires: executable=python3; scope=test

from persistence.testing import db_session
from cli.testing import cli_runner

with db_session() as db:
    rc, out, err = cli_runner("account", "get")
    assert rc == 2
    assert out == ""
    rc, out, err = cli_runner("account", "get", "ZZAG3", "EXTRA")
    assert rc == 2
    assert out == ""
=== END AC account-get-usage ===

## User Acceptance

- None.

## Guardrails

- The command is read-only and never writes to the database.
- Count and balance are computed from stored transactions, never cached or embedded.
- Amounts are integer cents; no floating point is used for money.
- Failures write nothing to standard output.

</pblock>

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

# FEATURE: Transaction Delete

| Field | Value |
|-------|-------|
| Version | 20261027 V1 |
| Description | Implements `ledger txn delete <id>`, which removes a transaction unless its account balance would go below zero. |
| Depends On | FEATURE-TxnPost.md, FEATURE-BalanceRule.md, FEATURE-CliEntry.md, DATABASE.md |
| Provides | ledger txn delete |
| Consumes | ledger_core.transactions, ledger_core.balances, cli.registry |

## Purpose

Delete one transaction by id. Persistence is reached only through `ledger_core.transactions`, which calls the generated `persistence` package.

## Behavior

1. Argument count other than one after `txn delete` exits 2.
2. A non-integer id exits 3.
3. An absent id exits 4.
4. The account's balance after removal is the stored balance minus the transaction's amount, in integer cents through `ledger_core.balances`. A negative result exits 3 and the row is kept.
5. Otherwise the row is deleted and the command prints two lines: `deleted` and the id.
6. A failing command writes nothing to standard output and one diagnostic line to standard error.

## Database Interface

- None — persistence is owned by DATABASE.md and reached through `ledger_core.transactions`.

## Programmatic Acceptance

=== AC txn-delete-success ===
Intent: Deleting an existing transaction exits 0, prints `deleted` then the id, and a separate read finds no row.

from cli.testing import cli_runner
from persistence.testing import db_session
import csv
import io

acct, cat, tid = "ZZDL1", "ZZDLC1", 900200001
with db_session() as db:
    db.accounts.create(account=acct, name="Delete Account")
    db.categories.create(category=cat, description="Delete Category")
    db.transactions.create(txn_id=tid, date="2026-05-01", account=acct, category=cat, amount=-500, memo="")
    db.transactions.create(txn_id=tid + 1, date="2026-05-01", account=acct, category=cat, amount=9000, memo="")
    code, out, err = cli_runner("txn", "delete", str(tid))
    print(out)
    print(err)
    assert code == 0
    rows = list(csv.reader(io.StringIO(out)))
    assert len(rows) == 2
    assert rows[1] == [str(tid)]
    assert rows[0] == ["deleted"]
    assert db.transactions.get(txn_id=tid) is None
    assert db.transactions.get(txn_id=tid + 1) is not None
=== END AC txn-delete-success ===

=== AC txn-delete-absent ===
Intent: Deleting an id that does not exist exits 4 with nothing on stdout.

from cli.testing import cli_runner
from persistence.testing import db_session

tid = 900299999
with db_session() as db:
    assert db.transactions.get(txn_id=tid) is None
    code, out, err = cli_runner("txn", "delete", str(tid))
    print(out)
    print(err)
    assert code == 4
    assert out == ""
=== END AC txn-delete-absent ===

=== AC txn-delete-negative-balance ===
Intent: Deleting a +10000 deposit while a -4000 payment remains would leave -4000, so exit 3 and the row stays; deleting the payment instead leaves a positive balance and succeeds.

from cli.testing import cli_runner
from persistence.testing import db_session

def f(row, name):
    return row[name] if isinstance(row, dict) else getattr(row, name)

acct, cat = "ZZDL2", "ZZDLC2"
tid_in, tid_out = 900200002, 900200003
amount_in = 10000
with db_session() as db:
    db.accounts.create(account=acct, name="Delete Account")
    db.categories.create(category=cat, description="Delete Category")
    db.transactions.create(txn_id=tid_in, date="2026-05-02", account=acct, category=cat, amount=amount_in, memo="")
    db.transactions.create(txn_id=tid_out, date="2026-05-02", account=acct, category=cat, amount=-4000, memo="")
    code, out, err = cli_runner("txn", "delete", str(tid_in))
    print(out)
    print(err)
    assert code == 3
    assert out == ""
    kept = db.transactions.get(txn_id=tid_in)
    assert kept is not None
    assert f(kept, "amount") == amount_in
    code, out, err = cli_runner("txn", "delete", str(tid_out))
    print(out)
    print(err)
    assert code == 0
    assert db.transactions.get(txn_id=tid_out) is None
=== END AC txn-delete-negative-balance ===

=== AC txn-delete-bad-id ===
Intent: A non-integer id is rejected with exit 3 and nothing on stdout.

from cli.testing import cli_runner

code, out, err = cli_runner("txn", "delete", "abc")
print(out)
print(err)
assert code == 3
assert out == ""
=== END AC txn-delete-bad-id ===

=== AC txn-delete-usage ===
Intent: A wrong argument count for txn delete exits 2 with nothing on stdout.

from cli.testing import cli_runner

for args in [("txn", "delete"), ("txn", "delete", "1", "2")]:
    code, out, err = cli_runner(*args)
    print(out)
    print(err)
    assert code == 2
    assert out == ""
=== END AC txn-delete-usage ===

## User Acceptance

- None.

## Guardrails

- The balance check runs before the delete, so a rejected delete writes nothing.
- Standard output stays empty on any failure; the diagnostic goes to standard error.
- Amounts are integer cents; floating point is never used for money.

</pblock>

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

# FEATURE: Transaction Amend

| Field | Value |
|-------|-------|
| Version | 20261027 V1 |
| Description | Implements `ledger txn amend <id> <amount>`, which changes only a transaction's amount without leaving any account balance below zero. |
| Depends On | FEATURE-TxnPost.md, FEATURE-Validation.md, FEATURE-BalanceRule.md, FEATURE-CliEntry.md, DATABASE.md |
| Provides | ledger txn amend |
| Consumes | ledger_core.transactions, ledger_core.validation, ledger_core.balances, cli.registry |

## Purpose

Amend the amount of an existing transaction. Only the amount changes; date, account, category, and memo are untouched. Persistence is reached only through `ledger_core.transactions`, which calls the generated `persistence` package.

## Behavior

1. Argument count other than two after `txn amend` exits 2.
2. The id must be an integer; otherwise exit 3.
3. The amount is validated with `ledger_core.validation` (`-?DIGITS[.D[D]]`, at most two decimals, never zero); a violation exits 3.
4. An absent id exits 4.
5. The resulting balance of the transaction's account is the stored balance minus the old amount plus the new amount, computed in integer cents through `ledger_core.balances`. A negative result exits 3 and nothing is written.
6. Otherwise only the amount is updated and the updated row is printed as `txn_id,date,account,category,amount,memo` with a two-decimal amount.
7. A failing command writes nothing to standard output and one diagnostic line to standard error.

## Database Interface

- None — persistence is owned by DATABASE.md and reached through `ledger_core.transactions`.

## Programmatic Acceptance

=== AC txn-amend-success ===
Intent: Amending an existing transaction exits 0, prints the updated row with the supplied amount text, and a separate read shows the new integer cents.

from cli.testing import cli_runner
from persistence.testing import db_session
import csv
import io

def f(row, name):
    return row[name] if isinstance(row, dict) else getattr(row, name)

acct, cat, tid = "ZZAM1", "ZZAMC1", 900100001
day = "2026-05-01"
newtext = "50.00"
with db_session() as db:
    db.accounts.create(account=acct, name="Amend Account")
    db.categories.create(category=cat, description="Amend Category")
    db.transactions.create(txn_id=tid, date=day, account=acct, category=cat, amount=10000, memo="amend probe")
    code, out, err = cli_runner("txn", "amend", str(tid), newtext)
    print(out)
    print(err)
    assert code == 0
    rows = list(csv.reader(io.StringIO(out)))
    assert len(rows) == 2
    assert rows[1][0] == str(tid)
    assert rows[1][1] == day
    assert rows[1][4] == newtext
    assert f(db.transactions.get(txn_id=tid), "amount") == int(newtext.replace(".", ""))
=== END AC txn-amend-success ===

=== AC txn-amend-only-amount ===
Intent: Amend changes only the amount; date, account, category, and memo read back exactly as they were created.

from cli.testing import cli_runner
from persistence.testing import db_session

def f(row, name):
    return row[name] if isinstance(row, dict) else getattr(row, name)

acct, cat, tid = "ZZAM2", "ZZAMC2", 900100002
day = "2026-05-02"
note = "keep this memo"
with db_session() as db:
    db.accounts.create(account=acct, name="Amend Account")
    db.categories.create(category=cat, description="Amend Category")
    db.transactions.create(txn_id=tid, date=day, account=acct, category=cat, amount=2000, memo=note)
    code, out, err = cli_runner("txn", "amend", str(tid), "35.50")
    print(out)
    print(err)
    assert code == 0
    back = db.transactions.get(txn_id=tid)
    assert f(back, "date") == day
    assert f(back, "account") == acct
    assert f(back, "category") == cat
    assert f(back, "memo") == note
=== END AC txn-amend-only-amount ===

=== AC txn-amend-absent ===
Intent: Amending an id that does not exist exits 4, prints nothing to stdout, and creates no row.

from cli.testing import cli_runner
from persistence.testing import db_session

tid = 900199999
with db_session() as db:
    assert db.transactions.get(txn_id=tid) is None
    code, out, err = cli_runner("txn", "amend", str(tid), "5.00")
    print(out)
    print(err)
    assert code == 4
    assert out == ""
    assert db.transactions.get(txn_id=tid) is None
=== END AC txn-amend-absent ===

=== AC txn-amend-negative-balance ===
Intent: An amend that would leave the account balance below zero exits 3 and keeps the original amount, while an amend landing exactly on zero succeeds. The account holds +10000 and -4000 cents, so lowering the first to 3000 gives -1000 and lowering it to 4000 gives 0.

from cli.testing import cli_runner
from persistence.testing import db_session

def f(row, name):
    return row[name] if isinstance(row, dict) else getattr(row, name)

acct, cat = "ZZAM3", "ZZAMC3"
tid_in, tid_out = 900100003, 900100004
too_low, exact = "30.00", "40.00"
with db_session() as db:
    db.accounts.create(account=acct, name="Amend Account")
    db.categories.create(category=cat, description="Amend Category")
    db.transactions.create(txn_id=tid_in, date="2026-05-03", account=acct, category=cat, amount=10000, memo="")
    db.transactions.create(txn_id=tid_out, date="2026-05-03", account=acct, category=cat, amount=-4000, memo="")
    code, out, err = cli_runner("txn", "amend", str(tid_in), too_low)
    print(out)
    print(err)
    assert code == 3
    assert out == ""
    assert f(db.transactions.get(txn_id=tid_in), "amount") == 10000
    code, out, err = cli_runner("txn", "amend", str(tid_in), exact)
    print(out)
    print(err)
    assert code == 0
    assert f(db.transactions.get(txn_id=tid_in), "amount") == int(exact.replace(".", ""))
=== END AC txn-amend-negative-balance ===

=== AC txn-amend-invalid-amount ===
Intent: Amounts with three decimals, a zero amount, and a non-numeric amount are rejected with exit 3 and the stored amount is unchanged.

from cli.testing import cli_runner
from persistence.testing import db_session

def f(row, name):
    return row[name] if isinstance(row, dict) else getattr(row, name)

acct, cat, tid = "ZZAM4", "ZZAMC4", 900100005
original = 10000
with db_session() as db:
    db.accounts.create(account=acct, name="Amend Account")
    db.categories.create(category=cat, description="Amend Category")
    db.transactions.create(txn_id=tid, date="2026-05-04", account=acct, category=cat, amount=original, memo="")
    for bad in ["1.234", "0", "0.00", "abc"]:
        code, out, err = cli_runner("txn", "amend", str(tid), bad)
        print(out)
        print(err)
        assert code == 3
        assert out == ""
        assert f(db.transactions.get(txn_id=tid), "amount") == original
=== END AC txn-amend-invalid-amount ===

=== AC txn-amend-usage ===
Intent: A wrong argument count for txn amend exits 2 with nothing on stdout.

from cli.testing import cli_runner

for args in [("txn", "amend"), ("txn", "amend", "1"), ("txn", "amend", "1", "2.00", "extra")]:
    code, out, err = cli_runner(*args)
    print(out)
    print(err)
    assert code == 2
    assert out == ""
=== END AC txn-amend-usage ===

## User Acceptance

- None.

## Guardrails

- Amounts are integer cents in every layer; floating point is never used for money.
- The balance check runs before the update, so a rejected amend writes nothing.
- Only the amount column changes; no other column is ever written by this command.
- Standard output stays empty on any failure; the diagnostic goes to standard error.

</pblock>

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

# FEATURE: Load Categories

| Field | Value |
|-------|-------|
| Version | 20261027 V1 |
| Description | Implements `ledger load categories <csv>` as an all-or-nothing bulk load. |
| Depends On | FEATURE-LoadCsvReader.md, FEATURE-Validation.md, DATABASE.md |
| Provides | ledger load categories |
| Consumes | ledger_core.csvio, ledger_core.validation, cli.registry |

## Purpose

Load categories from a CSV file whose header is `category,description`, applying the same
validate-everything-then-write rule as the accounts load.

## Behavior

1. `ledger load categories <csv>` takes exactly one file argument; other counts exit 2.
2. Read the file with `ledger_core.csvio.read_rows(path, ("category", "description"))`. An
   unreadable file exits 1; a wrong header or wrong field count exits 3.
3. Validate every row before any write: the code is 1 to 12 characters of `A-Z0-9`, the description
   is 1 to 40 characters with no comma or newline, the code does not repeat within the file, and the
   code is not already stored.
4. Insert every row in one atomic unit; a rejection stores none of them.
5. Print `table,loaded` then `categories,<rows>`.
6. Any rejection exits 3 with nothing on standard output and one diagnostic line on standard error.

## Database Interface

- `FEATURE-CATEGORY-005` — read: list stored categories to detect duplicate keys - supplies: — - returns: `category`, `description`
- `FEATURE-CATEGORY-001` — write: create a category - supplies: `category`, `description` - returns: `category`, `description`

## Programmatic Acceptance

=== AC load-categories-success ===
Intent: a valid categories file loads every row, prints the declared two CSV rows with the loaded count, and the rows are readable afterward.
Requires: executable=python3; scope=test

import csv
import io
import os
import tempfile
from cli.testing import cli_runner
from persistence.testing import db_session

rows = [["ZZKA1", "Cat One"], ["ZZKA2", "Cat Two"], ["ZZKA3", "Cat Three"]]
with tempfile.TemporaryDirectory() as d:
    path = os.path.join(d, "categories.csv")
    with open(path, "w", newline="") as fh:
        w = csv.writer(fh, lineterminator="\n")
        w.writerow(["category", "description"])
        w.writerows(rows)
    with db_session() as db:
        code, out, err = cli_runner("load", "categories", path)
        print(out, err)
        assert code == 0
        parsed = list(csv.reader(io.StringIO(out)))
        assert parsed == [["table", "loaded"], ["categories", str(len(rows))]]
        for cat, text in rows:
            row = db.categories.get(category=cat)
            assert row is not None
            got = row["description"] if isinstance(row, dict) else row.description
            assert got == text
=== END AC load-categories-success ===

=== AC load-categories-rejected-row-stores-nothing ===
Intent: when a later row is invalid, exit 3 is returned, stdout is empty, and none of the earlier valid rows is stored.
Requires: executable=python3; scope=test

import csv
import os
import tempfile
from cli.testing import cli_runner
from persistence.testing import db_session

good = [["ZZKB%d" % i, "Good %d" % i] for i in range(1, 6)]
bad = ["ZZKBBAD", "x" * 41]
with tempfile.TemporaryDirectory() as d:
    path = os.path.join(d, "categories.csv")
    with open(path, "w", newline="") as fh:
        w = csv.writer(fh, lineterminator="\n")
        w.writerow(["category", "description"])
        w.writerows(good)
        w.writerow(bad)
    with db_session() as db:
        before = len(db.categories.list())
        code, out, err = cli_runner("load", "categories", path)
        assert code == 3
        assert out == ""
        assert len(db.categories.list()) == before
        for cat, _ in good:
            assert db.categories.get(category=cat) is None
=== END AC load-categories-rejected-row-stores-nothing ===

=== AC load-categories-invalid-fields ===
Intent: each invalid code or description (bad characters, empty, over length, comma) rejects the whole file with exit 3 and stores no row.
Requires: executable=python3; scope=test

import csv
import os
import tempfile
from cli.testing import cli_runner
from persistence.testing import db_session

first = ["ZZKCOK", "Valid First"]
bad_rows = [
    ["zzkc1", "Lowercase"],
    ["ABCDEFGHIJKLM", "Too Long Code"],
    ["", "Empty Code"],
    ["ZZKC2", ""],
    ["ZZKC3", "has,comma"],
]
with tempfile.TemporaryDirectory() as d:
    with db_session() as db:
        for i, bad in enumerate(bad_rows):
            path = os.path.join(d, "c%d.csv" % i)
            with open(path, "w", newline="") as fh:
                w = csv.writer(fh, lineterminator="\n")
                w.writerow(["category", "description"])
                w.writerow(first)
                w.writerow(bad)
            code, out, err = cli_runner("load", "categories", path)
            assert code == 3, bad
            assert out == ""
            assert db.categories.get(category=first[0]) is None
=== END AC load-categories-invalid-fields ===

=== AC load-categories-duplicates-rejected ===
Intent: a code repeated inside the file, and a code already stored, each reject the whole file with exit 3 and leave the stored row unchanged.
Requires: executable=python3; scope=test

import csv
import os
import tempfile
from cli.testing import cli_runner
from persistence.testing import db_session

def write(path, rows):
    with open(path, "w", newline="") as fh:
        w = csv.writer(fh, lineterminator="\n")
        w.writerow(["category", "description"])
        w.writerows(rows)

with tempfile.TemporaryDirectory() as d:
    with db_session() as db:
        p1 = os.path.join(d, "dup_in_file.csv")
        write(p1, [["ZZKD1", "One"], ["ZZKD1", "One Again"]])
        code, out, err = cli_runner("load", "categories", p1)
        assert code == 3
        assert out == ""
        assert db.categories.get(category="ZZKD1") is None

        stored = "ZZKD2"
        stored_text = "Already Stored"
        db.categories.create(category=stored, description=stored_text)
        p2 = os.path.join(d, "dup_stored.csv")
        write(p2, [["ZZKD3", "Fresh"], [stored, "Replacement"]])
        code, out, err = cli_runner("load", "categories", p2)
        assert code == 3
        assert out == ""
        assert db.categories.get(category="ZZKD3") is None
        row = db.categories.get(category=stored)
        got = row["description"] if isinstance(row, dict) else row.description
        assert got == stored_text
=== END AC load-categories-duplicates-rejected ===

=== AC load-categories-header-and-usage ===
Intent: a wrong header exits 3 with nothing stored, and a missing file argument is a usage error with exit 2.
Requires: executable=python3; scope=test

import csv
import os
import tempfile
from cli.testing import cli_runner
from persistence.testing import db_session

with tempfile.TemporaryDirectory() as d:
    path = os.path.join(d, "wrong_header.csv")
    with open(path, "w", newline="") as fh:
        w = csv.writer(fh, lineterminator="\n")
        w.writerow(["category", "name"])
        w.writerow(["ZZKE1", "Wrong Header"])
    with db_session() as db:
        code, out, err = cli_runner("load", "categories", path)
        assert code == 3
        assert out == ""
        assert db.categories.get(category="ZZKE1") is None
        code, out, err = cli_runner("load", "categories")
        assert code == 2
        assert out == ""
=== END AC load-categories-header-and-usage ===

## User Acceptance

- None.

## Guardrails

- No row is written until every row in the file has been validated.
- Seed files are never read by application code; the file path comes only from the command line.
- A failing command writes nothing to standard output.

</pblock>

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

# FEATURE: Transfer

| Field | Value |
|-------|-------|
| Version | 20261027 V1 |
| Description | Implements `ledger transfer <from> <to> <amount> <date>`, an atomic two-row move of cash between distinct accounts in category TRANSFER. |
| Depends On | FEATURE-TxnPost.md, FEATURE-Validation.md, FEATURE-BalanceRule.md, FEATURE-CliEntry.md, DATABASE.md |
| Provides | ledger transfer |
| Consumes | ledger_core.transactions, ledger_core.validation, ledger_core.balances, cli.registry |

## Purpose

Move cash between two accounts as two transaction rows that are stored together or not at all. Persistence is reached only through `ledger_core.transactions`, which calls the generated `persistence` package.

## Behavior

1. Argument count other than four after `transfer` exits 2.
2. Validate before any write: the amount is positive with at most two decimals, the date is a real `YYYY-MM-DD` date, both accounts exist, they differ, and category `TRANSFER` exists. Any violation exits 3.
3. The source balance after the debit must not be below zero, checked through `ledger_core.balances`; otherwise exit 3.
4. The outgoing row takes id max(txn_id)+1 (or 1 when empty): amount `-amount`, account `<from>`, category `TRANSFER`, memo `transfer to <to>`. The incoming row takes the next id: amount `+amount`, account `<to>`, memo `transfer from <from>`.
5. Both rows are inserted atomically and printed under the header `txn_id,date,account,category,amount,memo`.
6. A failing command writes nothing to standard output and stores neither row.

## Database Interface

- None — persistence is owned by DATABASE.md and reached through `ledger_core.transactions`.

## Programmatic Acceptance

=== AC transfer-success ===
Intent: A valid transfer exits 0 and prints two rows with consecutive ids starting at the previous maximum plus one, category TRANSFER, the signed amounts, and the specified memos; a separate read shows both stored.

from cli.testing import cli_runner
from persistence.testing import db_session
import csv
import io

def f(row, name):
    return row[name] if isinstance(row, dict) else getattr(row, name)

src, dst, cat = "ZZTF1", "ZZTF2", "TRANSFER"
day = "2026-05-10"
amount_text = "250.00"
cents = int(amount_text.replace(".", ""))
with db_session() as db:
    db.accounts.create(account=src, name="Source Account")
    db.accounts.create(account=dst, name="Dest Account")
    if db.categories.get(category=cat) is None:
        db.categories.create(category=cat, description="Internal transfer")
    db.transactions.create(txn_id=900300001, date="2026-05-01", account=src, category=cat, amount=100000, memo="funding")
    before_max = max(f(r, "txn_id") for r in db.transactions.list())
    code, out, err = cli_runner("transfer", src, dst, amount_text, day)
    print(out)
    print(err)
    assert code == 0
    rows = list(csv.reader(io.StringIO(out)))
    assert len(rows) == 3
    out_row, in_row = rows[1], rows[2]
    assert int(out_row[0]) == before_max + 1
    assert int(in_row[0]) == int(out_row[0]) + 1
    assert out_row[1] == day and in_row[1] == day
    assert out_row[2] == src and in_row[2] == dst
    assert out_row[3] == cat and in_row[3] == cat
    assert out_row[4] == "-" + amount_text
    assert in_row[4] == amount_text
    assert out_row[5] == "transfer to " + dst
    assert in_row[5] == "transfer from " + src
    assert f(db.transactions.get(txn_id=int(out_row[0])), "amount") == -cents
    assert f(db.transactions.get(txn_id=int(in_row[0])), "amount") == cents
=== END AC transfer-success ===

=== AC transfer-conserves-cash ===
Intent: A valid transfer moves cash without changing the total held by the two accounts, computed from stored rows before and after.

from cli.testing import cli_runner
from persistence.testing import db_session

def f(row, name):
    return row[name] if isinstance(row, dict) else getattr(row, name)

src, dst, cat = "ZZTF3", "ZZTF4", "TRANSFER"
with db_session() as db:
    db.accounts.create(account=src, name="Source Account")
    db.accounts.create(account=dst, name="Dest Account")
    if db.categories.get(category=cat) is None:
        db.categories.create(category=cat, description="Internal transfer")
    db.transactions.create(txn_id=900300010, date="2026-05-01", account=src, category=cat, amount=50000, memo="funding")

    def balance(code_):
        return sum(f(r, "amount") for r in db.transactions.list(account=code_))

    src_before, dst_before = balance(src), balance(dst)
    code, out, err = cli_runner("transfer", src, dst, "123.45", "2026-05-11")
    print(out)
    print(err)
    assert code == 0
    assert balance(src) + balance(dst) == src_before + dst_before
    assert balance(src) == src_before - 12345
    assert balance(dst) == dst_before + 12345
=== END AC transfer-conserves-cash ===

=== AC transfer-insufficient-funds ===
Intent: A transfer exceeding the source balance by one cent exits 3 and stores neither row; a transfer of exactly the balance then succeeds and leaves the source at zero.

from cli.testing import cli_runner
from persistence.testing import db_session

def f(row, name):
    return row[name] if isinstance(row, dict) else getattr(row, name)

src, dst, cat = "ZZTF5", "ZZTF6", "TRANSFER"
with db_session() as db:
    db.accounts.create(account=src, name="Source Account")
    db.accounts.create(account=dst, name="Dest Account")
    if db.categories.get(category=cat) is None:
        db.categories.create(category=cat, description="Internal transfer")
    db.transactions.create(txn_id=900300020, date="2026-05-01", account=src, category=cat, amount=10000, memo="funding")
    total_before = len(db.transactions.list())
    code, out, err = cli_runner("transfer", src, dst, "100.01", "2026-05-12")
    print(out)
    print(err)
    assert code == 3
    assert out == ""
    assert len(db.transactions.list()) == total_before
    assert db.transactions.list(account=dst) == []
    code, out, err = cli_runner("transfer", src, dst, "100.00", "2026-05-12")
    print(out)
    print(err)
    assert code == 0
    assert sum(f(r, "amount") for r in db.transactions.list(account=src)) == 0
=== END AC transfer-insufficient-funds ===

=== AC transfer-rejections ===
Intent: Same source and destination, zero or negative amounts, three decimals, an impossible date, and an unknown account are each rejected with exit 3, with empty stdout and no new rows.

from cli.testing import cli_runner
from persistence.testing import db_session

src, dst, cat = "ZZTF7", "ZZTF8", "TRANSFER"
missing = "ZZTFNONE"
with db_session() as db:
    db.accounts.create(account=src, name="Source Account")
    db.accounts.create(account=dst, name="Dest Account")
    if db.categories.get(category=cat) is None:
        db.categories.create(category=cat, description="Internal transfer")
    db.transactions.create(txn_id=900300030, date="2026-05-01", account=src, category=cat, amount=100000, memo="funding")
    assert db.accounts.get(account=missing) is None
    total_before = len(db.transactions.list())
    cases = [
        (src, src, "5.00", "2026-05-13"),
        (src, dst, "0", "2026-05-13"),
        (src, dst, "-5.00", "2026-05-13"),
        (src, dst, "5.001", "2026-05-13"),
        (src, dst, "5.00", "2026-02-30"),
        (src, missing, "5.00", "2026-05-13"),
        (missing, dst, "5.00", "2026-05-13"),
    ]
    for args in cases:
        code, out, err = cli_runner("transfer", *args)
        print(args, code, out, err)
        assert code == 3
        assert out == ""
        assert len(db.transactions.list()) == total_before
=== END AC transfer-rejections ===

=== AC transfer-usage ===
Intent: A wrong argument count for transfer exits 2 with nothing on stdout.

from cli.testing import cli_runner

for args in [("transfer",), ("transfer", "A", "B", "1.00"), ("transfer", "A", "B", "1.00", "2026-05-01", "extra")]:
    code, out, err = cli_runner(*args)
    print(out)
    print(err)
    assert code == 2
    assert out == ""
=== END AC transfer-usage ===

## User Acceptance

- None.

## Guardrails

- Both rows are written together or neither is; every check runs before the first write.
- Amounts are integer cents; floating point is never used for money.
- Standard output stays empty on any failure; the diagnostic goes to standard error.
- Ids are never hardcoded; they derive from the largest stored `txn_id`.

</pblock>

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

Build instructions for this block

Implement ledger load accounts <csv> as an all-or-nothing load. (feature-load-accounts)

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.

Implement ledger account delete <code>. (feature-account-delete)

Check existence (absent exits 4), then check the account has no transactions (otherwise exit 3), then delete and print deleted and the code.

Implement ledger txn get <id>. (feature-txn-get)

Print the transaction row; an absent id exits 4 and a non-integer id exits 3.

Implement ledger account rename <code> <name>. (feature-account-rename)

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.

Implement ledger account get <code>. (feature-account-get)

Print the current account row with live transaction count and balance. An absent code exits 4.

Implement ledger txn delete <id>. (feature-txn-delete)

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.

Implement ledger txn amend <id> <amount>. (feature-txn-amend)

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.

Implement ledger load categories <csv> as an all-or-nothing load. (feature-load-categories)

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.

Implement ledger transfer <from> <to> <amount> <date> as an atomic two-row write. (feature-transfer)

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.

</pblock>

Agent Task

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

authoritative; implement them exactly.

Operating contract:

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

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

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

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

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

not as additional work to perform.

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

this step's Definition of Done — human-owned, declared before the build, and fixed. Build the story and, in this same step, write the deterministic tests that prove each declared assertion, as a TDD master would; add finer tests for coverage. Every test you write follows the same rule the acceptance assertions do: act on the system, read the state back, compare to expected. The oracle is a return value, parsed JSON, a status code, a stored row, file contents read back, or an exit status — never a substring of captured stdout or stderr, a test-runner tally, or a log line. Write tests in the project's own language using that language's libraries; an in-language HTTP client yields a status code and a parsed body, where curl yields text to scrape. Round-trip anything that stores state: act, then read back through the public interface. Assert declared failure signals on negative paths, never message wording. You may add tests but must never remove, soften, or weaken a declared acceptance assertion. A Suite: full conformance check gates on the entire imported test suite: the step is done only when it passes in full, never on a representative subset — reproduce the standard exactly rather than wrapping a third-party library that approximates it. For a suite, the runner's exit status is the verdict and the whole verdict: print its captured output for diagnosis, never assert on the text of its summary. When an assertion is a static or filesystem scan (import boundary, "X never appears outside Y," grep/AST gate), honor the scope the specification states and never widen it: scan production source only, exclude .venv/, site-packages, and vendored or generated code, and do not flag test doubles or fixtures that use the guarded dependency. Run targeted tests for the behavior you change and preserve existing passing behavior. Drydock executes every declared acceptance assertion after your call and owns the verdict. Use available failure logs before rerunning suites to rediscover failures; use section or example filters to diagnose the underlying behavior, never example-specific exceptions. If you run a suite, wait for completion or its declared timeout; silence is not a hang. During repair, select a failing example, reproduce it before editing, and trace its actual execution branch. Add a regression that fails on the current code, fix the cause, and run that regression plus a passing neighbor. Revise an ineffective edit within this call. Report only tests actually executed, with their command and result; label unrun tests unrun.

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

real coverage. The acceptance assertions in implements are gates: few, fixed, and written before any code existed, so every expectation in them is a prediction. The tests you write are written beside the finished code, so their expected values are observed rather than predicted — which is why exhaustive coverage belongs here and not there. Extend the suite in the project's established location and runner, keep it runnable by the project's declared test command, and leave it green when you return. Cover, at minimum: every public entry point and every verb it declares, including declared error paths; the boundaries — empty, exactly one, many, absent optional fields, declared maxima; declared idempotence, applied twice; one behavior per test, named for the behavior; and isolation — database criteria use the provisioned application store and the shipped rollback fixture, passing its connection into the feature. Other connections and durability tests use criterion-owned records, idempotent setup and checked cleanup through supported interfaces. Never replace the configured store, reapply schema, or delete unrelated business records. When Drydock supplies a disposable SQLite store in DATABASE_URL/DATABASE_PATH, use those inherited values for development tests. Each agent call receives a fresh provisioned test store. Never delete a default database path to clean test failures. Project tests still need fixture-owned setup and cleanup so repeated tests in the same call do not depend on order. A managed-state violation stops the block and retains a recovery snapshot; do not restore or reprovision shared state yourself. Preserve published text even when a conflicting criterion requests formatting: report the source conflict and its evidence instead of changing semantics. Where a staged authoritative suite already covers a surface, use it as the coverage; do not duplicate its cases. Any invocation must respect this step's declared scope. Do not run the unscoped entry point for a Suite: scoped story, or run a suite this step does not declare. Report only completed checks and their observed results.

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

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

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

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

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

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

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

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

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

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

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

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

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

FILES CHANGED:
- relative/path

SUMMARY:
<brief reviewable summary>

BLOCKERS:
- <only if any>

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

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

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

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

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

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

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

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

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

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

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