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

2. **Input Context** — begins with the heading `# Input Context`. All blocks are wrapped in
   `<pblock>` tags. Two block types:
   - File blocks: `<pblock filename="<name>" role="<role>" guidance="...">` — optional
     `guidance` attribute carries context-specific instructions; content is in a fenced block.
   - Metadata/section blocks: `<pblock label="<label>" kind="<kind>">` — job parameters,
     rules, instructions, or group headers.

3. **Agent Task** — begins with the heading `# Agent Task`. Defines your persona, constraints,
   and required outputs. Read all input context before acting on this section.


# Input Context

<pblock label="Build block job" kind="job">
## Build block job
- TARGET: LayersTesting
- BUILD_DIRECTORY: /mnt/c/Users/barlo/projects/drydock/uat/LayersTesting/runs/20261027.135355/build/LayersTesting
- WORKING_DIRECTORY: /mnt/c/Users/barlo/projects/drydock/uat/LayersTesting/runs/20261027.135355/build/LayersTesting
- BUILD_BLOCK: Block 3 · Foundational (block-3)
- STORIES: Provide the `ledger` executable at the application root with a command registry, usage-error handling, and the stdout/stderr contract. (foundation-cli)
- DATE: 2026-10-27
- BUILD_SCOPE: exactly one MANIFEST.md build block

</pblock>

<pblock label="Stories in this block" kind="section">
## Stories in this block
- Provide the `ledger` executable at the application root with a command registry, usage-error handling, and the stdout/stderr contract. (foundation-cli) [story]

</pblock>

<pblock label="Files on disk" kind="section">
## Files on disk in the build directory
- sources/run.sh
- sources/seed_accounts.csv
- sources/seed_categories.csv
- sources/seed_transactions.csv
- sources/seed_transactions_bad.csv

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

</pblock>


## 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.">
```markdown
# 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.md" role="context" path="/mnt/c/Users/barlo/projects/drydock/uat/LayersTesting/runs/20261027.135355/workspace/targets/LayersTesting/blueprint/DATABASE.md" guidance="Database and PersistenceSpecification">
```markdown
# DATABASE: LayersTesting

| Field | Value |
|-------|-------|
| Version | 20261027 V1 |
| Description | Persistence stores and typed interfaces for the LayersTesting cash ledger. |
| Depends On | ARCHITECTURE.md |
| Provides | persistence.accounts, persistence.categories, persistence.transactions |
| Build Order | 1 |

## Persistence Boundary

| Boundary | Rule |
|----------|------|
| Raw storage access | Only the generated `persistence/` package reaches the store. |
| Caller dependency | Features depend on declared access patterns and their DTOs, not on schemas. |
| Implementation | Generated from this file at the DATABASE build step; never written by hand. |
| Money | Amounts are stored as integer cents; no floating point at any layer. |
| Aggregates | Counts, sums, and the largest `txn_id` are computed by callers from `list` results; no aggregate operation is declared. |

## Access Patterns

### FEATURE-ACCOUNT-001 — Create an account

| Field | Value |
|-------|-------|
| Owner | DATABASE.md |
| Access | write |
| Repository operation | `accounts.create` |
| Compatibility | unchanged |

Input: AccountsCreateInput

| Field | Type | Notes |
|-------|------|-------|
| account | TEXT | Account code |
| name | TEXT | Account name |

Output: AccountsCreateOutput

| Field | Type | Notes |
|-------|------|-------|
| account | TEXT | Account code |
| name | TEXT | Account name |

### FEATURE-ACCOUNT-002 — Get an account by code

| Field | Value |
|-------|-------|
| Owner | DATABASE.md |
| Access | read |
| Repository operation | `accounts.get` |
| Compatibility | unchanged |

Input: AccountsGetInput

| Field | Type | Notes |
|-------|------|-------|
| account | TEXT | Account code |

Output: AccountsGetOutput

| Field | Type | Notes |
|-------|------|-------|
| account | TEXT | Account code |
| name | TEXT | Account name |

### FEATURE-ACCOUNT-003 — Rename an account

| Field | Value |
|-------|-------|
| Owner | DATABASE.md |
| Access | write |
| Repository operation | `accounts.update` |
| Match | `account` |
| Compatibility | unchanged |

Input: AccountsUpdateInput

| Field | Type | Notes |
|-------|------|-------|
| account | TEXT | Account code (match) |
| name | TEXT | New name |

Output: AccountsUpdateOutput

| Field | Type | Notes |
|-------|------|-------|
| account | TEXT | Account code |
| name | TEXT | Account name |

### FEATURE-ACCOUNT-004 — Delete an account

