# Attribute Stories to Source Requirements

You are the lineage attribution agent. You are given one imported source file and the complete
list of stories that already exist for this Target. Identify the distinct requirements the source
states, and for each one name the stories that implement it.

This is a matching task against a closed set. Every story you may name is listed in `<stories>`.
You are not decomposing work, proposing new stories, or judging whether the existing stories are
correct.

## Method

1. Read the source and identify each distinct requirement it states. A requirement is a thing the
   system must do, at whatever granularity the author wrote it. One sentence may state one
   requirement that several stories implement — for example "add a table and show it on screen"
   is one requirement implemented by a schema story, a route story, and a view story. Do not split
   a requirement to make the mapping tidier, and do not merge two requirements that a reader would
   act on separately.
2. Give each requirement a short kebab-case name that describes it. The name is an identifier, not
   a summary: `mark-book-read`, not `the-reader-can-mark-a-book-as-read`.
3. For each requirement, list every story that implements any part of it. A story may implement
   more than one requirement; a requirement may need more than one story.
4. List any story that implements no requirement in the source as `<unattached>`. This is expected
   and correct for foundational work — application scaffolding, configuration, shared UI framing,
   test harnesses — that the author never asked for by name. Do not force such a story onto an
   unrelated requirement.

## Rules

- Copy story ids byte-for-byte from `<stories>`, preserving underscores, hyphens, and case; never invent or normalize one.
- Every story appears in one or more requirement `stories` attributes, or once as `<unattached>`, never both.
- Quote the requirement text verbatim from the source in the tag body. Do not paraphrase it.
- Emit nothing but the tags below. No preamble, no commentary, no explanation.

## Output

```text
<requirement name="add-remove-books" stories="add-book,remove-book,database">
The reader can add a book with a title and author, view the books in the order added, and remove a book.
</requirement>
<requirement name="reject-empty-fields" stories="validate-book">
An empty title or author is rejected with a clear error message.
</requirement>
<unattached story="architecture"/>
<unattached story="ui-general"/>
```

# Attribution job

<source name="INSTRUCTIONS.md">
# Build Instructions: A Cash Ledger

## Objective

Build a command-line cash ledger for a small shop. The shop keeps cash in a few places (drawers,
a safe, petty cash), records every receipt and payment against one of those places, and asks for
three reports: balances by account, totals by category, and totals by month.

The product is an executable named `ledger` at the application root. It stores everything in a
relational database through the shipped persistence library, and every command either completes
in full or changes nothing.

## Stack

Implement in Python 3.11 or newer over SQLite, through the shipped Python persistence
library. Tests run under pytest. The contract below is the same for every language and database: the same
commands, the same output, and the same exit codes.

## Run Harness

`sources/run.sh` is the scoring entry point. It is supplied, not authored, and is staged verbatim
into the application root with the seed files. `drydock uat` runs `sh sources/run.sh` from the
completed application root and takes its exit code and output as the score.

The harness creates a fresh database, runs `./ledger init`, loads the seed files, and then runs a
fixed sequence of 43 checks. Each check compares one command's exit code and standard output
with a known answer. Standard error is never compared. The harness prints `PASS` or `FAIL` per
check and ends with:

```text
LayersTesting: NN passed, NN failed (of 43)
```

## Read-only scoring assets

These files are the exam. Do not modify, rewrite, regenerate, or substitute them:

- `sources/run.sh` — the scoring entry point and its known answers
- `sources/seed_accounts.csv` — 4 accounts
- `sources/seed_categories.csv` — 7 categories
- `sources/seed_transactions.csv` — 120 transactions, January to March 2026
- `sources/seed_transactions_bad.csv` — 11 transactions; row 11 names an unknown account

Application code never reads `sources/run.sh` and never embeds a report answer. Every report is
computed from the database.

## Database

The database is SQLite. `DATABASE_URL` names the SQLite file path, optionally prefixed
`sqlite://`. When `DATABASE_URL` is unset, `DATABASE_PATH` is used, then `data/app.db`.

Three tables. Amounts are stored as integer cents and never as floating point.

