# 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 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. - `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). /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, useAutoGrow, useModalFocus (NEW 2026-10-13 — shared by every modal component below: focuses the overlay the instant it becomes visible, so Esc closes it immediately) /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), 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, TransactionsTable (now also hosts its own top bar — a Results dropdown, DocumentNavBar, and the Download button; this is ResultCard.vue's old content, merged in and that file deleted outright, 2026-10-13 — see "Document delete/ rename..." under Key decisions & lessons — plus the "Move to project" select + its own ConfirmModal), TransactionRow, ResizablePanels. `RestoreBanner` was removed in Stage B.2 (see Key decisions & lessons) — PocketBase being the real backend left no ambiguity for it to explain. Every button/ nav icon site-wide uses FontAwesome solid icons (`@fortawesome/fontawesome-free`) in place of the original vanilla-JS build's unicode entities. /views/ExtractorView.vue — the extraction page itself: upload, result, document navigation, side-by-side review. No longer owns a page-level layout wrapper or ProjectSidebar (both moved up to App.vue's shell 2026-10-13 — ProjectSidebar is account-wide chrome, not specific to this one page). `App.vue` gates the whole shell behind `authStore.isAuthenticated`, showing `LoginView` otherwise. ``` **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. **PocketBase - a third real service, added 2026-10-13.** The "no DB" framing elsewhere in this file (Stage 1's own repository-layer judgment call, and the original Build scope status note) describes a decision this project later, deliberately revisited - not an oversight. Accounts, client projects, and processed-document records now live in PocketBase; see "PocketBase: accounts, R2-backed files, project sidebar" under Key decisions & lessons for the full reasoning (why PocketBase, why R2 for the original statement files, why every document is required to belong to a project from day one). ``` /pocketbase Dockerfile — no official PocketBase image exists; this is the minimal pattern from PocketBase's own docs (pinned binary download, data at /pb/pb_data) pb_migrations/1_create_collections.js — schema as code: users (auth, self-registration open), projects (owner-scoped), documents (owner- AND project-scoped, project REQUIRED not optional, a sourceFile field for the original PDF/image). Pure schema, no secrets — safe to commit. pb_migrations/2_add_timestamps.js — projects/documents came out of migration 1 with NO created/updated fields at all (confirmed for real, not assumed — a plain base collection doesn't get them automatically the way the users auth collection does). Adds autodate created/updated to both. pb_migrations/3_add_export_file.js — adds exportFile (type:"file") to documents - the generated Excel workbook, stored in R2 same as sourceFile, overwritten on every re-export rather than kept as a history (see "Excel exports moved to R2" under Key decisions & lessons). pb_hooks/ensure_default_project.pb.js — fires on every new users record (password signup and Google OAuth2 signup both create one the same way) and creates that user's "General" project (isDefault:true) — guarantees the required documents.project relation always has somewhere to point, even for a brand new account. configure-secrets.sh — the ONLY place R2/Google credentials are handled; reads them from a gitignored .env (see .env.example) and PATCHes PocketBase's own /api/settings (R2 as its S3 storage backend) and the users collection (Google OAuth2 provider). Never run from a migration — those are committed to git, secrets must not be. ``` Frontend talks to PocketBase directly (`frontend/src/repositories/pocketbaseRepository.js` — the one place the JS SDK is instantiated), not proxied through Flask — PocketBase's own intended usage pattern. `/api/process`/`/api/recheck`/`/api/export` keep going through Flask exactly as before; PocketBase is purely the persistence layer for accounts/projects/documents, not a replacement for the extraction pipeline. ## 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. **Multi-document upload, sequential extraction, prev/next navigation, and Download All, done 2026-10-13 (Stage 1 of 2 - client-project sidebar is Stage 2, not yet built).** Previously the app handled exactly one statement at a time end-to-end: one `currentResult` in `extractionStore`, one `chosenFile`/`currentPdfUrl` in `useFileUpload`, and the file `` had no `multiple` attribute at all (confirmed - even a multi-select silently kept only `files[0]`). `extractionStore` is now a LIST of documents + `activeIndex` (see the Architecture section's own entry above for the full shape); `useExtraction.js` was deleted outright, replaced by `useBatchExtraction.js`, which runs a chosen file list SEQUENTIALLY - one `/api/process` call at a time, each awaited before the next starts, a failed file logged and skipped rather than aborting the rest of the batch. No backend changes were needed anywhere - `/api/process`/`/api/recheck`/`/api/export` already each take exactly one file/document per call, which is exactly what "process one at a time" needs. Two decisions were revised after the user reviewed the plan before any code was written (Plan Mode caught these before they shipped, not after): - **Focus never moves on its own except to show the very first result.** The first draft auto-advanced `activeIndex` to every newly-finished document; the user correctly flagged this as disruptive if they're already reviewing or editing an earlier one mid-batch. `addDocument` now only sets `activeIndex` when the list was empty beforehand (there's nothing else to show yet) - every document after that is appended without touching which one is active; only prev/next (`DocumentNavBar.vue`, visible once there's more than one document) ever changes it from then on. - **Download All** (`ResultCard.vue`, beside the existing Download Excel button) - added per explicit request, shown only once `!isBatchProcessing && documents.length > 1` (matching "only when more than one file" and "when all docs have finished"). Loops every loaded document and triggers the same per-document export `handleDownload` already made, just N times in a row - not a zip bundle (would need a new backend endpoint + dependency for no real gain here). Some browsers prompt to allow multiple downloads from one click; a known, minor wrinkle, not worth a zip endpoint unless it turns out to actually bother someone in practice. **Two real bugs caught during a post-implementation review pass, before either was ever tested in a browser:** - `TransactionRow`s were keyed only by `entry.index` in the `v-for` (`:key="entry.index"`). Harmless for a single document, but with several documents now possibly sharing the same row INDEX, switching documents via prev/next while mid-edit on a row could have let Vue reuse the same component instance across two entirely different documents' data - `useRowEditing`'s own `draft` only loads once at setup, not reactively, so the reused instance would keep showing the OLD document's row content under the new document's own index. Fixed by keying on `` `${docKey}:${index}` `` instead, forcing a fresh component (and a fresh `loadDraft()`) every time the active document changes, not just when the index does. - `addDocument` called `recomputeFlags()`, which only ever targets `activeDocument`. With focus-stability now meaning a newly-added document often ISN'T the active one, that document's own `flaggedIndexes` would stay stuck at the empty `Set` it was initialized with, and nothing would ever recompute it later either - prev/next just changes `activeIndex`, it doesn't recompute anything. A document added while the user was looking at an earlier one would silently show NO flagged rows even with real check failures, until... never, there was no path that fixed it. Fixed by extracting the flag-computation logic into a plain `computeFlags(result)` function (not a store method bound to `activeDocument`), called directly in `addDocument` for whichever document was just pushed, regardless of whether it's the active one. Confirmed via the same direct-Pinia- execution technique as the rest of this stage's verification: added a document with a real flagged row while a DIFFERENT document stayed active, confirmed its `flaggedIndexes` was already correct before ever navigating to it. Also needed, easy to miss: `openingBalanceInput`/`closingBalanceInput` used to be flat store state, settable even before any document existed (so the balance fields are enterable before clicking Extract - a deliberately preserved, pre-existing behavior, see "Frontend / UI state" below). Once these moved onto each document, there was nowhere for that PRE-extraction typed text to live - `extractionStore.pendingOpeningBalance`/ `pendingClosingBalance` hold it until the first document is added, which seeds that document's own fields from it (so a later Recheck Balance doesn't start blank) and every later document in the same batch does too. `openingBalanceInputDisplay`/ `closingBalanceInputDisplay` getters pick pending-vs-per-document automatically so `TransactionsTable.vue`'s inputs don't need to know which case they're in. Known, accepted gap: staging a SECOND batch while earlier documents are still loaded won't route through the pending fields again, since the visible inputs are already showing the active document's own field by then - not something the current ask requires, not fixed. Restore-on-reload generalized from "last ONE document" to "last BATCH": `extractionService .lastDocKey()`/`LAST_DOC_KEY` became `lastBatchKeys()`/`LAST_BATCH_KEYS` (an array, appended to as each document in a batch completes), and `persistResult` now saves `{fileName, result}` instead of a bare result object, so a restored multi-document batch can show which file is which (`RestoreBanner`'s text, `DocumentNavBar`'s name) - with a backward-compatible fallback in `restoreResult` for anything saved under the old bare-result shape from before this change. One shared restore banner for the whole batch ("Restored N documents..."), not one per document; Discard removes every currently-loaded document's persisted copy (safe to use `extractionStore.documents` wholesale for this - the banner auto-hides the moment any NEW batch finishes, so it's only ever visible while the list still matches exactly what was restored) and clears the last-batch pointer, but - same as the single-document version's own behavior - does NOT clear the in-memory documents being viewed; "discard" means "don't keep this for next time," not "get rid of what I'm looking at right now." Verified: `npm run build`; every new/changed store action and getter executed directly against real Pinia with synthetic multi-document scenarios (focus-stability on `addDocument`, independent per-document balance fields and `applyCheckResults`/flag scoping, prev/next clamping, pending-vs-per-document fallback - not just read, actually run); the real Docker container rebuilt and hit with two sequential `/api/process` calls (HSBC-Sep then RBC) confirming identical results to the pre-change baseline; `measure.py` unaffected (no backend code touched). Interactive behavior (actual multi-file drag/drop, the prev/next buttons, Download All's browser download-permission prompt, localStorage restore across a real reload) still needs the user's own browser to confirm - same honest limitation as every other frontend change this session, Claude-in-Chrome has not connected. **PocketBase: accounts, R2-backed files, project sidebar - Stage B.1 done and fully verified, 2026-10-13 (B.2/B.3 not started - see below).** The client-project sidebar was originally planned as a localStorage-only feature (consistent with this app's "no DB" architecture). The user asked to reconsider and introduce PocketBase instead - explicitly flagged as a real scope jump from "single local user" territory, confirmed deliberately via `AskUserQuestion` rather than assumed. Grew further during plan review into two more specific asks, each changing the design: - **Original statement files (PDF/image) live in Cloudflare R2**, not the app server's own disk - "keep the VPS as app + database server mainly." Researched rather than assumed: PocketBase has NATIVE S3-compatible storage support (confirmed R2-compatible, endpoint `https://{account-id}.r2.cloudflarestorage.com`), configured instance-wide via `PATCH /api/settings`'s `s3` object. Chose this over the app managing R2 directly (which would mean either R2 credentials somewhere in the browser, or new presigned- upload routes in Flask) because PocketBase's own file API already gives per-user access control on the file for free, the same `owner = @request.auth.id` rule that already scopes everything else - app code never touches R2 directly, no AWS SDK anywhere in this repo. A `sourceFile` field on `documents` also closes a real, previously-accepted gap: the localStorage-only version could never restore a document's source-preview after a reload ("re-select the file to see it again") - with the real file in R2, a restored document's preview can actually work. - **Accounts are self-service - email/password signup AND "Sign in with Google"**, not admin-provisioned. `users.createRule = ""` (open) + `users.oauth2 = {enabled:true, providers:[{name:'google',...}]}`, the latter configured PER AUTH COLLECTION (not instance-wide) - confirmed via research before writing the migration, since guessing wrong here would've meant a setup that silently doesn't work. Email verification stays OFF (would need SMTP configured - another set of secrets, out of scope unless it actually becomes a problem). **One more pivot, mid-plan-review, from the user directly (not a Claude judgment call):** every document is scoped to a project - REQUIRED, not optional, overriding the first draft's "project is an optional filing afterthought." Reason given: a planned future categorization-mapper feature needs PER-PROJECT keyword→chart-of-accounts mappings (different clients map the same bank description differently), so every document needs to be scoped from day one or it's a messy retrofit later. Solved with a PocketBase HOOK (`pb_hooks/ensure_default_project.pb.js`, fires on every new `users` record - covers password AND Google signup uniformly, since both create a `users` record the same way) that auto-creates a `isDefault:true` "General" project the moment an account exists - new users always have somewhere for their first upload to land with zero setup, and can rename or reassign documents to a real client/project as they organize (see Architecture's own PocketBase entry above for the schema itself). **Secrets discipline, decided up front and held to:** R2 credentials and the Google OAuth2 client secret are real secrets - NEVER in a migration file (migrations are code, committed to git) and never sent to the browser. Both are handled exclusively by `pocketbase/configure-secrets.sh`, which reads from a gitignored `.env` (`.env` was NOT previously excluded - confirmed by reading `.gitignore` directly before adding it) and PATCHes PocketBase's own REST API. Migrations stay pure, committable schema. **What's actually been verified, as of this entry (Stage B.1 - schema/hooks/backend auth built and tested; B.2 document-persistence migration and B.3 sidebar UI not started yet):** - PocketBase built and run for real (not just the Dockerfile read) - `docker compose exec` needed a `WORKDIR /pb` fix in the Dockerfile the first pass didn't have (confirmed by the exec actually failing: `./pocketbase: no such file or directory`, since `exec` doesn't inherit the image's implicit CMD-relative path without an explicit WORKDIR). - The full migration + hook verified via REAL REST API calls against the running container, not just read: superuser auth works; `users`/`projects`/`documents` all exist with the expected fields; `users.createRule`/`oauth2.enabled` both confirmed set; password signup at the PUBLIC endpoint succeeds and immediately logs in; the hook fires for real - a freshly signed-up user's own `projects` list shows exactly one record, "General", `isDefault:true`; a SECOND signed-up user gets their OWN separate "General" (not sharing or seeing the first user's); creating a `documents` record with NO `project` field correctly FAILS validation ("Cannot be blank") - confirms the frontend genuinely must resolve and pass a project id itself, PocketBase does not silently default it; creating one WITH the resolved project id succeeds; a second user's token cannot list a first user's `documents` (0 results, not an error - PocketBase's `listRule` filters rather than denies, confirmed empirically rather than assumed from the rule string alone). - `authService.js`'s actual functions (not a re-implementation of them) exercised directly against the live container from a plain Node script: signup → immediately authenticated → the hook's project visible through the SDK → logout clears `authStore.isValid` → re-login restores it. `npm run build` passes with the new auth layer (`pocketbaseRepository.js`/`authService.js`/`authStore.js`/`LoginView.vue`/`App.vue`'s gate) wired in. - **Real R2/Google credentials added 2026-10-13, `configure-secrets.sh` run for real and fully verified**, not just assumed from the script exiting cleanly: `/api/settings` confirms `s3.enabled`/`bucket`/`endpoint` match the real R2 bucket; `/api/collections/ users` confirms `oauth2.enabled` + the `google` provider; `/api/collections/users/ auth-methods` (the exact endpoint the frontend SDK itself calls to build the OAuth2 flow) returns a real, well-formed Google authorization URL with the actual client_id embedded. Most importantly, an actual file was round-tripped through R2 end-to-end: created a `documents` record with a real multipart `sourceFile` upload, then fetched it back via PocketBase's own `/api/files/...` URL and confirmed the exact byte content came back - proves R2 storage genuinely works, not just that the PATCH to enable it succeeded. The one thing still unconfirmed is the live Google consent-screen round trip itself (needs a real browser clicking through Google's own UI, not curl) - everything on this repo's own side of that handshake is now verified correct. - **One real catch before any of the above ran:** the user had copied `.env.example` to `.env` and filled in real R2/Google values, but left `POCKETBASE_SUPERUSER_EMAIL`/ `_PASSWORD` as the literal placeholders (`admin@example.com`/`change-me-min-10-chars`) - caught by checking the password's actual value against the known placeholder string before running the superuser upsert, not assumed safe just because the field was "filled in." That account has full admin access to every user's data and the instance's own settings, so this was flagged and confirmed with the user before proceeding rather than silently upserting a well-known default credential. **PocketBase Stage B.2 - document persistence moved from localStorage to PocketBase, 2026-10-13 (B.3 sidebar UI still not started).** `extractionService.js`'s old localStorage-backed `persistResult`/`restoreResult`/`lastBatchKeys`/`appendToLastBatch`/ `startNewBatch`/`discardPersisted` are GONE, not kept alongside the new path - one source of truth. Replaced by two new services: `projectsService.js` (minimal for now - `getDefaultProject()`/`listProjects()`; B.3 adds create/rename/delete) and `documentsService.js` (`saveDocument`/`updateDocument`/`listDocuments`/`deleteDocument`/ `sourceFileUrl`). `extractionStore.js`'s document entries gained a `pbId` field (the PocketBase record id) - needed because a row edit now has to know WHICH record to PATCH; set from `saveDocument`'s own create response (fresh extraction) or a listed record's own `id` (restore). Deliberately NOT cached: `projectsService.getDefaultProject()` queries PocketBase fresh every call rather than caching the id in a module variable - a cache would leak across a logout/login within the same page session (user B getting user A's cached project id). This is a local PocketBase instance; the extra round trip is cheap, correctness wins. **`RestoreBanner.vue`/`uiStore`'s `restoreBannerVisible`/`restoreBannerText`/ `showRestoreBanner`/`hideRestoreBanner` deleted outright**, not repurposed - this followed through on what the Stage B.1 entry flagged as likely. The localStorage version's banner existed because loading saved data was ambiguous ("did a crash happen?"); now that PocketBase is the real, authoritative backend, there's no ambiguity left to explain - a logged-in user's documents just load, the same way any other app shows your own data. `useFileUpload.js`'s `restoreOnLoad()` was renamed `loadDocuments()` to match (fetches via `documentsService.listDocuments()`, newest first) and simplified from the plan's own "a watcher on authStore.isAuthenticated, not just onMount" - turned out unnecessary: `App.vue`'s auth gate means `ExtractorView` (where `onMounted(loadDocuments)` lives) literally cannot mount before `isAuthenticated` is true, whether that's a fresh login (the `
` branch mounts fresh the moment the gate flips) or a page reload while already logged in (the Pinia authStore is seeded synchronously from the SDK's own already-restored token before first render) - one mechanism covers both cases for free. **Two real bugs caught via the established discipline of executing the actual service code against the real running PocketBase, not just reading it or trusting a 200 from `saveDocument` alone:** - `documentsService.listDocuments()` passed `filter: ''` when there was nothing to filter by - PocketBase rejects an empty-string filter outright (a generic 400, not a helpful field-level error), it is NOT treated as "no filter." Fixed by omitting the `filter` key from the options object entirely when there's no project to filter by, rather than passing an empty string. - Even after that fix, `listDocuments()` still failed - traced to `sort: '-created'` referencing a field that simply didn't exist: `projects`/`documents` came out of migration 1 with no `created`/`updated` fields at all. Unlike the `users` auth collection (which has them built in), a plain base collection doesn't get them unless declared explicitly - confirmed by listing the collection's own fields via the REST API and seeing they were genuinely absent, not by guessing. Fixed with a SECOND migration (`2_add_timestamps.js`, not editing migration 1, which had already run) adding `{type:"autodate", name:"created", onCreate:true}` and `{..."updated", onCreate:true, onUpdate:true}` to both collections - the exact field shape copied from `users`' own `created`/`updated` fields via the REST API, not guessed from memory. **Verified end-to-end with the real, already-committed services** (not a re- implementation of their logic, the actual `documentsService.js`/`projectsService.js` files imported and run from a plain Node script against the live container): signup → `getDefaultProject()` resolves "General" → `saveDocument()` with a REAL `File` object as `sourceFile` → the created record's `project` matches the default → `listDocuments()` returns it → `sourceFileUrl()`'s URL, fetched for real, returns the exact original file bytes (not just that the create call succeeded) → `updateDocument()` (simulating a row edit) → re-`listDocuments()` confirms the change actually persisted, not just that the PATCH response echoed it back. `npm run build` passes. `measure.py` + both services' health checks unaffected (no backend Python or Docling code touched); R2/Google settings confirmed to survive the PocketBase container rebuild (named volume, not reset). **Excel exports moved to R2; a real dead-code/storage bug found and removed along the way, 2026-10-13.** The user's actual request was simple - store generated Excel exports in R2 too, "until we determine a data retention duration" (same VPS-storage concern that prompted moving source PDFs/images to R2 in Stage B.1/B.2). Investigating where exports were being written surfaced something worse than expected: **`/api/process` built and saved a full Excel workbook to disk on EVERY SINGLE extraction, and nothing in the frontend ever called `/api/download/` to retrieve it** (confirmed by grepping the entire frontend for any reference to that route - none existed). Every extraction was silently leaving a permanently-orphaned `.xlsx` file in `outputs/` for no reason at all. Checking the real local `outputs/` directory from this session's own testing found **91 orphaned files already accumulated** - concrete, not hypothetical, proof of the exact problem the user was worried about. This wasn't "move existing storage to R2," it was "most of this was pure waste that should never have been written anywhere." Fixed in two parts: 1. **Removed the dead work entirely**: `/api/process` no longer builds or saves a workbook at all (just returns the pipeline result + title). `/api/download/`, `file_repository.save_workbook`, `file_repository.resolve_output_path`, and the `OUTPUT_FOLDER` env var/volume/directory are all gone - nothing else referenced any of them (confirmed by grep before removing, not assumed). `outputs/` itself was deleted, including its 91 accumulated files and its `.gitkeep`/`.gitignore` entries. 2. **`/api/export`** (the ONLY path that was ever actually used - triggered deliberately by Download Excel/All) was rewritten to build the workbook into an in-memory `BytesIO` and `send_file` straight from that buffer - it never touches disk at all now, not even temporarily. The frontend is what persists the result long-term: `documentsService.saveExportFile(pbId, blob, fileName)` uploads the SAME `Blob` the browser download already used (Blobs are immutable/reusable - one fetch serves both, no second request) to a new `exportFile` field on the `documents` collection (`pb_migrations/3_add_export_file.js`), stored in R2 the same way `sourceFile` already is. Deliberately overwrites the previous export rather than keeping a history - a real retention policy (how long to keep exports, or anything else, at all) hasn't been decided yet, and keeping every past version would just relocate the exact unbounded- growth problem this was meant to solve from the VPS to R2 instead of fixing it. Persisting to R2 is best-effort from `ResultCard.vue`'s side - a failure there is reported but never blocks or undoes the browser download the user actually asked for. Verified for real, not assumed from the diff: `curl`'d `/api/process` and confirmed `filename` is gone from the response while `title` (still genuinely used) remains; `curl`'d `/api/export` and confirmed it still streams a valid, correctly-typed `.xlsx` with the right `Content-Disposition`; confirmed `/app/outputs` no longer exists inside the rebuilt container; confirmed hitting the old `/api/download/...` URL now falls through to the ordinary SPA catch-all (the same 200+index.html any other unmatched path already gets, not a leftover route in disguise - checked against a second, unrelated nonexistent path to be sure). Then ran the real `documentsService.saveExportFile` against the REAL `.xlsx` bytes `/api/export` had just produced (not a fake test file): uploaded it, fetched it back through the R2-backed URL, confirmed a byte-for-byte match: and confirmed a second export on the same document overwrites (`exportFile`'s own name changes) rather than creating a second document record. `measure.py` unaffected (the extraction pipeline itself untouched); `npm run build` passes. **Separately, a real explanation gap worth recording honestly:** earlier in this same conversation, "every processed document now saves directly to PocketBase" was accurate about the API/record-creation path but read as if the file BYTES land in PocketBase's own storage, which isn't what happens once R2 is configured - the user caught this and asked directly which statement was correct. Resolution: both were consistent with the same real behavior, just one used "PocketBase" loosely (the system/API as a whole, replacing localStorage) and the other precisely (the record/metadata lives in PocketBase's SQLite; the file bytes themselves are transparently redirected to R2, never touching PocketBase's own local disk). Worth remembering when describing this architecture again: say "the PocketBase *record*" vs. "the file bytes in R2" explicitly, rather than "stored in PocketBase" unqualified. **PocketBase Stage B.3 - the project sidebar UI, 2026-10-13. This closes out the three-stage PocketBase plan (B.1 auth, B.2 persistence, B.3 sidebar) in full.** `projectsService.js` extended with real CRUD - `createProject(name)`, `renameProject(id, name)`, `deleteProject(project)`. `deleteProject` enforces two guard rails as thrown errors, not silent no-ops: refuses the `isDefault:true` project (the required `documents.project` relation must always have somewhere to point), and refuses a non-empty project (checks `documentsService.listDocuments({project: project.id})` first, reporting the document count in the error) - a document is never orphaned by deleting its project out from under it. New `projectsStore.js` (Pinia) wraps the service and keeps `projects`/`activeProjectId` in sync locally after each mutation rather than re-fetching the whole list every time (`createProject` pushes, `renameProject` patches the matching entry's `name`, `deleteProject` filters it out and clears `activeProjectId` if it was the one removed). New `useDocuments.js` composable (`loadDocuments(filter)`) extracted from `useFileUpload.js`'s old `loadDocuments`, which has now been fully split back into a pure staging concern (file selection/drag-drop only) - `ExtractorView.vue` composes both separately. New `ProjectSidebar.vue`: an "All" entry plus one per project, click to filter (`loadDocuments({project: id})` or `{}` for All), double-click or a pencil icon to rename inline, an "x" to delete (hidden on the default project), a "+ New Project" input. Collapses to a slim strip via its own `uiStore.sidebarHidden`/`toggleSidebar` - unlike Hide Source Doc, there's no sibling component left standing to host the toggle when this one collapses, so it owns its own expand/collapse affordance (`project-sidebar-toggle`) rather than delegating it elsewhere. `ExtractorView.vue`'s template restructured into a `.page-layout` flex row (`ProjectSidebar` + a `.page-main` wrapper around everything that used to be the page's direct children) so the sidebar sits beside the whole page, not nested inside `ResizablePanels` with the source-doc/ transactions split. A "Move to project" `` previously used a bare `:value` bound straight to `extractionStore.activeDocument?.project`. Switching to a confirm-before-apply flow requires being able to REVERT the dropdown's own visible selection when the user cancels - but a plain `:value` binding can't do that reliably, because the browser already shows whichever option was clicked the instant the user picks it, and Vue only re-syncs a `` populated from whatever statuses are actually present (never offers one the statement doesn't have), and a small × button in the corner cell to clear every filter at once (only rendered while a filter is active). Filtering to zero rows shows a "No transactions match the current filters" row instead of an empty table. **The one thing that had to be gotten right:** `TransactionRow`/`useRowEditing` read and write `currentResult.transactions` by its own ORIGINAL index, not by position in whatever's currently displayed — so `visibleRows` is a list of `{index, transaction}` pairs (original index preserved through both the filter and the sort), never a plain re-ordered array, or editing/flagging would silently target the wrong row the moment a sort or filter was active. Confirmed correct by executing the real composable directly (not just reading it): sorted/filtered a 3-row fixture several ways and checked the original index stayed attached to the right transaction through every case. Both the header row and the filter row stay pinned while the table body scrolls (`.txn-col table thead tr:first-child th`/`thead tr.filter-row th`, each `position: sticky`) — these used to be ONE rule matching every `thead th` with `top:0`, which made both rows stick to the exact same position at once; the filter row (later in the DOM, painted on top) visually covered the header row the moment the table scrolled, which read as "the header disappears on scroll, the filter row stays" (reported 2026-10-12) rather than what it actually was - a stacking collision, not a missing sticky rule. Fixed by giving the header row an explicit height (`34px`) and offsetting the filter row's own `top` by that same value, so they stack instead of overlapping. - Per-row edit lock (`TransactionRow.vue`/`useRowEditing.js`): cells are read-only until that row's pencil icon is clicked (pencil rendered in the blue accent color, fixed 2026-10-11 — it was the default muted gray, inconsistent with the Save button's own blue); a per-row Save commits the edit and triggers a recheck; Cancel discards. The description textarea's auto-height had a real bug, also fixed 2026-10-11: hiding the Source Document panel widens the transactions column, which can change how description text wraps, but nothing re-measured the textarea height when that happened (only an actual edit/save did) — now `uiStore.layoutVersion` bumps on that toggle (and on a resize-drag ending) and every row's own textarea watches it to re-measure. - All numeric displays are comma-formatted (`formatService.js`'s `fmtMoney`/`fmtNum`). - Edits persist to PocketBase (`documentsService.js`'s `saveDocument`/`updateDocument` - as of 2026-10-13, replacing the earlier localStorage-only version entirely, not alongside it). Every document a logged-in user has ever processed loads automatically on page load/login (`useFileUpload.js`'s `loadDocuments()`, newest first) - there's no "restore banner"/"discard" step anymore (removed outright, not repurposed): the old banner existed because a localStorage cache's presence was ambiguous ("did a crash happen?"); PocketBase being the real backend means there's nothing ambiguous left to explain. A document's own source-preview now loads for real too (`sourceFileUrl`, backed by R2) - the localStorage-only version could never do this at all ("re-select the file to see it again" was a permanent limitation, not just an edge case). - The Extract button shows simulated processing-phase text with an animated ellipsis while `/api/process` is in flight (`useProcessingPhases.js`/`ProcessingIndicator.vue`, added 2026-10-12) — honestly simulated, not real progress (the backend is one synchronous request with no streaming signal): cycles through an ordered, honestly-labeled phase sequence on a timer, holding on the last phase rather than looping if the real request runs long. ## Outstanding before Phase 1 can be called done - [x] Write `measure.py` (the harness from the plan's step 10) and actually run it. Lives at `backend/measure.py`, run as `python3 backend/measure.py` from the repo root (or inside the `app` container). Auto-discovers its corpus: every `fixtures/*.pdf` with a matching `_ground_truth.xlsx` sibling is measured for both of section 11's measures (untouched pass rate, field accuracy on date/description/amount/balance, position-matched); a fixture with no ground truth still gets an untouched-pass reading but is reported as "no ground truth" for field accuracy, never silently skipped. Writes a dated JSON report to `results/` (gitignored — each run produces a new file, not meant to be committed) and prints a console summary. Confirmed working against the real dual-engine pipeline (Docling + pdfplumber, not a fallback stub) as of 2026-10-11. - [x] Commit an RBC fixture + hand-derived ground truth — `fixtures/RBC-CAD-Aug26.pdf` (copied from `docs/RBC-CAD-Aug26.pdf`, which the user had placed there) plus `fixtures/RBC-CAD-Aug26_ground_truth.xlsx`, hand-verified by reading all 4 statement pages visually (via `pdftoppm`/poppler) against the extractor's own output — all 108 transactions, the opening balance ($66,857.70), and the closing balance ($90,569.13) matched exactly. One real extraction bug was caught in the process and became a permanent regression case, since-fixed (2026-10-12, see below): the last transaction on page 4 absorbed the page's trailing `Account Fees: $48.75` footer line into its own description. `fixtures/HSBC-USD-Sep2026_ground_truth.xlsx` was built and verified the same way (all 32 transactions visually confirmed page-by-page); HSBC's own opening/closing ground truth is `None`/`None`, matching `extract_statement_facts` — HSBC genuinely doesn't print these within the table (confirmed visually: the only balance figures on the statement are a "Closing ledger balance brought forward" and "Current ledger balance" dated 01–02 Oct, outside the Sep 1–30 statement period, not this statement's own opening/ closing). `fixtures/HSBC-USD-August2026_ground_truth.xlsx` was built 2026-10-12 (see below) the same way — all 31 transactions visually confirmed page-by-page, including the two blank-balance rows and the Cancelled wire around the `running_balance` flag (also `None`/`None` opening/closing, same reason as Sep). - [x] `git init` this repo — done 2026-10-11, initial commit `16f74f7`. - [x] Decide whether a `README.md` is wanted — yes; added 2026-10-12. Short: what the product is, `docker compose up`, project layout, `measure.py` usage, and a pointer to this file for the deeper architecture/decision record. Doesn't duplicate anything CLAUDE.md already covers in depth. - [x] `fixtures/ground_truth_sep_reference.xlsx` was discovered to be mismatched (a bank-description→accounting-category mapping from the separate `bank_statement_categorizer` tool, not this product's own extraction ground truth) and had nothing in this repo referencing it — deleted 2026-10-12 rather than repurposed, since this product deliberately doesn't categorize transactions at all (see "What this is" at the top of this file), so there was no use it could be put to here. - [x] The HSBC-Aug `running_balance`/`engine_agreement` and RBC `engine_agreement` issues `measure.py` surfaces — investigated 2026-10-12, not extraction bugs. HSBC-Aug's single `running_balance` mismatch is the Cancelled wire on page 3 (`-22,386.00`, no printed balance) doing exactly what "never silently correct or exclude data" requires: its amount genuinely doesn't apply to the real balance chain (it was cancelled), so the chain breaks by exactly that amount and the check correctly flags it rather than smoothing it over - confirmed by rendering all 4 pages and reading every row against the extracted output (see the new ground truth entry above), not just by eyeballing the mismatch in isolation; one other row on page 4 that looked like a second anomaly at a glance (a balance that drops by exactly the prior row's own $150,000 credit) turned out to be ordinary newest-first chain math checked out correctly by the automated check, not a second break. `engine_agreement` on both HSBC-Aug (Docling found no table on pages [1, 2, 4]) and RBC (page 4, the same column-mis-segmentation bug documented under "Docling spike finding"/the Architecture section's `docling_parser.py` note) is the architecture working as designed - Docling missed a table, pdfplumber's own result was used instead, correctly flagged `needs_review`/`fail` for lower cross-engine confidence rather than silently trusted. Nothing to fix in either case - these are real, correctly-surfaced statement/engine conditions, confirmed by building the missing ground truth (HSBC-Aug) and getting 1.0 field accuracy on it, same as the other two fixtures now that the RBC footer bug above is also fixed. Nothing else from the original Phase 1 step list (scaffold, Docling spike, extractor, reconciler, pipeline, checks, UI, Excel export) is outstanding — those are built. Phases 2–7 are deferred by design, not oversight; don't start on them without the user asking. ## Working across directories This repo is a sibling to `eib-processor/`, not nested inside it. If you're in a Claude Code session rooted in a different directory and need to touch files here, use `/add-dir ` (session-only) or add it to `permissions.additionalDirectories` in `~/.claude/settings.json` (persistent). The cleanest setup for sustained work on this project specifically is to run a Claude Code session rooted directly in this directory (`cd` here, then `claude`) — this file loads automatically when that session starts.