| Field | Value |
|-------|-------|
| Owner | DATABASE.md |
| Access | write |
| Repository operation | `accounts.delete` |
| Match | `account` |
| Compatibility | unchanged |

Input: AccountsDeleteInput

| Field | Type | Notes |
|-------|------|-------|
| account | TEXT | Account code |

Output: AccountsDeleteOutput

| Field | Type | Notes |
|-------|------|-------|
| account | TEXT | Account code |

### FEATURE-ACCOUNT-005 — List accounts by code

| Field | Value |
|-------|-------|
| Owner | DATABASE.md |
| Access | read |
| Repository operation | `accounts.list` |
| Kind | list |
| Order | `account` asc |
| Compatibility | unchanged |

Input: AccountsListInput

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

Output: AccountsListOutput

| Field | Type | Notes |
|-------|------|-------|
| account | TEXT | Account code |
| name | TEXT | Account name |

### FEATURE-ACCOUNT-006 — Remove accounts from a code onward

| Field | Value |
|-------|-------|
| Owner | DATABASE.md |
| Access | write |
| Repository operation | `accounts.clear` |
| Kind | delete |
| Match | `account >= min_account` |
| Compatibility | unchanged |

Input: AccountsClearInput

| Field | Type | Notes |
|-------|------|-------|
| min_account | TEXT | Lowest code removed; an empty string removes every account |

Output: AccountsClearOutput

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

### FEATURE-CATEGORY-001 — Create a category

| Field | Value |
|-------|-------|
| Owner | DATABASE.md |
| Access | write |
| Repository operation | `categories.create` |
| Compatibility | unchanged |

Input: CategoriesCreateInput

| Field | Type | Notes |
|-------|------|-------|
| category | TEXT | Category code |
| description | TEXT | Description |

Output: CategoriesCreateOutput

| Field | Type | Notes |
|-------|------|-------|
| category | TEXT | Category code |
| description | TEXT | Description |

### FEATURE-CATEGORY-002 — Get a category by code

| Field | Value |
|-------|-------|
| Owner | DATABASE.md |
| Access | read |
| Repository operation | `categories.get` |
| Compatibility | unchanged |

Input: CategoriesGetInput

| Field | Type | Notes |
|-------|------|-------|
| category | TEXT | Category code |

Output: CategoriesGetOutput

| Field | Type | Notes |
|-------|------|-------|
| category | TEXT | Category code |
| description | TEXT | Description |

### FEATURE-CATEGORY-003 — Change a category description

| Field | Value |
|-------|-------|
| Owner | DATABASE.md |
| Access | write |
| Repository operation | `categories.update` |
| Match | `category` |
| Compatibility | unchanged |

Input: CategoriesUpdateInput

| Field | Type | Notes |
|-------|------|-------|
| category | TEXT | Category code (match) |
| description | TEXT | New description |

Output: CategoriesUpdateOutput

| Field | Type | Notes |
|-------|------|-------|
| category | TEXT | Category code |
| description | TEXT | Description |

### FEATURE-CATEGORY-004 — Delete a category

| Field | Value |
|-------|-------|
| Owner | DATABASE.md |
| Access | write |
| Repository operation | `categories.delete` |
| Match | `category` |
| Compatibility | unchanged |

Input: CategoriesDeleteInput

| Field | Type | Notes |
|-------|------|-------|
| category | TEXT | Category code |

Output: CategoriesDeleteOutput

| Field | Type | Notes |
|-------|------|-------|
| category | TEXT | Category code |

### FEATURE-CATEGORY-005 — List categories by code

| Field | Value |
|-------|-------|
| Owner | DATABASE.md |
| Access | read |
| Repository operation | `categories.list` |
| Kind | list |
| Order | `category` asc |
| Compatibility | unchanged |

Input: CategoriesListInput

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

Output: CategoriesListOutput

| Field | Type | Notes |
|-------|------|-------|
| category | TEXT | Category code |
| description | TEXT | Description |

### FEATURE-CATEGORY-006 — Remove categories from a code onward

| Field | Value |
|-------|-------|
| Owner | DATABASE.md |
| Access | write |
| Repository operation | `categories.clear` |
| Kind | delete |
| Match | `category >= min_category` |
| Compatibility | unchanged |

Input: CategoriesClearInput

| Field | Type | Notes |
|-------|------|-------|
| min_category | TEXT | Lowest code removed; an empty string removes every category |

Output: CategoriesClearOutput

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

### FEATURE-TXN-001 — Create a transaction

