# 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. **Update 2026-10-31: this product now DOES optionally categorize transactions** - a deliberate, explicit scope expansion past the line below, not an oversight (see "Transaction categorization" under Key decisions & lessons for the full record). The original framing, kept here for history: this product used to deliberately not categorize transactions (bank description → accounting description) - it only structured the statement and proved the math, a narrower scope than the in-app `bank_statement_categorizer` tools that live inside `eib-processor`. Categorization here is still architecturally separate from extraction/checks - it's a user-maintained, project-scoped set of pattern→accounting-category rules applied entirely client-side to the transactions this app has already extracted and verified, shown as a second "Categorization" tab beside Transactions - not a second parsing pass, and the extraction pipeline itself was never touched. 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 (now superseded); 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 (R.1-R.5) complete as of 2026-10-13** (see "Review screen"/"R.2"/"R.3"/"R.4"/"R.5" under Key decisions & lessons) — R.1 (source-position capture + the pdf.js highlighting viewer), R.2 (plain-language flags + jump-to-flagged navigation), R.3 (the suggested-fix engine - debit/credit swap, transposed digits, OCR digit misread), R.4 (structural row edits - flip sign, insert, split, merge, delete, behind a "more actions" menu), and R.5 (edit log + acknowledge/accept workflow + an optional Excel "Edits" sheet) all shipped; "date format swapped" and a separate "bulk column fix" both investigated and found not to apply to this pipeline's own data shape (see R.3/R.4's own entries) | | 3 | Layout mapper (fingerprinting, versioning, drift detection) | **Pulled forward and in progress as of 2026-10-14** (see "Layout mapper" under Key decisions & lessons) - staged L.1-L.8, full spec scope (§6/§6.1/§9) plus a superuser-review promotion path beyond what's written. L.1 (a modular "layout quirks" tier for mechanical geometric oddities, ahead of the mapper itself) shipped - fixed a real new statement (an Equals Money account) whose header label wrapped across physical lines, plus two more real differences the same statement surfaced (a "$"-prefixed money format, an ISO-shaped date format). L.2 (fingerprinting + the forced-mapping backend contract, no UI/PocketBase yet) shipped - also surfaced and fixed a real gap (a forced mapping had no page-boundary concept, swallowing a cover page's own letterhead into the first transaction; fixed with a new `start_page` field). L.3 (the `layoutMappings`/`layoutMappingVersions` PocketBase schema + the auto-promotion hook) shipped - found and fixed a real rule gap during testing (an owner could self-promote their own mapping to "shared" via a plain update; PocketBase rules gate who can update, not which fields). L.4 (the frontend fingerprint-lookup orchestration, including a real, clickable confirm dialog in `ExtractorView.vue` - not deferred to L.6) shipped - found and fixed two real bugs in the near-match comparator while testing it against the spec's own documented example (per-line vs per-field label text; a 70% overlap threshold that was too strict for that very example, corrected to 50%). L.5 (multi-highlight `SourceDocumentPanel` + a new click-and-drag region tool, `useRegionDraw.js`) shipped. **L.6 (`ManualMappingView.vue`, the core deliverable) shipped** - the full save-once-apply-forever loop proven end to end against a real synthetic statement; also caught and fixed a real, consequential bug along the way (forced-mapping column zones were unpadded, so a word landing a fraction of a point past a raw boundary - or a human's own imprecise mouse drag - could silently exclude a whole transaction with no error). **L.7 (the Layouts page + drift detection) shipped** - found and fixed two MORE real bugs in the same "computed correctly this session, never actually persisted" category: `startPage` and a new `headerBottom` (the real header row text on the mapped page itself, not just whole pages before it) were both missing from what got saved, meaning every future auto-apply of a saved mapping would have silently corrupted data again. Drift detection now also wired into every recheck, not just the original extraction. **L.8 (the superuser review screen) shipped 2026-10-15 - completes the full L.1-L.8 plan.** **Follow-on "value-pattern mapping" (a narrower tier, not part of the original L.1-L.8 numbering) shipped 2026-10-31** - lets a user teach the extractor to CLEAN a raw value it can't parse (e.g. a currency-code wrapper no deterministic fallback recognizes yet) by correcting one example row, with no region-drawing at all; reuses the L.1-L.8 fingerprint/exact-match/near-match/versioning/sharing infrastructure outright. See its own two entries under Key decisions & lessons. | | 4 | ~~Multi-tenant practice/client accounts, Frappe data model~~ | **Dropped 2026-11-24, by explicit user decision - see "Phase 4 dropped" under Key decisions & lessons.** A `users` account stays the permanent unit of isolation; a bookkeeper handling several clients uses one account's own `projects` (already built, Stage B.1-B.3) to separate them, not a new tenant/practice entity. | | 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). As of the layout-mapper work's L.2 stage (2026-10-14), /api/process also catches LayoutMappingRequired ahead of the generic ValueError handler, returning HTTP 422 with {needs_mapping, fingerprint, fingerprintHash} — see "Layout mapper" under Key decisions & lessons. As of 2026-11-19, POST /api/export/qbo is a second export format alongside /export — same recheck-then-build shape, requires a `bank_account` field, returns a .qbo attachment via qbo_service.py instead of excel_service.py; see ".qbo export" under Key decisions & lessons (renamed/corrected from an earlier route of the same name ending in ".qfx" - see that entry for why). POST /api/export/xero-csv, same day, is a THIRD — reuses parse_export_request as-is (no extra required field, unlike qbo), returns a .csv via xero_csv_service.py; see "Xero export" under Key decisions & lessons for why it needs no bank-account field at all, unlike qbo. POST /api/export/csv, same day, is a FOURTH — also reuses parse_export_request as-is, returns a .csv via csv_service.py (a plain, generic transactions dump, distinct from xero-csv's own import-specific shape); see "Four export formats consolidated" under Key decisions & lessons 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). As of L.2, also owns LayoutMappingRequired (raised once tiers 1+2 both fail on every page) and run()'s own forced_mapping=None parameter, which bypasses auto-detection/layout_quirks entirely when a layout mapping is supplied checks_service.py — the checks (was checks.py, near-direct relocate) pipeline_service.py — composes extraction_service + checks_service (was pipeline.py); as of 2026-10-13 also calls suggested_fixes_service.suggest_fixes in both run() and recheck(), adding a `suggestions` list to their shared return shape (see below) suggested_fixes_service.py — NEW 2026-10-13, review screen R.3 — one-click suggested fixes for running_balance mismatches (debit/credit swap, transposed digits, OCR digit misread), tested by applying a candidate value to a COPY of the real transactions and re-running the real check_running_balance, not by re-deriving its own bridging/direction math — see "R.3" under Key decisions & lessons for the real bug this approach surfaced (a suggestion's fix-target row can differ from the row the UI shows flagged) and how it was fixed (`flag_index` alongside `index`) 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) qbo_service.py — NEW 2026-11-19 (renamed/corrected same day from an earlier qfx_service.py - see ".qbo export" under Key decisions & lessons for why) — builds a QuickBooks (Web Connect .qbo) export string entirely in memory, OFX 1.x SGML (not XML), same no-disk discipline as excel_service.py — reuses this pipeline's own existing `transactions` data, no new extraction logic; see ".qbo export" under Key decisions & lessons for the FITID/escaping design, the INTU.BID finding, and the real bugs this stage's own testing caught xero_csv_service.py — NEW 2026-11-19, same day as qbo_service.py — builds a Xero-compatible statement-import CSV (Date/Amount/ Payee/Description), using Python's stdlib csv module for safe quoting. Needs no bank-account input at all (Xero's own CSV import has no equivalent) and reuses this pipeline's own existing "DD Mon YYYY" date text unchanged - see "Xero export" under Key decisions & lessons for the research behind both of those design choices csv_service.py — NEW 2026-11-19, same day — a plain, generic transactions CSV (Date/Description/Amount/Balance/ Status/Check flags, matching excel_service.py's own Transactions sheet exactly, reusing that module's own _flagged_row_indexes() directly). Unlike xero_csv_service.py, writes EVERY transaction row regardless of a missing date/amount - a plain dump has no structural requirement to violate; see "Four export formats consolidated" under Key decisions & lessons /extraction — pure parsing/domain logic, no I/O: table_extract.py — the pdfplumber extractor. As of the layout-mapper work's L.1/L.2/L.6/L.7 stages (2026-10-14/15): calls layout_quirks.normalize() as a fallback when the plain single-line header detector finds nothing; _MONEY_RE accepts an optional leading "$"; normalize_date()/header_candidate_geometry() are new. As of 2026-10-30, money-shape detection is a standing fail-safe, not just _MONEY_RE's own exact format: _parse_money()/_money_value() fall back to recognizing ANY currency-wrapped amount (a currency-code prefix, any real Unicode currency symbol) via _MONEY_FALLBACK_CORE_RE + Unicode's "Sc" category, gated by _dominant_money_marker() (stashed as zones["_native_marker"]) so a one-off foreign-currency annotation elsewhere on the page can't be mistaken for this ledger's own money - see "A real new-statement bug..." under Key decisions & lessons for the real phantom-transaction regression this needed to guard against. As of 2026-11-16, _parse_money() also recognizes a parenthesized amount ("(25.00)") as negative, via a shared _split_sign() helper also used by _parse_money_with_patterns() - see "Parenthesized negative amounts recognized" under Key decisions & lessons for the real blank-extraction bug this fixed on a single-Amount-column statement. extract_pdf()/ extract_page() gained forced_zones/forced_sign_convention/ ignored_row_rules/date_format/start_page/ header_bottom params, all no-ops when omitted; each forced_zones range is padded by _FORCED_ZONE_PADDING=3pt before use (L.6 - a real bug this fixed: an unpadded zone boundary could silently exclude a word whose own reported x1 landed a fraction of a point past it); header_bottom (L.7 - excludes the real header row text on the forced mapping's own start page, which start_page alone can't, since it only skips whole pages) uses that same padding as a safety margin so it can never exclude the real first row — see "Layout mapper" under Key decisions & lessons layout_rules.py — shared column/balance keyword vocabulary. As of L.1, also owns the public match_line_fields/ resolve_header_matches (relocated from table_extract.py's own private versions, so layout_quirks.py can depend on this module alone) layout_quirks.py — NEW 2026-10-14 — modular, independently-addable fixes for mechanical layout oddities the keyword/ geometry detector can't see on its own; tried only after that detector has already failed, so it's a guaranteed no-op for every statement that already works layout_fingerprint.py — NEW 2026-10-14 — compute_fingerprint()/ fingerprint_hash(), only ever called once tier 1 AND tier 2 (layout_quirks) have both failed on every page (see extraction_service.py's own LayoutMappingRequired) 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. As of L.1, also shares table_extract.py's own layout_quirks fallback and normalize_date() via the same _find_zones() call both engines already use /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). As of the layout-mapper work's L.1 stage (2026-10-14), `_find_header_row`'s own line-to-fields resolution lives in `layout_rules.py` as public `match_line_fields`/`resolve_header_matches` (relocated from this module's own private `_line_field_matches`/`_resolve_header_matches` - a pure move, needed so the new `layout_quirks.py` can reuse it without a circular import); `_find_zones` now falls back to `layout_quirks.normalize()` whenever the plain single-line detector finds nothing, and returns the (possibly merged) `lines_by_top` as a third value so `extract_page()`'s own row loop sees the same merge. `_MONEY_RE` accepts an optional leading `"$"` (stripped in `_classify_money` alongside the existing comma-stripping); a new `_normalize_date_text()` recognizes an unambiguous `YYYY/MM/DD`/`YYYY-MM-DD` date and converts it to the canonical "DD Mon YYYY" shape every downstream consumer expects - both fixed alongside the quirks module itself, see "Layout mapper" under Key decisions & lessons for the real statement that surfaced all three gaps and the full verification record. - `backend/services/extraction/layout_quirks.py` (NEW 2026-10-14) — modular, independently-addable fixes for mechanical layout oddities the keyword/geometry detector can't see on its own (e.g. a header label wrapped across physical lines) - tried only after that detector has already failed, so it's a guaranteed no-op for every statement that already works. Deliberately NOT the same thing as the layout mapper (stored, fingerprinted mappings + a manual mapping UI, not started yet) - a quirk is a deterministic rule a developer can write for a pattern with no human judgment involved; see "Layout mapper" under Key decisions & lessons. - `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. As of the manual "Map" button (2026-11-14), `run()` also computes `fingerprint`/`fingerprintHash` unconditionally on a SUCCESSFUL extraction (not just the two failure paths, which already did) — so the frontend can open the manual mapping screen against an already-successful extraction to CORRECT it, not just an outright-failed one; see that entry under Key decisions & lessons. As of manual layout mapping for OCR sources (also 2026-11-14), `_run_ocr_only(file_path, docling_url, forced_mapping=None)` gained that same `forced_mapping` parameter — when it carries a `columnMap`, Docling's own table-structure call is skipped entirely and the request routes straight to `raw_ocr_extract.py`'s new forced-zone support, and the fingerprint computed on every path (including now the OCR auto-detect failure path, via `LayoutMappingRequired`) is no longer hardcoded `None`/`None` — it's a real fingerprint from the new `_ocr_header_candidate_geometry`/`_ocr_fingerprint` helpers. See "Manual layout mapping for OCR-sourced statements" under Key decisions & lessons. - `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. As of review screen R.5 (2026-10-14), also writes an optional "Edits" sheet (`_write_edits_sheet`) whenever the export request carries a non-empty `edit_log` - see that entry under Key decisions & lessons. As of transaction categorization (2026-10-31), also writes an optional "Categorized Summary" sheet (`_write_categorized_summary_sheet`) whenever the export request carries a `categorization` object - built entirely client-side (`useCategorization.js`), this backend never computes or even understands a categorization rule itself, just renders whatever plain `{matched, unmatched}` structure it's handed - see "Transaction categorization" under Key decisions & lessons. - `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. As of manual layout mapping for OCR sources (2026-11-14), `extract_pdf`/ `extract_image` also accept the same `forced_zones`/`forced_sign_convention`/ `ignored_row_rules`/`date_format`/`header_bottom`/`value_patterns` parameters `table_extract.extract_pdf` does (plus `start_page` on `extract_pdf` only - a bare image has no multi-page concept), and a new `header_candidate_geometry(file_path, is_image)` - the OCR-side equivalent of `table_extract.header_candidate_geometry()` - computes a real fingerprint from OCR'd words. See "Manual layout mapping for OCR-sourced statements" under Key decisions & lessons for the full record, including a real bug this stage's own testing caught (`extract_image` was initially missing `header_bottom` entirely). As of 2026-11-16, `_extract_words()` also upscales a low-resolution image to `_MIN_OCR_WIDTH_PX=1600px` before running tesserocr (never downscales an already- adequate one) - a real reported "Preview returns blank" statement turned out to be a 480x800px phone photo tesserocr could barely read at all at its native size; see "Two real bugs found investigating a specific real-world statement report" under Key decisions & lessons. - `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). As of layout mapper L.8 (2026-10-15), checked FIRST, ahead of the auth gate: any route starting with `/admin` renders its own `` directly, bypassing LoginView/authStore/the whole shell entirely - a PocketBase superuser is never a `users` record, so `/admin/layouts` (AdminLayoutReviewView.vue) has no relationship to the app's own login at all. /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 — kept as a real router per the standards doc's structure. Four routes as of the layout mapper work: '/' -> ExtractorView, '/map-layout' -> ManualMappingView (L.6), '/layouts' -> LayoutsView (L.7), '/admin/layouts' -> AdminLayoutReviewView (L.8 - rendered by App.vue OUTSIDE the normal authStore-gated shell entirely, see below) /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. `applyCheckResults` also sets `suggestions` as of R.3 (not just `status`/`checks`), re-applied on every recheck so a stale one a manual edit already resolved disappears on its own. `flipTransactionSign`/`deleteTransaction`/ `insertTransactionAfter(index, template?)`/`mergeWithNext` (NEW 2026-10-13, review screen R.4 - see that entry under Key decisions & lessons for the full record, including why there's no separate `splitTransaction` action). `appendEditLogEntry`/`acknowledgeFlag`/`unacknowledgeFlag`/ `flagAcknowledged`/`allFlagsAcknowledged`/`acceptDocument` (NEW 2026-10-14, review screen R.5 - see that entry under Key decisions & lessons; `editLog`/`acknowledgedFlags`/ `accepted`/`acceptedAt` all live directly on `doc.result`, no new PocketBase migration needed). `addPendingMappingDocument`/`replacePendingMappingDocument`/ `removePendingMappingDocument` (NEW 2026-11-15, per-document mapping queue for batch uploads) - a document entry's own `pendingMapping` field (`{file, fingerprint, fingerprintHash, needsValueConfirmation, candidateRow, fieldOrder}` or `null`) is now where "this statement still needs manual mapping" lives, not layoutMapperStore's old single pending-file slot - see that entry under Key decisions & lessons for the real bug this fixes (a second needs-mapping file in the same batch used to silently overwrite and lose the first's pending state). 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. `highlightRequest`/`requestHighlight()`/ `clearHighlightRequest()` (NEW 2026-10-13, review screen R.2) - the bridge between `TransactionRow`'s "Show on source" and `SourceDocumentPanel`'s exposed `showHighlight()`, siblings three levels apart with no direct prop/event path between them - see "R.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. layoutMapperStore.js (NEW 2026-10-14, layout mapper L.6) — holds the ONE statement currently waiting on manual mapping (`pendingFile`/`pendingFingerprint`/ `pendingFingerprintHash`) - a real `File` can't survive a router navigation on its own, so this is the bridge between `useBatchExtraction.js` (sets it on a `no_match` result) and `ManualMappingView.vue` (reads/clears it). As of value-pattern mapping (2026-10-31), also holds `pendingCandidateRow`/`pendingFieldOrder` (set by the new `setPendingValueConfirmation()`, sibling to `setPending` - never both at once) for the narrower needs_value_confirmation case - see CLAUDE.md's own "Value-pattern mapping" entries under Key decisions & lessons. As of the manual "Map" button (2026-11-14), also holds `pendingDocumentId` - null for the normal auto- triggered flow, set when the mapper was launched manually (TransactionsTable.vue) to CORRECT an already- loaded document instead of mapping a freshly-failed one - see that entry under Key decisions & lessons for why `ManualMappingView.vue`'s own Save needs to tell the two apart. As of the per-document mapping queue (2026-11-15), no longer holds "which statements still need mapping" at all - that moved to extractionStore's own `pendingMapping` field on each placeholder document (a real reported bug fix: this store's old single-slot design silently lost every needs-mapping file in a batch except whichever one happened to be here last). This store is now purely the short-lived bridge across ONE /map-layout navigation - gained a `pendingDocKey` alongside `pendingDocumentId`, set when the mapper was launched from a queued placeholder rather than either of the other two cases, so Save knows to replace that placeholder's own queue slot - see "Per- document mapping queue for batch uploads" under Key decisions & lessons. usageStore.js (NEW 2026-11-16, billing/usage-tracking foundation — `pagesThisPeriod`/`loadUsage()`/ `recordExtraction()`, the live counter `AppHeader.vue`'s own badge reads; "this period" is currently just the calendar month, an explicit placeholder until a real subscription/plan record exists to anchor the user's own described pause/resume billing cycle against instead — see "Usage tracking foundation" under Key decisions & lessons). /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`), pocketbaseAdminRepository.js (NEW 2026-10-14, layout mapper L.4 — a SECOND, separate PocketBase client instance used only for a real PocketBase superuser session; never shares `pb.authStore` with the logged-in app user's own client) /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). flagCatalogService.js (NEW 2026-10-13, review screen R.2 - translates each check's raw mismatch/issue data into the spec's four-part plain-language flag; only running_balance/date_sanity/structure_sanity/ narrative_direction ever carry row-level data, see "R.2" under Key decisions & lessons). 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. `savePendingMappingDocument` (NEW 2026-11-16) saves a needs-mapping/needs-value-confirmation placeholder - same multipart shape as `saveDocument`, just with no `result` and the new `needsMapping`/`pendingFingerprint`/etc fields instead - see "Persisted pending-mapping statements" under Key decisions & lessons). 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). layoutMappingsService.js (NEW 2026-10-14, layout mapper L.4 — `listMine`/`listSharedAndMine`/`findByFingerprintHash`/ `createMapping`/`createVersion`/`recordUsage`/`markStale`/ `retire`, plus the near-match comparator `scoreNearMatch`/`findBestMatch` — see "Layout mapper" under Key decisions & lessons for the two real bugs found testing it against the spec's own documented example; L.7 added `getMapping`/`updateMapping`/`listVersions`/ `rollbackToVersion`, and promoted `checksPassed` from a private `useBatchExtraction.js` helper to a shared export so drift detection has one definition, not three). adminLayoutsService.js (NEW 2026-10-14, extended 2026-10-15 for L.8 — the superuser's own `login`/ `logout`/`isLoggedIn`/`listPending`/`approve`, plus `getSourceDocument`/`sourceFileUrl` (L.8 - resolves a mapping's own sourceDocument/file through pbAdmin, since a superuser session never shares the app user's `pb` client); uses pbAdmin throughout, never `pb`. categorizationRulesService.js (NEW 2026-10-31, transaction categorization — `listForProject`/`createRule`/ `deleteRule`, project-scoped PocketBase CRUD; also exports the pure, non-PocketBase `matchDescription(description, rules)` in the same file, alongside the CRUD — same precedent `layoutMappingsService.js` sets with `scoreNearMatch`/`findBestMatch`. Case-insensitive substring match, longest matching pattern wins when more than one rule matches — see "Transaction categorization" under Key decisions & lessons for the full design). usageService.js (NEW 2026-11-16, billing/usage-tracking foundation — `recordUsage`/`getPagesSince`, thin PocketBase wrappers over the new `usageEvents` collection; see "Usage tracking foundation" under Key decisions & lessons for a real date-filter bug this stage's own testing found and fixed in `getPagesSince`). bankAccountProfilesService.js (NEW 2026-11-19, QBO export foundation — `listForProject`/ `createProfile`/`deleteProfile`, same thin-wrapper shape as categorizationRulesService.js, over the new bankAccountProfiles collection; see "QBO export" under Key decisions & lessons). extractionService.js itself gained `exportQbo(result, openingBalance, closingBalance, bankAccount)` the same day — mirrors `exportWorkbook` exactly, routes to a new `/api/export/qbo` backend endpoint instead. Also gained `exportXeroCsv(result, openingBalance, closingBalance)` the same day, no bankAccount parameter — routes to `/api/export/xero-csv`; see "Xero export" under Key decisions & lessons for why this one needs no bank- account input at all, unlike exportQbo. Also gained `exportCsv(result, openingBalance, closingBalance)` the same day — a plain, generic CSV (distinct from exportXeroCsv's own import-specific shape), routes to `/api/export/csv`; reused inside TransactionsTable.vue's own new `DOWNLOAD_FORMATS` lookup alongside `exportWorkbook`, see "Four export formats consolidated" under Key decisions & lessons. /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. As of 2026-11-16, also probes each staged IMAGE's own real resolution (`lowResolutionWarnings`, fired-not-awaited so staging itself stays synchronous) and flags one below `LOW_RESOLUTION_WIDTH_PX` - the same threshold `raw_ocr_extract._MIN_OCR_WIDTH_PX` uses server-side to decide whether to upscale before OCR, kept deliberately in sync - see "Low-resolution image upload warning" under Key decisions & lessons), 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`; as of layout mapper L.4 takes an optional `confirmMappingFn` param, passed straight through to useLayoutMapping below, and reacts to a `needs_mapping: true` response by resolving a mapping and retrying before giving up; as of value-pattern mapping (2026-10-31) also reacts to the narrower `needs_value_confirmation: true` the same way, differing only in what it does on `reason: 'no_match'` - `layoutMapperStore.setPendingValueConfirmation()` instead of `setPending()`), useLayoutMapping (NEW 2026-10-14 — `resolveNeedsMapping()`, the layout mapper's own client-side exact/near-match orchestration; see "Layout mapper" under Key decisions & lessons - `forcedMappingFor()` gained a `valuePatterns` key 2026-10-31, reused as-is for the new trigger since this function is already agnostic to WHY a fingerprint needed resolving), 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; as of layout-mapper L.5 (2026-10-14) also exposes a public `zoom` ref and a parallel `highlights`/`showHighlights`/`clearHighlights` for several labeled boxes at once, independent of the single highlight above), 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; gained the same public `zoom`/`highlights`/`showHighlights`/ `clearHighlights` as useImageZoom above, L.5), useRegionDraw (NEW 2026-10-14, layout mapper L.5 — the click-and-drag-to-define-a-region interaction the manual mapping screen, L.6, will use; owned by SourceDocumentPanel.vue via a new `regionDrawMode` prop, a no-op everywhere today), useCategorization (NEW 2026-10-31, transaction categorization — groups the active document's own already-extracted `transactions` against the active DOCUMENT's own `project` field's categorizationRules (deliberately NOT `projectsStore.activeProjectId` - the sidebar's "All" filter can be active while a specific document, which still belongs to exactly one project, is open). Recomputed live from whatever rules exist right now, never persisted on the document itself. Exposes `rules`/`matched`/`unmatched`/`summaryForExport` (the exact shape `excel_service.py`'s `_write_categorized_summary_sheet` expects) plus `addRule`/`removeRule`, both re-bucketing immediately with no refetch - see "Transaction categorization" under Key decisions & lessons), useBankAccountProfiles (NEW 2026-11-19, QBO export foundation — same loading shape as useCategorization's own rules-half, scoped to the active document's own project; `profiles`/`addProfile`, no transaction-matching equivalent since a bank account profile isn't matched against anything - see "QBO export" under Key decisions & lessons) /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 `