=== BEGIN ARTIFACT FEATURE-ReportMonthly.md ===
# FEATURE: Report Monthly
| Field | Value |
|-------|-------|
| Version | 20261027 V1 |
| Description | Implements `ledger report monthly`, the per-month transaction, inflow, outflow, and net totals computed from stored transactions. |
| Depends On | ARCHITECTURE.md, DATABASE.md, FEATURE-CliEntry.md, FEATURE-Validation.md |
| Provides | ledger report monthly |
| Consumes | ledger_core.money, cli.registry |
## Questions
- None.
## Purpose
Give the shop a report of cash movement by calendar month. Every value is computed from the
database at call time; no total is embedded.
## Interface
`ledger report monthly` takes no further arguments. Extra arguments are a usage error (exit 2).
Output on success (CSV, `\n` endings, no quoting, no trailing spaces):
- Header: `month,transactions,inflow,outflow,net`
- One row per `YYYY-MM` that has at least one transaction, ascending by month. The month is the
first seven characters of the stored date.
- `transactions` is the count of that month's transactions.
- `inflow` is the sum of positive amounts, `outflow` the sum of the absolute values of negative
amounts (written positive), `net` is `inflow - outflow`.
- Final row `TOTAL,<count>,<inflow>,<outflow>,<net>` over all transactions.
- Amounts are computed in integer cents and written with exactly two decimals via `ledger_core.money`.
A month with no transactions is absent. An empty ledger prints the header and a TOTAL row of zeros.
## Behavior
1. Read all transactions with `db.transactions.list(...)`.
2. Group by the first seven characters of `date` in integer cents; never use floating point.
3. Emit rows in ascending month order, then the TOTAL row.
## Database Interface
- `FEATURE-TXN-005` — read: list transactions for aggregation - supplies: — - returns: `date`, `amount`
## Programmatic Acceptance
=== AC report-monthly-rows ===
Intent: Monthly rows, ordering, and the TOTAL row are computed from posted transactions; expected counts and sums are derived from the supplied amounts with Decimal.
import csv
import io
from decimal import Decimal
from cli.testing import cli_runner
from persistence.testing import db_session
def parse(out):
return list(csv.reader(io.StringIO(out)))
acct = "ZZRM1"
cat = "ZZRMC"
with db_session() as db:
if db.categories.get(category=cat) is None:
db.categories.create(category=cat, description="Monthly Probe")
code, out, err = cli_runner("account", "add", acct, "Monthly Probe")
print(out, err)
assert code == 0
postings = [("2099-01-05", "100.50"), ("2099-01-20", "40.25"), ("2099-01-21", "-30.10"), ("2099-03-02", "10.00")]
for day, amount in postings:
code, out, err = cli_runner("txn", "post", acct, cat, amount, day, "m")
print(out, err)
assert code == 0
code, out, err = cli_runner("report", "monthly")
print(out, err)
assert code == 0
table = parse(out)
assert table[0] == ["month", "transactions", "inflow", "outflow", "net"]
body = table[1:-1]
months = [r[0] for r in body]
assert months == sorted(months)
by_month = {r[0]: r for r in body}
assert "2099-02" not in by_month
for month in ("2099-01", "2099-03"):
amounts = [Decimal(a) for d, a in postings if d[:7] == month]
inflow = sum((a for a in amounts if a > 0), Decimal(0))
outflow = sum((-a for a in amounts if a < 0), Decimal(0))
row = by_month[month]
assert int(row[1]) == len(amounts)
assert Decimal(row[2]) == inflow
assert Decimal(row[3]) == outflow
assert Decimal(row[4]) == inflow - outflow
for cell in row[2:]:
assert len(cell.split(".")[1]) == 2
total = table[-1]
assert total[0] == "TOTAL" and len(total) == 5
assert int(total[1]) == sum(int(r[1]) for r in body)
assert Decimal(total[2]) == sum(Decimal(r[2]) for r in body)
assert Decimal(total[3]) == sum(Decimal(r[3]) for r in body)
assert Decimal(total[4]) == Decimal(total[2]) - Decimal(total[3])
=== END AC report-monthly-rows ===
=== AC report-monthly-usage ===
Intent: Extra arguments to report monthly are a usage error with exit 2 and nothing on standard output.
from cli.testing import cli_runner
code, out, err = cli_runner("report", "monthly", "extra")
print(out, err)
assert code == 2
assert out == ""
=== END AC report-monthly-usage ===
=== AC report-monthly-reflects-changes ===
Intent: The report is recomputed from the database: posting one more transaction in a new month adds exactly one month row with the posted amount as inflow.
import csv
import io
from decimal import Decimal
from cli.testing import cli_runner
from persistence.testing import db_session
def parse(out):
return list(csv.reader(io.StringIO(out)))
acct = "ZZRM2"
cat = "ZZRMD"
month = "2098-07"
amount = "12.34"
with db_session() as db:
if db.categories.get(category=cat) is None:
db.categories.create(category=cat, description="Monthly Probe")
code, out, err = cli_runner("account", "add", acct, "Monthly Probe 2")
assert code == 0
code, out, err = cli_runner("report", "monthly")
assert code == 0
before = {r[0] for r in parse(out)[1:-1]}
assert month not in before
code, out, err = cli_runner("txn", "post", acct, cat, amount, month + "-10", "m")
print(out, err)
assert code == 0
code, out, err = cli_runner("report", "monthly")
assert code == 0
rows = {r[0]: r for r in parse(out)[1:-1]}
assert set(rows) == before | {month}
assert int(rows[month][1]) == 1
assert Decimal(rows[month][2]) == Decimal(amount)
assert Decimal(rows[month][3]) == Decimal(0)
=== END AC report-monthly-reflects-changes ===
## User Acceptance
- None.
## Guardrails
- Every value comes from a database query; no row, count, or total is hardcoded.
- Money is integer cents at every layer; floating point is never used.
- A failing command writes nothing to standard output.
=== END ARTIFACT ===
=== BEGIN ARTIFACT FEATURE-CommandContract.md ===
# FEATURE: Command Contract
| Field | Value |
|-------|-------|
| Version | 20261027 V1 |
| Description | Assembly story verifying the CSV output contract and exit codes across every delivered ledger command. |
| Depends On | FEATURE-InitCount.md, FEATURE-LoadAccounts.md, FEATURE-LoadCategories.md, FEATURE-LoadTransactions.md, FEATURE-AccountAdd.md, FEATURE-AccountGet.md, FEATURE-AccountRename.md, FEATURE-AccountDelete.md, FEATURE-TxnPost.md, FEATURE-TxnGet.md, FEATURE-TxnAmend.md, FEATURE-TxnDelete.md, FEATURE-Transfer.md, FEATURE-ReportBalances.md, FEATURE-ReportCategories.md, FEATURE-ReportMonthly.md |
| Provides | — |
| Consumes | ledger init, ledger count, ledger load accounts, ledger load categories, ledger load transactions, ledger account add, ledger account get, ledger account rename, ledger account delete, ledger txn post, ledger txn get, ledger txn amend, ledger txn delete, ledger transfer, ledger report balances, ledger report categories, ledger report monthly |
## Questions
- None.
## Purpose
Assembly and intent only. Verify across the delivered commands that:
- successful output is CSV with the specified headers, `\n` endings, two-decimal amounts, no quoting, and no trailing spaces;
- a failing command writes nothing to standard output and one diagnostic line to standard error;
- exit 2 results from unknown commands, tables, reports, and wrong argument counts;
- exit 1 results from an unreadable file, 3 from rejection, 4 from not found;
- every rejected writing command leaves the table counts unchanged.
Any seam defect is fixed in the owning module; this story adds no new behavior.
## Database Interface
- None — persistence is owned by DATABASE.md.
## Programmatic Acceptance
=== AC contract-usage-errors ===
Intent: Unknown commands, unknown tables or reports, and wrong argument counts all exit 2 with empty standard output.
from cli.testing import cli_runner
cases = [
("frobnicate",),
("report", "nosuch"),
("report",),
("load", "nosuch", "x.csv"),
("account",),
("account", "get"),
("txn", "post", "A"),
("transfer", "A", "B"),
("count", "extra"),
]
for args in cases:
code, out, err = cli_runner(*args)
print(args, code, err)
assert code == 2, args
assert out == "", args
=== END AC contract-usage-errors ===
=== AC contract-csv-format ===
Intent: Successful commands emit the declared headers, newline-only endings, no trailing spaces, and amounts with exactly two decimals.
import csv
import io
import re
from cli.testing import cli_runner
from persistence.testing import db_session
def parse(out):
return list(csv.reader(io.StringIO(out)))
def clean(out):
assert out.endswith("\n")
assert "\r" not in out
for line in out.split("\n"):
assert line == line.rstrip(" ")
acct = "ZZCF1"
cat = "ZZCFC"
with db_session() as db:
if db.categories.get(category=cat) is None:
db.categories.create(category=cat, description="Format Probe")
code, out, err = cli_runner("account", "add", acct, "Format Probe")
assert code == 0
clean(out)
assert parse(out)[0] == ["account", "name", "transactions", "balance"]
code, out, err = cli_runner("txn", "post", acct, cat, "7.5", "2099-05-05", "fmt")
print(out, err)
assert code == 0
clean(out)
table = parse(out)
assert table[0] == ["txn_id", "date", "account", "category", "amount", "memo"]
assert re.fullmatch(r"-?\d+\.\d{2}", table[1][4])
code, out, err = cli_runner("count")
assert code == 0
clean(out)
table = parse(out)
assert table[0] == ["table", "rows"]
assert [r[0] for r in table[1:]] == ["accounts", "categories", "transactions"]
code, out, err = cli_runner("report", "balances")
assert code == 0
clean(out)
assert parse(out)[0] == ["account", "name", "transactions", "balance"]
code, out, err = cli_runner("report", "categories")
assert code == 0
clean(out)
assert parse(out)[0] == ["category", "description", "transactions", "inflow", "outflow", "net"]
code, out, err = cli_runner("report", "monthly")
assert code == 0
clean(out)
assert parse(out)[0] == ["month", "transactions", "inflow", "outflow", "net"]
=== END AC contract-csv-format ===
=== AC contract-failures-silent-stdout ===
Intent: Failing commands write nothing to standard output and exactly one diagnostic line to standard error, with the documented exit code for each failure class.
from cli.testing import cli_runner
cases = [
(("account", "get", "ZZNOSUCH9"), 4),
(("account", "add", "lower", "Bad Code"), 3),
(("txn", "get", "999999999"), 4),
(("txn", "post", "ZZNOSUCH9", "ZZNOCAT9", "1.00", "2099-01-01"), 3),
(("load", "accounts", "/nonexistent-dir/zz-missing.csv"), 1),
]
for args, want in cases:
code, out, err = cli_runner(*args)
print(args, code, err)
assert code == want, args
assert out == "", args
assert len(err.strip().splitlines()) == 1, args
=== END AC contract-failures-silent-stdout ===
=== AC contract-rejected-writes-change-nothing ===
Intent: Rejected writing commands exit 3 and leave the counts of all three tables unchanged.
import csv
import io
from cli.testing import cli_runner
from persistence.testing import db_session
def counts():
code, out, err = cli_runner("count")
assert code == 0
return {r[0]: int(r[1]) for r in list(csv.reader(io.StringIO(out)))[1:]}
acct = "ZZCR1"
other = "ZZCR2"
cat = "ZZCRC"
with db_session() as db:
if db.categories.get(category=cat) is None:
db.categories.create(category=cat, description="Reject Probe")
for a in (acct, other):
code, out, err = cli_runner("account", "add", a, "Reject " + a)
assert code == 0
code, out, err = cli_runner("txn", "post", acct, cat, "5.00", "2099-02-02", "seed")
assert code == 0
before = counts()
rejected = [
("account", "add", acct, "Duplicate"),
("account", "add", "bad code", "Name"),
("account", "delete", acct),
("txn", "post", acct, cat, "1.234", "2099-02-03"),
("txn", "post", acct, cat, "1.00", "2026-02-30"),
("txn", "post", acct, "ZZNOCAT9", "1.00", "2099-02-03"),
("txn", "post", acct, cat, "0", "2099-02-03"),
("transfer", acct, acct, "1.00", "2099-02-03"),
("transfer", acct, other, "0.50", "2099-02-30"),
]
for args in rejected:
code, out, err = cli_runner(*args)
print(args, code, err)
assert code == 3, args
assert out == "", args
assert counts() == before
=== END AC contract-rejected-writes-change-nothing ===
## User Acceptance
- None.
## Guardrails
- This story adds no new command behavior; defects are fixed in the owning module.
- Acceptance reads state by parsing CSV output and exit codes, never message wording.
=== END ARTIFACT ===
=== BEGIN ARTIFACT FEATURE-NoNegativeBalance.md ===
# FEATURE: No Negative Balance
| Field | Value |
|-------|-------|
| Version | 20261027 V1 |
| Description | Assembly story verifying that load, post, amend, delete, and transfer each reject any command that would leave an account balance below zero and change nothing. |
| Depends On | FEATURE-LoadTransactions.md, FEATURE-TxnPost.md, FEATURE-TxnAmend.md, FEATURE-TxnDelete.md, FEATURE-Transfer.md |
| Provides | — |
| Consumes | ledger load transactions, ledger txn post, ledger txn amend, ledger txn delete, ledger transfer |
## Questions
- None.
## Purpose
Assembly and intent only. An account's balance is the sum of its transaction amounts and must never
be below zero. For each of load, post, amend, delete, and transfer, a case that would leave a
balance below zero exits 3 and leaves balances and row counts unchanged. A load file whose later
rows make an earlier-valid balance negative is rejected whole.
## Database Interface
- None — persistence is owned by DATABASE.md.
## Programmatic Acceptance
=== AC nonneg-load ===
Intent: A transactions load whose earlier rows are individually valid but whose combined effect makes the balance negative is rejected whole with exit 3 and stores none of its rows.
import csv
import io
import os
import tempfile
from cli.testing import cli_runner
from persistence.testing import db_session
def parse(out):
return list(csv.reader(io.StringIO(out)))
def counts():
code, out, err = cli_runner("count")
assert code == 0
return {r[0]: int(r[1]) for r in parse(out)[1:]}
acct = "ZZNL1"
cat = "ZZNLC"
with db_session() as db:
if db.categories.get(category=cat) is None:
db.categories.create(category=cat, description="Load Probe")
code, out, err = cli_runner("account", "add", acct, "Load Probe")
assert code == 0
before = counts()
rows = [
["800000001", "2099-03-01", acct, cat, "50.00", "in"],
["800000002", "2099-03-02", acct, cat, "-30.00", "out one"],
["800000003", "2099-03-03", acct, cat, "-30.00", "out two"],
]
with tempfile.TemporaryDirectory() as tmp:
path = os.path.join(tmp, "txns.csv")
with open(path, "w", newline="") as fh:
w = csv.writer(fh, lineterminator="\n")
w.writerow(["txn_id", "date", "account", "category", "amount", "memo"])
w.writerows(rows)
code, out, err = cli_runner("load", "transactions", path)
print(out, err)
assert code == 3
assert out == ""
assert counts() == before
code, out, err = cli_runner("txn", "get", rows[0][0])
assert code == 4
code, out, err = cli_runner("account", "get", acct)
assert parse(out)[1][2] == "0"
=== END AC nonneg-load ===
=== AC nonneg-post ===
Intent: Posting an outflow larger than the balance exits 3 and leaves the balance and transaction count unchanged.
import csv
import io
from decimal import Decimal
from cli.testing import cli_runner
from persistence.testing import db_session
def parse(out):
return list(csv.reader(io.StringIO(out)))
acct = "ZZNP1"
cat = "ZZNPC"
with db_session() as db:
if db.categories.get(category=cat) is None:
db.categories.create(category=cat, description="Post Probe")
code, out, err = cli_runner("account", "add", acct, "Post Probe")
assert code == 0
deposit = Decimal("10.00")
code, out, err = cli_runner("txn", "post", acct, cat, str(deposit), "2099-03-01", "in")
assert code == 0
code, out, err = cli_runner("txn", "post", acct, cat, str(-(deposit + Decimal("0.01"))), "2099-03-02", "out")
print(out, err)
assert code == 3
assert out == ""
code, out, err = cli_runner("account", "get", acct)
row = parse(out)[1]
assert row[2] == "1"
assert Decimal(row[3]) == deposit
=== END AC nonneg-post ===
=== AC nonneg-amend ===
Intent: Amending a deposit down so the account would go negative exits 3 and the original amount remains.
import csv
import io
from decimal import Decimal
from cli.testing import cli_runner
from persistence.testing import db_session
def parse(out):
return list(csv.reader(io.StringIO(out)))
acct = "ZZNA1"
cat = "ZZNAC"
with db_session() as db:
if db.categories.get(category=cat) is None:
db.categories.create(category=cat, description="Amend Probe")
code, out, err = cli_runner("account", "add", acct, "Amend Probe")
assert code == 0
big, spend = Decimal("100.00"), Decimal("60.00")
code, out, err = cli_runner("txn", "post", acct, cat, str(big), "2099-03-01", "in")
assert code == 0
deposit_id = parse(out)[1][0]
code, out, err = cli_runner("txn", "post", acct, cat, str(-spend), "2099-03-02", "out")
assert code == 0
code, out, err = cli_runner("txn", "amend", deposit_id, "50.00")
print(out, err)
assert code == 3
assert out == ""
code, out, err = cli_runner("txn", "get", deposit_id)
assert code == 0
assert Decimal(parse(out)[1][4]) == big
code, out, err = cli_runner("account", "get", acct)
assert Decimal(parse(out)[1][3]) == big - spend
=== END AC nonneg-amend ===
=== AC nonneg-delete ===
Intent: Deleting a deposit that funds a later outflow exits 3, keeps the row, and leaves the balance unchanged.
import csv
import io
from decimal import Decimal
from cli.testing import cli_runner
from persistence.testing import db_session
def parse(out):
return list(csv.reader(io.StringIO(out)))
acct = "ZZND1"
cat = "ZZNDC"
with db_session() as db:
if db.categories.get(category=cat) is None:
db.categories.create(category=cat, description="Delete Probe")
code, out, err = cli_runner("account", "add", acct, "Delete Probe")
assert code == 0
big, spend = Decimal("100.00"), Decimal("60.00")
code, out, err = cli_runner("txn", "post", acct, cat, str(big), "2099-03-01", "in")
assert code == 0
deposit_id = parse(out)[1][0]
code, out, err = cli_runner("txn", "post", acct, cat, str(-spend), "2099-03-02", "out")
assert code == 0
code, out, err = cli_runner("txn", "delete", deposit_id)
print(out, err)
assert code == 3
assert out == ""
code, out, err = cli_runner("txn", "get", deposit_id)
assert code == 0
code, out, err = cli_runner("account", "get", acct)
row = parse(out)[1]
assert row[2] == "2"
assert Decimal(row[3]) == big - spend
=== END AC nonneg-delete ===
=== AC nonneg-transfer ===
Intent: A transfer larger than the source balance exits 3 and stores neither row; both balances and the table count are unchanged.
import csv
import io
from decimal import Decimal
from cli.testing import cli_runner
from persistence.testing import db_session
def parse(out):
return list(csv.reader(io.StringIO(out)))
def txn_count():
code, out, err = cli_runner("count")
assert code == 0
return {r[0]: int(r[1]) for r in parse(out)[1:]}["transactions"]
src, dst = "ZZNT1", "ZZNT2"
cat = "ZZNTC"
with db_session() as db:
for c, d in ((cat, "Transfer Probe"), ("TRANSFER", "Internal transfer")):
if db.categories.get(category=c) is None:
db.categories.create(category=c, description=d)
for a in (src, dst):
code, out, err = cli_runner("account", "add", a, "Xfer " + a)
assert code == 0
funds = Decimal("20.00")
code, out, err = cli_runner("txn", "post", src, cat, str(funds), "2099-03-01", "in")
assert code == 0
before = txn_count()
code, out, err = cli_runner("transfer", src, dst, str(funds + Decimal("0.01")), "2099-03-02")
print(out, err)
assert code == 3
assert out == ""
assert txn_count() == before
code, out, err = cli_runner("account", "get", src)
assert Decimal(parse(out)[1][3]) == funds
code, out, err = cli_runner("account", "get", dst)
assert Decimal(parse(out)[1][3]) == Decimal("0")
=== END AC nonneg-transfer ===
## User Acceptance
- None.
## Guardrails
- The balance check runs before the first write of every writing command.
- A rejected command writes nothing to standard output and changes no stored record.
=== END ARTIFACT ===
=== BEGIN ARTIFACT FEATURE-Verification.md ===
# FEATURE: Verification
| Field | Value |
|-------|-------|
| Version | 20261027 V1 |
| Description | Terminal gate that runs the supplied end-to-end grader and the project's own test suite. |
| Depends On | ARCHITECTURE.md, DATABASE.md, FEATURE-CommandContract.md, FEATURE-NoNegativeBalance.md |
| Provides | — |
| Consumes | ledger |
## Questions
- None.
## Purpose
Terminal story. After every other story has closed, run `sh sources/run.sh` and `sh bin/test.sh`,
each of which must exit zero. Nothing under `sources/` is modified. Failures are fixed in the
owning module, never by editing the grader or its seed files.
The grader creates its own temporary SQLite database and runs `ledger init`, which empties the
database. The criterion therefore removes `DATABASE_URL` and `DATABASE_PATH` from the otherwise
inherited environment so the managed store is never touched by a child process.
## Database Interface
- None — persistence is owned by DATABASE.md.
## Programmatic Acceptance
=== AC verification-full-suite ===
Intent: The supplied grader and the project's own test suite both exit zero when run from the application root against their own temporary databases.
Suite: full
Requires: executable=sh; scope=test
import os
import subprocess
import sys
env = {k: v for k, v in os.environ.items() if k not in ("DATABASE_URL", "DATABASE_PATH")}
grader = subprocess.run(["sh", "sources/run.sh"], capture_output=True, text=True, env=env)
print(grader.stdout)
print(grader.stderr, file=sys.stderr)
assert grader.returncode == 0
suite = subprocess.run(["sh", "bin/test.sh"], capture_output=True, text=True, env=env)
print(suite.stdout)
print(suite.stderr, file=sys.stderr)
assert suite.returncode == 0
=== END AC verification-full-suite ===
## User Acceptance
- None.
## Guardrails
- Do not modify, rewrite, regenerate, or substitute anything under `sources/`.
- Application code never reads `sources/run.sh` or any seed file.
- Child processes never receive the managed store's `DATABASE_URL` or `DATABASE_PATH`.
=== END ARTIFACT ===Run artifact