| Field | Value |
|-------|-------|
| Owner | DATABASE.md |
| Access | write |
| Repository operation | `transactions.create` |
| Compatibility | unchanged |

Input: TransactionsCreateInput

| Field | Type | Notes |
|-------|------|-------|
| txn_id | INTEGER | Caller-assigned id (loaded id, or largest id plus one) |
| date | TEXT | YYYY-MM-DD |
| account | TEXT | Existing account code |
| category | TEXT | Existing category code |
| amount | INTEGER | Cents, signed |
| memo | TEXT | Memo, possibly empty |

Output: TransactionsCreateOutput

| Field | Type | Notes |
|-------|------|-------|
| txn_id | INTEGER | Transaction id |
| date | TEXT | YYYY-MM-DD |
| account | TEXT | Account code |
| category | TEXT | Category code |
| amount | INTEGER | Cents, signed |
| memo | TEXT | Memo |

### FEATURE-TXN-002 — Get a transaction by id

| Field | Value |
|-------|-------|
| Owner | DATABASE.md |
| Access | read |
| Repository operation | `transactions.get` |
| Compatibility | unchanged |

Input: TransactionsGetInput

| Field | Type | Notes |
|-------|------|-------|
| txn_id | INTEGER | Transaction id |

Output: TransactionsGetOutput

| Field | Type | Notes |
|-------|------|-------|
| txn_id | INTEGER | Transaction id |
| date | TEXT | YYYY-MM-DD |
| account | TEXT | Account code |
| category | TEXT | Category code |
| amount | INTEGER | Cents, signed |
| memo | TEXT | Memo |

### FEATURE-TXN-003 — Amend a transaction amount

| Field | Value |
|-------|-------|
| Owner | DATABASE.md |
| Access | write |
| Repository operation | `transactions.update` |
| Match | `txn_id` |
| Compatibility | unchanged |

Input: TransactionsUpdateInput

| Field | Type | Notes |
|-------|------|-------|
| txn_id | INTEGER | Transaction id (match) |
| amount | INTEGER | New amount in cents |

Output: TransactionsUpdateOutput

| Field | Type | Notes |
|-------|------|-------|
| txn_id | INTEGER | Transaction id |
| date | TEXT | YYYY-MM-DD |
| account | TEXT | Account code |
| category | TEXT | Category code |
| amount | INTEGER | Cents, signed |
| memo | TEXT | Memo |

### FEATURE-TXN-004 — Delete a transaction

| Field | Value |
|-------|-------|
| Owner | DATABASE.md |
| Access | write |
| Repository operation | `transactions.delete` |
| Match | `txn_id` |
| Compatibility | unchanged |

Input: TransactionsDeleteInput

| Field | Type | Notes |
|-------|------|-------|
| txn_id | INTEGER | Transaction id |

Output: TransactionsDeleteOutput

| Field | Type | Notes |
|-------|------|-------|
| txn_id | INTEGER | Transaction id |

### FEATURE-TXN-005 — List transactions by account, category, or date range

| Field | Value |
|-------|-------|
| Owner | DATABASE.md |
| Access | read |
| Repository operation | `transactions.list` |
| Kind | list |
| Match | `account`, `category`, `date >= start_date`, `date <= end_date` |
| Order | `txn_id` asc |
| Compatibility | unchanged |

Input: TransactionsListInput

| Field | Type | Notes |
|-------|------|-------|
| account | TEXT | Optional filter |
| category | TEXT | Optional filter |
| start_date | TEXT | Optional lower bound, inclusive |
| end_date | TEXT | Optional upper bound, inclusive |

Output: TransactionsListOutput

| Field | Type | Notes |
|-------|------|-------|
| txn_id | INTEGER | Transaction id |
| date | TEXT | YYYY-MM-DD |
| account | TEXT | Account code |
| category | TEXT | Category code |
| amount | INTEGER | Cents, signed |
| memo | TEXT | Memo |

### FEATURE-TXN-006 — Remove transactions from an id onward

| Field | Value |
|-------|-------|
| Owner | DATABASE.md |
| Access | write |
| Repository operation | `transactions.clear` |
| Kind | delete |
| Match | `txn_id >= min_txn_id` |
| Compatibility | unchanged |

Input: TransactionsClearInput

| Field | Type | Notes |
|-------|------|-------|
| min_txn_id | INTEGER | Lowest id removed; 0 removes every transaction |

Output: TransactionsClearOutput

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

## Schemas

## `accounts`

| Field | Type | Notes |
|-------|------|-------|
| account | TEXT PK | Code, 1 to 12 characters of A-Z and 0-9 |
| name | TEXT NOT NULL | 1 to 40 characters |

