20 KiB
CLAUDE.md
This file provides guidance to Claude Code (claude.ai/code) when working with code in this repository.
What this is
Bettersight Statement Extractor — a standalone bookkeeping tool that turns a bank
statement PDF into clean, structured transaction rows, proves the arithmetic against
six automated checks, and exports to Excel. It's the first phase of a planned paid
product line ("Bettersight"), built as its own repo/container stack (sibling to, and
independent of, eib-processor/ — not a tool hosted inside that platform). See
UI_DESIGN_THEME.md for the Bettersight brand system and UI_DESIGN_THEME_ENTERPRISE.md
for this app's own light-theme override of it.
This product deliberately does not categorize transactions (bank description →
accounting description) — it only structures the statement and proves the math. That's
a different, narrower scope than the in-app bank_statement_categorizer tools that live
inside eib-processor. The original full product spec this was scoped down from is
copied into this repo at docs/bankstatement.md — section 1.3 there is where the
categorization boundary is defined; section 15 is the full 7-phase table referenced below.
Build scope & status
This repo exists to build Phase 1 only of that 7-phase spec. The original planning
session (its record lives at /Users/jason/.claude/plans/valiant-leaping-stonebraker.md
on the machine this was built on — not guaranteed to persist or be readable from a fresh
environment, so its substance is captured here instead) mapped the spec's own phase table
to rough effort:
| Phase | Contains | Status here |
|---|---|---|
| 1 | Extraction + 6 checks + Excel export, dual-engine, measurement harness | In progress — see gaps below |
| 2 | Review screen, suggested-fix patterns, OCR, 2nd+ bank support | Not started |
| 3 | Layout mapper (fingerprinting, versioning, drift detection) | Not started |
| 4 | Multi-tenant practice/client accounts, Frappe data model | Not started |
| 5 | Free front door, public accuracy page | Not started |
| 6 | Append mode, credit cards, multi-account statements | Not started |
| 7 | Reconciliation against the ledger | Not started |
Divergence from the spec's own literal Phase 1 (docs/bankstatement.md §15): the
spec defines Phase 1 as "Command-line extraction for one bank, text PDFs, all six checks,
Excel output. Measure against real statements. Also build the measurement harness..." —
CLI-only, one bank. This repo's Phase 1 deliberately diverged from that in two ways,
decided in the original planning session: a minimal web UI was built from the start
instead of a CLI, and two banks (HSBC and RBC) ended up supported instead of one. Both
are intentional scope decisions, not drift.
What's actually built and verified, as of 2026-10-11:
- Extraction (
app/table_extract.py+app/layout_rules.py) generalized to be bank-agnostic — validated against real HSBC statements AND a real RBC statement with exact-match totals, despite the two banks using different column layouts, debit-sign conventions, and balance-chain directions. Only HSBC PDFs are saved underfixtures/(HSBC-USD-Sep2026.pdf,HSBC-USD-August2026.pdf,ground_truth_sep_reference.xlsx) — no RBC fixture or ground-truth file has been committed, so that validation isn't currently reproducible from this repo alone; the RBC statement used for that work lives only wherever it was originally uploaded from. - Dual-engine cross-check (
app/reconcile.py), the six checks plus the 7th narrative-direction check (app/checks.py), the pipeline (app/pipeline.py), and Excel export (app/excel_export.py) are all built and wired through the live UI. - The minimal web UI (upload → table + status → download, per the plan's explicit "not the full review screen" scope decision) is built and has had extensive layout/theme polish — see "Frontend / UI state" below.
As of 2026-10-11, the measurement harness, RBC fixture, and git init from the gaps below are done — see "Outstanding before Phase 1 can be called done" for current detail. Kept here as the historical record of what this section originally found missing:
No— nowmeasure.pyapp/measure.py, run and verified against the real dual-engine pipeline.No RBC fixture/ground truth— nowfixtures/RBC-CAD-Aug26.pdf+..._ground_truth.xlsx, hand-verified.Not a git repository—git initdone, initial commit16f74f7.- No
README.md— still undecided.
Docling spike finding (why the extractor is dual-engine, not Docling-primary): a real
4-page HSBC statement was run through Docling requesting to_formats=[md, json]. Docling's
TableFormer model correctly recovered row/column structure on pages 1–3 (7, 10, 11
transaction rows — exact match to hand-verified ground truth) but completely failed to
recognize page 4 as a table at all, returning flat, unstructured positioned text instead.
Separately, on a page it did structure correctly, one cell quietly merged two distinct
values together ("Time" + "Balance" into one cell) — a silent mis-grouping, not a hard
failure, that wouldn't trip an error on its own. Docling's own self-reported table_score
came back None on this run, so it couldn't even be used as a confidence signal.
This is why reconcile.py runs both engines on every page, always (not Docling with
pdfplumber as an emergency-only fallback): agreement on count/dates/amounts → high
confidence, use Docling's structured result; Docling missed a table but pdfplumber found
one → use pdfplumber's result, flagged informationally; the two disagree → flagged for
review with specifics, never silently picked between — this subsumes and strengthens
two of the spec's own six checks (page coverage, totals) by using cross-engine
disagreement itself as the confidence signal, rather than trusting either engine's own
self-reported score.
Commands
docker compose up --build # start everything (app + Docling), foreground
docker compose up --build -d app # rebuild + restart just the Flask app after code changes
docker compose down # stop and remove both containers
- App: http://localhost:8091
- No hot reload — template/code edits require a rebuild to show up.
- There is still no test suite, but the measurement harness now exists:
python3 app/measure.py(from the repo root; needsopenpyxl,pdfplumberon PATH/venv — the samerequirements.txtthe app itself uses) runs everyfixtures/*.pdfwith a matching*_ground_truth.xlsxthrough the real pipeline and reports untouched pass rate + field accuracy. Works with or without the Docling container up (degrades to pdfplumber-only per page if unreachable — same behavior as the live app).python3 -m py_compile <file>is still the fastest sanity check after editing a.pyfile that doesn't have fixture coverage.
Architecture
app/main.py— minimal Flask app factory.app/docling_client.py— wraps the self-hosted Docling container (to_formats=[md,json]) to get structured table output per page, not just flat markdown.app/table_extract.py— the generalized pdfplumber extractor. Bank-agnostic: derives each column's role (date/description/debit/credit/balance) from the header row's own word positions and a shared keyword dictionary (app/layout_rules.py), rather than hardcoded per-bank pixel zones. Also auto-detects the debit-sign convention, the running-balance/date-ordering direction (forward vs. backward), and the narrative- attachment direction (which transaction a wrapped description line belongs to) via a per-gap hybrid: an explicit column label is the primary signal when present (tracked via asaw_labelflag kept independent of whether that label's own text is empty); geometric vertical-proximity is the fallback when no label exists, with a confidence margin that flags genuinely ambiguous gaps (ambiguous_indices) rather than guessing silently. Also captures opening/closing balance values straight from in-table summary rows when the statement prints them (RBC-style), as a fallback under the user's own typed values.app/reconcile.py— runs Docling and pdfplumber on every page in parallel (not a pipeline — pdfplumber re-reads the PDF's own text layer independently) and cross-checks them: agreement → high confidence; Docling missed a table but pdfplumber found one → use pdfplumber's result, flagged informationally; disagreement → flagged for review, never silently resolved.app/pipeline.py— orchestrates extract → reconcile → normalize → run checks.app/checks.py— the six checks (statement balance, running-balance continuity, totals, date sanity, structure sanity, page coverage) plus a 7th,check_narrative_direction, surfacing ambiguous narrative-attachment gaps.check_statement_balancealways computes and returnscalculated_closingwhenever an opening balance is known, independent of whether a closing balance is available, so the UI can show it even when the check itself is "not available." Running-balance and date-ordering checks try both directions and pick whichever has fewer violations, rather than assuming one.app/excel_export.py— Transactions + Summary sheet export.app/measure.py— the measurement harness. Auto-discovers its corpus fromfixtures/*.pdfwith a matching*_ground_truth.xlsxsibling (each ground-truth file is aTransactionssheet of date/status/description/amount/balance rows in the same canonical, newest-first order as pipeline output, plus aSummarysheet with opening_balance/closing_balance), runs each through the realpipeline.run, and reports/logs both of the spec's section-11 measures. Position-matched field comparison (not matched by value), so a swapped-order bug shows up as a mismatch rather than being silently absorbed.templates/index.html— the entire frontend: a single vanilla-JS page, no framework, no build step. See "Frontend / UI state" below — it has been through many rounds of layout and theme iteration and the current state is not obvious from a first read.
Key decisions & lessons
Governing rule: never silently correct or exclude data. This shows up in several concrete places, not just as an abstract principle:
- A row with an unusual status (e.g. HSBC's "Cancelled" wires) stays in the output and is allowed to break the running-balance chain, surfaced as a flag — the earlier in-app categorizer tool used to silently drop these rows before running checks; this product deliberately does not repeat that.
- An ambiguous narrative-attachment gap (see below) is flagged (
ambiguous_indices), not guessed toward whichever direction seems more likely. - Engine disagreement between Docling and pdfplumber is flagged with specifics, never auto-resolved by picking one engine's result.
- The opening/closing balance input fields never auto-fill — a separate read-only "Calculated" readout shows the auto-detected value instead, so the UI never shows a number in an editable field that the user didn't actually type themselves.
Narrative-direction detection went through a real debugging cycle worth knowing about
if this logic needs to change again. The first approach — counting blank lines to guess
which transaction a wrapped description belongs to — was wrong for RBC (confirmed via an
Oyster payroll example where text was misattributed to the preceding fee transaction
instead of the correct following one). The fix was a per-gap hybrid in _decide_gap():
an explicit column label (e.g. "Narrative") is the primary, always-confident signal when
present; geometric vertical-proximity is the fallback when no label exists. A second bug
surfaced during this fix: HSBC's narrative label line usually has no text after the label
word itself, so filtering empty-text rows before checking their label flag silently
dropped the label signal. Fixed by tracking saw_label as its own boolean, updated
regardless of whether that row's own text is empty, independent of the buffer list
(which only holds non-empty entries).
Balance-chain and date-ordering direction are auto-detected, not hardcoded per bank —
checks.py tries both forward and backward (and both newest-first and oldest-first) and
keeps whichever has fewer violations, because RBC and HSBC don't share a convention and a
third bank is unlikely to either.
UI iteration has mostly been many small, specific, explicitly-approved requests — the
one explicit correction worth remembering: an early request to fix the Date/Amount/Balance
column widths was initially (wrongly) read as "remove the side-by-side resizer layout
entirely." The correct scope was much narrower (fixed-width columns via <colgroup> +
table-layout:fixed, Description column left flexible) and the resizer/side-by-side
structure was never meant to change. When a UI request could be read either as a small,
scoped fix or a larger structural change, confirm before assuming the larger one.
Frontend / UI state (as of 2026-10-11)
Theme is enterprise-light, not the Bettersight brand default. UI_DESIGN_THEME.md
specifies a dark-first brand system (deep navy base, single lime-green accent) — that's
the default for Bettersight-family products. This app's templates/index.html was
explicitly converted away from that default, on direct user request, to match a specific
enterprise-SaaS reference screenshot (light background, standard blue #2563EB accent,
white cards, 8px radii). The conversion kept the same set of CSS custom properties
defined in UI_DESIGN_THEME.md (same names, same count) and only changed their values
— including reusing that doc's own already-specified "light surface" and "text on light
surfaces" token values where they existed, rather than inventing new ones. If asked to
touch the theme again, preserve this token-value-only discipline rather than restructuring
the :root block or hardcoding colors inline.
Key current UI behaviors, each the result of an explicit, specific user request (don't "simplify" these away without asking first):
- PDF ("Source Document") and Transactions sit side-by-side with a draggable resizer
(
.resizer, styled as a vertical grip-knob), both wrapped in.review-gridwhich is what'sposition:sticky(not the PDF column alone) so they scroll as one unit. - A Hide/Show toggle in the Transactions header (
#togglePdfBtn, labeled "Hide Source Doc"/"Show Source Doc") collapses the PDF column so Transactions fills the row. - The Result card is collapsible: a chevron + "Result" heading on the left toggle the
status banner/checks list; Download Excel stays on the right, always visible; every
fresh extraction starts collapsed (
setResultExpanded(false)runs inrenderResult). - Opening/closing balance inputs always start blank (never auto-filled) — a separate
read-only "Calculated: $X" readout below each one shows the auto-detected or typed
value, turning green when
statement_balancecheck outcome is "pass". This was a deliberate choice to reduce confusion about what's user-entered vs. auto-detected. - Per-row edit lock: cells are read-only until that row's pencil icon is clicked; a
per-row Save commits to
currentResultand triggers/api/recheck; Cancel discards. - All numeric displays are comma-formatted (
fmtMoney/fmtNum). - Edits persist to
localStorage, keyed by the source file's name+size (docKeyFor), so a crash/reload can restore in-progress edits; the PDF preview itself can't be persisted this way and needs the same file re-selected to reappear.
Outstanding before Phase 1 can be called done
- Write
measure.py(the harness from the plan's step 10) and actually run it. Lives atapp/measure.py, run aspython3 app/measure.pyfrom the repo root (or inside theappcontainer). Auto-discovers its corpus: everyfixtures/*.pdfwith a matching<name>_ground_truth.xlsxsibling is measured for both of section 11's measures (untouched pass rate, field accuracy on date/description/amount/balance, position-matched); a fixture with no ground truth still gets an untouched-pass reading but is reported as "no ground truth" for field accuracy, never silently skipped. Writes a dated JSON report toresults/(gitignored — each run produces a new file, not meant to be committed) and prints a console summary. Confirmed working against the real dual-engine pipeline (Docling + pdfplumber, not a fallback stub) as of 2026-10-11. - Commit an RBC fixture + hand-derived ground truth —
fixtures/RBC-CAD-Aug26.pdf(copied fromdocs/RBC-CAD-Aug26.pdf, which the user had placed there) plusfixtures/RBC-CAD-Aug26_ground_truth.xlsx, hand-verified by reading all 4 statement pages visually (viapdftoppm/poppler) against the extractor's own output — all 108 transactions, the opening balance ($66,857.70), and the closing balance ($90,569.13) matched exactly. One real extraction bug was caught in the process and is now a permanent regression case: the last transaction on page 4 absorbs the page's trailingAccount Fees: $48.75footer line into its own description (not yet fixed intable_extract.py— ground truth encodes the correct value, someasure.pyreports this row's description as a mismatch every run until it's fixed).fixtures/HSBC-USD-Sep2026_ground_truth.xlsxwas built and verified the same way (all 32 transactions visually confirmed page-by-page); HSBC's own opening/closing ground truth isNone/None, matchingextract_statement_facts— HSBC genuinely doesn't print these within the table (confirmed visually: the only balance figures on the statement are a "Closing ledger balance brought forward" and "Current ledger balance" dated 01–02 Oct, outside the Sep 1–30 statement period, not this statement's own opening/ closing).fixtures/HSBC-USD-August2026.pdfstill has no ground truth (only Sep was built) —measure.pyreports it (untouched pass only), which surfaced a pre-existing, real problem: it currently failsrunning_balance(1 broken row) andengine_agreement(Docling found no table on 3 of 4 pages) — not caused by this work, but now visible and tracked instead of silent. git initthis repo — done 2026-10-11, initial commit16f74f7.- Decide whether a
README.mdis wanted. fixtures/ground_truth_sep_reference.xlsxwas discovered to be mismatched: it's a bank-description→accounting-category mapping (Bank Description / Accounting Description / Amount columns, 8 rows, no date or balance) — categorization data from the separatebank_statement_categorizertool, not this product's own per-transaction extraction ground truth. It was left in place rather than deleted unilaterally; decide whether to remove it or repurpose it.- The HSBC-Aug and RBC
engine_agreement/running_balanceissuesmeasure.pynow surfaces (above) aren't fixed — this harness's job was to make them visible and regression-tracked, not to resolve them.
Nothing else from the original Phase 1 step list (scaffold, Docling spike, extractor, reconciler, pipeline, checks, UI, Excel export) is outstanding — those are built. Phases 2–7 are deferred by design, not oversight; don't start on them without the user asking.
Working across directories
This repo is a sibling to eib-processor/, not nested inside it. If you're in a Claude
Code session rooted in a different directory and need to touch files here, use
/add-dir <this-repo-path> (session-only) or add it to permissions.additionalDirectories
in ~/.claude/settings.json (persistent). The cleanest setup for sustained work on this
project specifically is to run a Claude Code session rooted directly in this directory
(cd here, then claude) — this file loads automatically when that session starts.