# 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 4 · Service (block-4)
- STORIES: Validate codes, names, memos, amounts, and dates, and format integer cents as two-decimal text. (feature-validation), Check that a proposed set of transaction changes leaves no account balance below zero before any write. (feature-balance-rule)
- 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
- Validate codes, names, memos, amounts, and dates, and format integer cents as two-decimal text. (feature-validation) [story]
- Check that a proposed set of transaction changes leaves no account balance below zero before any write. (feature-balance-rule) [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>


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

| Field | Value |
|-------|-------|
| Version | 20261027 V1 |
| Description | Pure validation of codes, names, memos, amounts, and dates, and conversion between integer cents and two-decimal text. |
| Depends On | ARCHITECTURE.md |
| Provides | ledger_core.validation, ledger_core.money |

## Purpose

Every command validates its inputs with these functions before it writes. They touch no storage and print nothing. Every violation raises `ledger_core.errors.Rejected` (exit code 3).

## Interface

`ledger_core.validation`, each returning the validated string unchanged:

| Function | Rule |
|---|---|
| `validate_code(value)` | 1 to 12 characters, each in `A-Z` or `0-9`. |
| `validate_name(value)` | 1 to 40 characters, no comma, no newline. Used for account names and category descriptions. |
| `validate_memo(value)` | 0 to 60 characters, no comma, no newline. |
| `validate_date(value)` | A real calendar date written `YYYY-MM-DD` with four-digit year, two-digit month and day. `2026-02-30` is rejected. |

`ledger_core.money`:

| Function | Rule |
|---|---|
| `parse_amount(text) -> int` | Input matches `-?DIGITS[.D[D]]`: at least one digit, an optional single decimal part of one or two digits, no sign other than `-`, no spaces. Returns integer cents. Zero (`0`, `0.00`, `-0`) is rejected. Three or more decimals are rejected. No floating point is used. |
| `format_cents(cents) -> str` | Exactly two decimal places, a leading `-` when negative, no thousands separator: `-12.50`, `0.00`, `5000.00`. |

## Database Interface

- None — this feature is pure and reaches no repository.

## Programmatic Acceptance

=== AC validation-code ===
Intent: Codes of 1 to 12 characters from A-Z and 0-9 are returned unchanged; empty, lowercase, too long, and other characters are rejected with exit code 3.

from ledger_core.validation import validate_code
from ledger_core.errors import Rejected

def rejected(value):
    try:
        validate_code(value)
    except Rejected as err:
        assert err.exit_code == 3
        return True
    return False

for good in ["DRAWER1", "A", "0", "ABCDEFGHIJKL", "Z9Z9Z9Z9Z9Z9"]:
    assert validate_code(good) == good
for bad in ["", "drawer1", "Drawer", "ABCDEFGHIJKLM", "AB-C", "A B", "A_B"]:
    assert rejected(bad), bad
=== END AC validation-code ===

=== AC validation-name ===
Intent: Names of 1 to 40 characters without comma or newline are accepted; empty, 41 characters, comma, and newline are rejected.

from ledger_core.validation import validate_name
from ledger_core.errors import Rejected

def rejected(value):
    try:
        validate_name(value)
    except Rejected as err:
        assert err.exit_code == 3
        return True
    return False

for good in ["Front Drawer", "x", "x" * 40]:
    assert validate_name(good) == good
for bad in ["", "x" * 41, "a,b", "a\nb"]:
    assert rejected(bad), repr(bad)
=== END AC validation-name ===

=== AC validation-memo ===
Intent: Memos of 0 to 60 characters without comma or newline are accepted, including the empty memo; 61 characters, comma, and newline are rejected.

from ledger_core.validation import validate_memo
from ledger_core.errors import Rejected

def rejected(value):
    try:
        validate_memo(value)
    except Rejected as err:
        assert err.exit_code == 3
        return True
    return False

for good in ["", "walk in sale", "m" * 60]:
    assert validate_memo(good) == good
for bad in ["m" * 61, "a,b", "a\nb"]:
    assert rejected(bad), repr(bad)
=== END AC validation-memo ===

=== AC validation-date ===
Intent: Real calendar dates in YYYY-MM-DD form are accepted, including a leap day; impossible dates and other layouts are rejected.

from ledger_core.validation import validate_date
from ledger_core.errors import Rejected

def rejected(value):
    try:
        validate_date(value)
    except Rejected as err:
        assert err.exit_code == 3
        return True
    return False

for good in ["2026-04-01", "2024-02-29", "2026-12-31"]:
    assert validate_date(good) == good
for bad in ["2026-02-30", "2026-02-29", "2026-13-01", "2026-00-10", "2026-4-1", "20260401", "", "2026-04-01x"]:
    assert rejected(bad), bad
=== END AC validation-date ===

=== AC money-parse-valid ===
Intent: Valid amount text parses to the integer cents it denotes, as an int and not a float.

from ledger_core.money import parse_amount

cases = [("45.50", 4550), ("-12.34", -1234), ("7", 700), ("1.5", 150),
         ("0.01", 1), ("5000.00", 500000), ("-0.99", -99), ("-3", -300)]
for text, cents in cases:
    value = parse_amount(text)
    assert type(value) is int, text
    assert value == cents, text
=== END AC money-parse-valid ===

=== AC money-parse-invalid ===
Intent: Zero, three or more decimals, and text outside -?DIGITS[.D[D]] are rejected with exit code 3.

from ledger_core.money import parse_amount
from ledger_core.errors import Rejected

def rejected(value):
    try:
        parse_amount(value)
    except Rejected as err:
        assert err.exit_code == 3
        return True
    return False

for bad in ["0", "0.00", "-0", "-0.0", "1.234", "1.000", "abc", "1.", ".5", "+5", "1,5", "", "-", "1 .5", "--5"]:
    assert rejected(bad), repr(bad)
=== END AC money-parse-invalid ===

=== AC money-format ===
Intent: Integer cents format with exactly two decimals, a leading minus when negative, and no thousands separator.

from ledger_core.money import format_cents

cases = [(-1250, "-12.50"), (0, "0.00"), (500000, "5000.00"),
         (5, "0.05"), (-5, "-0.05"), (123456789, "1234567.89")]
for cents, text in cases:
    assert format_cents(cents) == text, cents
=== END AC money-format ===

=== AC money-round-trip ===
Intent: Parsing the formatted text of any nonzero cents value returns the same cents.

from ledger_core.money import parse_amount, format_cents

for cents in [1, -1, 99, 100, -100, 12345, -987654, 500000]:
    assert parse_amount(format_cents(cents)) == cents
=== END AC money-round-trip ===

## User Acceptance

- None.

## Guardrails

- No floating point is used for money, in parsing or formatting.
- Validation functions write nothing and read nothing from storage.
- A violation raises `Rejected`; no other exception type signals invalid input.
```
</pblock>

<pblock filename="FEATURE-BalanceRule.md" role="implements" path="/mnt/c/Users/barlo/projects/drydock/uat/LayersTesting/runs/20261027.135355/workspace/targets/LayersTesting/blueprint/FEATURE-BalanceRule.md" guidance="Feature Specification">
```markdown
# FEATURE: Balance Rule

| Field | Value |
|-------|-------|
| Version | 20261027 V1 |
| Description | Checks that a proposed set of transaction changes leaves no account balance below zero before anything is written. |
| Depends On | ARCHITECTURE.md, DATABASE.md |
| Provides | ledger_core.balances |
| Consumes | persistence.transactions |

## Purpose

An account's balance is the sum of its transaction amounts in integer cents. Load, post, amend, delete, and transfer call this module before their first write. It only reads and never writes.

## Interface

`ledger_core.balances`:

| Name | Meaning |
|---|---|
| `Insert(account, amount)` | A transaction to be added to `account` with `amount` cents. |
| `Edit(txn_id, amount)` | A stored transaction whose amount becomes `amount`. |
| `Delete(txn_id)` | A stored transaction to be removed. |
| `current_balance(db, account) -> int` | Sum of the stored amounts of `account`; `0` when it has none. |
| `check_no_negative(db, changes)` | Raises `Rejected` (exit 3) if any affected account's resulting balance is below zero; returns `None` otherwise. |

`check_no_negative` groups all changes by account, takes each account's stored balance, applies the combined net delta (an `Edit` contributes new minus stored amount, a `Delete` contributes minus the stored amount), and rejects when any result is below zero. Changes are judged together, not one after another, so the order of changes does not matter. A resulting balance of exactly zero is allowed.

## Database Interface

- `FEATURE-TXN-002` — read: get a stored transaction for an edit or delete - supplies: `txn_id` - returns: `account`, `amount`
- `FEATURE-TXN-005` — read: list an account's transactions to sum its balance - supplies: — - returns: `amount`

## Programmatic Acceptance

=== AC balance-current ===
Intent: current_balance sums an account's stored amounts and is zero for an account with no transactions.

from persistence.testing import db_session
from ledger_core.balances import current_balance

acct, empty, cat = "ZZBR1", "ZZBR2", "ZZBRC1"
with db_session() as db:
    db.accounts.create(account=acct, name="Balance Probe")
    db.accounts.create(account=empty, name="Empty Probe")
    db.categories.create(category=cat, description="Balance Cat")
    amounts = [1000, -300]
    for offset, cents in enumerate(amounts):
        db.transactions.create(txn_id=900100001 + offset, date="2026-05-01", account=acct,
                               category=cat, amount=cents, memo="")
    assert current_balance(db, acct) == sum(amounts)
    assert current_balance(db, empty) == 0
=== END AC balance-current ===

=== AC balance-insert ===
Intent: An insert that lands the balance at zero passes, one cent below zero is rejected with exit 3, and nothing is written either way.

from persistence.testing import db_session
from ledger_core.balances import check_no_negative, Insert
from ledger_core.errors import Rejected

acct, cat = "ZZBR3", "ZZBRC3"
with db_session() as db:
    db.accounts.create(account=acct, name="Insert Probe")
    db.categories.create(category=cat, description="Balance Cat")
    db.transactions.create(txn_id=900100011, date="2026-05-01", account=acct, category=cat, amount=700, memo="")
    before = len(db.transactions.list(account=acct))
    assert check_no_negative(db, [Insert(acct, -700)]) is None
    raised = None
    try:
        check_no_negative(db, [Insert(acct, -701)])
    except Rejected as err:
        raised = err
    assert raised is not None
    assert raised.exit_code == 3
    assert len(db.transactions.list(account=acct)) == before
=== END AC balance-insert ===

=== AC balance-insert-new-account ===
Intent: An account with no transactions accepts a positive insert and rejects a negative one.

from persistence.testing import db_session
from ledger_core.balances import check_no_negative, Insert
from ledger_core.errors import Rejected

acct = "ZZBR4"
with db_session() as db:
    db.accounts.create(account=acct, name="Fresh Probe")
    assert check_no_negative(db, [Insert(acct, 500)]) is None
    raised = False
    try:
        check_no_negative(db, [Insert(acct, -1)])
    except Rejected:
        raised = True
    assert raised
=== END AC balance-insert-new-account ===

=== AC balance-edit ===
Intent: Editing the larger credit below what the debits need is rejected; editing it to exactly cover them passes.

from persistence.testing import db_session
from ledger_core.balances import check_no_negative, Edit
from ledger_core.errors import Rejected

acct, cat = "ZZBR5", "ZZBRC5"
credit, debit = 900100021, 900100022
with db_session() as db:
    db.accounts.create(account=acct, name="Edit Probe")
    db.categories.create(category=cat, description="Balance Cat")
    db.transactions.create(txn_id=credit, date="2026-05-01", account=acct, category=cat, amount=1000, memo="")
    db.transactions.create(txn_id=debit, date="2026-05-02", account=acct, category=cat, amount=-300, memo="")
    assert check_no_negative(db, [Edit(credit, 300)]) is None
    raised = None
    try:
        check_no_negative(db, [Edit(credit, 299)])
    except Rejected as err:
        raised = err
    assert raised is not None
    assert raised.exit_code == 3
    stored = db.transactions.get(txn_id=credit)
    amount = stored["amount"] if isinstance(stored, dict) else stored.amount
    assert amount == 1000
=== END AC balance-edit ===

=== AC balance-delete ===
Intent: Deleting the credit that funds a debit is rejected; deleting the debit passes.

from persistence.testing import db_session
from ledger_core.balances import check_no_negative, Delete
from ledger_core.errors import Rejected

acct, cat = "ZZBR6", "ZZBRC6"
credit, debit = 900100031, 900100032
with db_session() as db:
    db.accounts.create(account=acct, name="Delete Probe")
    db.categories.create(category=cat, description="Balance Cat")
    db.transactions.create(txn_id=credit, date="2026-05-01", account=acct, category=cat, amount=1000, memo="")
    db.transactions.create(txn_id=debit, date="2026-05-02", account=acct, category=cat, amount=-300, memo="")
    assert check_no_negative(db, [Delete(debit)]) is None
    raised = None
    try:
        check_no_negative(db, [Delete(credit)])
    except Rejected as err:
        raised = err
    assert raised is not None
    assert raised.exit_code == 3
    assert db.transactions.get(txn_id=credit) is not None
=== END AC balance-delete ===

=== AC balance-combined ===
Intent: Several changes to one account are judged by their net effect regardless of order; a credit and a debit that net to a non-negative balance pass in either order.

from persistence.testing import db_session
from ledger_core.balances import check_no_negative, Insert
from ledger_core.errors import Rejected

acct, cat = "ZZBR7", "ZZBRC7"
with db_session() as db:
    db.accounts.create(account=acct, name="Combined Probe")
    db.categories.create(category=cat, description="Balance Cat")
    db.transactions.create(txn_id=900100041, date="2026-05-01", account=acct, category=cat, amount=700, memo="")
    credit, debit = Insert(acct, 500), Insert(acct, -1100)
    assert check_no_negative(db, [credit, debit]) is None
    assert check_no_negative(db, [debit, credit]) is None
    over = Insert(acct, -1300)
    raised = False
    try:
        check_no_negative(db, [credit, over])
    except Rejected:
        raised = True
    assert raised
=== END AC balance-combined ===

=== AC balance-multi-account ===
Intent: When one of several affected accounts would go negative the whole set is rejected and nothing is written.

from persistence.testing import db_session
from ledger_core.balances import check_no_negative, Insert
from ledger_core.errors import Rejected

good, poor, cat = "ZZBR8", "ZZBR9", "ZZBRC8"
with db_session() as db:
    db.accounts.create(account=good, name="Rich Probe")
    db.accounts.create(account=poor, name="Poor Probe")
    db.categories.create(category=cat, description="Balance Cat")
    db.transactions.create(txn_id=900100051, date="2026-05-01", account=good, category=cat, amount=900, memo="")
    db.transactions.create(txn_id=900100052, date="2026-05-01", account=poor, category=cat, amount=100, memo="")
    before = len(db.transactions.list(account=good)) + len(db.transactions.list(account=poor))
    raised = None
    try:
        check_no_negative(db, [Insert(good, -900), Insert(poor, -101)])
    except Rejected as err:
        raised = err
    assert raised is not None
    assert raised.exit_code == 3
    after = len(db.transactions.list(account=good)) + len(db.transactions.list(account=poor))
    assert after == before
=== END AC balance-multi-account ===

## User Acceptance

- None.

## Guardrails

- The check writes nothing; it only reads through the declared repository operations.
- Amounts are integer cents; no floating point is used.
- Only accounts touched by the proposed changes are judged; other accounts' balances do not affect the result.
- Balances are computed from stored rows, never cached or hardcoded.
```
</pblock>

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

#### Validate codes, names, memos, amounts, and dates, and format integer cents as two-decimal text. (feature-validation)
Implement pure functions. Codes: 1 to 12 chars of A-Z0-9. Names/descriptions: 1 to 40 chars;
memos 0 to 60; none contains a comma or newline. Amounts on input match `-?DIGITS[.D[D]]`,
parse to integer cents with Decimal-free integer arithmetic or Decimal, never float, and reject
zero and three or more decimals. Dates are real calendar dates `YYYY-MM-DD` (reject 2026-02-30).
`format_cents` writes exactly two decimals, leading `-` when negative, no thousands separator.
Violations raise Rejected (exit 3).

#### Check that a proposed set of transaction changes leaves no account balance below zero before any write. (feature-balance-rule)
Provide `check_no_negative(db, changes)` where changes are inserts, amount edits, and deletions of
transaction rows. It computes each affected account's resulting balance as the stored sum plus the
net delta, and raises Rejected if any resulting balance is below zero. An account's balance is the
sum of its amounts. It writes nothing. Used by load, post, amend, delete, and transfer.

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