## `categories`

| Field | Type | Notes |
|-------|------|-------|
| category | TEXT PK | Code, 1 to 12 characters of A-Z and 0-9 |
| description | TEXT NOT NULL | 1 to 40 characters |

## `transactions`

| Field | Type | Notes |
|-------|------|-------|
| txn_id | INTEGER PK | Transaction id |
| date | TEXT NOT NULL | YYYY-MM-DD |
| account | TEXT NOT NULL REFERENCES accounts(account) | Owning account |
| category | TEXT NOT NULL REFERENCES categories(category) | Category |
| amount | INTEGER NOT NULL | Integer cents, signed, never zero |
| memo | TEXT NOT NULL DEFAULT '' | 0 to 60 characters |

- INDEX (account, date)

## Migrations

Each relational change has one staged record in `migrations/MIGRATION-<AccessPatternId>.md`.
The record carries Alembic `upgrade`/`downgrade` snippets and progresses from `planned` to `built`
only when its DATABASE build story completes. Alembic records deployment application separately.

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

## Config (.env)

| Key | Type | Required | Notes |
|-----|------|----------|-------|
| DATABASE_URL | string | No | SQLite file path, optionally prefixed `sqlite://`; consulted first |
| DATABASE_PATH | string | No | SQLite file path; consulted when DATABASE_URL is unset; default `data/app.db` |

## File Stores

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

## External Services

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

## External Libraries

| Library | Ownership | Distribution | Consumer Contract |
|---------|-----------|--------------|-------------------|

## Programmatic Acceptance

=== AC accounts-create ===
Intent: accounts.create stores a row and returns the declared Output, which a separate get reads back.

from persistence.testing import db_session

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

code = "ZZCR1"
label = "Create Probe"
with db_session() as db:
    out = db.accounts.create(account=code, name=label)
    assert f(out, "account") == code
    assert f(out, "name") == label
    back = db.accounts.get(account=code)
    assert back is not None
    assert f(back, "name") == label
=== END AC accounts-create ===

=== AC accounts-get ===
Intent: accounts.get returns the stored row for an existing code and None for an absent one.

from persistence.testing import db_session

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

code = "ZZGET1"
label = "Get Probe"
with db_session() as db:
    db.accounts.create(account=code, name=label)
    row = db.accounts.get(account=code)
    assert row is not None
    assert f(row, "account") == code
    assert f(row, "name") == label
    assert db.accounts.get(account="ZZGETNONE") is None
=== END AC accounts-get ===

=== AC accounts-update ===
Intent: accounts.update changes only the name and the change is visible on a separate read.

from persistence.testing import db_session

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

code = "ZZUPD1"
before = "Before Name"
after = "After Name"
with db_session() as db:
    db.accounts.create(account=code, name=before)
    out = db.accounts.update(account=code, name=after)
    assert out is not None
    assert f(out, "name") == after
    back = db.accounts.get(account=code)
    assert f(back, "name") == after
    assert f(back, "account") == code
=== END AC accounts-update ===

=== AC accounts-delete ===
Intent: accounts.delete removes the row so a later get finds nothing.

from persistence.testing import db_session

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

code = "ZZDEL1"
with db_session() as db:
    db.accounts.create(account=code, name="Delete Probe")
    out = db.accounts.delete(account=code)
    assert out is not None
    assert f(out, "account") == code
    assert db.accounts.get(account=code) is None
=== END AC accounts-delete ===

=== AC accounts-list ===
Intent: accounts.list returns rows ordered by account code ascending; two codes created in reverse order appear in sorted order.

from persistence.testing import db_session

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

codes = ["ZZLA2", "ZZLA1"]
with db_session() as db:
    for c in codes:
        db.accounts.create(account=c, name="List " + c)
    rows = db.accounts.list()
    seen = [f(r, "account") for r in rows if f(r, "account") in codes]
    assert seen == sorted(codes)
    allcodes = [f(r, "account") for r in rows]
    assert allcodes == sorted(allcodes)
=== END AC accounts-list ===

=== AC accounts-clear ===
Intent: accounts.clear removes accounts whose code is at or above the bound, reports a positive count, and leaves none readable.

from persistence.testing import db_session

code = "ZZCLR1"
with db_session() as db:
    db.accounts.create(account=code, name="Clear Probe")
    removed = db.accounts.clear(min_account=code)
    assert removed >= 1
    assert db.accounts.get(account=code) is None
=== END AC accounts-clear ===

=== AC categories-create ===
Intent: categories.create stores a row and returns the declared Output, which a separate get reads back.

from persistence.testing import db_session

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

