Reconcile the bank statement to the ledger.
Done by an agent. Checked twice.
Every bank line and ledger entry is matched or listed with a reason and the two closing balances tie to the cent.
Real files in
- balances.md
Opening and closing balances for one month of an operating bank account. 10 lines, 371 bytes. - bank_statement.csv
Forty-three bank statement lines for the month with a running balance. 44 lines, 2 KB. - ledger_cash.csv
Forty-five ledger entries on the cash account, with a double entry, a mistyped amount, a missing check number and unpresented items planted in them. 46 lines, 3 KB.
Sample data written by Atris. Not a real company.
Three steps
- 1.Read the statement and the ledger
- 2.Match every line
- 3.Write the result
Claude Sonnet 5.5, 1 min 8 s. No web. It never saw the check.
Checked twice
- Passed: 18 of 18 unmatched items are listed in unmatched.csv and 0 matched items are listed by mistake
- Passed: 18 of 18 reasons equal the reason recomputed from the input files
- Passed: 18 of 18 listed items carry the date and amount of their source row
- Passed: ledger balance 43,123.03 minus unmatched ledger items 2,756.65 plus unmatched bank items -195.72 comes to 40,170.66 against a statement balance of 40,170.66
- Passed: reconciliation.md states the statement closing balance of 40,170.66 and the ledger closing balance of 43,123.03 and puts the proof on one line
- Passed: reconciliation.md states 8 unmatched bank lines with a total of -195.72 and 10 unmatched ledger entries with a total of 2,756.65
- Passed: 18 of 18 unmatched items are listed in reconciliation.md under their own reason with their date and amount
- Passed: 63 of 63 figures and dates in reconciliation.md and 22 of 22 in the notes equal a figure of the item they sit beside, a check number in the files, a balance or a recomputed total
- Passed: 15 of 15 times a check number is written beside an item that is a check, it includes that item's own check number
Second review by Claude Opus 5.5: pass.
Then we broke a copy of the output 6 ways on purpose. The check caught 6.
Statement closing balance: 40170.66 Ledger closing balance: 43123.03 (opening 48210.37 plus all 45 ledger entries) Unmatched bank lines: 8, signed total -195.72 Unmatched ledger entries: 10, signed total 2756.65 Proof: 43123.03 - 2756.65 + (-195.72) = 40170.66, which equals the statement closing balance. Matched: 35 of 43 bank lines (17 non-check pairs and 18 checks) are paired one to one with 35 of 45 ledger entries. Facts not in the files: the cause of the returned deposit item B-025 (which deposit it reverses) and whether the December statement shows the ledger items dated 2026-11-30; the notes say "likely" where this is inferred. ## amount_differs - bank B-036, 2026-11-26, -1485.00, check 2217
How this was run
An AI agent on Claude Sonnet 5.5 was given a folder with the files below and a three-step flow, and nothing else. It had no web access and never saw the check. The check was written before the run and made stricter after it. It works the answer out again from the input files. Then Claude Opus 5.5 reviewed the result against the inputs. The input files are sample data written by Atris, with the problems a real week has planted in them.
Run 3 of 3 on 1 December 2026. The agent took 1 min 8 s. Run 1 passed both checks and the job was run again later. Run 2 passed both checks and the job was run again later. Each run starts clean. Between runs the written flow was made clearer, or a check was corrected or made stricter. Nobody edits the output.
What the second review verified
- Re-ran the matching rules from scratch and got the same 18 unmatched items with the same reasons. Examples: check 2217 is amount_differs (B-036 -1485.00 vs L-032 -1845.00), L-018 is a duplicate_entry of check 2209, and B-027/L-022 (955.00) stay unmatched because their dates are 7 days apart, more than the 5 allowed.
- Ledger closing balance is 48210.37 plus all 45 entries = 43123.03. The unmatched bank lines total -195.72 and the unmatched ledger entries total 2756.65, so the proof is 43123.03 - 2756.65 - 195.72 = 40170.66, which equals the statement closing balance.
- Every row's date and amount match its source row, the rows are sorted by side and then id, and every note is one sentence of 12 to 30 words.
- Matched counts add up: 18 of the 20 bank checks are paired (B-029 has no ledger check 2214, and B-036's amount differs) and 17 of the 23 non-check lines are paired, so 35 bank lines match 35 of the 45 ledger entries.
What this run does not show
- The first run was recorded as a pass although the second review noted 7 notes of two sentences where the flow asks for one, so the flow was made stricter and the job run again.
- The check compares the figures and check numbers in each note and cannot tell good advice from poor advice.
- Counts in the write-up are compared with a list of counts the check works out, so a count swapped for another real count would pass.
Would the check catch a wrong answer?
A check that cannot fail proves nothing. After the run we took a copy of the output, broke it one small way at a time and ran the check again. It caught 6 of 6. The check was made stricter after the first try at this, and the same untouched output was graded again.
Open every file
flow.md · the three steps the agent followed
# Reconcile the bank statement to the ledger function: finance for: the bookkeeper who closes the cash account each month goal: Every bank line and every ledger entry is either matched or listed with the reason and the two closing balances are tied together. ## 1. Read the statement and the ledger Read input/balances.md, input/bank_statement.csv and input/ledger_cash.csv. Amounts are signed: money in is positive, money out is negative. The ledger closing balance is the ledger opening balance plus every ledger entry. A bank line or ledger entry is a check when its check_no is filled. ## 2. Match every line Each bank line pairs with at most one ledger entry and each ledger entry with at most one bank line. - Checks first. When two or more ledger entries carry the same check_no, keep the earliest (by date, then entry_id) and give each later one the reason `duplicate_entry`. A bank check pairs with the kept ledger entry that has the same check_no. If the amounts are equal they are matched. If the amounts differ, list both with the reason `amount_differs`. - Then everything else. A bank line with no check_no pairs with a ledger entry with no check_no when the amounts are exactly equal and the two dates are no more than 5 calendar days apart. Work through the bank lines by date then line_id. If more than one ledger entry fits, take the one with the closest date, then the lowest entry_id. - Never pair a check with a line that is not a check. Never pair on a near amount. If two leftover lines look like the same payment, keep both unmatched and say so in the note. - Every bank line left over gets the reason `not_in_ledger`. Every ledger entry left over gets the reason `not_on_statement`. ## 3. Write the result Write output/unmatched.csv with columns side,id,date,amount,reason,note. One row per unmatched item and no row for a matched one. side is `bank` or `ledger`. id is the line_id or entry_id. date and amount are copied from the source row. note is exactly one sentence, never two, of at most 40 words: what the item most likely is and what the bookkeeper should do. Sort by side, then id. Write output/reconciliation.md with these facts, each on its own line, money as plain numbers with two decimals: the statement closing balance, the ledger closing balance, the number and signed total of unmatched bank lines, the number and signed total of unmatched ledger entries and the proof that ledger closing balance minus the unmatched ledger total plus the unmatched bank total equals the statement closing balance. Then list the unmatched items grouped by reason. ## Done looks like - Every bank line and ledger entry is either matched or appears once in unmatched.csv. - The proof line in reconciliation.md works out to the statement closing balance to the cent. - No item is matched on a guess.
input/balances.md · 10 lines, 371 bytes
# Cash account, November 2026 Account: operating account ending 4471 Period: 2026-11-01 to 2026-11-30 - Bank statement opening balance on 2026-11-01: 48,210.37 - Bank statement closing balance on 2026-11-30: 40,170.66 - Ledger cash account opening balance on 2026-11-01: 48,210.37 The ledger closing balance is the opening balance plus every entry in ledger_cash.csv.
input/bank_statement.csv · 44 lines, 2 KB
line_id,date,check_no,description,amount,balance B-001,2026-11-02,,ACH DEBIT CALLOWAY ESTATES RENT,-6400.00,41810.37 B-002,2026-11-04,,DEPOSIT,3275.00,45085.37 B-003,2026-11-04,,MERCHANT SETTLEMENT 1103,1500.00,46585.37 B-004,2026-11-05,2201,CHECK 2201,-1312.40,45272.97 B-005,2026-11-05,,WIRE IN TIVERTON SCHOOL,8940.00,54212.97 B-006,2026-11-06,2202,CHECK 2202,-486.00,53726.97 B-007,2026-11-09,2203,CHECK 2203,-2190.75,51536.22 B-008,2026-11-09,,DEPOSIT,2118.60,53654.82 B-009,2026-11-09,,LOAN PAYMENT 00417,-1875.00,51779.82 B-010,2026-11-10,2204,CHECK 2204,-918.33,50861.49 B-011,2026-11-11,,DEPOSIT,5610.25,56471.74 B-012,2026-11-11,,MERCHANT SETTLEMENT 1110,1500.00,57971.74 B-013,2026-11-12,2205,CHECK 2205,-640.00,57331.74 B-014,2026-11-13,,ACH DEBIT PAYROLL 1113,-14286.42,43045.32 B-015,2026-11-13,2206,CHECK 2206,-1077.15,41968.17 B-016,2026-11-13,,DEPOSIT,2530.00,44498.17 B-017,2026-11-16,,ACH DEBIT NORTHWAY INS,-289.00,44209.17 B-018,2026-11-16,2207,CHECK 2207,-1420.00,42789.17 B-019,2026-11-16,,DEPOSIT,3275.00,46064.17 B-020,2026-11-17,2208,CHECK 2208,-395.00,45669.17 B-021,2026-11-18,2209,CHECK 2209,-732.50,44936.67 B-022,2026-11-18,,MERCHANT SETTLEMENT 1117,1742.80,46679.47 B-023,2026-11-18,,WIRE IN WEXCOMBE HOTEL,12400.00,59079.47 B-024,2026-11-19,2210,CHECK 2210,-1984.00,57095.47 B-025,2026-11-19,,RETURNED DEPOSIT ITEM,-1120.00,55975.47 B-026,2026-11-20,2211,CHECK 2211,-268.90,55706.57 B-027,2026-11-20,,DEPOSIT,955.00,56661.57 B-028,2026-11-23,2212,CHECK 2212,-2204.60,54456.97 B-029,2026-11-23,2214,CHECK 2214,-764.20,53692.77 B-030,2026-11-23,,DEPOSIT,1986.00,55678.77 B-031,2026-11-24,2213,CHECK 2213,-402.18,55276.59 B-032,2026-11-24,2215,CHECK 2215,-158.44,55118.15 B-033,2026-11-25,,ACH DEBIT STATE REVENUE,-3318.00,51800.15 B-034,2026-11-25,2216,CHECK 2216,-395.00,51405.15 B-035,2026-11-25,,MERCHANT SETTLEMENT 1124,1688.35,53093.50 B-036,2026-11-26,2217,CHECK 2217,-1485.00,51608.50 B-037,2026-11-27,,ACH DEBIT PAYROLL 1127,-14102.77,37505.73 B-038,2026-11-27,2218,CHECK 2218,-1190.00,36315.73 B-039,2026-11-30,2219,CHECK 2219,-2051.20,34264.53 B-040,2026-11-30,2220,CHECK 2220,-271.35,33993.18 B-041,2026-11-30,,INTEREST PAID,12.48,34005.66 B-042,2026-11-30,,MONTHLY SERVICE FEE,-35.00,33970.66 B-043,2026-11-30,,WIRE IN TIVERTON SCHOOL,6200.00,40170.66
input/ledger_cash.csv · 46 lines, 3 KB
entry_id,date,check_no,description,amount L-001,2026-11-02,2201,"Halvorsen Supply, packaging",-1312.40 L-002,2026-11-02,,"Rent November, Calloway Estates",-6400.00 L-003,2026-11-03,2202,"Quillfeather Print, brochures",-486.00 L-004,2026-11-03,,Card sales settlement,1500.00 L-005,2026-11-04,2203,"Marrow Lane Logistics, freight",-2190.75 L-006,2026-11-04,,"Customer receipt, Brannock Dental",3275.00 L-007,2026-11-05,2204,"Osprey Utilities, electricity",-918.33 L-008,2026-11-05,,"Customer receipt, Tiverton School",8940.00 L-009,2026-11-06,2205,"Pell & Sons, repairs",-640.00 L-010,2026-11-06,,"Customer receipt, Ashgrove Clinic",2118.60 L-011,2026-11-09,2206,"Halverson Supply, packaging",-1077.15 L-012,2026-11-09,,"Loan repayment, Fenmoor Bank",-1875.00 L-013,2026-11-10,2207,"Greywell Insurance, premium",-1420.00 L-014,2026-11-10,,Card sales settlement,1500.00 L-015,2026-11-11,2208,Thornbury Cleaning,-395.00 L-016,2026-11-11,,"Customer receipt, Lindqvist Motors",5610.25 L-017,2026-11-12,2209,"Quillfeather Print, signage",-732.50 L-018,2026-11-12,2209,"Quillfeather Print, signage",-732.50 L-019,2026-11-12,,"Customer receipt, Wexcombe Hotel",2350.00 L-020,2026-11-13,2210,"Marrow Lane Logistics, freight",-1984.00 L-021,2026-11-13,,"Payroll, first half November",-14286.42 L-022,2026-11-13,,"Customer receipt, Sorrel Bakery",955.00 L-023,2026-11-16,2211,Castlereach Telecom,-268.90 L-024,2026-11-16,,"Customer receipt, Brannock Dental",3275.00 L-025,2026-11-17,2212,"Halvorsen Supply, packaging",-2204.60 L-026,2026-11-17,,Card sales settlement,1742.80 L-027,2026-11-18,2213,"Osprey Utilities, gas",-402.18 L-028,2026-11-18,,"Pell & Sons, repairs (check)",-764.20 L-029,2026-11-18,,"Customer receipt, Wexcombe Hotel",12400.00 L-030,2026-11-19,2215,Dovecote Stationery,-158.44 L-031,2026-11-20,2216,Thornbury Cleaning,-395.00 L-032,2026-11-20,2217,"Greywell Insurance, vehicle cover",-1845.00 L-033,2026-11-20,,"Customer receipt, Ashgrove Clinic",1986.00 L-034,2026-11-23,2218,"Pell & Sons, repairs",-1190.00 L-035,2026-11-24,2219,"Marrow Lane Logistics, freight",-2051.20 L-036,2026-11-24,,Card sales settlement,1688.35 L-037,2026-11-25,2220,Castlereach Telecom,-271.35 L-038,2026-11-25,2221,"Halvorsen Supply, packaging",-1648.00 L-039,2026-11-25,,Sales tax payment,-3318.00 L-040,2026-11-27,2222,"Greywell Insurance, premium",-1420.00 L-041,2026-11-27,,"Payroll, second half November",-14102.77 L-042,2026-11-27,,"Customer receipt, Tiverton School",6200.00 L-043,2026-11-30,2223,Dovecote Stationery,-212.75 L-044,2026-11-30,,Card sales settlement,1594.10 L-045,2026-11-30,,"Customer receipt, Lindqvist Motors",4480.00
output/reconciliation.md · written by the agent, 37 lines
# Bank reconciliation, operating account ending 4471, November 2026 Statement closing balance: 40170.66 Ledger closing balance: 43123.03 (opening 48210.37 plus all 45 ledger entries) Unmatched bank lines: 8, signed total -195.72 Unmatched ledger entries: 10, signed total 2756.65 Proof: 43123.03 - 2756.65 + (-195.72) = 40170.66, which equals the statement closing balance. Matched: 35 of 43 bank lines (17 non-check pairs and 18 checks) are paired one to one with 35 of 45 ledger entries. Facts not in the files: the cause of the returned deposit item B-025 (which deposit it reverses) and whether the December statement shows the ledger items dated 2026-11-30; the notes say "likely" where this is inferred. ## amount_differs - bank B-036, 2026-11-26, -1485.00, check 2217 - ledger L-032, 2026-11-20, -1845.00, check 2217 ## duplicate_entry - ledger L-018, 2026-11-12, -732.50, check 2209 (duplicate of L-017) ## not_in_ledger - bank B-016, 2026-11-13, 2530.00 - bank B-017, 2026-11-16, -289.00 - bank B-025, 2026-11-19, -1120.00 - bank B-027, 2026-11-20, 955.00 (looks like L-022, kept unmatched: 7 days apart) - bank B-029, 2026-11-23, -764.20 (check 2214; looks like L-028, kept unmatched: ledger entry has no check number) - bank B-041, 2026-11-30, 12.48 - bank B-042, 2026-11-30, -35.00 ## not_on_statement - ledger L-019, 2026-11-12, 2350.00 (close to B-016 but not equal, kept unmatched) - ledger L-022, 2026-11-13, 955.00 (looks like B-027) - ledger L-028, 2026-11-18, -764.20 (looks like B-029) - ledger L-038, 2026-11-25, -1648.00, check 2221 - ledger L-040, 2026-11-27, -1420.00, check 2222 - ledger L-043, 2026-11-30, -212.75, check 2223 - ledger L-044, 2026-11-30, 1594.10 - ledger L-045, 2026-11-30, 4480.00
output/unmatched.csv · written by the agent, 19 lines
side,id,date,amount,reason,note bank,B-016,2026-11-13,2530.00,not_in_ledger,"Deposit with no ledger entry that may be the 2350.00 Wexcombe receipt L-019 with digits transposed, so check the deposit slip and correct whichever side is wrong." bank,B-017,2026-11-16,-289.00,not_in_ledger,"Northway insurance ACH debit that was never recorded, so confirm the invoice and book the 289.00 expense." bank,B-025,2026-11-19,-1120.00,not_in_ledger,"Likely a customer deposit that bounced, so find the original deposit, record the reversal in the ledger and follow up with the customer." bank,B-027,2026-11-20,955.00,not_in_ledger,"Likely the same payment as Sorrel Bakery receipt L-022, which is dated 7 days earlier and outside the 5-day window, so confirm the deposit date and correct the ledger date." bank,B-029,2026-11-23,-764.20,not_in_ledger,"Check 2214 likely the same payment as L-028, which was entered without a check number, so confirm and add check number 2214 to that ledger entry." bank,B-036,2026-11-26,-1485.00,amount_differs,"Check 2217 cleared for 1485.00 while the ledger shows 1845.00, likely transposed digits, so check the check image and correct the 360.00 difference in the ledger." bank,B-041,2026-11-30,12.48,not_in_ledger,"Bank interest credit not yet recorded, so book 12.48 as interest income." bank,B-042,2026-11-30,-35.00,not_in_ledger,"Monthly bank service fee not yet recorded, so book 35.00 as bank charges." ledger,L-018,2026-11-12,-732.50,duplicate_entry,"Second entry of check 2209 with the same payee and amount as L-017, likely entered twice, so void or delete it." ledger,L-019,2026-11-12,2350.00,not_on_statement,"Wexcombe receipt that may be the 2530.00 deposit B-016 with digits transposed, so check the deposit slip and correct whichever side is wrong." ledger,L-022,2026-11-13,955.00,not_on_statement,"Likely the same payment as bank deposit B-027, which posted 7 days later and outside the 5-day window, so confirm the deposit date and correct this entry date." ledger,L-028,2026-11-18,-764.20,not_on_statement,"Likely check 2214 cleared as B-029, recorded here without a check number, so confirm and add check number 2214 to this entry." ledger,L-032,2026-11-20,-1845.00,amount_differs,"Check 2217 cleared the bank for 1485.00 against 1845.00 here, likely transposed digits, so check the check image and correct the 360.00 difference." ledger,L-038,2026-11-25,-1648.00,not_on_statement,"Check 2221 has not cleared and is likely outstanding, so keep it on the outstanding list and look for it on the December statement." ledger,L-040,2026-11-27,-1420.00,not_on_statement,"Check 2222 is likely outstanding but matches check 2207 in payee and amount, so confirm it is not a duplicate premium payment before it clears." ledger,L-043,2026-11-30,-212.75,not_on_statement,"Check 2223 written on the last day is likely outstanding, so keep it on the outstanding list and look for it on the December statement." ledger,L-044,2026-11-30,1594.10,not_on_statement,"Card settlement dated the last day is likely a deposit in transit, so confirm it appears on the December statement." ledger,L-045,2026-11-30,4480.00,not_on_statement,"Lindqvist Motors receipt dated the last day is likely a deposit in transit, so confirm it appears on the December statement."
check.py · the check, written before the run
"""Redoes the reconciliation from the input files and compares it with what the agent wrote."""
import csv, re, sys
from datetime import date
from decimal import Decimal
from pathlib import Path
root = Path(sys.argv[1]); ok = True
def say(passed, text):
global ok; ok = ok and passed; print(("PASS " if passed else "FAIL ") + text)
def money(s):
try: return round(float(str(s).replace(",", "").replace("$", "").strip()), 2)
except ValueError: return None
# Figures in the written files. A figure is a number that is not part of an id or a date.
FIG = re.compile(r"(?<![\w.])(?<!\w-)(?:\d{1,3}(?:,\d{3})+|\d+)(?:\.\d+)?(?!\w|-\w)")
DAY = re.compile(r"\d{4}-\d{2}-\d{2}")
def dec(x): return abs(Decimal(str(x).replace(",", "").replace("$", "").strip()))
def figs(line): return [dec(m.group(0)) for m in FIG.finditer(line)]
def together(text, *vals):
"""True when one line of the text carries every one of these figures."""
return any(all(dec(v) in figs(ln) for v in vals) for ln in text.splitlines())
def writeup(text, id_re, rec, glob):
"""Every figure of two or more characters and every date must belong to a record named on its line
or to the facts that hold for the whole file. Returns how many were seen and the ones that do not."""
seen, bad = 0, []
for ln in text.splitlines():
allow = set(glob).union(*(rec[i] for i in re.findall(id_re, ln) if i in rec))
for t in [m.group(0) for m in FIG.finditer(ln) if len(m.group(0)) > 1] + DAY.findall(ln):
seen += 1
if (t if DAY.fullmatch(t) else dec(t)) not in allow: bad.append(t)
return seen, bad
def day(s): return date.fromisoformat(s.strip())
bank = list(csv.DictReader((root/"input/bank_statement.csv").open()))
ledger = list(csv.DictReader((root/"input/ledger_cash.csv").open()))
bal = (root/"input/balances.md").read_text()
def stated(label):
return money(re.search(label + r"[^:\n]*:\s*(-?[\d,]+\.\d{2})", bal).group(1))
bank_open, bank_close, led_open = stated("statement opening"), stated("statement closing"), stated("Ledger cash account opening")
led_close = round(led_open + sum(money(r["amount"]) for r in ledger), 2)
want = {} # (side, id) -> reason
kept, used = {}, set()
for r in sorted((r for r in ledger if r["check_no"].strip()), key=lambda r: (r["date"], r["entry_id"])):
if r["check_no"].strip() in kept: want[("ledger", r["entry_id"])] = "duplicate_entry"
else: kept[r["check_no"].strip()] = r
for b in bank:
if not b["check_no"].strip(): continue
l = kept.get(b["check_no"].strip())
if l is None: want[("bank", b["line_id"])] = "not_in_ledger"; continue
used.add(l["entry_id"])
if money(l["amount"]) != money(b["amount"]):
want[("bank", b["line_id"])] = "amount_differs"; want[("ledger", l["entry_id"])] = "amount_differs"
for b in sorted((b for b in bank if not b["check_no"].strip()), key=lambda b: (b["date"], b["line_id"])):
fits = [l for l in ledger if not l["check_no"].strip() and l["entry_id"] not in used
and money(l["amount"]) == money(b["amount"]) and abs((day(l["date"]) - day(b["date"])).days) <= 5]
if not fits: want[("bank", b["line_id"])] = "not_in_ledger"; continue
fits.sort(key=lambda l: (abs((day(l["date"]) - day(b["date"])).days), l["entry_id"]))
used.add(fits[0]["entry_id"])
for l in ledger:
if l["entry_id"] not in used and ("ledger", l["entry_id"]) not in want:
want[("ledger", l["entry_id"])] = "not_on_statement"
src = {("bank", b["line_id"]): b for b in bank} | {("ledger", l["entry_id"]): l for l in ledger}
path = root/"output/unmatched.csv"
if not path.exists():
say(False, "output/unmatched.csv was not written"); sys.exit(1)
rows = list(csv.DictReader(path.open()))
got = {((r.get("side") or "").strip().lower(), (r.get("id") or "").strip()): r for r in rows}
n = len(want)
found = len(set(got) & set(want)); extra = len(set(got) - set(want))
say(found == n and extra == 0 and len(rows) == n,
f"{found} of {n} unmatched items are listed in unmatched.csv and {extra} matched items are listed by mistake")
right = sum(1 for k, v in want.items() if (got.get(k, {}).get("reason") or "").strip() == v)
say(right == n, f"{right} of {n} reasons equal the reason recomputed from the input files")
same = sum(1 for k in want if k in got and money(got[k].get("amount")) == money(src[k]["amount"])
and (got[k].get("date") or "").strip() == src[k]["date"])
say(same == n, f"{same} of {n} listed items carry the date and amount of their source row")
gb = round(sum(money(r.get("amount")) or 0 for k, r in got.items() if k[0] == "bank"), 2)
gl = round(sum(money(r.get("amount")) or 0 for k, r in got.items() if k[0] == "ledger"), 2)
proof = round(led_close - gl + gb, 2)
say(proof == bank_close, f"ledger balance {led_close:,.2f} minus unmatched ledger items {gl:,.2f} plus unmatched bank items {gb:,.2f} "
f"comes to {proof:,.2f} against a statement balance of {bank_close:,.2f}")
md = (root/"output/reconciliation.md").read_text() if (root/"output/reconciliation.md").exists() else ""
nums = {abs(money(x)) for x in re.findall(r"-?\d[\d,]*\.\d{2}", md)}
wb = round(sum(money(src[k]["amount"]) for k in want if k[0] == "bank"), 2)
wl = round(sum(money(src[k]["amount"]) for k in want if k[0] == "ledger"), 2)
nb = sum(1 for k in want if k[0] == "bank"); nl = n - nb
say(bank_close in nums and led_close in nums and together(md, led_close, wl, wb, bank_close),
f"reconciliation.md states the statement closing balance of {bank_close:,.2f} and the ledger closing balance of {led_close:,.2f} and puts the proof on one line")
say(abs(wb) in nums and abs(wl) in nums and together(md, wb, nb) and together(md, wl, nl),
f"reconciliation.md states {nb} unmatched bank lines with a total of {wb:,.2f} and {nl} unmatched ledger entries with a total of {wl:,.2f}")
# the list grouped by reason: each item sits under its own reason with its date and amount
under, cur = {}, None
for ln in md.splitlines():
here = [r for r in set(want.values()) if r in ln]
ids = re.findall(r"\b[BL]-\d+", ln)
if len(here) == 1 and not ids: cur = here[0]
for i in ids:
k = ("bank" if i.startswith("B") else "ledger", i)
if k in want and cur == want[k] and src[k]["date"] in ln and dec(src[k]["amount"]) in figs(ln): under[k] = True
say(len(under) == n, f"{len(under)} of {n} unmatched items are listed in reconciliation.md under their own reason with their date and amount")
# Every figure and date beside a bank line or ledger entry must belong to it. A check number names every row that
# carries it, so the amounts of those rows and the gap between them may be written beside any of them.
rec, by_check = {}, {}
for (side, i), r in src.items():
rec[i] = {dec(r["amount"]), r["date"]} | ({dec(r["balance"])} if r.get("balance") else set())
if r["check_no"].strip(): by_check.setdefault(r["check_no"].strip(), []).append(r)
for no, group in by_check.items():
amounts = {money(r["amount"]) for r in group}
rec[no] = {dec(no)} | {dec(a) for a in amounts} | {dec(round(a - b, 2)) for a in amounts for b in amounts if a != b}
for r in group: rec[r.get("line_id") or r.get("entry_id")] |= rec[no]
matched_b = len(bank) - nb; checks_b = sum(1 for b in bank if b["check_no"].strip() and ("bank", b["line_id"]) not in want)
tally = {}
for (side, _), reason in want.items(): tally[(side, reason)] = tally.get((side, reason), 0) + 1; tally[reason] = tally.get(reason, 0) + 1
facts = set(figs(bal)) | set(DAY.findall(bal)) | {dec(x) for x in (bank_open, bank_close, led_open, led_close, wb, wl, len(bank), len(ledger), n, nb, nl, matched_b, len(ledger) - nl,
checks_b, matched_b - checks_b, round(wl - wb, 2), round(led_close - bank_close, 2))} | {dec(c) for c in tally.values()}
ID = r"\b[BL]-\d+|(?<![\w.,-])\d{4}(?![\w.,-])"
def pair_gaps(text): # the gap between two items named together may be written beside them
ids = [i for i in re.findall(r"\b[BL]-\d+", text) if i in rec]
return {dec(round(money(a) - money(b), 2)) for x in ids for y in ids for a in [next(v["amount"] for k, v in src.items() if k[1] == x)] for b in [next(v["amount"] for k, v in src.items() if k[1] == y)]}
seen_n = bad_n = 0
for ln in md.splitlines():
s1, b1 = writeup(ln, ID, rec, facts | pair_gaps(ln)); seen_n += s1; bad_n += len(b1)
seen2 = bad2 = 0
for k, r in got.items():
note = r.get("note") or ""
s2, b2 = writeup(note, ID, rec, rec.get(k[1], set()) | pair_gaps(k[1] + " " + note)); seen2 += s2; bad2 += len(b2)
say(seen_n > 0 and bad_n == 0 and bad2 == 0, f"{seen_n - bad_n} of {seen_n} figures and dates in reconciliation.md and {seen2 - bad2} of {seen2} in the notes equal a figure of the item they sit beside, a check number in the files, a balance or a recomputed total")
# a check number written beside an item that is a check must include that item's own number
def own_check(text, extra=()):
named = {src[k]["check_no"].strip() for k in src if (k[1] in re.findall(r"\b[BL]-\d+", text) or k[1] in extra) and src[k]["check_no"].strip()}
shown = {t for t in re.findall(r"(?<![\w.,-])\d{4}(?![\w.,-])", text) if t in by_check}
return (0, 0) if not (named and shown) else (1, int(bool(named & shown)))
ck_all = ck_ok = 0
for a, b in [own_check(ln) for ln in md.splitlines()] + [own_check(r.get("note") or "", (k[1],)) for k, r in got.items()]:
ck_all += a; ck_ok += b
say(ck_all > 0 and ck_ok == ck_all, f"{ck_ok} of {ck_all} times a check number is written beside an item that is a check, it includes that item's own check number")
sys.exit(0 if ok else 1)
balances.md: sample data written by Atris. Fingerprint 0abde11c382d.
bank_statement.csv: sample data written by Atris. Fingerprint 4a1efef3898d.
ledger_cash.csv: sample data written by Atris. Fingerprint bd653de1c07f.
reconciliation.md: written by the agent. Fingerprint cdf420a2a4ba.
unmatched.csv: written by the agent. Fingerprint de8d47c36b34.