# 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 **in progress, staged R.1-R.5** (see "Review screen" under Key decisions & lessons) — R.1's backend half (per-row source-position capture) shipped 2026-10-13; the pdf.js highlighting viewer, R.2's plain-language flags, and R.3's suggested-fix engine are not started yet | | 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 read from env once at import time; repositories import this directly rather than reaching into Flask's current_app (OUTPUT_FOLDER removed 2026-10-13 — see below, nothing writes generated Excel files to disk anymore) measure.py — the measurement harness (see below), relocated /routes extraction.py — Blueprint: POST /api/process, /recheck, /export — request in, call a service, response out, no business logic. GET /api/download/ removed 2026-10-13 (was dead — nothing ever called it, see below) 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 entirely in memory — never touches disk itself (the *building* half of the old excel_export.py; the *saving* half used to be file_repository.save_workbook, removed 2026-10-13 — /api/export now streams straight from an in-memory buffer, see below) /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 (was main.py's ad hoc f.save/os.remove calls). Used to also save a workbook to disk and resolve an output path for /api/download — both removed 2026-10-13, see below; this is now upload-only. /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. As of the review-screen R.1 work (2026-10-13), also emits each transaction's own `source_page`/`source_bbox` - a shared `_line_bbox()` helper (reused by `raw_ocr_extract.py` too) and a `_union_bbox()` that grows a transaction's box as narrative lines merge into it; purely additive, read by nothing in this module's own classification logic, `None` for a row with no real position data (see "Review screen" under Key decisions & lessons for the full record and the real visual verification this got). - `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` — Transactions + Summary sheet export, built entirely in memory. No disk-write repository boundary anymore (there used to be one, `file_repository.save_workbook` — removed 2026-10-13 along with /api/process's own dead workbook generation and the never-called /api/download/ route; see "Excel exports moved to R2" under Key decisions & lessons for the full story). The frontend is what persists an export long-term now (`documentsService.saveExportFile`, PocketBase/R2), not this backend at all. - `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'); imports @fortawesome/fontawesome-free's all.min.css once here (an npm dependency, not a CDN link - keeps the Docker build offline-reproducible) ahead of main.css App.vue — the auth gate, then the full app shell: AppHeader + ProjectSidebar + routed view + AppFooter (see "Enterprise app-shell redesign" under Key decisions & lessons - modeled on docs/sample_ui.png, same enterprise-light theme) /assets/main.css — started as the original CSS moved verbatim; grown substantially since (table/sidebar/account-bar/app-shell sections each added for their own stage - see Key decisions & lessons for which) /router/index.js — one route today ('/' -> ExtractorView), kept as a real router per the standards doc's structure /stores (Pinia) extractionStore.js — a LIST of documents (`documents`, each `{pbId, docKey, fileName, project, previewUrl, isImage, result, flaggedIndexes, openingBalanceInput, closingBalanceInput}`) + `activeIndex`, not a single document - see "Multi-document upload, sequential extraction..." and "PocketBase Stage B.2/B.3" under Key decisions & lessons for the full restructure record. `pbId` is the PocketBase record id (set from `saveDocument`'s create response or a listed record's own `id`) and `project` is that record's project id - both added once persistence moved to PocketBase. `currentResult`/`currentDocKey`/`flaggedIndexes`/ `effectiveOpeningBalance`/`effectiveClosingBalance` are GETTERS derived from `activeDocument` (`documents[activeIndex]`), keeping their exact pre-restructure names so most consuming components needed zero changes. `errorMessage` stays the one shared error area across upload/process/download, same as before. `pendingOpeningBalance`/`pendingClosingBalance` hold typed balance text BEFORE any document exists yet (nothing to attach it to); `openingBalanceInputDisplay`/ `closingBalanceInputDisplay` getters and `setOpeningBalanceInput`/`setClosingBalanceInput` actions route to the right one automatically. `isBatchProcessing`/ `batchTotal`/`batchCurrentIndex`/`batchCurrentFileName` drive the "Extracting 2/4" progress text AND gate ResultCard's Download All button - store state, not a composable-local ref, specifically so a sibling component can react to it without prop-drilling. `setActiveDocumentProject(projectId)` (added for Stage B.3) updates just the active document entry's `project` field locally after a successful "Move to project" call, rather than reloading the whole list. `setActiveDocumentFileName`/ `removeDocument(pbId)` (NEW 2026-10-13, for DocumentNavBar's rename/delete) - `removeDocument` also re-settles `activeIndex` to keep pointing at the right document after a splice, see "Document delete/rename..." under Key decisions & lessons for the exact rules. uiStore.js — `resultsOpen`/`toggleResultsOpen()`/`closeResultsOpen()` (renamed from `resultExpanded`/`toggleResultExpanded` - 2026-10-13, now drives TransactionsTable's own Results dropdown, kept in the store rather than a component-local ref so useBatchExtraction.js can still reset it closed after every fresh extraction), pdfColHidden, pdfColWidthPct, 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), `sidebarHidden`/`toggleSidebar()` (added for Stage B.3's `ProjectSidebar`, same collapse pattern as `pdfColHidden`). `restoreBannerVisible` etc. were removed along with `RestoreBanner.vue` in Stage B.2 - see "PocketBase Stage B.2" under Key decisions & lessons. authStore.js — `user` (mirrors `pb.authStore.record`), `isAuthenticated` getter, `syncWithAuthStore()` (registered once in `App.vue`'s `onMounted`, keeps the store in sync with the SDK's own `pb.authStore.onChange`). projectsStore.js — `projects`, `activeProjectId`. Actions wrap `projectsService` and keep the local list in sync with each mutation rather than re-fetching (`createProject` pushes, `renameProject` patches the matching entry's `name`, `deleteProject` filters it out and clears `activeProjectId` if it was the one removed). `documentsByProject` (NEW - per-project id, lazy-loaded) is the single shared cache behind `ProjectSidebar.vue`'s own document hierarchy - moved here from a component-local `reactive({})` specifically so `useBatchExtraction.js`/ `TransactionsTable.vue`'s "Move to project"/ `DocumentNavBar.vue`'s delete can all keep an already-expanded project's list live via `addDocumentToCache`/`removeDocumentFromCache`/ `moveDocumentInCache` (each a no-op if that project was never expanded) - see "Sidebar's per-project document list didn't update live" under Key decisions & lessons for the real bug this fixed and the full verification record. /repositories — raw HTTP/storage access only: extractionRepository.js (fetch calls to /api/process|recheck|export), localStorageRepository.js (kept for any future per-viewer preference; lost its one real caller when document persistence moved to PocketBase, see below), pocketbaseRepository.js (the one place the PocketBase JS SDK client is instantiated — `VITE_POCKETBASE_URL`, default `http://localhost:8090`) /services — extractionService.js (docKeyFor, effectiveBalance, process/recheck/export orchestration — its old localStorage-backed persist/restore/batch-key functions were removed outright in Stage B.2, replaced by documentsService.js below). formatService.js (fmtMoney/fmtNum/parseNum - escapeHtml dropped, redundant once Vue's own {{ }} auto-escapes). authService.js (login/ signup/loginWithGoogle/logout, thin wrappers over the PocketBase SDK — the SDK itself persists/restores the auth token). documentsService.js (`saveDocument`/ `updateDocument`/`listDocuments`/`deleteDocument`/ `saveExportFile`/`sourceFileUrl`/`moveToProject` — the real, authoritative document persistence layer now). projectsService.js (`getDefaultProject`/`listProjects`/ `createProject`/`renameProject`/`deleteProject` — see "PocketBase Stage B.2/B.3" under Key decisions & lessons for the delete-guard rules and the deliberate circular import with documentsService.js, confirmed safe at runtime). /composables — useFileUpload (pure staging concern only as of Stage B.3 — `chosenFiles` accumulate-not-replace with dedup, drag/drop handlers; no longer owns `loadDocuments`, moved out to useDocuments below), useDocuments (`loadDocuments(filter)` — fetches via `documentsService.listDocuments`, used by both `ExtractorView`'s initial load and `ProjectSidebar`'s per-project filtering), useBatchExtraction (runs a file list SEQUENTIALLY, one `/api/process` call at a time, each awaited before the next starts, then `documentsService.saveDocument`s the result into `projectsStore.activeProjectId`), useProcessingPhases (per-file, untouched by the batch work - the batch composable just prefixes its text with "Extracting N/M: filename —"), useRowEditing (saveEdit() now calls `documentsService.updateDocument`, best-effort), useImageZoom (gained `highlight`/`highlightStyle`/`showHighlight`/ `clearHighlight` 2026-10-13, for the review screen's row-highlighting on an image upload — reuses its own existing zoom math), useAutoGrow, useModalFocus (shared by every modal component below: focuses the overlay the instant it becomes visible, so Esc closes it immediately), usePdfViewer (NEW 2026-10-13 — pdf.js document loading, per-page canvas rendering, zoom, "scroll to page N and highlight bbox"; parallels useImageZoom's own shape — see "Review screen" under Key decisions & lessons for the full record) /components — AppHeader (sticky top bar — brand mark, active-project breadcrumb, account menu with email + sign out; added 2026-10-13, see "Enterprise app-shell redesign" under Key decisions & lessons), AppFooter (slim bottom bar, same entry), FileUploadZone (multi-select input), DocumentNavBar (the active document's filename — click to rename/delete it via DocumentOptionsModal below — plus prev/next; renders for ANY loaded document as of 2026-10-13, not just once there's more than one, so delete is reachable with just one document loaded), ProjectSidebar (the app's primary left nav as of 2026-10-13 — project list/select/create/rename/delete, a client-side project search box, filters the document list, collapses to an icon-only rail; each project also expands into its own lazy-loaded document hierarchy, open or delete a document straight from here), LoginView (Sign In/Sign Up toggle + "Continue with Google"), ConfirmModal (generic confirm/cancel dialog over a dimmed backdrop; `danger`/`busy` props added 2026-10-13 for the delete-document flow — red confirm button, stays open with a spinner mid-request), DocumentOptionsModal (NEW 2026-10-13 — inline rename + hands off to a second ConfirmModal for delete), DownloadChoiceModal (NEW 2026-10-13 — "current document" vs. "all N documents", replacing a separate always-visible Download All button), ProcessingIndicator, SourceDocumentPanel (PDF path renders via pdf.js/usePdfViewer as of 2026-10-13, not the browser's native `