code = "ZZCCR1"
text = "Create Probe"
with db_session() as db:
    out = db.categories.create(category=code, description=text)
    assert f(out, "category") == code
    assert f(out, "description") == text
    back = db.categories.get(category=code)
    assert back is not None
    assert f(back, "description") == text
=== END AC categories-create ===

=== AC categories-get ===
Intent: categories.get returns the stored row for an existing code and None for an absent one.

from persistence.testing import db_session

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

code = "ZZCGET1"
text = "Get Probe"
with db_session() as db:
    db.categories.create(category=code, description=text)
    row = db.categories.get(category=code)
    assert row is not None
    assert f(row, "category") == code
    assert f(row, "description") == text
    assert db.categories.get(category="ZZCGETNONE") is None
=== END AC categories-get ===

=== AC categories-update ===
Intent: categories.update changes the description and the change is visible on a separate read.

from persistence.testing import db_session

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

code = "ZZCUPD1"
before = "Before Text"
after = "After Text"
with db_session() as db:
    db.categories.create(category=code, description=before)
    out = db.categories.update(category=code, description=after)
    assert out is not None
    assert f(out, "description") == after
    back = db.categories.get(category=code)
    assert f(back, "description") == after
=== END AC categories-update ===

=== AC categories-delete ===
Intent: categories.delete removes the row so a later get finds nothing.

from persistence.testing import db_session

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

code = "ZZCDEL1"
with db_session() as db:
    db.categories.create(category=code, description="Delete Probe")
    out = db.categories.delete(category=code)
    assert out is not None
    assert f(out, "category") == code
    assert db.categories.get(category=code) is None
=== END AC categories-delete ===

=== AC categories-list ===
Intent: categories.list returns rows ordered by category code ascending; two codes created in reverse order appear in sorted order.

from persistence.testing import db_session

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

codes = ["ZZCLA2", "ZZCLA1"]
with db_session() as db:
    for c in codes:
        db.categories.create(category=c, description="List " + c)
    rows = db.categories.list()
    seen = [f(r, "category") for r in rows if f(r, "category") in codes]
    assert seen == sorted(codes)
    allcodes = [f(r, "category") for r in rows]
    assert allcodes == sorted(allcodes)
=== END AC categories-list ===

=== AC categories-clear ===
Intent: categories.clear removes categories whose code is at or above the bound, reports a positive count, and leaves none readable.

from persistence.testing import db_session

code = "ZZCCLR1"
with db_session() as db:
    db.categories.create(category=code, description="Clear Probe")
    removed = db.categories.clear(min_category=code)
    assert removed >= 1
    assert db.categories.get(category=code) is None
=== END AC categories-clear ===

=== AC transactions-create ===
Intent: transactions.create stores a signed integer-cents row under the supplied id and returns it, and a separate get reads every column back.

from persistence.testing import db_session

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

acct, cat = "ZZTA1", "ZZTC1"
tid = 900000001
day = "2026-05-01"
cents = -1234
note = "create probe"
with db_session() as db:
    db.accounts.create(account=acct, name="Txn Account")
    db.categories.create(category=cat, description="Txn Category")
    out = db.transactions.create(txn_id=tid, date=day, account=acct, category=cat, amount=cents, memo=note)
    assert f(out, "txn_id") == tid
    back = db.transactions.get(txn_id=tid)
    assert back is not None
    assert f(back, "date") == day
    assert f(back, "account") == acct
    assert f(back, "category") == cat
    assert f(back, "amount") == cents
    assert f(back, "memo") == note
=== END AC transactions-create ===

=== AC transactions-get ===
Intent: transactions.get returns the stored row for an existing id and None for an absent id.

from persistence.testing import db_session

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

acct, cat = "ZZTA2", "ZZTC2"
tid = 900000002
cents = 5050
with db_session() as db:
    db.accounts.create(account=acct, name="Txn Account")
    db.categories.create(category=cat, description="Txn Category")
    db.transactions.create(txn_id=tid, date="2026-05-02", account=acct, category=cat, amount=cents, memo="")
    row = db.transactions.get(txn_id=tid)
    assert row is not None
    assert f(row, "amount") == cents
    assert db.transactions.get(txn_id=tid + 1000) is None
=== END AC transactions-get ===

=== AC transactions-update ===
Intent: transactions.update changes only the amount and the change is visible on a separate read.

from persistence.testing import db_session

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