| Table | Columns | Keys |
|---|---|---|
| `accounts` | `account` text, `name` text | primary key `account` |
| `categories` | `category` text, `description` text | primary key `category` |
| `transactions` | `txn_id` integer, `date` text `YYYY-MM-DD`, `account` text, `category` text, `amount` integer cents, `memo` text | primary key `txn_id`; `account` references `accounts`; `category` references `categories` |

All database access goes through the shipped persistence library and the relational layer
generated from `DATABASE.md`. Application code never opens a database driver directly.

## Rules

1. **A rejected command changes nothing.** A command checks every input and rule before its
   first write. A load that rejects row 11 stores none of rows 1 to 10. A transfer stores both of
   its rows or neither.
2. **No command leaves an account balance below zero.** An account's balance is the sum of its
   transaction amounts. Posting, amending, deleting, transferring, and loading are all subject to
   this rule, checked before the command writes anything.
3. **Codes** (`account`, `category`) are 1 to 12 characters from `A-Z` and `0-9`.
4. **Names and descriptions** are 1 to 40 characters. **Memos** are 0 to 60 characters. None of
   them contains a comma or a newline.
5. **Amounts** on input match `-?DIGITS[.D[D]]`: at most two decimal places, never zero. On output
   an amount is written with exactly two decimal places, a leading `-` when negative, and no
   thousands separator: `-12.50`, `0.00`, `5000.00`.
6. **Dates** are real calendar dates written `YYYY-MM-DD`. `2026-02-30` is rejected.
7. **Transaction ids.** A loaded transaction keeps the `txn_id` from its file. A posted
   transaction receives one more than the largest `txn_id` present, or `1` in an empty table. A
   transfer's outgoing row takes that id and its incoming row the next.

## Output

Every successful command except `init` writes CSV to standard output: one header row, then data
rows, comma-separated, no quoting, no trailing spaces, `\n` line endings. `init` writes nothing.
A failing command writes nothing to standard output and one diagnostic line to standard error.

The account row is `account,name,transactions,balance`, where `transactions` counts the account's
transactions. The transaction row is `txn_id,date,account,category,amount,memo`.

## Commands

| Command | Output on success |
|---|---|
| `ledger init` | Prepares an empty ledger for loading and use; removes existing ledger records when rerun. Nothing written. |
| `ledger count` | `table,rows`, then `accounts`, `categories`, `transactions` rows in that order. |
| `ledger load <table> <csv>` | Loads `accounts`, `categories`, or `transactions` from a file whose header matches the table's columns in the order above. Writes `table,loaded` and `<table>,<rows>`. |
| `ledger account add <code> <name>` | The new account row. |
| `ledger account get <code>` | The account row. |
| `ledger account rename <code> <name>` | The updated account row. |
| `ledger account delete <code>` | `deleted` and the code. Refused while the account has transactions. |
| `ledger txn post <account> <category> <amount> <date> [<memo>]` | The new transaction row. |
| `ledger txn get <id>` | The transaction row. |
| `ledger txn amend <id> <amount>` | The updated transaction row. Only the amount changes. |
| `ledger txn delete <id>` | `deleted` and the id. |
| `ledger transfer <from> <to> <amount> <date>` | Two transaction rows in category `TRANSFER`: `-amount` on `<from>` with memo `transfer to <to>`, then `+amount` on `<to>` with memo `transfer from <from>`. The amount is positive and the accounts differ. |
| `ledger report balances` | `account,name,transactions,balance` per account ordered by code, then `TOTAL,,<count>,<sum>`. |
| `ledger report categories` | `category,description,transactions,inflow,outflow,net` per category ordered by code, including categories with no transactions, then `TOTAL,,<count>,<inflow>,<outflow>,<net>`. |
| `ledger report monthly` | `month,transactions,inflow,outflow,net` per `YYYY-MM` that has transactions, ascending, then `TOTAL,<count>,<inflow>,<outflow>,<net>`. |

`inflow` is the sum of positive amounts. `outflow` is the sum of the absolute values of negative
amounts, written as a positive number. `net` is `inflow - outflow`.

## Exit codes

