# 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 | OCR routing + working Docling-fallback (`raw_ocr_extract.py`) built and verified against a real multi-page scan 2026-10-11 — one known single-page edge case remains unreliable, see "OCR / scanned statements" below — review screen and suggested-fix patterns 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 under `fixtures/` (`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 `measure.py`~~ — now `backend/measure.py` (moved there in the 2026-10-11 backend restructure; was `app/measure.py` when first written), run and verified against the real dual-engine pipeline. - ~~No RBC fixture/ground truth~~ — now `fixtures/RBC-CAD-Aug26.pdf` + `..._ground_truth.xlsx`, hand-verified. - ~~Not a git repository~~ — `git init` done, initial commit `16f74f7`. - 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 ```bash 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 - Backend edits require a Docker rebuild (`docker compose up --build -d app`) to show up — no hot reload inside the container. Frontend development has its own faster loop: `cd frontend && npm run dev` runs Vite's dev server (default `localhost:5173`) with real hot module reload, proxying `/api/*` to `localhost:8091` (see `frontend/vite.config.js`) so it talks to the same running backend/Docling containers without any CORS setup. The Docker image itself always serves the *built* `frontend/dist` (`npm run build`, done automatically as the Dockerfile's first stage) — rebuild the image to see frontend changes at `:8091`, same as a backend change. - There is still no test suite, but the measurement harness now exists: `python3 backend/measure.py` (from the repo root; needs `openpyxl`, `pdfplumber` on PATH/venv — the same `requirements.txt` the app itself uses) runs every `fixtures/*.pdf` with a matching `*_ground_truth.xlsx` through 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 ` is still the fastest sanity check after editing a `.py` file that doesn't have fixture coverage. ## Architecture **Restructured 2026-10-11/12 into `backend/` + `frontend/`, layered per `ENTERPRISE_STANDARDS.md`** — backend: routes → services → repositories → schemas; frontend: views → components → composables → services → repositories, Pinia for global state. The old flat `app/` directory and `templates/index.html` no longer exist — both restructures are done (see "Enterprise-standards restructure" and "Frontend restructure to Vue 3" under Key decisions & lessons for the scope decision on each: structure + commenting + applicable security only, not the full SaaS-shaped doc — and the judgment call on what counts as a "repository" here, since there's no DB). `backend/app.py` now serves the built Vue app (`frontend/dist`, produced by `npm run build`) as static files at `/`, not a Jinja template. ``` /backend app.py — Flask app factory: registers blueprints; "/" and any other non-API path serve frontend/dist's index.html (SPA fallback) or the matching static asset if one exists dependencies.py — DOCLING_URL/UPLOAD_FOLDER/OUTPUT_FOLDER read from env once at import time; repositories import this directly rather than reaching into Flask's current_app measure.py — the measurement harness (see below), relocated /routes extraction.py — Blueprint: POST /api/process, /recheck, /export, GET /api/download/ — request in, call a service, response out, no business logic health.py — GET /health — pings Docling via docling_repository /services extraction_service.py — text-PDF-vs-OCR routing + the dual-engine cross-check (was reconcile.py) checks_service.py — the checks (was checks.py, near-direct relocate) pipeline_service.py — composes extraction_service + checks_service (was pipeline.py) excel_service.py — builds the openpyxl Workbook object (the *building* half of the old excel_export.py — saving to disk moved to file_repository) /extraction — pure parsing/domain logic, no I/O: table_extract.py — the pdfplumber extractor (unchanged) layout_rules.py — shared column/balance keyword vocabulary (unchanged) docling_parser.py — the PARSING half of the old docling_client.py (tables_by_page, _resolve_columns, extract_transactions, ocr_table_to_rows, ocr_extract_pdf) — the HTTP call itself moved to docling_repository raw_ocr_extract.py — the per-page OCR fallback (unchanged logic, import paths updated) /repositories — the only two real data-access boundaries this app has (no DB — see the restructure note above for why local library calls like pdfplumber/tesserocr/openpyxl are NOT treated as repositories): docling_repository.py — the raw HTTP POST to Docling (was docling_client.convert() alone) file_repository.py — save/remove an upload, save a workbook, resolve an output path (was main.py's ad hoc f.save/os.remove/ workbook.save/send_file calls) /schemas extraction_schema.py — validates/shapes the process/recheck/export request bodies (was main.py's inline _opt_float helpers) ``` - `backend/services/extraction/docling_parser.py` — `_resolve_columns()` is the column-role resolver shared by both `extract_transactions()` (the cross-check-only path) and `ocr_table_to_rows()` (the OCR-canonical path below) — it's collision-aware, not first-match-wins: a header cell whose text matches vocabulary from two genuinely different fields at once (confirmed for real on an RBC page where Docling's own table-structure model mis-segmented a wrapped header, scrambling "Debits"/"Deposits" text across the wrong cells) is excluded rather than silently guessed at — but a losing match that's merely a *substring* of the winning one (e.g. "amount" inside "credit amount") isn't treated as contamination, and two separately clean columns that both legitimately match the same field (confirmed for real on HSBC, which has two genuine date columns — "Value date" and "Post date") resolve via whichever matched the longer, more specific phrase rather than being excluded outright. See its own docstring for the full reasoning — this took two iterations to get right, each broke a real fixture, and is exactly the kind of logic worth reading before touching again. `ocr_table_to_rows()`/ `ocr_extract_pdf()` reshape a Docling-OCR'd table into the identical row format `table_extract.extract_page()` produces, so `table_extract.rows_to_transactions`/ `extract_statement_facts` run unchanged on OCR'd data too — see "OCR / scanned statements" under Key decisions & lessons for what this does and doesn't currently handle well. `docling_repository.convert()` guesses the upload's content-type from its own extension (not hardcoded to `application/pdf`) so a raw image upload reaches Docling's OCR correctly — confirmed for real that Docling accepts and OCRs a raw PNG directly when sent with its correct `image/png` content-type. - `backend/services/extraction/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 (`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 a `saw_label` flag 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. - `backend/services/extraction_service.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. `_needs_ocr()` routes an upload with no embedded text layer at all (a raw image, or a PDF wrapping a scan/photo) to `_run_ocr_only()` instead — Docling's OCR becomes the sole canonical source there (no pdfplumber pass is even possible), not just the cross-check role it plays for a normal text PDF. `_run_ocr_only()` additionally falls back to `raw_ocr_extract.py` on a PER-PAGE basis when Docling's own table-structure recognition fails for a given page (zero transaction rows) — see "OCR / scanned statements" below. - `backend/services/pipeline_service.py` — orchestrates extract → reconcile → normalize → run checks. - `backend/services/checks_service.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_balance` always computes and returns `calculated_closing` whenever 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. - `backend/services/excel_service.py` + `backend/repositories/file_repository.py` — Transactions + Summary sheet export, split across the build (service) and disk-write (repository) boundary. - `backend/services/extraction/raw_ocr_extract.py` — the per-page fallback for `extraction_service._run_ocr_only` when Docling's table-structure recognition fails on a scanned/photographed page. Runs OCR directly (`tesserocr`) for raw word text + pixel position, bypassing any table-structure model's row/column grouping entirely, then reuses `table_extract.py`'s own column-geometry logic unchanged. See "OCR / scanned statements" below for the full reasoning, the two real adaptations this needed (pixel-to-point scaling, cross-page zone sharing), and the one known edge case that isn't reliably fixed. - `backend/measure.py` — the measurement harness. Auto-discovers its corpus from `fixtures/*.pdf` with a matching `*_ground_truth.xlsx` sibling (each ground-truth file is a `Transactions` sheet of date/status/description/amount/balance rows in the same canonical, newest-first order as pipeline output, plus a `Summary` sheet with opening_balance/closing_balance), runs each through the real `pipeline_service.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. Run from the repo root: `python3 backend/measure.py`. - `frontend/` — Vue 3 + Vite, replacing the old single-file `templates/index.html` (896 lines of vanilla JS, no framework, no build step). See "Frontend restructure to Vue 3" under Key decisions & lessons for the full migration record, and "Frontend / UI state" below for every behavior this had to faithfully reproduce (sticky layout, resizer, per-row editing, localStorage persistence, image zoom, etc.) — it went through many rounds of layout/theme iteration before this restructure and none of that was simplified away in the rewrite. ``` /frontend/src main.js — createApp(App).use(pinia).use(router).mount('#app') App.vue — page chrome (
wrapper) around the routed view /assets/main.css — the full original CSS, moved verbatim - same tokens, same rules /router/index.js — one route today ('/' -> ExtractorView), kept as a real router per the standards doc's structure /stores (Pinia) extractionStore.js — currentResult (kept as one cohesive object matching the server's own shape), currentDocKey, flaggedIndexes, errorMessage (the SAME shared error area the original used for upload/process/download errors alike - not split per component), openingBalanceInput/closingBalanceInput (read live by any recheck/export call, not just the inputs themselves) + effectiveOpeningBalance/effectiveClosingBalance getters uiStore.js — resultExpanded, pdfColHidden, pdfColWidthPct, restoreBannerVisible, layoutVersion (an incrementing counter every TransactionRow's own description textarea watches to re-measure its height - replaces the original's global autoGrowAll() call, bumped on a resize-drag ending or the Hide/Show toggle, the same two trigger points the original had) /repositories — raw HTTP/storage access only: extractionRepository.js (fetch calls to /api/process|recheck|export), localStorageRepository.js /services — extractionService.js (docKeyFor, persist/restore, effectiveBalance, process/recheck/export orchestration), formatService.js (fmtMoney/fmtNum/parseNum - escapeHtml dropped, redundant once Vue's own {{ }} auto-escapes) /composables — useFileUpload, useExtraction, useProcessingPhases (NEW - the original ask that started this detour, see below), useRowEditing, useImageZoom, useAutoGrow /components — FileUploadZone, ProcessingIndicator (NEW), RestoreBanner, ResultCard, SourceDocumentPanel, TransactionsTable, TransactionRow, ResizablePanels /views/ExtractorView.vue — composes everything above - this IS the whole page ``` **One real bug caught and fixed during this restructure, server-side:** the production `Dockerfile` serves `frontend/dist` from Flask via a catch-all route (`@app.route("/")`) that serves a real static file if one exists at that path, else falls back to `index.html` (SPA routing). The first version of this also left Flask's OWN automatic static route enabled (`static_folder=FRONTEND_DIST, static_url_path=""`) — registering TWO rules against the identical `/` pattern. Fixed by setting `static_folder=None` and handling serving entirely in the manual catch-all. Confirmed working end-to-end against the real container: `/` serves the SPA, a real asset path (`/assets/*.js`) serves with the correct content-type, `/health` and `/api/*` aren't shadowed by the catch-all. ## Key decisions & lessons **Enterprise-standards restructure, Stage 1 of 2 (backend), done 2026-10-11 — see "Frontend restructure to Vue 3" below for Stage 2.** User asked to split this repo into `frontend/`/`backend/` and rebuild both per `ENTERPRISE_STANDARDS.md` — a generic template written for a multi-tenant SaaS (JWT auth, PocketBase, Sentry, circuit breakers, CI/CD with staging/production, 80%-enforced test coverage, daily backups), none of which exists in this repo or matches where this product actually is (multi-tenancy is Phase 4 here, not started; there's no DB — output is a direct Excel export; no login exists to attach JWT auth to). Scope was confirmed explicit with the user: **structure (§2-3) + commenting (§10) + the parts of §4 security that map onto an app with no user/tenant model — not §5-9** (observability/resilience/80%-coverage-testing/deployment/backups). `/health` was added anyway despite being arguably §5-adjacent — it's §11's one "never skipped" rule and costs nothing. One real judgment call worth knowing if this gets revisited: the standards doc defines a "repository" as "all data access (DB reads/writes, external API calls)." This app has no DB, so the only genuine repository-shaped boundaries are the Docling HTTP call (`docling_repository.py`) and local filesystem I/O (`file_repository.py`). Local *library* calls — pdfplumber, tesserocr, openpyxl — are treated as things services call directly, not repositories, since they aren't access to an external system; `table_extract.py` was already calling pdfplumber directly before this restructure, and that didn't change. This was **Stage 1 (backend) only, by explicit agreement** — the user asked to checkpoint before the much larger, riskier Stage 2 (frontend → Vue 3 + Vite, Pinia, composables, ~10 components replacing ~830 lines of vanilla JS) — done the next day, see below. `backend/app.py` deliberately still served `templates/index.html` at `/` unchanged throughout Stage 1 — stripping that out before Vue existed to replace it would have broken the UI the user was testing in their own browser; that only changed once Stage 2 shipped. Verified identical behavior before deleting the old `app/` directory: `measure.py` against the fixture corpus (same field accuracy as the pre-restructure baseline), plus real end-to-end `curl` tests through the rebuilt Docker container on both the dual-engine path and the hardest case — the 2-page scanned-PDF OCR + per-page raw-OCR-words fallback (`docs/scanned_statement_2page.pdf`) — came back byte-for-byte identical (17/17 transactions, same signs, same balances, same per-page engine attribution). One pre-existing latent bug found during this relocation, fixed 2026-10-11 in a dedicated follow-up pass (deliberately not bundled into the structural move itself): `pipeline_service.recheck()`'s OCR-sourced check originally only matched the `"ocr_only"` page status, not `"ocr_raw_words"` — if every page of a recheck's `page_reports` ended up `"ocr_raw_words"` (Docling failed everywhere, the per-page fallback rescued every page), this incorrectly treated a genuinely OCR-sourced recheck as not OCR-sourced, letting it reach "Verified" when it shouldn't be able to. Now checks membership in `("ocr_only", "ocr_raw_words")`. Carried over verbatim from the original `pipeline.py` until this fix. Verified directly (not just via `measure.py`, which only exercises `pipeline_service.run()`, never `recheck()`): an all-`"ocr_raw_words"` `page_reports` now correctly surfaces the `ocr_source` check and stays below "Verified", a mixed `ocr_only`/`ocr_raw_words` case does the same, and a normal dual-engine `"ok"` case is unaffected — confirmed both as a direct function call and through `/api/recheck` on the real running app. **Frontend restructure to Vue 3, Stage 2 of 2, done 2026-10-12.** Rebuilt `templates/index.html` (896 lines of vanilla JS, read in full before starting — every function enumerated against the plan, not re-derived from memory) as `frontend/`, a Vue 3 + Vite app per `ENTERPRISE_STANDARDS.md`'s frontend layering (views → components → composables → services → repositories, Pinia for stores) — same scope agreement as Stage 1. Full structure is in the Architecture section above; this entry is about what the migration itself required getting right. The original ask that triggered this whole detour — processing-phase text with an animated ellipsis during `/api/process` — landed here as the one genuinely new feature (`useProcessingPhases.js` + `ProcessingIndicator.vue`), built once in Vue rather than once in vanilla JS and then rewritten. It's honestly simulated, not real progress: `/api/process` is one synchronous request with no streaming signal, so the phase labels ("Reading document…" → "Extracting transactions…" → "Cross-checking with a second engine…" → "Running verification checks…" → "Preparing results…") cycle on a timer that holds on the last phase if the real request runs long, rather than looping back in a way that would misleadingly suggest the work restarted. **One real bug caught mid-build, before it ever shipped:** `ResultCard.vue`'s first draft gave the Download button's own errors a separate local `error-note`, instead of routing them through the shared `extractionStore.errorMessage` the original vanilla-JS version used for upload/process/download errors alike (one `#errorNote` element, several different call sites). Caught by checking the draft against the plan's own explicit callout of this shared-error-area behavior, fixed before the build was ever run. **Honest account of what got verified and how, since the browser extension couldn't connect for interactive testing (tried repeatedly):** - `npm run build` succeeds; `formatService.js`'s pure functions tested directly in Node - Every prop/emit name and every Pinia store field/action reference cross-checked by hand across all ~20 new files (`grep` every usage site, confirm each matches its definition) — this is how the Flask static-route duplication bug (see the Architecture section's own callout) was the only other real bug found, everything else checked out - Full regression through the real Docker container: `/` serves the SPA, static assets serve with correct content-types, `/health` and `/api/*` untouched, dual-engine extraction returns identical results to the pre-restructure baseline, `measure.py` unaffected (this stage touches no backend code) - **Actual interactive behavior — file upload, drag/drop, the processing-phase animation, pencil-to-edit/Save/Cancel, image zoom, the resizer, Hide/Show Source Doc, the collapsible Result card, localStorage persistence/restore, Download Excel — was verified by the user in their own browser, not by Claude.** `templates/index.html` was deliberately kept in place as a fallback until the user confirmed this worked, then deleted once they had. If this is ever revisited and something in that list turns out subtly broken, this is the honest paper trail of what was and wasn't machine-verified. **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 `` + `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. **OCR / scanned statements (added 2026-10-11, routing built; real-world reliability unresolved).** pdfplumber has zero OCR capability — confirmed by building an image-only PDF (no text layer, same as a real scan) from a real statement page and watching `extract_text()` return nothing. Before this work, the pipeline's own guard clause (`if not any(pages_rows.values())`) caught that and raised a *misleading* error — "could not recognize this statement's column layout," which is the message written for a different problem (a text PDF whose bank layout isn't supported yet), not "no text layer at all." `reconcile._needs_ocr()` now distinguishes the two: a raw image upload or a scanned/photographed PDF routes to `_run_ocr_only()` (Docling's OCR as the sole canonical source, correctly worded error if even OCR fails), while a text PDF this extractor just doesn't recognize still gets the original, differently-worded error. An OCR-sourced extraction can never reach "Verified" — `checks.check_ocr_source()` always reports `needs_review`, by design: there is no second engine to cross-check Docling's OCR against, so the core safety property every other check result rests on (two independent engines, never trust one alone) doesn't hold here. This is enforced by construction (the check's own outcome), not a bolted-on status override. **The honest limitation this surfaced, confirmed empirically, not assumed:** Docling's own table-structure recognition is meaningfully less reliable on rasterized/OCR'd input than on a native PDF's text layer — this was already known from the original Docling spike (see above) on the *clean* text-PDF path; this work reconfirmed it's worse again once OCR is also in the loop. Four real test renders this session, same real HSBC statement, different pages/settings: page 1 alone → Docling merged the account-summary preamble block in *above* the real header row into one table (fixed here — `ocr_table_to_rows` now searches for the header row via the same pattern `table_extract._find_header_row` already uses for pdfplumber, rather than assuming row 0); that same render *also* merged "Credit amount" and "Debit amount" into a single cell, which can't be safely split back into two columns after the fact (the column-collision detector correctly refuses to guess, leaving `debit` unresolved) — not fixed, and not safely fixable by reshaping alone. Page 2 alone, at both 200 and 300 DPI, wasn't recognized as a table at all (flat OCR text instead, same failure mode the original spike documented on page 4 of the clean PDF). So: the routing and row-reshaping infrastructure is built and unit-verified correct (confirmed end-to-end through the real running app for both a text-PDF upload and a raw-image upload), but whether a *given* real scan or photo actually extracts anything still depends on Docling's own, inconsistent table-structure call on that specific image — not something this session resolved, and not something straightforward to fix from this repo's side (it's the external model's own behavior, not a parsing bug in this codebase). Test images from this session are kept at `docs/scanned_statement.pdf` and `docs/scan_test_page-1.png` for whoever picks this up next. **PaddleOCR (PP-StructureV3) was benchmarked and rejected, 2026-10-11.** Built as a standalone adapter (own venv — `paddlepaddle` has no wheel for the main app's Python version), reshaping its table output into the same canonical row format Docling's OCR path uses and run through the real `table_extract.rows_to_transactions`/`checks.run_all` pipeline — not just a raw-OCR-text comparison. Against the same problem image Docling struggled with (`docs/scan_test_page-1.png`), PP-StructureV3 did worse, not better: its table-structure HTML was more severely corrupted (mismatched colspans, cell content from different real rows jumbled together), and while its best candidate header row recovered `status`/`date`/`credit`/`debit` correctly, the "Balance" column header was lost entirely with no recoverable cell anywhere — one field short of usable, 0 transactions extracted. One data point against one hard image, not a broad verdict, but enough to not pursue it further here — the adapter code was removed rather than kept unused. **`raw_ocr_extract.py` (now `backend/services/extraction/raw_ocr_extract.py`) — a working fallback for Docling's OCR-structure failures, shipped 2026-10-11.** Also benchmarked: Docling's own alternate OCR engines (`tesseract`, `rapidocr`) and `table_mode: fast` against the same problem image — all produced the identical grid (same merges, same failure) or worse; neither the OCR engine nor the table mode was ever the actual bottleneck. The real fix came from a different idea: don't trust ANY table-structure model's row/column grouping at all. Run OCR directly (`tesserocr`) to get raw per-word text + pixel position, then reuse `table_extract.py`'s own column- geometry logic (`_find_zones`/`_classify_money`/etc. — the same code already proven correct for HSBC and RBC's real pdfplumber path) to derive columns from word geometry itself, same as it already does for a native PDF. Two adaptations beyond the pdfplumber path, both confirmed necessary by testing against real rendered pages, not assumed: 1. **Pixel-to-point scaling.** `_assign_money_columns`'s `max_distance=60` is tuned for PDF points (72/inch), meaningless for raw pixel coordinates. For a scanned PDF the exact scale is knowable (pdfplumber reports a page's real point-dimensions even with no text layer) and used directly. For a bare photo with no PDF page to anchor against, there's no way to know true scale, so the image's own pixel width is treated as if it were a standard portrait US Letter page (612pt) — a real, documented assumption, not a fact; wrong for a landscape photo or non-Letter paper. 2. **Cross-page zone sharing.** A single page with one-sided data (e.g. zero debit transactions, confirmed for real on HSBC's own page 1) makes its own column-clustering genuinely ambiguous — its lone value cluster can get assigned to the wrong field purely by which header word sits pixel-closer, a geometric coin-flip with no data on that page able to correct it (confirmed for real: this exact case resolved correctly in one test run and would plausibly resolve wrong in another — it is NOT reliably fixed when only one page exists, see below). `table_extract.py`'s own `carry_zones` only carries FORWARD; this instead resolves zones on every page first, keeps whichever page resolved the MOST complete shape (both credit and debit present), and applies that single zone definition across every page. Confirmed fixing a real case: HSBC page 1 (all credits) alone always mis-signed every amount as a negative debit; processed together with page 2 (which has real debits, resolves cleanly on its own), page 1's 7 transactions came back with correct positive amounts, deterministically, every time — verified through the actual running app, not just the extraction function in isolation. **Wired into `reconcile._run_ocr_only` as a per-page fallback, not document-level** — confirmed necessary for real: on an actual 2-page scan, Docling succeeded on page 1 but missed page 2's table entirely in the SAME conversion call; a document-level "did ANY page get rows" check would have silently kept page 2 empty (10 real transactions, including both debits, would have vanished with no error) since page 1 alone made the overall result non-empty. The fallback runs the whole document through `raw_ocr_extract` whenever any page comes back empty from Docling (so its cross-page zone-sharing can still use a good page), then only replaces the specific pages Docling actually failed — a page Docling got right is never second-guessed. `page_reports[].status` is `"ocr_only"` or `"ocr_raw_words"` per page so it's visible which engine produced which page. Verified end-to-end through the real running app on a genuine 2-page scanned test file (`docs/scanned_statement_2page.pdf`, built from real HSBC pages 1+2): 17/17 transactions, correct signs, correct balances; `date_sanity` correctly flagged the one real OCR date misread rather than hiding it. `measure.py` confirms zero regression on the existing text-PDF corpus. **Known, honest limitation, not glossed over:** the one-sided-data edge case above is only reliably fixed when a SECOND page with both debits and credits exists to borrow zones from. A genuine single-page photo upload with only one-sided data on it has no second page to borrow from — the geometric assignment stays a close call, and which way it resolves isn't guaranteed. New dependencies: `tesserocr`, `pypdfium2`, `pillow`, plus `tesseract-ocr`/ `libtesseract-dev`/`libleptonica-dev` at the OS level (Dockerfile) — `TESSDATA_PREFIX` must be set explicitly (`/usr/share/tesseract-ocr/5/tessdata`); tesserocr does not reliably auto-discover Debian's tessdata location on its own (confirmed for real: failed with "invalid tessdata path: ./" without it). ## Frontend / UI state (as of 2026-10-12) **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 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. This lives in `frontend/src/assets/main.css` now (moved verbatim in the Vue restructure — see Key decisions & lessons — not rewritten). 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) — implementation pointers reflect the Vue restructure; the behavior itself predates it and is unchanged: - The upload zone accepts `.pdf`, `.jpg`/`.jpeg`, and `.png` (added 2026-10-11 for OCR support — see "OCR / scanned statements" above). A PDF gets the browser's native viewer (its own zoom toolbar) in an iframe; an image gets its own dedicated zoomable/scrollable panel instead (added 2026-10-11, after the OCR support landed — an image in the same iframe has no viewer chrome at all, confirmed by testing it) — see `SourceDocumentPanel.vue`/`useImageZoom.js`: −/+/Fit controls, width-based zoom (not CSS `transform:scale`, so the panel's `overflow:auto` actually produces real scrollbars when zoomed in), opens at fit-width by default (the same first impression the PDF viewer's own `view=FitH` gives). - PDF/image ("Source Document") and Transactions sit side-by-side with a draggable resizer (`ResizablePanels.vue`, the handle styled as a vertical grip-knob), both wrapped in one sticky flex row so they scroll as one unit (not the source-doc column alone). - A Hide/Show toggle in the Transactions header (`TransactionsTable.vue`, driven by `uiStore.pdfColHidden`, labeled "Hide Source Doc"/"Show Source Doc") collapses the source-doc column so Transactions fills the row. - The Result card (`ResultCard.vue`) is collapsible: a chevron + "Result" heading on the left toggle the status banner/checks list (`uiStore.resultExpanded`); Download Excel stays on the right, always visible; every fresh extraction starts collapsed. - 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 the `statement_balance` check outcome is "pass". Deliberate, to reduce confusion about what's user-entered vs. auto-detected. One real asymmetry worth knowing if this is ever touched: the opening readout is a snapshot of the ORIGINAL extraction's own `opening_balance` (the backend never returns a new one on recheck, only status/checks change) while the closing readout recomputes live on every recheck — confirmed by reading the original vanilla-JS implementation closely before the Vue rewrite, and reproduced deliberately rather than "fixed" as an inconsistency (see `TransactionsTable.vue`'s own comment). - An explicit "Recheck Balance" button (`TransactionsTable.vue`) re-runs just the checks (via `/api/recheck`, no re-extraction) against whichever balance values are currently *effective* — `extractionStore.effectiveOpeningBalance`/`effectiveClosingBalance`: the typed input if non-blank, else that frozen original `opening_balance`/`closing_balance` from the initial extraction — so clearing a typed value and clicking Recheck restores the statement's own original figures, same check as the first run. Added so a user who forgot to type a balance before Extract can still run the full check afterward (typing alone was never wired to a recheck, same as the original vanilla-JS version — only a row Save or Download triggered one). Below the fields, an `error-note` surfaces the check's own `detail` text whenever the outcome isn't "pass": a leading "Balance doesn't match the statement — " prefix for "fail" (its own detail is just the raw math), no prefix for "not_available" (its detail — "No opening and/or closing balance available..." — already reads as a complete sentence) — both outcomes used to leave the readout silently grey with no explanation; "not_available"'s case was only noticed and fixed 2026-10-12, after "fail" already had it. On wide viewports the button is wrapped in `.recheck-wrap` with an invisible `.recheck-spacer` label above it mirroring `.fields label`'s own box (same font-size/margin-bottom) — this is what lines the button's top edge up with the balance inputs' own top edge rather than the row's labels, without a hardcoded pixel offset that would drift if the label style ever changes. The spacer is hidden at the 640px mobile breakpoint, where the button drops below the fields instead (see above). - Sort + filter/search on the transactions table (`TransactionsTable.vue` + `useTransactionFilters.js`, added 2026-10-12) — purely client-side display state, no backend involvement, same scope as `useImageZoom.js`. Each sortable header (Date, Description, Amount, Balance, Status) gets its own up/down arrow pair (`.sort-arrows`/`.sort-arrow`) rather than one toggle arrow, so both directions stay visible; the active column+direction turns blue. A second `` sits inside ``, directly beneath the header row (so it inherits the same `colgroup` widths via `table-layout:fixed`) — free-text filter inputs per column (Description's doubles as the search box), Status as an exact-match `