acct, cat = "ZZTA3", "ZZTC3"
tid = 900000003
day = "2026-05-03"
note = "amend probe"
old, new = 1000, 2500
with db_session() as db:
    db.accounts.create(account=acct, name="Txn Account")
    db.categories.create(category=cat, description="Txn Category")
    db.transactions.create(txn_id=tid, date=day, account=acct, category=cat, amount=old, memo=note)
    out = db.transactions.update(txn_id=tid, amount=new)
    assert out is not None
    assert f(out, "amount") == new
    back = db.transactions.get(txn_id=tid)
    assert f(back, "amount") == new
    assert f(back, "date") == day
    assert f(back, "memo") == note
    assert f(back, "account") == acct
=== END AC transactions-update ===

=== AC transactions-delete ===
Intent: transactions.delete removes the row so a later get finds nothing.

from persistence.testing import db_session

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

acct, cat = "ZZTA4", "ZZTC4"
tid = 900000004
with db_session() as db:
    db.accounts.create(account=acct, name="Txn Account")
    db.categories.create(category=cat, description="Txn Category")
    db.transactions.create(txn_id=tid, date="2026-05-04", account=acct, category=cat, amount=700, memo="")
    out = db.transactions.delete(txn_id=tid)
    assert out is not None
    assert f(out, "txn_id") == tid
    assert db.transactions.get(txn_id=tid) is None
=== END AC transactions-delete ===

=== AC transactions-list ===
Intent: transactions.list filters by account and inclusive date range and returns rows by txn_id ascending; rows outside the range or on another account are excluded.

from persistence.testing import db_session

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

acct, other, cat = "ZZTA5", "ZZTA6", "ZZTC5"
rows_in = [(900000012, "2026-06-10"), (900000011, "2026-06-05")]
outside = (900000013, "2026-07-01")
with db_session() as db:
    db.accounts.create(account=acct, name="Txn Account")
    db.accounts.create(account=other, name="Other Account")
    db.categories.create(category=cat, description="Txn Category")
    for tid, day in rows_in:
        db.transactions.create(txn_id=tid, date=day, account=acct, category=cat, amount=100, memo="")
    db.transactions.create(txn_id=outside[0], date=outside[1], account=acct, category=cat, amount=100, memo="")
    db.transactions.create(txn_id=900000014, date="2026-06-07", account=other, category=cat, amount=100, memo="")
    got = db.transactions.list(account=acct, start_date="2026-06-01", end_date="2026-06-30")
    ids = [f(r, "txn_id") for r in got]
    assert ids == sorted(t for t, _ in rows_in)
    assert all(f(r, "account") == acct for r in got)
=== END AC transactions-list ===

=== AC transactions-clear ===
Intent: transactions.clear removes transactions at or above the bound, reports a positive count, and leaves none readable.

from persistence.testing import db_session

acct, cat = "ZZTA7", "ZZTC7"
tid = 900000021
with db_session() as db:
    db.accounts.create(account=acct, name="Txn Account")
    db.categories.create(category=cat, description="Txn Category")
    db.transactions.create(txn_id=tid, date="2026-05-07", account=acct, category=cat, amount=300, memo="")
    removed = db.transactions.clear(min_txn_id=tid)
    assert removed >= 1
    assert db.transactions.get(txn_id=tid) is None
=== END AC transactions-clear ===

## User Acceptance

- None.

## Guardrails

- Only the generated `persistence/` package opens a database driver; application code calls `db.<table>.<operation>(...)`.
- Amounts are integer cents in every column, DTO, and caller; floating point is never used for money.
- Counts, balances, and the next `txn_id` are computed by callers from `list` results, never hardcoded.
- Acceptance criteria never apply DDL, replace DATABASE_URL or DATABASE_PATH, or assume an empty store.
```
</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-CliEntry.md" role="implements" path="/mnt/c/Users/barlo/projects/drydock/uat/LayersTesting/runs/20261027.135355/workspace/targets/LayersTesting/blueprint/FEATURE-CliEntry.md" guidance="Feature Specification">
```markdown
# FEATURE: CLI Entry

| Field | Value |
|-------|-------|
| Version | 20261027 V1 |
| Description | The `ledger` executable, command registry, dispatch rules, and stdout/stderr/exit-code contract. |
| Depends On | ARCHITECTURE.md, DATABASE.md |
| Provides | ledger, cli.registry |
| Consumes | persistence.accounts, persistence.categories, persistence.transactions |

## Purpose

Provide the single entry point through which every command runs. It resolves the command words, checks the argument count, opens the database, calls the handler, and turns the result into CSV on stdout or one diagnostic line on stderr with the contract exit code.

## Interface