| Code | Meaning |
|---|---|
| `0` | Success. |
| `1` | Operational failure: a file named on the command line cannot be read. |
| `2` | Usage error: unknown command, unknown table or report, wrong argument count. |
| `3` | Rejected: invalid code, name, amount, date, or file row; duplicate key; unknown account or category; account in use; any change that would leave a negative balance. |
| `4` | Not found: `account get/rename/delete` of an absent account, `txn get/amend/delete` of an absent id. |

## Tests

The completed application provides a POSIX-compatible `bin/test.sh` that runs its own automated
test suite from the application root and exits zero only when every test passes. The suite
covers each command, each exit code, and each rule above against a real temporary database.
</source>

<stories>
  <story id="foundation-python" implements="ARCHITECTURE.md">Stand up the Python project tree, environment, dependency manifest, pytest runner, and bin/test.sh.</story>
  <story id="foundation-database" implements="DATABASE.md">Declare the accounts, categories, and transactions tables and every repository operation the stories need.</story>
  <story id="foundation-cli" implements="FEATURE-CliEntry.md">Provide the `ledger` executable at the application root with a command registry, usage-error handling, and the stdout/stderr contract.</story>
  <story id="feature-validation" implements="FEATURE-Validation.md">Validate codes, names, memos, amounts, and dates, and format integer cents as two-decimal text.</story>
  <story id="feature-balance-rule" implements="FEATURE-BalanceRule.md">Check that a proposed set of transaction changes leaves no account balance below zero before any write.</story>
  <story id="feature-init-count" implements="FEATURE-InitCount.md">Implement `ledger init` and `ledger count`.</story>
  <story id="feature-load-csv-reader" implements="FEATURE-LoadCsvReader.md">Read and header-check a CSV file named on the command line, exiting 1 when it cannot be read.</story>
  <story id="feature-account-add" implements="FEATURE-AccountAdd.md">Implement `ledger account add <code> <name>`.</story>
  <story id="feature-txn-post" implements="FEATURE-TxnPost.md">Implement `ledger txn post <account> <category> <amount> <date> [<memo>]`.</story>
  <story id="feature-load-accounts" implements="FEATURE-LoadAccounts.md">Implement `ledger load accounts <csv>` as an all-or-nothing load.</story>
  <story id="feature-account-delete" implements="FEATURE-AccountDelete.md">Implement `ledger account delete <code>`.</story>
  <story id="feature-txn-get" implements="FEATURE-TxnGet.md">Implement `ledger txn get <id>`.</story>
  <story id="feature-account-rename" implements="FEATURE-AccountRename.md">Implement `ledger account rename <code> <name>`.</story>
  <story id="feature-account-get" implements="FEATURE-AccountGet.md">Implement `ledger account get <code>`.</story>
  <story id="feature-txn-delete" implements="FEATURE-TxnDelete.md">Implement `ledger txn delete <id>`.</story>
  <story id="feature-txn-amend" implements="FEATURE-TxnAmend.md">Implement `ledger txn amend <id> <amount>`.</story>
  <story id="feature-load-categories" implements="FEATURE-LoadCategories.md">Implement `ledger load categories <csv>` as an all-or-nothing load.</story>
  <story id="feature-transfer" implements="FEATURE-Transfer.md">Implement `ledger transfer <from> <to> <amount> <date>` as an atomic two-row write.</story>
  <story id="feature-load-transactions" implements="FEATURE-LoadTransactions.md">Implement `ledger load transactions <csv>` with foreign-key, date, amount, and balance validation before any write.</story>
  <story id="feature-report-balances" implements="FEATURE-ReportBalances.md">Implement `ledger report balances`.</story>
  <story id="feature-report-monthly" implements="FEATURE-ReportMonthly.md">Implement `ledger report monthly`.</story>
  <story id="feature-report-categories" implements="FEATURE-ReportCategories.md">Implement `ledger report categories`.</story>
  <story id="feature-command-contract" implements="FEATURE-CommandContract.md">Assemble and verify the CSV output contract and exit codes across every command.</story>
  <story id="feature-no-negative-balance" implements="FEATURE-NoNegativeBalance.md">Assemble and verify that every writing command enforces the no-negative-balance rule atomically.</story>
  <story id="feature-verification" implements="FEATURE-Verification.md">Terminal gate: run the supplied grader and the full project test suite.</story>
</stories>