- `ledger` at the application root: a POSIX launcher that activates `.venv` and calls `cli.main(sys.argv[1:])`, exiting with its return value.
- `cli.main(argv: list[str] | None = None) -> int`.
- `cli.testing.cli_runner(*args) -> (exit_code, stdout, stderr)`, running `main` in process.
- `cli.registry`:
  - `Command(handler, min_args, max_args)`, a named tuple. `max_args` is `None` when unbounded.
  - `COMMANDS: dict[tuple[str, ...], Command]`, keyed by command words such as `("account", "add")`.
  - `load()`, idempotent: imports every module in `cli/commands/` and adds the entries of each module's `COMMANDS` mapping. It never removes entries.
- Handler signature: `handler(db, args: list[str]) -> list[list[str]]`, where `db` is the opened database and `args` are the words after the command words. It returns every output row, header first, as lists of text.

## Dispatch Rules

1. Call `registry.load()`.
2. Match the longest command-word prefix of `argv` in `COMMANDS`. No match, an empty `argv`, or a known group word with an unknown sub-word (unknown table or report) is a usage error.
3. An argument count outside `min_args..max_args` is a usage error.
4. A usage error exits `2`, writes one diagnostic line to stderr, and writes nothing to stdout.
5. Open the database with `persistence.open_database(ledger_core.config.database_path())`. A failure to open exits `1`.
6. Call the handler. On success, write the rows to stdout as CSV: comma-separated, no quoting, no trailing spaces, `\n` line endings. Nothing is written to stdout before the handler returns.
7. A `LedgerError` exits with its `exit_code` and one stderr line. Any other exception exits `1` with one stderr line. Stdout stays empty in both cases.

Handlers validate every input and rule before their first write. Check order inside a handler: input validation (exit 3), then existence lookups (exit 4), then business rules (exit 3).

## Database Interface

- None — persistence is owned by DATABASE.md; this entry point only opens the database and passes it to handlers.

## Programmatic Acceptance

=== AC cli-registry-load ===
Intent: Registry loading is idempotent and every key is a tuple of words.

from cli import registry

registry.load()
count = len(registry.COMMANDS)
registry.load()
assert len(registry.COMMANDS) == count
for words in registry.COMMANDS:
    assert isinstance(words, tuple)
    assert all(isinstance(w, str) for w in words)
=== END AC cli-registry-load ===

=== AC cli-unknown-command ===
Intent: An unknown command, or no command at all, exits 2 with an empty stdout and exactly one stderr line.

from cli.testing import cli_runner

for args in [("zzfrobnicate",), ()]:
    code, out, err = cli_runner(*args)
    print(code, repr(out), repr(err))
    assert code == 2
    assert out == ""
    assert len(err.strip().splitlines()) == 1
=== END AC cli-unknown-command ===

=== AC cli-dispatch-success ===
Intent: A registered command receives its arguments and its rows print as unquoted CSV with newline endings.

import csv
import io
from cli import registry
from cli.testing import cli_runner

arg = "alpha"
words = ("zzgrp", "ok")

def handler(db, args):
    return [["h1", "h2"], [args[0], "v"]]

registry.load()
registry.COMMANDS[words] = registry.Command(handler, 1, 1)
try:
    code, out, err = cli_runner(*words, arg)
    print(code, repr(out), repr(err))
    assert code == 0
    assert list(csv.reader(io.StringIO(out))) == [["h1", "h2"], [arg, "v"]]
    assert "\r" not in out
    assert out.endswith("\n")
finally:
    registry.COMMANDS.pop(words, None)
=== END AC cli-dispatch-success ===

=== AC cli-usage-errors ===
Intent: A wrong argument count, a bare group word, and a group word with an unknown sub-word each exit 2 with empty stdout.

from cli import registry
from cli.testing import cli_runner

words = ("zzgrp2", "ok")

def handler(db, args):
    return [["h"], [args[0]]]

registry.load()
registry.COMMANDS[words] = registry.Command(handler, 1, 1)
try:
    cases = [words, words + ("a", "b"), ("zzgrp2",), ("zzgrp2", "nosuch")]
    for args in cases:
        code, out, err = cli_runner(*args)
        print(args, code, repr(out), repr(err))
        assert code == 2
        assert out == ""
        assert err.strip() != ""
finally:
    registry.COMMANDS.pop(words, None)
=== END AC cli-usage-errors ===

=== AC cli-domain-error-codes ===
Intent: Handlers raising Rejected, NotFound, or Operational exit 3, 4, or 1 and print nothing to stdout.

from cli import registry
from cli.testing import cli_runner
from ledger_core.errors import Rejected, NotFound, Operational

cases = {"rej": (Rejected, 3), "nf": (NotFound, 4), "op": (Operational, 1)}
registry.load()
added = []
try:
    for word, (cls, expected) in cases.items():
        def handler(db, args, cls=cls):
            raise cls("probe failure")
        key = ("zzerr", word)
        registry.COMMANDS[key] = registry.Command(handler, 0, 0)
        added.append(key)
        code, out, err = cli_runner(*key)
        print(word, code, repr(out), repr(err))
        assert code == expected
        assert out == ""
        assert len(err.strip().splitlines()) == 1
finally:
    for key in added:
        registry.COMMANDS.pop(key, None)
=== END AC cli-domain-error-codes ===

=== AC cli-unopenable-database ===
Intent: A database location that cannot be opened exits 1 with empty stdout.

from drydock_acceptance import database_environment
from cli import registry
from cli.testing import cli_runner

words = ("zzopen", "ok")

def handler(db, args):
    return [["h"]]

registry.load()
registry.COMMANDS[words] = registry.Command(handler, 0, 0)
try:
    with database_environment(url="missing/app.db"):
        code, out, err = cli_runner(*words)
        print(code, repr(out), repr(err))
        assert code == 1
        assert out == ""
finally:
    registry.COMMANDS.pop(words, None)
=== END AC cli-unopenable-database ===

=== AC cli-launcher ===
Intent: The ledger launcher at the application root is executable and exits 2 for an unknown command with empty stdout.

import os
import subprocess

assert os.access("ledger", os.X_OK)
result = subprocess.run(["./ledger", "zzfrobnicate"], capture_output=True, text=True)
print(result.stdout)
print(result.stderr)
assert result.returncode == 2
assert result.stdout == ""
=== END AC cli-launcher ===

## User Acceptance

- None.

## Guardrails

- A failing command writes nothing to stdout and exactly one diagnostic line to stderr.
- Stdout is written only after the handler has returned successfully.
- Output uses `\n` line endings, no quoting, and no trailing spaces.
- Only `cli` dispatch produces exit code 2.
```
</pblock>

<pblock label="Build instructions" kind="instructions">
### Build instructions for this block

#### Provide the `ledger` executable at the application root with a command registry, usage-error handling, and the stdout/stderr contract. (foundation-cli)
Create the executable `ledger` (POSIX launcher that activates .venv and calls `cli.main`), the
`cli` package with `main(argv) -> int` and `cli/testing.py` with `cli_runner`.

Commands are discovered from modules in `cli/commands/`; each module exposes a COMMANDS mapping from
a word tuple such as ("account", "add") to a handler. Dispatch rules: unknown first word, a known
group word with an unknown sub-word (unknown table or report), or a wrong argument count exit 2 with
one stderr line and no stdout. A handler returns the rows to print; stdout is written only after the
handler succeeds, so a failing command never prints. Domain errors map to exit codes: Rejected 3,
NotFound 4, Operational 1. Output is CSV with `\n` endings, no quoting, no trailing spaces.

</pblock>

<pblock label="Reusable compact request" kind="section">
## Reusable compacts

The Blueprint sources below are consumed as context by later Manifest blocks.
In this same response, extract their consumer-facing contract surface. Preserve
interfaces, schemas, constraints, configuration, and cross-file obligations; drop
implementation narrative and repetition. Do not write these files yourself.

Before the required RESULT block, emit one optional payload per source exactly as:
<reusable-compact filename="SOURCE.md">
compact content
</reusable-compact>

Emit no payload when a source has no useful technical surface. These payloads are
advisory and do not change the required build result or file-change report.

Sources eligible for reusable compaction:
- DATABASE.md

</pblock>


# Agent Task

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

- `compass` — the Target's COMPASS.md orientation.
- `implements` — the Typed Specification files this step builds. These are
  authoritative; implement them exactly.
- `context` — read-only support specifications. Do not reimplement them.
- `stack` — enterprise stack and technology rules. Honor them.
- `rules` — governance and branding rules. Honor them.

Operating contract:

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.
2. 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.
3. Implement only this step. Use `context`, `stack`, and `rules` as constraints,
   not as additional work to perform.
4. Follow the stack and rules for languages, structure, naming, and branding.
5. 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.
6. 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.
7. Treat `User Acceptance` entries as review evidence requirements. Implement
   the supporting behavior, but do not claim to have performed human judgment.
8. 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.
9. 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.
10. 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`.
11. 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.
12. 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.
13. End your response with this exact closing structure:

```text
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:

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

14. `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.
15. 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.

```text
FAILURE_SUMMARY: <one line naming the cause>
FAILURE_DETAIL: <what happened, why, and what to change before rerunning>
```

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

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

