414 KiB
CLAUDE.md
This file provides guidance to Claude Code (claude.ai/code) when working with code in this repository.
What this is
Bettersight Statement Extractor — a standalone bookkeeping tool that turns a bank
statement PDF into clean, structured transaction rows, proves the arithmetic against
six automated checks, and exports to Excel. It's the first phase of a planned paid
product line ("Bettersight"), built as its own repo/container stack (sibling to, and
independent of, eib-processor/ — not a tool hosted inside that platform). See
UI_DESIGN_THEME.md for the Bettersight brand system and UI_DESIGN_THEME_ENTERPRISE.md
for this app's own light-theme override of it.
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 | 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 underfixtures/(HSBC-USD-Sep2026.pdf,HSBC-USD-August2026.pdf,ground_truth_sep_reference.xlsx) — no RBC fixture or ground-truth file has been committed, so that validation isn't currently reproducible from this repo alone; the RBC statement used for that work lives only wherever it was originally uploaded from. - Dual-engine cross-check (
app/reconcile.py), the six checks plus the 7th narrative-direction check (app/checks.py), the pipeline (app/pipeline.py), and Excel export (app/excel_export.py) are all built and wired through the live UI. - The minimal web UI (upload → table + status → download, per the plan's explicit "not the full review screen" scope decision) is built and has had extensive layout/theme polish — see "Frontend / UI state" below.
As of 2026-10-11, the measurement harness, RBC fixture, and git init from the gaps below are done — see "Outstanding before Phase 1 can be called done" for current detail. Kept here as the historical record of what this section originally found missing:
No— nowmeasure.pybackend/measure.py(moved there in the 2026-10-11 backend restructure; wasapp/measure.pywhen first written), run and verified against the real dual-engine pipeline.No RBC fixture/ground truth— nowfixtures/RBC-CAD-Aug26.pdf+..._ground_truth.xlsx, hand-verified.Not a git repository—git initdone, initial commit16f74f7.- No
README.md— still undecided.
Docling spike finding (why the extractor is dual-engine, not Docling-primary): a real
4-page HSBC statement was run through Docling requesting to_formats=[md, json]. Docling's
TableFormer model correctly recovered row/column structure on pages 1–3 (7, 10, 11
transaction rows — exact match to hand-verified ground truth) but completely failed to
recognize page 4 as a table at all, returning flat, unstructured positioned text instead.
Separately, on a page it did structure correctly, one cell quietly merged two distinct
values together ("Time" + "Balance" into one cell) — a silent mis-grouping, not a hard
failure, that wouldn't trip an error on its own. Docling's own self-reported table_score
came back None on this run, so it couldn't even be used as a confidence signal.
This is why reconcile.py runs both engines on every page, always (not Docling with
pdfplumber as an emergency-only fallback): agreement on count/dates/amounts → high
confidence, use Docling's structured result; Docling missed a table but pdfplumber found
one → use pdfplumber's result, flagged informationally; the two disagree → flagged for
review with specifics, never silently picked between — this subsumes and strengthens
two of the spec's own six checks (page coverage, totals) by using cross-engine
disagreement itself as the confidence signal, rather than trusting either engine's own
self-reported score.
Commands
docker compose up --build # start everything (app + Docling), foreground
docker compose up --build -d app # rebuild + restart just the Flask app after code changes
docker compose down # stop and remove both containers
- App: http://localhost:8091
- 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 devruns Vite's dev server (defaultlocalhost:5173) with real hot module reload, proxying/api/*tolocalhost:8091(seefrontend/vite.config.js) so it talks to the same running backend/Docling containers without any CORS setup. The Docker image itself always serves the builtfrontend/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; needsopenpyxl,pdfplumberon PATH/venv — the samerequirements.txtthe app itself uses) runs everyfixtures/*.pdfwith a matching*_ground_truth.xlsxthrough the real pipeline and reports untouched pass rate + field accuracy. Works with or without the Docling container up (degrades to pdfplumber-only per page if unreachable — same behavior as the live app).python3 -m py_compile <file>is still the fastest sanity check after editing a.pyfile that doesn't have fixture coverage.
Architecture
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/<filename> 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 <BANKACCTFROM>
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 bothextract_transactions()(the cross-check-only path) andocr_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 formattable_extract.extract_page()produces, sotable_extract.rows_to_transactions/extract_statement_factsrun 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 toapplication/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 correctimage/pngcontent-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 asaw_labelflag kept independent of whether that label's own text is empty); geometric vertical-proximity is the fallback when no label exists, with a confidence margin that flags genuinely ambiguous gaps (ambiguous_indices) rather than guessing silently. Also captures opening/closing balance values straight from in-table summary rows when the statement prints them (RBC-style), as a fallback under the user's own typed values. As of the review-screen R.1 work (2026-10-13), also emits each transaction's ownsource_page/source_bbox- a shared_line_bbox()helper (reused byraw_ocr_extract.pytoo) 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,Nonefor 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 inlayout_rules.pyas publicmatch_line_fields/resolve_header_matches(relocated from this module's own private_line_field_matches/_resolve_header_matches- a pure move, needed so the newlayout_quirks.pycan reuse it without a circular import);_find_zonesnow falls back tolayout_quirks.normalize()whenever the plain single-line detector finds nothing, and returns the (possibly merged)lines_by_topas a third value soextract_page()'s own row loop sees the same merge._MONEY_REaccepts an optional leading"$"(stripped in_classify_moneyalongside the existing comma-stripping); a new_normalize_date_text()recognizes an unambiguousYYYY/MM/DD/YYYY-MM-DDdate 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 toraw_ocr_extract.pyon 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 computesfingerprint/fingerprintHashunconditionally 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 sameforced_mappingparameter — when it carries acolumnMap, Docling's own table-structure call is skipped entirely and the request routes straight toraw_ocr_extract.py's new forced-zone support, and the fingerprint computed on every path (including now the OCR auto-detect failure path, viaLayoutMappingRequired) is no longer hardcodedNone/None— it's a real fingerprint from the new_ocr_header_candidate_geometry/_ocr_fingerprinthelpers. 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_balancealways computes and returnscalculated_closingwhenever an opening balance is known, independent of whether a closing balance is available, so the UI can show it even when the check itself is "not available." Running-balance and date-ordering checks try both directions and pick whichever has fewer violations, rather than assuming one.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-emptyedit_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 acategorizationobject - 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 forextraction_service._run_ocr_onlywhen 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 reusestable_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_imagealso accept the sameforced_zones/forced_sign_convention/ignored_row_rules/date_format/header_bottom/value_patternsparameterstable_extract.extract_pdfdoes (plusstart_pageonextract_pdfonly - a bare image has no multi-page concept), and a newheader_candidate_geometry(file_path, is_image)- the OCR-side equivalent oftable_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_imagewas initially missingheader_bottomentirely). As of 2026-11-16,_extract_words()also upscales a low-resolution image to_MIN_OCR_WIDTH_PX=1600pxbefore 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 fromfixtures/*.pdfwith a matching*_ground_truth.xlsxsibling (each ground-truth file is aTransactionssheet of date/status/description/amount/balance rows in the same canonical, newest-first order as pipeline output, plus aSummarysheet with opening_balance/closing_balance), runs each through the realpipeline_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-filetemplates/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.
One real bug caught and fixed during this restructure, server-side: the production/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 `<RouterView>` 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 `<iframe>` — see "Review screen" under Key decisions & lessons; exposes `showHighlight`/`clearHighlight` for the review screen, called via `ExtractorView.vue`'s own watch on `uiStore.highlightRequest` as of R.2), 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; as of transaction categorization (2026-10-31), its own `.txn-col-head` is a two-item Transactions/Categorization tab switch rather than a bare heading - see that entry under Key decisions & lessons; as of the manual "Map" button (2026-11-14), `.txn-actions-right` also has a "Map" button - re-fetches the active document's own sourceFile and launches `/map-layout` against it, to CORRECT an already-successful extraction that still got something wrong, not just the auto-triggered flow for a failed one - see that entry under Key decisions & lessons. QBO/Xero export support landed in `.txn-top-bar-right` the same day (2026-11-19) as their own separate buttons at first - see "QBO export"/"Xero export" under Key decisions & lessons for each format's own design - but a real reported UI problem (three download buttons crowding the row) meant they were consolidated, same day, into ONE "Download" trigger + chevron dropdown (QuickBooks/Xero/CSV/Excel, in that order) - see "Four export formats consolidated" under Key decisions & lessons for the full restructure, including the new generic CSV format and the generalization of Excel's own single/all download logic to also cover it), TransactionRow, ResizablePanels, CategorizationPanel (NEW 2026-10-31 - the Categorization tab's own body: a rules list + inline "add rule" form, a "Categorized" table grouped by accounting category, and an "Unmatched" section where each group of identically-described unmatched transactions gets its own inline "assign a category" control; takes a `useCategorization()` instance, instantiated once at TransactionsTable.vue's level, as a prop), BankAccountProfileModal (NEW 2026-11-19 - shown when a QBO download's own active document has no remembered bank account profile yet; picks an existing one or creates a new one inline - purely presentational, same "parent owns every PocketBase call" convention DocumentOptionsModal already established). TransactionRow gained its own exclude-from-export checkbox (NEW 2026-11-19, its own `.row-select` column, separate from `.row-actions`) - see "Per-transaction 'include in downloads' checkbox" under Key decisions & lessons; TransactionsTable.vue's own `resultForExport()` reads it at download time, plus a header "select/deselect all visible" checkbox. `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. As of layout mapper L.6 (2026-10-14), also shows a small banner (linking to /map-layout) while layoutMapperStore has a pending file. /views/ManualMappingView.vue — NEW 2026-10-14, layout mapper L.6 (the core deliverable of that whole plan) — routed at /map-layout. SourceDocumentPanel in regionDrawMode beside a field-role toolbar, date-format/sign-convention/ignored-row controls, a required Preview step, and Save Mapping - see "Layout mapper" under Key decisions & lessons for the full record, including the two real bugs this stage's own end-to-end testing caught (a stale-reference save-field bug, and a real forced-zone boundary-precision bug fixed in table_extract.py itself). As of value-pattern mapping (2026-10-31), has a SECOND mode (told apart purely by whether `layoutMapperStore.pendingCandidateRow` is set) - a "Confirm values" card replaces the region-drawing one: one row per field with the raw text as read and an editable correction, validated inline (`fieldError()`), with the derived `{stripPrefix?, stripSuffix?}` per field (`valuePatterns`) the only thing sent as `forcedMapping` - no `columnMap` at all, letting auto-detection resolve the rest. See "Value-pattern mapping" under Key decisions & lessons for the real sign-handling bug this needed (a second instance of the SAME bug already found and fixed on the backend the same day) and the `hasRequiredShape`→ `canPreview` gate-coverage fix caught during plan review. As of the manual "Map" button (2026-11-14), reachable WITHOUT a failed extraction at all - its own region- drawing UI/Preview/startPage/headerBottom inference needed zero changes; only `handleSaveMapping()` branches on a new `layoutMapperStore.pendingDocumentId` to UPDATE the existing document in place instead of creating a second, duplicate one - see that entry under Key decisions & lessons. As of 2026-11-16, a new `imagePointScale` converts every drawn region's own `columnMap`/`headerBottom` value from the image's natural pixel space into PDF points (a no-op for a PDF) before `forced_mapping` is sent - a real, systemic bug fix: every image-sourced mapping before this sent zones in the WRONG coordinate space entirely, since the backend's own OCR path scales word positions to points first. See "Two real bugs found investigating a specific real-world statement report" under Key decisions & lessons. /views/LayoutsView.vue — NEW 2026-10-15, layout mapper L.7 — routed at /layouts (linked from AppHeader.vue's own new nav item). List/ Inspect/Test/Version-history/Rollback/Retire for every mapping the user can see - see "Layout mapper" under Key decisions & lessons for the deliberate "no visual Edit" scope deviation and the two more real bugs (startPage/ headerBottom never being persisted) this stage's own end-to-end testing caught. As of value-pattern mapping (2026-10-31): its own separate `forcedMappingFor()` (used by "Test") gained `valuePatterns`; Inspect gained a `v-else` for a value-pattern-only mapping's empty `columnMap`, plus a "Value corrections" card showing `mapping.valuePatterns` itself. /views/AdminLayoutReviewView.vue — NEW 2026-10-15, layout mapper L.8 (the plan's final stage) — routed at /admin/layouts, rendered by App.vue OUTSIDE the normal authStore-gated shell entirely (no AppHeader/ProjectSidebar/AppFooter — a PocketBase superuser is never a `users` record). Its own tiny inline login form against `pbAdmin.collection('_superusers') .authWithPassword(...)`; once signed in, every `status = "private"` mapping across every owner (a real superuser session bypasses PocketBase's rules automatically), each expanding into a read-only SourceDocumentPanel with every columnMap field drawn as a labeled vertical strip (same Inspect pattern L.7's LayoutsView.vue already established) plus dateFormat/ signConvention/ignoredRowRules as plain text, and an Approve button (via ConfirmModal) that promotes straight to shared.Dockerfileservesfrontend/distfrom Flask via a catch-all route (@app.route("/<path:path>")) that serves a real static file if one exists at that path, else falls back toindex.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/<path:...>pattern. Fixed by settingstatic_folder=Noneand 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,/healthand/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_migrations/4_add_layout_mapper_schema.js
— NEW 2026-10-14, layout-mapper L.3 — creates
layoutMappings/layoutMappingVersions (see "Layout
mapper" under Key decisions & lessons for the full
field list/rules).
pb_migrations/5_add_layout_mapping_fields.js
— adds layoutMappingUsed/layoutMappingVersionUsed/
layoutApplied/layoutFingerprintHash to documents.
pb_migrations/6_fix_layout_mapping_update_rule.js
— tightens layoutMappings' updateRule to block an
owner from self-promoting their own mapping to
"shared" via a plain PATCH - a real gap found by
testing the live rule, not caught by review (see
"Layout mapper" under Key decisions & lessons).
pb_migrations/7_add_layout_mapping_start_page.js
— adds startPage to layoutMappings/
layoutMappingVersions - a real gap found while
building the Layouts page (L.7): startPage was
computed correctly each mapping session but never
actually persisted, so every future auto-apply
would have silently reset to page 1.
pb_migrations/8_add_layout_mapping_header_bottom.js
— adds headerBottom to layoutMappings/
layoutMappingVersions - a second real gap (L.7):
startPage alone only skips whole pages, not the
real header row text still on the start page
itself - see table_extract.py's own extract_pdf
docstring and "Layout mapper" under Key decisions
& lessons for the full story.
pb_migrations/9_add_layout_mapping_value_patterns.js
— NEW 2026-10-31 — adds valuePatterns (json,
optional) to layoutMappings/layoutMappingVersions -
the value-pattern mapping work's own per-field
cleanup rule, see "Value-pattern mapping" under Key
decisions & lessons.
pb_migrations/10_relax_layout_mapping_column_map_required.js
— NEW 2026-10-31 — relaxes columnMap from required
to optional on both collections - a value-pattern-
only mapping genuinely has no column positions to
store; confirmed empirically (not assumed) that
PocketBase's required:true rejects an empty JSON
object the same way it rejects a missing one.
pb_migrations/11_add_categorization_rules.js
— NEW 2026-10-31 — creates categorizationRules
(transaction categorization - see that entry under
Key decisions & lessons). Project-scoped (owner +
project relation, mirroring documents.project's own
shape) with no sharing/promotion concept at all,
unlike layoutMappings - a client's own chart-of-
accounts mapping has no cross-user "two independent
confirmations" scenario, so no hook is involved.
pb_migrations/12_add_pending_mapping_fields.js
— NEW 2026-11-16 — relaxes documents.result to
optional and adds needsMapping/needsValueConfirmation/
pendingFingerprint/pendingFingerprintHash/
pendingCandidateRow/pendingFieldOrder - lets a
statement still waiting on manual mapping survive a
page reload instead of only ever living in memory;
see "Persisted pending-mapping statements" under Key
decisions & lessons.
pb_migrations/13_add_usage_events.js
— NEW 2026-11-16 — creates usageEvents (billing/usage-
tracking foundation - see "Usage tracking foundation"
under Key decisions & lessons). Append-only/immutable
(owner can create but never update/delete their own
record) - one event per successfully delivered
extraction, carrying its own page count.
pb_migrations/14_add_bank_account_profiles.js
— NEW 2026-11-19 — creates bankAccountProfiles (QBO
export foundation - see "QBO export" under Key
decisions & lessons) and adds
documents.bankAccountProfile. Project-scoped, same
no-sharing pattern categorizationRules already
established - a bank account profile has no cross-
user confirmation scenario. `accountId` deliberately
not required/labeled as the real account number.
pb_hooks/promote_shared_layout_mapping.pb.js
— NEW 2026-10-14 — onRecordAfterCreateSuccess on
layoutMappings: promotes both records to "shared"
when a second, different owner creates a mapping
with the same fingerprintHash.
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 buildsucceeds;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 (
grepevery 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,/healthand/api/*untouched, dual-engine extraction returns identical results to the pre-restructure baseline,measure.pyunaffected (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.htmlwas 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
<input> 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
activeIndexto every newly-finished document; the user correctly flagged this as disruptive if they're already reviewing or editing an earlier one mid-batch.addDocumentnow only setsactiveIndexwhen 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 exporthandleDownloadalready 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:
TransactionRows were keyed only byentry.indexin thev-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 owndraftonly 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 freshloadDraft()) every time the active document changes, not just when the index does.addDocumentcalledrecomputeFlags(), which only ever targetsactiveDocument. With focus-stability now meaning a newly-added document often ISN'T the active one, that document's ownflaggedIndexeswould stay stuck at the emptySetit was initialized with, and nothing would ever recompute it later either - prev/next just changesactiveIndex, 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 plaincomputeFlags(result)function (not a store method bound toactiveDocument), called directly inaddDocumentfor 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 itsflaggedIndexeswas 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 viaPATCH /api/settings'ss3object. 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 sameowner = @request.auth.idrule that already scopes everything else - app code never touches R2 directly, no AWS SDK anywhere in this repo. AsourceFilefield ondocumentsalso 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 execneeded aWORKDIR /pbfix in the Dockerfile the first pass didn't have (confirmed by the exec actually failing:./pocketbase: no such file or directory, sinceexecdoesn'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/documentsall exist with the expected fields;users.createRule/oauth2.enabledboth confirmed set; password signup at the PUBLIC endpoint succeeds and immediately logs in; the hook fires for real - a freshly signed-up user's ownprojectslist 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 adocumentsrecord with NOprojectfield 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'sdocuments(0 results, not an error - PocketBase'slistRulefilters 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 clearsauthStore.isValid→ re-login restores it.npm run buildpasses 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.shrun for real and fully verified, not just assumed from the script exiting cleanly:/api/settingsconfirmss3.enabled/bucket/endpointmatch the real R2 bucket;/api/collections/ usersconfirmsoauth2.enabled+ thegoogleprovider;/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 adocumentsrecord with a real multipartsourceFileupload, 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.exampleto.envand filled in real R2/Google values, but leftPOCKETBASE_SUPERUSER_EMAIL/_PASSWORDas 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 <main> 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()passedfilter: ''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 thefilterkey 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 tosort: '-created'referencing a field that simply didn't exist:projects/documentscame out of migration 1 with nocreated/updatedfields at all. Unlike theusersauth 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 fromusers' owncreated/updatedfields 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/<filename> 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:
- Removed the dead work entirely:
/api/processno longer builds or saves a workbook at all (just returns the pipeline result + title)./api/download/<filename>,file_repository.save_workbook,file_repository.resolve_output_path, and theOUTPUT_FOLDERenv 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/.gitignoreentries. /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-memoryBytesIOandsend_filestraight 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 SAMEBlobthe browser download already used (Blobs are immutable/reusable - one fetch serves both, no second request) to a newexportFilefield on thedocumentscollection (pb_migrations/3_add_export_file.js), stored in R2 the same waysourceFilealready 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 fromResultCard.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" <select> was added to TransactionsTable.vue, right under
DocumentNavBar, independent of the nav bar's own >1 document visibility gate (moving
a single uploaded document to a different project is a valid action with just one
document loaded). Calls documentsService.moveToProject(pbId, projectId) then
extractionStore.setActiveDocumentProject(projectId) (a new store action, updates just
the active document entry's project field locally rather than reloading everything).
One real binding bug caught during implementation, before any build/test ran: the
select's :value was first written as result.project - but result is
extractionStore.currentResult, the raw backend extraction JSON (transactions/checks/
etc.), which has no project field at all; that lives on the store's own document-entry
wrapper, not the backend response. Fixed to extractionStore.activeDocument?.project
before ever running the app.
Verified at both the service and store layer against the real running stack (the
actual files, imported and executed from plain Node scripts via the same
custom-ESM-extension-loader technique used throughout this PocketBase work, not
reimplementations): signup, then listProjects()'s sort: '-isDefault,name' string
resolves without error, createProject/renameProject, saveDocument into an
explicit project, deleteProject throws on a non-empty project, deleteProject throws
on the default project, moveToProject reassigns a document, deleteProject then
succeeds once the project is empty, and listDocuments({project}) correctly filters,
including returning an empty array (not an error) for a project with zero matches.
Separately, the Pinia store layer itself (projectsStore/extractionStore, not just
the services underneath): loadProjects/createProject/renameProject/deleteProject
all keep the in-memory projects list and activeProjectId correctly in sync with each
mutation, and extractionStore.addDocument/setActiveDocumentProject correctly carry
and update a document's project field. All results correct across both passes.
measure.py re-run and unaffected (no backend Python touched this stage, same baseline
as before: HSBC-Sep "Needs review", HSBC-Aug/RBC "Failed" on their pre-existing,
documented issues, field accuracy 1.0 across all three). npm run build passes; the
app container was rebuilt and confirmed serving the new bundle (project-sidebar CSS/
JS present in the built frontend/dist inside the running container).
Not machine-verified, same honest limitation as every other frontend-only change in this project: the actual interactive sidebar UI - collapse/expand, inline rename via double-click, click-to-filter, the "Move to project" dropdown - was never driven through a real browser this session (Claude-in-Chrome never connected). Everything underneath the UI (services, stores, PocketBase's own authorization rules) is confirmed correct by direct execution; the UI wiring on top of it follows the same prop/emit-name cross-checking discipline as the original Vue restructure, but is unconfirmed by an actual click until the user tries it in their own browser.
Enterprise app-shell redesign (header/sidebar/footer) + FontAwesome icon pass,
2026-10-13. The user's own assessment of the Stage B.3 sidebar: "not impressive at
all" - pointed at docs/sample_ui.png (a Cloudflare R2 dashboard screenshot) as the
reference to model the shell on, keeping the existing enterprise-light color theme
(blue #2563EB accent, white cards) unchanged, and asked for FontAwesome icons on
buttons and sidebar navigation "so they look professional and enterprise" rather than
hand-drawn ones. This was a real structural change, not just a restyle: ProjectSidebar
moved from being a child of ExtractorView (page-specific) to a child of App.vue
(account-wide chrome, same level as the new header/footer) - reasoned the same way as
the header/footer themselves: which project is active isn't specific to the extraction
page, it's account-level navigation.
New shell, built in App.vue: AppHeader (sticky, full width - a brand mark, a
breadcrumb showing the active project, and an account menu with email + sign out,
replacing the old plain .account-bar) + a body row (ProjectSidebar + .app-content
holding <RouterView>) + AppFooter (slim, real content only - app name/phase/
copyright, no fabricated Support/Careers/Status links the reference screenshot has but
this app doesn't actually have pages for). ProjectSidebar itself was rebuilt to match
the reference's own left-nav pattern: a project search/filter box (new, client-side
only), an icon-led nav list ("All Documents" + each project, fa-folder/
fa-folder-open when active), and a collapse toggle anchored at the bottom of the
sidebar rather than floating at its top - collapsed state is a narrow icon-only rail
(same pattern most enterprise dashboards use - Slack, Linear, etc.), not the old "shrink
to just a toggle button" treatment, so project icons stay clickable (with their own
title tooltips) even collapsed.
Deliberately kept page-level scrolling, not nested scroll panes. The reference
screenshot's own sidebar/content scroll independently of each other (a classic fixed-
viewport dashboard shell). This app's .review-grid/.pdf-col/.txn-col already rely
on position:sticky tracking the PAGE's own scroll (confirmed by reading their own
comments - "Sticky on the GROUP... keeps moving together... while the main page
scrolls"). Giving .app-content its own independent scroll container would have broken
that sticky behavior outright (sticky positioning needs its nearest scrolling ancestor
to actually be the page, not a nested pane) - not something this request asked to
touch, so .app-sidebar instead uses the exact same position:sticky pattern already
proven out elsewhere in this file (top:56px - the header's own height - instead of
top:24px), and the page keeps scrolling as a whole, same as before. This was a
deliberate judgment call to preserve working, already-verified behavior rather than
literally copy the reference's nested-scroll-pane structure.
FontAwesome, not hand-drawn icons, per explicit request. Installed as a real npm
dependency (@fortawesome/fontawesome-free, imported once in main.js) rather than a
CDN <link> - keeps the Docker build fully offline-reproducible, same reasoning as
every other dependency in this repo. Every unicode-entity icon left over from the
original vanilla-JS build (✎/✓/✕/←/→/▶/−/▲▼, scattered across TransactionRow,
DocumentNavBar, ResultCard, TransactionsTable, SourceDocumentPanel,
FileUploadZone, ProjectSidebar) was replaced with a solid FontAwesome icon of the
same meaning, not just the sidebar - the user's own framing ("the buttons AND the
sidebar navigation") read as the whole app, and leaving half the icons as unicode
glyphs after an icon pass would have been a worse, inconsistent result. Icons were
verified to actually exist in the installed FA7 free solid set by grepping the real
installed all.min.css for each class name used (fa-file-invoice-dollar,
fa-cloud-arrow-up, fa-folder-open, etc.) before using any of them, not assumed from
memory of FA's icon library.
One pre-existing dead CSS rule fixed as a side effect, not touched deliberately:
.img-zoom-controls button#imgZoomReset{...} (fit-to-width zoom button sizing) existed
in main.css since the original Vue restructure but matched nothing - the button it
targeted never actually had id="imgZoomReset" in SourceDocumentPanel.vue's markup.
Adding the icon to that button was also the moment to add the id it was always supposed
to have, so this rule now applies for the first time.
Verified: npm run build passes (FontAwesome's woff2 fonts bundle correctly into
dist/assets); every icon class name used was grepped against the real installed
all.min.css and confirmed present; the app container was rebuilt and curl-checked
end-to-end - / serves 200, the built CSS/JS bundles serve 200, the referenced
fa-solid-900-*.woff2 file the CSS points at resolves 200, and the built JS bundle
contains the new component class names/icon classes (app-sidebar, app-header,
app-footer, fa-file-invoice-dollar, etc.) - not just that the build didn't error.
measure.py re-run, unaffected (no backend touched). Not machine-verified: the
actual rendered page - whether the header/sidebar/footer look right, whether the
collapse rail behaves, whether any icon is misaligned - Claude-in-Chrome was not
connected this session either (tried again, same as every prior UI change in this
project); this is the one area of this change the user needs to confirm visually
themselves before considering it done.
"Move to project" confirm modal, 2026-10-13. The user reported genuine confusion
right after the shell redesign above: the "Move to project" dropdown in
TransactionsTable.vue actually worked (PATCHed the document's project field via
documentsService.moveToProject), but gave zero visible feedback - no confirmation,
no change to the document in view, nothing in the sidebar/breadcrumb updating - so a
successful move looked identical to a no-op. Asked for a modal confirm step
specifically "so we don't have to add another button to the actual div."
Built ConfirmModal.vue - a small, generic confirm/cancel dialog (dimmed backdrop,
reuses .card for its own surface, Esc/backdrop-click both cancel) - rather than a
one-off inline confirmation, since this is exactly the kind of "are you sure" step other
destructive-ish actions in this app (e.g. deleting a project) could reuse later, even
though nothing else is wired to it yet.
One real subtlety, caught before any code ran: the <select> 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 <select> element's displayed value through v-model,
not a bare :value (a known Vue gotcha, not something encountered by surprise at
runtime here - reasoned through up front). Fixed by giving the dropdown its own local
selectedProjectId ref driven by v-model, kept in sync with the real active document
via a watch (needed now since switching documents via DocumentNavBar no longer
auto-updates the select through a direct store binding), and explicitly reset back to
doc.project in cancelMove() and on a failed move.
Also addressed the original "no feedback" complaint: a moveConfirmNote ("Moved to
{project name}") appears next to the dropdown for 3.5s after a successful move. Label
text changed from the bare, ambiguous "Project" to "Move to project" per the earlier
exchange about what this control even does.
Verified: npm run build passes; the built JS bundle confirmed to contain the new
modal-overlay/ConfirmModal/"Moved to "/"Move to project" strings; the app container
rebuilt and curl-checked serving 200. measure.py re-run, unaffected (no backend
touched). Not machine-verified: the actual modal interaction (open/confirm/cancel/
Esc/backdrop-click, the dropdown correctly reverting on cancel) - same standing
limitation as every other UI change this session, Claude-in-Chrome did not connect.
Document delete/rename, consistent button heights, Download-choice modal, and ResultCard merged into TransactionsTable's top bar - all 2026-10-13, one combined request. Five distinct asks landed together:
-
A way to delete a loaded document before downloading it, with "a better visual UI clue that it's possible."
DocumentNavBar.vue's filename is a real<button>now (.doc-nav-label-btn), not inert text - a hover state plus a trailing mutedfa-ellipsisicon (.doc-nav-options-hint) signal it's clickable. Clicking it opensDocumentOptionsModal.vue(NEW) - an inline rename field + a "Delete this document" button - and delete hands off to a SECOND, separateConfirmModal(the same two-step "pick an action, then confirm the destructive one" pattern "Move to project" already established), now with adangerprop (red confirm button) and abusyprop (keeps the modal open with a spinner mid-request, disables Esc/backdrop/ both buttons until it resolves, instead of closing immediately with no feedback during the network call).DocumentNavBar itself had to change its own visibility gate to make this possible: it used to only render once
documents.length > 1(prev/next needed a second document to mean anything), which meant a SINGLE loaded document had no filename shown anywhere and thus no way to delete it. Now it renders for anylength > 0; prev/next arrows and the "(N of M)" position text stay gated behindlength > 1, but the filename - and the delete affordance - are always there once there's anything loaded at all.extractionStoregained two actions for this:setActiveDocumentFileName(name)(mirrorssetActiveDocumentProject) andremoveDocument(pbId)- finds the document by its PocketBase id, splices it out, and re-settlesactiveIndex: a removal EARLIER than the active index decrements it (keeps pointing at the same logical document, which just shifted left); a removal AT OR AFTER it leaves the number alone, then clamps to the new last index if that's now out of range (covers deleting the active document itself, including when it was the last one, and deleting the very last document in the list down to zero).documentsService .updateDocument(id, patch)was generalized from a hardcoded{result}destructure to accept any plain-object patch, so the same function serves both a row-edit save and a rename ({fileName}) without a second, near-duplicate service function. -
Consistent blue-button height.
.btn-toggle(Hide/Show Source Doc, Recheck Balance, Download, the Results toggle) now hasheight:36pxbaked into the base rule instead of.btn-recheckcarrying its own one-off override - every blue toggle button is the same height by construction now, not by each call site separately matching a number. -
"Download All" button removed; the single Download button asks when it matters. With more than one document loaded (and no batch still mid-flight - same gate the old standalone button used, so "all documents" can't be offered before every file in the batch has actually finished), clicking Download opens
DownloadChoiceModal.vue(NEW) - "Current document only" vs. "All N documents" - instead of needing a second, permanently-visible button competing for space. With exactly one document, it just downloads immediately, unchanged from before. -
ResultCard.vue deleted outright; its content merged into TransactionsTable's own top bar, replacing the old bare
<DocumentNavBar />line with a 3-part row: a "Results" toggle (left) opens the status banner + checks list in a dropdown panel;DocumentNavBar(center); the Download button (right, see #3). Centering is CSS Grid (grid-template-columns:1fr auto 1fr), not flexspace-between- the latter only truly centers the middle item when the left and right content happen to be equal width, which Results-toggle vs. Download button never reliably are. The filename's ownmax-widthwas tightened from 360px to 240px to match - sharing a row with two other controls now, not the whole width to itself.uiStore.resultExpanded/toggleResultExpandedwere renamed toresultsOpen/toggleResultsOpen, plus a newcloseResultsOpen()- kept in the STORE, not a component-local ref, specifically souseBatchExtraction.jscan keep resetting it closed after every fresh extraction (uiStore.closeResultsOpen()), the same behaviorresultExpanded = falsealways provided.Hover-sticky dropdown, per explicit spec ("stays visible as long as their mouse remains on it... collapse when they move their mouse away"): the trigger button and the dropdown panel both live inside one wrapper div (
.results-trigger-wrap) with a single@mouseleaveclosing it -mouseleavedoesn't fire when the pointer moves between a parent's own children (onlymouseoutdoes, which bubbles), so moving from the toggle button down onto the panel beneath it doesn't close it, but leaving the wrapper's combined bounding box entirely does, with no separate "is the panel itself hovered" state-tracking needed. A click still toggles it open/closed independent of hover, for anyone navigating by keyboard/touch rather than a mouse..result-head/.result-head-left/.result-head-actions/.collapse-arrow/.result-details(ResultCard's old block-accordion styling) and the long-dead, unreferenced#resultSection{display:none}rule (leftover from the original vanilla-JS build, confirmed via grep to match nothing in any.vuefile) were all removed frommain.cssrather than left unused. -
New shared composable,
useModalFocus.js- every modal (ConfirmModal,DocumentOptionsModal,DownloadChoiceModal) was duplicating the same "focus the overlay the instant it becomes visible, so Esc works immediately" watcher; factored out once three call sites existed, not speculatively ahead of need.
Verified: npm run build passes; every new icon class name checked against the
installed FontAwesome CSS (fa-ellipsis, fa-circle-question, fa-minus,
fa-chevron-down, confirmed present alongside everything already verified in the prior
entry). The app container rebuilt and the served JS bundle confirmed to contain the
new component/class names (txn-top-bar, results-toggle, doc-nav-options-hint,
DocumentOptionsModal, DownloadChoiceModal, modal-danger-btn, btn-danger).
extractionStore.removeDocument/setActiveDocumentFileName executed directly
against a real Pinia instance (not re-implemented, the actual store) across five
scenarios - removing a document earlier than the active one, removing the active
document itself (both mid-list and as the last one), emptying the list down to zero,
and a plain rename - all five came back correct, including the index-shift arithmetic.
documentsService.updateDocument(id, {fileName}) and deleteDocument(id) executed
directly against the real running PocketBase container (the actual service functions
DocumentNavBar now calls, not reimplementations): created a document, renamed it,
re-fetched to confirm the rename actually persisted (not just that the response echoed
it), deleted it, and confirmed a subsequent fetch correctly 404s. measure.py re-run,
unaffected (no backend touched). Not machine-verified: the actual interactive
behavior - the hover-sticky dropdown's timing, the delete/rename modals' click-through,
whether the 3-column header truly centers the nav at various widths - Claude-in-Chrome
still did not connect this session; this is the user's own check before calling it done.
Sidebar document hierarchy + a real hover-dropdown bug fix, 2026-10-13. Two more fixes from direct user feedback on the work above:
-
ProjectSidebar.vue's projects now expand into their own document hierarchy - a chevron toggle per project (toggleExpand), lazy-loaded on first expand viadocumentsService.listDocuments({project})and cached in aprojectDocumentsreactive object keyed by project id (re-fetched only if this same component deletes a document out from under it, not on every expand/collapse). Each listed document can be opened (click the name - loads its project's documents into the main view if they aren't already loaded, thenextractionStore.setActiveIndexs to it) or deleted straight from the sidebar, via the exact same two-step ConfirmModal pattern (danger/busyprops)DocumentNavBar's own delete flow already established - no new pattern invented, same one reused a third time now (Move to project, document delete, project-sidebar document delete).Required restructuring
<li>in the project list: the clickable row (expand chevron- folder icon/name + rename/delete) moved into its own
.project-rowdiv, since the<li>itself now also holds a second, block-level child - the nested.project-doc-list- which can't share a flex line with the row above it. The active-project highlight background moved from.project-list li.activeto.project-list li.active > .project-rowfor the same reason - so only the row itself highlights, not the whole block including its nested documents.
Deleting a document from here keeps BOTH places in sync: the sidebar's own cached
projectDocuments[project]array (spliced locally, not re-fetched) ANDextractionStore.removeDocument(doc.id)(a harmless no-op if that document wasn't also loaded in the main view) - so deleting a document from the sidebar while it's the one currently being reviewed in TransactionsTable removes it from both places in one action, not just the list it was clicked from. - folder icon/name + rename/delete) moved into its own
-
The Results dropdown's hover-sticky behavior had a real, reported bug: it collapsed if the user moved the mouse down SLOWLY from the toggle button toward the checks list, but stayed open when dragged down quickly - "it seems like the little gap... is causing it to detect as if the user navigated away, when all they are doing is navigating down." Diagnosed and confirmed exactly that: the panel was positioned via
top:calc(100% + 8px), an absolutely-positioned child, which does NOT extend its relatively-positioned parent's (.results-trigger-wrap) own hoverable bounding box - that box stays only as tall as the in-flow toggle button. The 8px visual gap therefore sat OUTSIDE the wrap's hover zone entirely; crossing it slowly gave the browser time to fire a genuinemouseleavebefore the pointer ever reached the panel, while a fast drag could skip past that dead strip within one pointer-event tick without one ever firing - exactly the "works fast, breaks slow" symptom reported, not a flaky timing issue.Fixed by moving the gap from a positioning offset into padding:
.results-dropdownnow sits flush against the toggle (top:100%, no offset) and is itself just an invisible hit-box withpadding-top:8px- padding is still part of the element's own box, so hovering through it counts as hovering a descendant of.results-trigger-wrap, the same as hovering the toggle button itself. The actual visible card moved into a new inner element,.results-dropdown-inner(still.card-styled), offset down by that padding alone - same 8px visual gap as before, now with zero dead zone in the hover path. Confirmed by reasoning through the box model precisely rather than guessing at a timing fix (e.g. a debounce/delay on mouseleave, which would have "fixed" the symptom without addressing why it happened, and would have made the dropdown feel laggy to close on a deliberate mouse-away).
Verified: npm run build passes; the served JS bundle confirmed to contain the new
sidebar class names (project-doc-list, project-doc-delete, results-dropdown-inner).
The two new Vue reactivity patterns this introduced - a reactive Set via
ref(new Set()) and dynamically-keyed property access on a reactive({}) object -
were executed directly against real Vue reactivity (an effect() watching each,
not assumed from documentation): both triggered re-runs correctly on .add/.delete
and on a brand-new key being assigned. measure.py re-run, unaffected (no backend
touched). Not machine-verified: whether the hover fix actually feels right in a
real browser, and the sidebar hierarchy's own click-through (expand/collapse, opening a
document, deleting one) - Claude-in-Chrome still did not connect this session.
Review screen (Phase 2), staged R.1-R.5 - plan approved 2026-10-13; R.1's backend half
shipped same day. Competitor analysis (DocuClipper reviews) surfaced "occasional
wrong data" - date confusion, reversed signs, missing balances, discovered by the user
rather than surfaced by the tool - as the loudest non-billing complaint. That's exactly
docs/bankstatement.md section 4/5's review screen: plain-language flags, one-click
suggested fixes with evidence, structural row edits, an accept/acknowledge workflow,
and a logged edit history. Confirmed as the next build, ahead of a categorizer feature
(grouping/summing transactions into accounting categories for manual journal entries -
the user's own placed reference material now lives at docs/bank_statement_categorizer/,
the actual source of the separate eib-processor tool CLAUDE.md's own "What this is"
section already named) - that's a real scope expansion beyond this product's documented
boundary ("does not decide how a transaction should be categorized") and gets its own
plan once the review screen ships, not designed yet.
Staged like the earlier PocketBase B.1-B.3 work, five independently-shippable pieces: R.1 source-position capture + a highlighting source viewer, R.2 plain-language flags + navigation, R.3 a suggested-fix engine, R.4 structural row edits, R.5 accept/acknowledge
- edit log. Full plan at the time of writing:
/Users/jason/.claude/plans/ witty-inventing-walrus.md(not guaranteed to persist - see the same caveat the original Phase 1 plan note already makes about this).
R.1 decision, confirmed via AskUserQuestion: include per-row highlighting on the
source document (not just today's side-by-side panels) - on the explicit condition that
it can't disrupt the existing extraction pipeline's own coordinate/classification logic,
already proven correct against the HSBC/RBC fixture corpus. Traced the real code
before designing anything: extraction_service.py::run()'s canonical transactions
list already always comes from pdfplumber (table_extract.py) for a normal text PDF -
Docling's own extract_transactions() only feeds the cross-check confidence signal,
never the returned data - so bbox capture needed to touch exactly two files, zero
changes to engine-selection/cross-check logic at all.
One real design correction during plan review: the first draft would have
duplicated the same min/max bbox computation in both table_extract.py and
raw_ocr_extract.py. The user asked directly whether the position-gathering approach
already built for the image/OCR path could be reused for the PDF path too - correct
instinct, and raw_ocr_extract.py already demonstrates the right pattern (it imports
table_extract._classify_money/_REF_RE rather than re-implementing them). Fixed by
factoring one shared table_extract._line_bbox(line_words) helper, called from both
extract_page()'s row-append sites and raw_ocr_extract.py's own three - one
definition of "a row's own bounding box," not two that could quietly diverge.
Shipped (R.1 backend half): table_extract.py - new _line_bbox() (shared,
described above) and _union_bbox() (grows a transaction's own bbox as narrative lines
merge into it, both the "trailing" direction HSBC uses and the "leading" direction RBC
uses - both merge sites in rows_to_transactions() updated). Every transaction now
carries source_page/source_bbox, null for a row sourced from Docling's own
OCR-table-structure path (a synthetic row-index, not a real position - graceful
no-highlight, not an error) - everything else about every transaction is completely
unchanged. raw_ocr_extract.py calls the same shared helper at its own three
row-append sites.
Verified, not assumed: measure.py run before and after - byte-identical untouched
pass rate and field accuracy (1.0/1.0, same transaction counts, same statuses) on all
three fixtures, proving zero behavioral change to the five fields already being
measured. A real /api/process call against both the HSBC and RBC fixtures through the
rebuilt container confirmed every existing field intact and the two new fields
populated. Then the one check measure.py structurally cannot make, since it never
looks at position data at all: rendered both fixtures' first page for real
(pdftoppm) and drew the reported source_bbox as a literal box on the actual page
image for several transactions on each - every box landed exactly on its correct
printed row (including HSBC's own trailing-Narrative-line merge correctly widening the
box to cover both lines, and RBC's tighter, differently-laid-out rows), not just "a
bbox exists" but "it's the right one." This is the real reason the fixture-rendering
discipline this project already uses for ground truth exists - a wrong but non-null
bbox would have passed every other check here.
R.1 frontend half - shipped same day. SourceDocumentPanel.vue's PDF path no
longer uses the browser's native <iframe> viewer - installed pdfjs-dist (a real npm
dependency, same offline-build reasoning as @fortawesome/fontawesome-free) and built
usePdfViewer.js (parallels useImageZoom.js's own shape: zoomIn/zoomOut/
resetZoom, fit-to-width on load). Every page renders to its own <canvas>, stacked
in one scrollable column (.pdf-pages-wrap) - the closest behavioral match to the old
iframe's own scrollable multi-page view, since an iframe has no hook to draw a box on a
specific row, which is the entire reason for this change. The browser's native PDF
toolbar (its own zoom/page-search chrome) is gone as a direct, accepted consequence -
zoom is rebuilt here, matching the image panel's own −/+/Fit pattern exactly.
Coordinate mapping confirmed correct empirically, not assumed: source_bbox's
x0/top/x1/bottom are already in PDF points with a top-down origin (pdfplumber's
own convention, confirmed during R.1's backend verification), the same orientation a
canvas's own pixel space uses - so the overlay box position is just value * zoom
(zoom here means direct points-to-pixels scale, not a 0-1 "percentage" - 1.0 = one
point per pixel), no axis flip needed. This is the exact mapping already proven correct
by R.1's own backend verification (rendering fixtures at a known DPI and drawing boxes
at value * (DPI/72) landed on the right row every time) - reused here, not
re-derived.
useImageZoom.js got the same highlight/highlightStyle/showHighlight/
clearHighlight shape added (the image case is simpler - source_bbox is already in
that image's own natural-pixel space, so the overlay reuses applyZoom()'s exact
existing math). SourceDocumentPanel.vue exposes one unified showHighlight(page, bbox)/clearHighlight() via defineExpose, routing to whichever viewer (pdf.js pages
or the image panel) is actually active for the current document - not called from
anywhere yet, since R.2 (the flagged-row UI that would actually trigger a highlight)
hasn't been built. R.1 only builds the capability, per the plan.
One accepted tradeoff, worth knowing if bundle size ever becomes a real problem:
pdf.js's own worker file is ~2.2MB, pushing the main JS bundle past Vite's default
500KB chunk-size warning threshold. Not code-split or lazy-loaded for this stage - this
is an internal bookkeeping tool over a LAN-fast connection, not a public marketing
page, so initial-load weight wasn't treated as a priority worth the added complexity of
dynamic import() here; revisit if that assumption ever stops holding.
Verified: npm run build passes (the pdf.js worker bundles correctly, confirmed
servable at its own URL - curl'd directly, 200 application/javascript); the app
container rebuilt; the built JS bundle confirmed to contain the new class/function
names (pdf-pages-wrap, source-highlight-box, showHighlight, getDocument).
measure.py re-run, unaffected (no backend touched this half). **Not machine-verified
- and more consequential than most prior UI changes this session to leave unverified:** canvas rendering, worker loading, zoom, and scroll behavior all depend on real browser behavior in a way a curl-based bundle check cannot confirm - Claude-in-Chrome still did not connect. This is the one piece of R.1 that most needs the user's own look before R.2 builds on top of it.
Two real usePdfViewer.js bugs found by the user's own first real test, fixed same
day. Confirmed this is exactly why that honest "not machine-verified" note above
mattered - a bundle/curl check cannot catch either of these.
getDocument(url)was called with the bare blob-URL string directly. The installedpdfjs-dist(6.4.299) does not accept that shorthand - confirmed by reading its own source (getDocument(src = {})only ever readssrc.url/src.data/src.range, never treatssrcitself as a url) - sosrc.urlwasundefinedand pdf.js threw its own "expected eitherdata,range, orurlparameter" error, exactly what the user saw. Fixed:getDocument({ url }).- Found during the fix for #1, before it ever reached the user again: document-switch
cleanup called
pdfDoc.value.destroy()- butdestroy()lives on the LOADING TASK (getDocument()'s own synchronous return value, before.promiseresolves), not on the resolvedPDFDocumentProxy- confirmed both by reading the installed package's own type definitions (PDFDocumentProxyhas nodestroymethod at all) and by a real Node script throwingdoc.destroy is not a functionagainst this exact installed version. Fixed by keeping the loading task itself (not just the resolved document) and callingloadingTask.destroy()instead.
Verified for real this time, not just re-reading the code - pdf.js has real Node
support, so both fixes were run directly (not re-implemented) against the actual HSBC
and RBC fixtures via a plain Node script: the buggy call shape reproduced the exact
reported error first (confirming the diagnosis, not just a plausible-sounding one); the
fixed shape loaded both fixtures correctly (4 pages each, correct page dimensions); and
loading a second document after destroying the first - the exact document-switching
scenario the app needs - succeeded cleanly. npm run build/container rebuild/
measure.py all re-run clean.
The user also reported the transactions table showing nothing for the same document.
Traced the code for a causal link and found none: loadDocument()'s own getDocument()
call was already inside a try/catch (the rejection surfaces as pdfLoadError, nothing
propagates past it), and TransactionsTable.vue's own currentResult is a completely
separate computed with no dependency on SourceDocumentPanel's state at all. Fixed the
confirmed bug; did not claim the transactions-table symptom is resolved - asked the
user to retest specifically that, since no code path was found connecting the two.
All three modal components teleported to <body>, fixing a real "modal appears behind
the page, unclickable" bug reported from the sidebar's own per-document delete. Root
cause: .app-sidebar (position:sticky) and .txn-col (container-type:inline-size,
which implies layout containment) each create their own CSS stacking context - ALWAYS,
with or without an explicit z-index. ConfirmModal/DocumentOptionsModal/
DownloadChoiceModal are all rendered as DOM descendants of one or the other depending
on which call site opened them, so their own .modal-overlay's z-index:50 was
trapped inside that ancestor's local stacking order - no z-index value could have
fixed this, since z-index is only ever compared against siblings within the SAME
stacking context; .app-sidebar/.txn-col themselves have no elevated z-index of their
own, so their entire subtree (modal included) could be painted under later, unrelated
page content regardless of what number the modal's own z-index carried.
Fixed with <Teleport to="body"> wrapping each modal's root element - the standard Vue
fix for this exact class of bug, not a bigger z-index (which cannot escape a stacking-
context trap no matter the value chosen). All three modals now always render as a
direct child of <body>, a SIBLING of #app rather than a descendant of whichever
component happened to open them, so they're never trapped inside any ancestor's
stacking context again, regardless of which future component ends up opening one.
Verified: npm run build passes; the built bundle confirmed to reference Teleport;
the app container rebuilt. measure.py unaffected (no backend touched). Not
machine-verified: whether the modal now actually appears above everything and is
clickable from every call site (sidebar delete, document delete, move-to-project,
download choice) - Claude-in-Chrome still did not connect this session.
A third usePdfViewer.js bug, found by the user's next real test: pages stayed blank
("a silhouette") until zoom was touched. Root cause, confirmed by re-reading
loadDocument()'s own code: it computed fitZoom/zoom correctly after loading, but
never actually called renderAllPages() - only zoomIn()/zoomOut()/resetZoom()
do (via applyZoom()), which is exactly why touching zoom "fixed" it. With nothing ever
drawing into them, every <canvas> sat at the browser's own unset-canvas default
(300×150px) - a small, blank, shadowed rectangle, matching "silhouette" exactly. The
render pipeline itself was never in question here (already proven correct by the user's
own zoom test succeeding) - this was purely a sequencing bug, nothing called it at the
right time.
Fixed with await nextTick(); await renderAllPages() right after numPages.value is
set and zoom is computed - nextTick() is needed because setting numPages only
queues the v-for's canvas elements; they don't exist in the DOM (so
canvasRefs.value stays empty) until Vue actually flushes that update, which
nextTick() explicitly waits for before renderAllPages() tries to draw into them.
The user also reported no longer seeing "the other top bar pdf options" of the source
panel. Checked the zoom-controls row's own gate (v-if="previewUrl", unconditional on
file type or load state) and its CSS (.img-zoom-controls{display:flex}, no hidden
state) - found no second bug there. Most likely the same blank-canvas symptom read as
"the whole panel looks broken, including its header" rather than a literally separate
issue, but not confirmed - flagged to the user to confirm specifically once the
render fix is live, rather than assumed fixed by the same change.
Verified: npm run build passes; the app container rebuilt. measure.py unaffected
(no backend touched). The render pipeline this fix now actually calls on load was
already independently proven correct (the user's own zoom-triggered render worked) -
the fix itself is a well-understood, standard Vue nextTick()-before-acting-on-refs
pattern, not new rendering logic needing its own from-scratch verification. Not
machine-verified: whether pages now actually paint on first load without needing a
zoom nudge - Claude-in-Chrome still did not connect this session.
Sidebar's per-project document list didn't update live - a real architectural gap,
fixed by centralizing the cache into projectsStore. Reported: a newly loaded
document didn't appear under its project in the sidebar, and the user correctly
anticipated the same gap for a document moved from the transactions view - right
instinct, confirmed by reading the code: ProjectSidebar.vue's per-project document
list was a reactive({}) local to that one component, lazy-loaded once per project
on first expand and then cached indefinitely, with zero way for useBatchExtraction.js
(new document), TransactionsTable.vue's "Move to project", or DocumentNavBar.vue's
own delete to ever tell it something changed.
Fixed by moving the cache itself into projectsStore.js (documentsByProject,
keyed by project id) - the natural owner, since it already holds projects/
activeProjectId, and every component that needs to read OR write this cache already
has access to the shared store, unlike reaching into a sibling component's local state.
Four new actions: loadProjectDocuments(projectId) (the same lazy-fetch-once behavior
ProjectSidebar.vue always had, just relocated), addDocumentToCache/
removeDocumentFromCache/moveDocumentInCache - each a no-op if that project's list
was never loaded in the first place (nothing stale to fix - it'll fetch fresh whenever
it IS expanded), so call sites don't need to know or care whether the sidebar has ever
touched that project. All three real mutation sites now call the relevant action
immediately after their own successful backend call: useBatchExtraction.js (new
document → addDocumentToCache), TransactionsTable.vue's confirmMove
(→ moveDocumentInCache, called before extractionStore.setActiveDocumentProject
mutates the document's own project field, so the OLD project id is still readable
at the moment of the call), and DocumentNavBar.vue's confirmDelete
(→ removeDocumentFromCache - this component didn't even import projectsStore
before, now does). ProjectSidebar.vue's own per-document delete already called the
equivalent local-cache cleanup; now calls the shared store action instead, the same as
the other three.
Verified end-to-end against the real running PocketBase, not just read: created a
project, loaded its (empty) cached list, created a document and confirmed
addDocumentToCache made it appear immediately, moved it to a second project and
confirmed moveDocumentInCache removed it from the first project's cache and added it
to the second's, deleted it and confirmed removeDocumentFromCache cleared it - then
re-fetched the first project's documents directly from PocketBase and confirmed the
server-side state matched the client-side cache exactly (0, the same as what the cache
showed) at every step. npm run build passes; the app container rebuilt;
measure.py unaffected (no backend touched). Not machine-verified: the actual
sidebar UI reflecting a live update without a manual collapse/re-expand -
Claude-in-Chrome still did not connect this session.
R.2 — plain-language flags + navigation, shipped 2026-10-13. The piece that actually gives R.1's highlighting infrastructure something to do, and the first genuinely new review-screen UI surface (R.1 was all plumbing - same page, same components, just a different PDF renderer underneath).
New flagCatalogService.js translates each check's own raw mismatch/issue data into
the spec's four-part plain-language flag (what/where/why/what-to-do,
docs/bankstatement.md §5.1). Only running_balance/date_sanity/
structure_sanity/narrative_direction ever carry row-level data - confirmed by
reading checks_service.py directly: statement_balance/page_coverage/
engine_agreement/ocr_source are whole-statement checks with no per-row
mismatches/issues key at all, so a transaction flagged only via one of those (e.g. an
OCR-sourced statement) has nothing to show here, correctly. date_sanity/
structure_sanity return a free-text issue string, not a structured type -
pattern-matched against the backend's own known message shapes, with a fallback that
always shows the raw text rather than ever silently dropping it if that text changes.
TransactionRow.vue gained a flag-icon toggle (the row-actions cell widened
34px→54px to fit it alongside edit/save/cancel) opening a second <tr> with every
flag's own explanation - Vue 3 components can have multiple root nodes, so this is a
genuine sibling table row, not a wrapped <div> that would make the table invalid
HTML. A row can carry more than one flag (e.g. a bad date AND a broken running
balance) - each shown as its own block, not just the first one found.
The real architectural question R.2 had to answer: how does a flagged row (deep
inside TransactionsTable) tell the source panel (SourceDocumentPanel, a sibling
three levels up, not an ancestor/descendant) to highlight itself? No direct prop or
event path exists between them. Solved with uiStore.highlightRequest
({page, bbox} | null) as the bridge - TransactionRow's "Show on source" button sets
it; ExtractorView.vue, the one place that holds an actual ref to
SourceDocumentPanel, watches it and calls the panel's own exposed
showHighlight(page, bbox) (built in R.1, unused until now).
SourceDocumentPanel.vue also now clears both the request and its own highlight state
whenever the active document changes, so a stale highlight box from a PREVIOUS
document can never linger visually over a newly-opened one.
useTransactionFilters.js gained a flaggedOnly toggle (a second, optional
flaggedIndexesRef argument - clearFilters resets it too, hasActiveFilters
includes it) and TransactionsTable.vue added "Flagged only"/"Next flagged" buttons,
shown only when at least one row is actually flagged. "Next flagged" cycles ascending
through flagged indices (wrapping back to the first after the last) via
scrollIntoView on each row's own id="txn-row-{index}" - simpler and more robust
than threading DOM refs for every row up through the parent, which a ref-per-row map
would have needed instead.
Verified: flagsForIndex executed directly (not re-implemented) against REAL backend
output - a live /api/process call against the HSBC-Aug fixture, which has a real,
already-documented running_balance mismatch - confirming the real evidence text reads
correctly ("Expected the balance to be $1,280,218.25 here, but the statement shows $1,257,832.25."), plus synthetic multi-check data exercising every one of the four
builders' own branches, including two different checks flagging the SAME row (both
shown, not just one) and confirming the whole-statement checks never contribute a row
flag. npm run build passes; the built bundle confirmed to contain the new UI strings;
the app container rebuilt; measure.py unaffected (no backend touched - this is
pure frontend presentation over data the backend already returns). Not
machine-verified: the actual click-through - the flag toggle, the highlight box
appearing on the right row/page, "Flagged only"/"Next flagged" behaving correctly -
Claude-in-Chrome still did not connect this session.
R.3 — the suggested-fix engine, shipped 2026-10-13. New backend/services/ suggested_fixes_service.py, wired into pipeline_service.py's run()/recheck() -
both now return a suggestions list alongside status/checks (no new endpoint;
/api/recheck already re-runs on every edit, so a suggestion a manual edit just
resolved disappears on the very next recheck, same as a stale flag already did).
Tested empirically, not hand-derived from check_running_balance's own bridging/
direction math: each candidate fix is applied to a COPY of the real transactions and
the REAL check function is re-run to see if it helps - safer (no risk of a
reimplemented balance-walk silently diverging from the one actually used) and simpler
than tracing which row a bridged, auto-direction-detected mismatch is "really" about.
Three patterns, tried in order (sign flip first, so a row it already explains isn't
also offered a digit-level fix for the same break): debit/credit swapped (negate
the amount), transposed digits (bounded search over every two-digit swap in the
amount's own string), OCR digit misread (same search, common digit-confusion
substitutions).
"Date format swapped" was investigated and found not to apply to this pipeline's
data at all - documented in the new module's own docstring, not silently dropped.
The spec's own pattern describes resolving a raw numeric day/month ambiguity (is
"03/04" 3 April or 4 March?). By the time a transaction reaches this module, its date
is already table_extract.py's own normalized "DD Mon[ YYYY]" text - the month is a
three-letter name, not a number, so that ambiguity was already resolved upstream, at
extraction time. There's nothing left for a suggested fix to resolve here. "Dropped
row"/"page not read"/"wrapped description as a new row" remain deferred for the
reasons already recorded in the earlier "Review screen" entry (unchanged - each needs
real extraction-pipeline capability this build doesn't have yet).
A real, genuine bug found by the FIRST end-to-end test - not by reading the code,
and not caught by any of the backend-only verification that came before it. The
running-balance check's own bridging logic means a mismatch recorded at row i can be
caused by either row i's own amount or row i-1's - suggested_fixes_service.py
already tried both as fix candidates (confirmed correct in isolation via curl: three
real corruption patterns, each correctly reverse-fixed). But the FRONTEND matched a
suggestion to a row by the fix target's own index - and the flag icon only ever
appears on the row the MISMATCH is reported against, which the bridging logic doesn't
guarantee is the same row. Confirmed for real: corrupting row 5's amount surfaced the
mismatch on row 6 - the suggestion correctly named row 5 as the one to fix, but was
completely unreachable from the UI, since row 5 was never flagged at all and so never
showed a flag icon to click. Fixed by adding a second field to each suggestion,
flag_index (the row the UI actually shows flagged) alongside the existing
index (the row the fix applies to) - TransactionRow.vue now looks up a row's own
suggestion by flag_index, and always applies the accepted fix to suggestion.index,
which can be a different row than the one the user clicked from.
This is exactly why this project's own verification discipline insists on running the real, full round trip, not just the individual pieces in isolation - the backend logic was already correct and separately verified; the bug only existed in how two correctly- built pieces were wired together, and no amount of re-reading either piece alone would have surfaced it.
TransactionRow.vue's suggestion block lives inside R.2's same flag-detail panel -
evidence text plus an "Apply fix" button that runs the exact same save→persist→recheck
pipeline useRowEditing.js's own saveEdit() already uses (one path for "a value on
this row changed," not a second one for suggestions). extractionStore .applyCheckResults now re-applies suggestions on every recheck, not just once.
Verified: the three corruption patterns run through the real running container via
curl against a known-good fixture - each detected and correctly reverse-fixed at the
exact right index, confirmed via the response JSON directly. The real HSBC-Aug
Cancelled-wire mismatch (a genuine, already-understood non-error case documented
elsewhere in this file) correctly produces ZERO suggestions, confirming the engine
doesn't force a misleading "fix" onto a mismatch that isn't actually a data error. The
full apply→persist→recheck→restore round trip was executed directly against real
Pinia plus the real running PocketBase (not reimplemented), including confirming the
PERSISTED record - not just in-memory state - reflects the fix. measure.py re-run,
unaffected. Not machine-verified: the actual click-through - the flag icon, the
evidence text, the "Apply fix" button - Claude-in-Chrome still did not connect this
session.
R.4 — structural row edits, shipped 2026-10-13. Frontend-only, as planned -
/api/recheck already accepted any transactions array regardless of length, so
add/delete/merge/split only needed new extractionStore.js actions:
flipTransactionSign, deleteTransaction, insertTransactionAfter(index, template?),
mergeWithNext.
Two deliberate deviations from the original plan, both decided for the same reason - don't build something that doesn't actually apply or doesn't actually need building:
- No separate
splitTransactionaction. "Split this row" isinsertTransactionAfter(index, {...row})- duplicates the row's OWN current values into a new row right after it, rather than guessing where to divide the amount (the same "never silently correct" rule as everywhere else in this app) - the user then edits both rows manually to the real figures. One action, two UI entry points ("Insert row after" passes no template - blank, for a row the extractor genuinely missed; "Split this row" passes the current row's own values as the template). - No "bulk column fix" (date-format swap). R.3 already established this pipeline's
dates have no day/month ambiguity left by the time a transaction reaches this layer
(already normalized to
"DD Mon YYYY"at extraction time) - there was nothing left for a bulk date fix to do, so it was dropped from scope rather than built as a no-op.
All four actions live behind a new "more actions" popover menu on TransactionRow.vue
(.row-menu, opened by a new row-btn.more icon) rather than more always-visible row
icons - these are rarer than edit/flag, and two are destructive. Delete and merge each
go through the same ConfirmModal (danger/busy) pattern every other destructive
action in this app already uses (move-to-project, document delete, project delete) -
flip/insert/split don't need one (additive, or trivially reversible by doing it again).
mergeWithNext concatenates descriptions, sums amounts, keeps the LATER row's own
balance (it reflects the cumulative state after both), and unions source_bbox when
both rows share a page, so "Show on source" still boxes the full merged area afterward,
not just the first row's original position.
A new shared persistAndRecheck() in TransactionRow.vue replaces what R.3's
applySuggestedFix had inline - now one function all five of this component's own
mutation paths (suggestion apply + the four structural actions) call, instead of a
sixth near-duplicate copy of the same three steps (manual field edits keep using
useRowEditing.js's own separate copy, since that composable has its own draft/
cancel state these don't need).
Verified: all four actions executed directly against real Pinia plus the real running
backend, not reimplemented - flip-then-restore (status returns to original), an
insert-then-delete round trip (status returns to original), and a real merge checked
field-by-field (description concatenation, summed amount, the later row's own balance,
and the unioned bbox's own top/bottom both confirmed against the two original rows'
real values) - including persisting the resulting SHORTER array for real and confirming
both /api/recheck and the PocketBase record itself correctly accept and reflect a
31-row statement that started at 32. measure.py re-run, unaffected (no backend
touched). Not machine-verified: the actual "more actions" menu, the two confirm
modals, and the resulting table row changes - Claude-in-Chrome still did not connect
this session.
R.5 — edit log + acknowledge/accept workflow, shipped 2026-10-14. This closes out
the full review screen plan (R.1-R.5). No new PocketBase migration needed - a
document's result field is already an arbitrary JSON blob the backend never
inspects the shape of (confirmed: documentsService.updateDocument PATCHes
{result} wholesale), so editLog/acknowledgedFlags/accepted/acceptedAt are
just new keys on that same object, written by the frontend and read back by it.
extractionStore.js gained: appendEditLogEntry(entry) (pushes {...entry, at: ISOString} onto doc.result.editLog, lazily initialized); acknowledgeFlag(checkName, index, note?)/unacknowledgeFlag(checkName, index) (write/delete
doc.result.acknowledgedFlags[checkName][index]); flagAcknowledged (parameterized
getter, (checkName, index) => boolean); allFlagsAcknowledged (getter - walks every
check in ROW_FLAG_CHECK_NAMES, imported from flagCatalogService.js rather than
re-listed, so this can't silently drift from that file's own four row-flagging checks -
and every one of that check's mismatches/issues entries, confirming each has a
matching acknowledgedFlags entry; vacuously true when nothing is flagged at all, so
a clean "Verified" document was never blocked on acknowledging zero flags);
acceptDocument() (sets accepted: true/acceptedAt: ISOString, trusting its caller
the same way every other store action here does - the actual accept GATE lives in the
UI, not the store).
Every mutation site that changes a transaction field now logs it, one entry per CHANGED field (not one undifferentiated "row changed" blob) so a single "merge with next" that touches description+amount+balance produces three log entries, not one:
useRowEditing.js'ssaveEdit()- diffs the draft against the transaction's actual prior values field-by-field (date/description/amount/balance/status) before committing, logging only the fields that actually changed,source: 'manual'.TransactionRow.vue'sapplySuggestedFix()- logs the one field the suggestion named, oldValue captured BEFORE the fix is applied,source: 'suggested_fix'(distinguishing an engine-proposed fix from a hand-typed edit in the log/Excel sheet).- The four R.4 structural actions, each with a descriptive, non-field label since
there's no single before/after VALUE to log for "a row was inserted":
handleFlipSign(logs the realamountold/new, since that's a genuine field change),handleInsertAfter(_row_inserted),handleSplit(_row_split),confirmMerge(_rows_merged,oldValueis the now-removed row's own index for traceability),confirmDeleteRow(_row_deleted,oldValueis the deleted row's own description) - allsource: 'manual'.
Acknowledge UI: each flag in TransactionRow.vue's existing R.2 flag-detail panel
gets its own "Mark as checked"/"Acknowledged" toggle button, keyed by that flag's own
checkName (already present on every flagsForIndex() result) - acknowledging doesn't
change any transaction data, it only records that a human reviewed it (the exact case
this exists for: HSBC-Aug's real Cancelled-wire running_balance mismatch, which is
correct-and-expected, not a data error to fix). Persisted best-effort via
documentsService.updateDocument, same discipline as every other row mutation, but the
toggle itself never blocks on that persist succeeding.
Accept UI: a new "Accept"/"Accepted" button in TransactionsTable.vue's top bar,
beside Download - enabled when status === 'Verified' (nothing to review) OR
allFlagsAcknowledged is true (everything flagged has been looked at); disabled
otherwise, with a title tooltip explaining why. Calls extractionStore.acceptDocument()
then persists via documentsService.updateDocument.
backend/services/excel_service.py - extraction_schema.parse_export_request()
now passes edit_log through unchanged (data.get("edit_log") or []), and
routes/extraction.py's /api/export includes it in the result dict it hands to
excel_service.build_workbook(). A new _write_edits_sheet(wb, edit_log) writes a
Row/Field/Old value/New value/When/Source table (1-based row numbers, matching the
Transactions sheet's own numbering - entry["index"] stays 0-based everywhere
internally), called conditionally - if result.get("edit_log"): - right before
build_workbook() returns, so an export with no edits made gains no empty "Edits"
sheet nobody asked for (docs/bankstatement.md §8's own spec: "Excel: ... optional
Edits sheet").
Verified, not assumed: backend/measure.py re-run, byte-identical to the pre-R.5
baseline (1.0 field accuracy on all three fixtures, same statuses) - this stage adds
only new, always-optional data, nothing existing changed. A real /api/process call
against the HSBC-Sep fixture, then a real /api/export call against that actual
result with a synthetic edit_log attached, confirmed the real, rebuilt container
("Edits" sheet appears with the right headers/values/1-based row numbers only when
edit_log is non-empty; omitted it entirely when the payload carried none) - this
caught a real gap in the test setup itself (the first attempt 500'd with a KeyError: 'pdfplumber_count' from hand-rolled page_reports that didn't match the real shape;
switching to an actual /api/process response fixed it, not a product bug).
extractionStore.js's new getters/actions were executed directly against real Pinia
(not reimplemented) across acknowledging one of two flags vs. both, unacknowledging,
allFlagsAcknowledged's vacuous-true case for an unflagged document, and
acceptDocument(). useRowEditing.js's edited saveEdit() was run for real against
a document actually created on the live PocketBase container: edited one field,
confirmed exactly one editLog entry with the correct old/new values and source: 'manual', confirmed the OTHER, unchanged field produced no entry, and re-fetched the
PocketBase record directly (not trusting the in-memory store) to confirm the edit log
was genuinely persisted, not just held in memory. npm run build passes; the app
container rebuilt and confirmed serving the new bundle (appendEditLogEntry present
in the built JS).
Layout mapper (Phase 3, pulled forward) + modular layout quirks - plan approved
2026-10-14; L.1 shipped same day. Uploading a real, never-seen statement (an
"Equals Money" account PDF, EQUALS - USD.pdf) failed with "could not recognize this
statement's column layout." Traced to the real PDF's own word positions: its
"Running balance" header label wraps across two extra physical lines that straddle
the single line carrying "Date"/"Payment type and details"/"Credits"/"Debits" -
table_extract.py grouped words into "lines" by exact round(w["top"]) with no
tolerance, so no single line ever had "date" and "balance" together, and the header
shape check failed on every page.
What started as "fix this one statement" became, at the user's explicit direction,
"build this so it stops being a code change every time a new bank shows up" - the
full layout mapper already specced in docs/bankstatement.md §6/§6.1/§9
(fingerprinting, exact/near-match auto-apply, a manual mapping screen as the last
resort, versioning, drift detection, a shared library), pulled forward from its
documented "Phase 3, not started" slot, plus one addition beyond the written spec:
a PocketBase superuser can review a new mapping against its real source document and
approve it straight to shared, instead of only ever waiting for a second independent
confirmation. Full staged plan (L.1-L.8) at
/Users/jason/.claude/plans/witty-inventing-walrus.md.
A real gap flagged explicitly at the time, since resolved by a deliberate scope
decision (2026-11-24 - see "Phase 4 dropped" under Key decisions & lessons): the
spec's own data model (§9) ties a Layout Mapping to a Practice/Client (the Frappe
multi-tenant model - originally "Phase 4, not started"). That model doesn't exist
here - every PocketBase users record is its own fully isolated account, no team/org
grouping at all. Everywhere the plan says "confirmed by a second practice," it
actually means confirmed by a second, different users account - this is no
longer a stand-in awaiting a future multi-tenant model; Phase 4 itself was dropped,
and a users account is the permanent unit of isolation. A "client" is a project
within one user's own account, not a separate tenant.
A smaller idea discussed first - a code-based "layout quirks" module that mechanically fixes geometric oddities with zero human involvement - was kept as an earlier, zero-friction tier rather than dropped in favor of the mapper: a quirk fixes a pattern a developer can anticipate and write a deterministic rule for; the mapper is for anything a rule can't describe at all (a genuinely different column set/ order/terminology), solved by asking a human once and remembering the answer for everyone after that. The four-tier pipeline, in order, each a true no-op fallthrough if it doesn't apply: (1) the existing keyword/geometry auto-detector, unchanged; (2) the new layout quirks module; (3) a stored-mapping fingerprint lookup (not built yet); (4) the manual mapping screen (not built yet, last resort).
L.1 shipped: the quirks module (tier 2), plus two MORE real differences the same
statement surfaced once its header-wrap was fixed and real rows started coming
through. layout_rules.py gained public match_line_fields/resolve_header_matches
(relocated from table_extract.py's private _line_field_matches/
_resolve_header_matches - a pure move, same logic) so the new
backend/services/extraction/layout_quirks.py could depend on the shared vocabulary
module alone, never on table_extract.py - avoiding a circular import, since
table_extract.py::_find_zones now calls layout_quirks.normalize(lines_by_top) as
a fallback whenever _find_header_row finds nothing on its own. The one quirk shipped,
_wrapped_header_label, is a guaranteed no-op whenever any single line already
resolves the required shape (true for HSBC/RBC, always); otherwise it tries merging
runs of consecutive lines within an 8pt gap (real quirk gaps measured ~6pt on the
actual PDF; real distinct body-text lines measured >=10pt apart) and keeps the first
merge whose UNION of words resolves the shape. _find_zones now returns the
(possibly merged) lines_by_top as a third value, which both extract_page() and
raw_ocr_extract.py::_extract_from_images now feed back into their own row-building
loop - without this, the pre-merge fragment lines (e.g. a lone "balance" label) would
still be iterated as if they were ordinary page content, corrupting whichever
transaction sits right after the header. Also fixed, regardless of everything else:
extraction_service.py's stale error text, which claimed "only supports HSBC
Business Account statements" - false since RBC shipped.
Two more real, separate differences this exact statement surfaced, fixed in the same pass since both are deterministic/unambiguous enough that a developer-written rule is the right place, not a human mapping decision:
- Money tokens prefixed with "$" (
"$33.62", vs. HSBC/RBC's bare"33.62") - every single amount on this statement failed_MONEY_REoutright, so nothing was ever classified as money at all. Fixed by widening_MONEY_REto^-?\$?[\d,]+\.\d{2}$and stripping"$"alongside the existing comma-stripping in_classify_money- the same category of generalization as the existing comma-handling, not a bank-specific special case. - Dates printed as
"2026/08/06"(ISO-shaped) instead of HSBC/RBC's own"DD Mon YYYY"text -checks_service._parse_dateonly recognizes the latter, so every single row faileddate_sanity. Fixed with newtable_extract._normalize_date_text- recognizes
YYYY/MM/DD/YYYY-MM-DDspecifically (never ambiguous, since the 4-digit year anchors which part is the year - unlike a bare"03/04", which genuinely needs a human's day/month call) and converts to the canonical"DD Mon YYYY"shape every downstream consumer (checks_service, suggested_fixes_service's own documented assumption) already expects. Applied whereverrow_dateis built in bothtable_extract.pyandraw_ocr_extract.py- a no-op for any date that doesn't match that exact numeric shape.
- recognizes
Verified end-to-end for real, not just unit-tested in isolation: backend/ measure.py byte-identical before/after on HSBC/RBC (proves the quirk/money/date
changes are true no-ops there). The actual Equals Money PDF, run through the real
rebuilt container's /api/process: 36/36 transactions; statement_balance pass
(opening 28,370.22 + credits 70,000.00 + debits -95,177.06 = 3,193.16, exactly
matching the statement's own printed closing balance); running_balance,
date_sanity, structure_sanity, narrative_direction all pass. Every
date/amount/balance spot-checked by hand against the real printed PDF text matched
exactly (the $70,000 PLANETERRA FOUNDATION credit, the $33.62/$12.43 card debits, the
$1,357.80 currency-exchange debit, the opening/closing balances). Overall status is
still "Failed" - engine_agreement fails because Docling found zero tables on every
page of this statement (confirmed in the real response: docling_count: 0 on pages
2-4) - the architecture working exactly as designed (pdfplumber's result trusted,
disagreement flagged rather than silently resolved), the same category of
already-accepted "Failed" status the RBC fixture carries for an analogous Docling
limitation, not a defect this stage introduced or was ever meant to fix.
page_coverage is needs_review because page 1 is a genuine cover/summary page with
no transaction table - also expected. The real OCR fallback path
(raw_ocr_extract.py, also touched here) was re-verified against the existing
docs/scanned_statement_2page.pdf fixture through the same rebuilt container - still
17/17 transactions, same per-page engine attribution, zero regression. No
ground-truth workbook exists yet for the Equals Money PDF - a reasonable follow-up,
not a blocker for this stage.
L.2 shipped same day: fingerprinting + the forced-mapping backend contract (no UI,
no PocketBase schema yet - that's L.3+). backend/services/extraction/ layout_fingerprint.py (NEW) - compute_fingerprint()/fingerprint_hash(), only
ever called once tier 1 (keyword detector) AND tier 2 (layout_quirks) have both
failed on every page. A new LayoutMappingRequired (in extraction_service.py, a
ValueError subclass so it's still caught by any not-yet-updated generic handler,
just with a worse message) carries the computed fingerprint; routes/extraction.py ::process() catches it ahead of the generic ValueError handler and returns HTTP
422 with {needs_mapping: true, fingerprint, fingerprintHash}. extraction_service .run()/pipeline_service.run() both gained forced_mapping=None - when supplied,
table_extract.extract_pdf() extracts directly from the given column positions
(forced_zones/forced_sign_convention/ignored_row_rules/date_format/
start_page), bypassing auto-detection and layout_quirks entirely. New
table_extract.normalize_date(raw_text, date_format) - always tries the already-
unambiguous textual/ISO path first (zero change for every statement that already
works), only falling back to a dmy/mdy/ymd hint - which only an explicit
mapping can ever supply, never auto-detection - when that finds nothing and a
numeric date token is present.
Two real deviations from the original plan, both found by actually running this against the real Equals Money PDF, not assumed from reading the code:
table_extract.header_candidate_geometry()was planned as "page 1 only," but the real statement that prompted this whole feature has a pure cover/summary page as its own page 1 - fingerprinting literally page 1 would have produced an empty, useless fingerprint for the exact case this exists to handle. Fixed by scanning every page and keeping whichever one matches the most distinct keyword-vocabulary fields across its own lines - the same "keep the most complete candidate" patternraw_ocr_extract.py's own cross-page zone sharing already uses, not a new one.- A forced mapping has no per-page
header_topof its own to anchor the existing "skip anything above the header" preamble filter against. Confirmed for real: the FIRST attempt at forcing the real Equals Money PDF's column zones produced a phantom extra "transaction" - page 1's own letterhead/address/legal narrative text had nothing to anchor a boundary against and got merged forward into the first real money-bearing row the forced zones happened to match. A one-offignoredRowRulesentry couldn't fix this generally (page 1 has many distinct narrative lines, not one line worth matching). Fixed by addingstart_page(1-based, default 1) to the forced-mapping contract -extract_pdf()now skips every page before it entirely, never classifying it as narrative or transaction data at all. The layout mapper's own manual screen (L.6, not built yet) will need to let the user set this, or infer it from which page they're looking at when they map.
Verified, all real: a hand-built, genuinely-unrecognizable one-page PDF
confirmed LayoutMappingRequired raises correctly with a valid (empty) fingerprint,
both calling extraction_service.run() directly and through a real /api/process
call against the rebuilt container (HTTP 422, a real fingerprint + hash in the
body). The real Equals Money PDF, forced through a hand-built mapping via curl:
the first attempt (no startPage) reproduced the phantom-transaction bug above,
confirming it was real; after adding start_page and setting startPage: 2, the
SAME statement produced 36/36 correct transactions with statement_balance/
running_balance/date_sanity/structure_sanity/narrative_direction all
pass - matching L.1's own auto-detected result exactly, proving the
forced-mapping contract is functionally equivalent once given the right inputs, not
just "doesn't crash." backend/measure.py re-run byte-identical on HSBC/RBC both
before and after the start_page addition.
L.3 shipped same day: the PocketBase schema for the layout mapper. Two new
migrations - 4_add_layout_mapper_schema.js (layoutMappings/
layoutMappingVersions collections) and 5_add_layout_mapping_fields.js
(documents.layoutMappingUsed/layoutMappingVersionUsed/layoutApplied/
layoutFingerprintHash) - plus a new hook, pb_hooks/ promote_shared_layout_mapping.pb.js. layoutMappingVersions is a genuinely
separate collection, not an embedded array like documents.editLog - the
(not-yet-built) Layouts page needs independently listable/comparable/roll-back-
able versions, and PocketBase can't query into elements of a JSON array.
The one deliberate rule deviation from every other collection's strict owner-only
pattern: layoutMappings' listRule/viewRule also allow status = "shared",
since the entire point of a shared mapping is that OTHER users' uploads can find
and apply it. The hook (onRecordAfterCreateSuccess on layoutMappings, same
pattern as ensure_default_project.pb.js): when a new mapping is created, it looks
for another mapping with the same fingerprintHash and a DIFFERENT owner (this
app's own permanent unit of isolation, by the decision recorded under "Phase 4
dropped" - a users account stands in for "a different practice" for good, not a
placeholder awaiting a multi-tenant model) via e.app (bypasses every rule); if found, both
records flip to status: "shared" immediately - kept as two separate records
rather than merged, avoiding a dangling relation from any documents .layoutMappingUsed already pointing at either one.
A real gap found by testing the actual rule against the actual running
collection, not by reading the rule text and trusting it: the first version of
updateRule was just owner = @request.auth.id - which gates WHO can update a
record, not WHICH fields they change. A plain owner could PATCH
{"status": "shared"} on their own still-private mapping and it would simply
succeed, completely defeating the "private until a second confirmation or
superuser approval" requirement this collection exists to enforce. Caught by
actually trying it (not assumed safe because the collection "has rules") before
this was ever reachable by a real user. Fixed in a follow-up migration,
6_fix_layout_mapping_update_rule.js (not by editing migration 4, which had
already applied): updateRule tightened to owner = @request.auth.id && @request.body.status != "shared" - blocks self-promotion specifically, while an
ordinary edit (rename, fix a column) or the owner setting their own mapping to
"retired" still works exactly as before.
Verified, all real, against the actual rebuilt container, not assumed from the
migration files: both new collections and all four new documents fields
confirmed present via the real REST API as the real PocketBase superuser. Two
different real signed-up users each creating a layoutMappings record with the
SAME fingerprintHash - the hook correctly flipped both to shared; a third,
unrelated signed-up user could then list both, while a still-PRIVATE mapping
correctly 404'd for every other user's GET/PATCH. After finding and fixing the
self-promotion gap: the same self-promotion PATCH now correctly fails; an ordinary
rename and a self-retire by the owner both still succeed; the hook itself
re-confirmed working unchanged after the rule tightening (it writes via e.app,
bypassing rules entirely either way).
L.4 shipped same day: the frontend fingerprint-lookup orchestration - including a
real, clickable confirm dialog, not a placeholder deferred to L.6. New
frontend/src/repositories/pocketbaseAdminRepository.js (a SECOND PocketBase client
instance - a superuser session on the same pb instance the logged-in app user
already uses would clobber their session, since pb.authStore is one global slot
per client), frontend/src/services/layoutMappingsService.js (the CRUD/lookup
wrappers plus the near-match comparator - entirely client-side, never duplicated in
Python), frontend/src/services/adminLayoutsService.js (the superuser's own
listPending()/approve(), ahead of L.8's actual review screen), and new
frontend/src/composables/useLayoutMapping.js (resolveNeedsMapping() - exact
match applies silently; a stale exact match or a near match needs confirmation via
an injected confirmFn; no match reports reason: 'no_match' honestly rather than
pretending to handle it). useBatchExtraction.js now accepts a confirmMappingFn
parameter wired straight through to useLayoutMapping, and ExtractorView.vue
supplies a REAL one backed by the existing <ConfirmModal> (a Promise that resolves
when the user clicks Confirm/Cancel) - the near-match confirmation step genuinely
works today, not just in a Node test.
Two real bugs found by testing the near-match comparator against the spec's own documented example, not by reading the code and trusting it:
layout_fingerprint.py::compute_fingerprint's first draft builtheader_labelsfrom each matched LINE's own full text (e.g. "date payment type and details credits debits" as one entry), not per-FIELD label text - meaning "only Debit/ Credit got renamed" could never be distinguished from "this is a totally different layout," since a whole line differs completely the moment any single word in it changes. Fixed by adding a newfield_labelskey ({field: literal matched text}) that the near-match comparator reads instead;header_labels(the flat set) stays as the EXACT-match hash's own input, where full-text precision is actually wanted.- Even after that fix, a real test of the documented example ITSELF ("Debit"/ "Credit" renamed to "Withdrawals"/"Deposits") still failed - the first-drafted 70% label-overlap threshold was simply too strict for the exact case it was written to cover: renaming 2 of a 4-field layout (date/debit/credit/balance, no description resolved on this candidate page) is precisely 50% overlap. Fixed by lowering the threshold to 50%, derived by actually working through the documented example's real numbers rather than picking a round number a second time.
Verified, all real: a hand-written Node script ran the REAL
layoutMappingsService.js/useLayoutMapping.js (not reimplementations) - 18
assertions: scoreNearMatch's three hard gates (shape, order, position) plus the
corrected per-field overlap check (the renamed-labels case now passes; a genuinely
different shape or far-shifted positions still correctly reject), then against the
real running PocketBase - findByFingerprintHash respects ownership/sharing
correctly, recordUsage flips a mapping to stale on its first recorded failure,
and resolveNeedsMapping correctly declines a stale exact match when its injected
confirm callback returns false, applies it (with the real columnMap carried
through) when it returns true, and reports reason: 'no_match' for a genuinely
unmatched fingerprint. Through the real rebuilt container: a synthetic
unrecognizable PDF's /api/process response now carries a real field_labels key
inside fingerprint, confirming the fix reaches the actual HTTP contract, not just
the Python function in isolation. backend/measure.py byte-identical throughout
(fingerprinting only ever runs on the already-isolated failure path). npm run build passes.
L.5 shipped same day: multi-highlight SourceDocumentPanel + a new click-and-
drag region tool - the groundwork the manual mapping screen (L.6, not built yet)
needs. usePdfViewer.js/useImageZoom.js each gained a parallel highlights
ref ([{page?, bbox, label?, color?}]) and showHighlights(boxes)/
clearHighlights(), entirely independent of the existing single highlight/
showHighlight/clearHighlight the review screen's own "Show on source" (R.2)
already depends on - that call site needed zero changes. SourceDocumentPanel.vue
exposes the plural versions the same way, and its template now renders a v-for
of labeled boxes (blue by default, overridable per box) alongside the existing
single amber highlight. New frontend/src/composables/useRegionDraw.js - the
click-and-drag-to-define-a-region interaction that didn't exist anywhere in this
app before - owned by SourceDocumentPanel.vue via a new regionDrawMode prop
(default false, a no-op everywhere today) and a region-drawn emit carrying
{page, bbox} in the same PDF-point/image-pixel space source_bbox already uses
everywhere else. Both viewer composables also had to start exposing their own raw
numeric zoom ref (previously only a formatted zoomLevelText string was public)
so the region tool can convert a drawn pixel rectangle back into that coordinate
space, the inverse of how a highlight box's own position is already computed.
Verified, all real: a hand-written Node script executed the REAL
useRegionDraw.js/usePdfViewer.js/useImageZoom.js (not reimplementations) via
a minimal fake window.addEventListener/removeEventListener - the only browser
API the region tool touches, so no real DOM was needed - covering 21 assertions:
a real drag's reported bbox correctly divides by zoom; dragging up-left still
normalizes to x0 < x1/top < bottom rather than an inverted box; a drag below
the minimum-pixel threshold never fires onRegionDrawn (no accidental zero-size
region from a stray click); both viewers' new multi-highlight state coexists with,
and never disturbs, the existing single-highlight state. npm run build passes;
the app container rebuilt and confirmed serving the new bundle. backend/ measure.py unaffected (no backend touched this stage). Not machine-verified:
multiple labeled boxes actually rendering correctly on a real page at several zoom
levels, and a real mouse drag in an actual browser - the coordinate math itself is
proven correct by the Node tests above, but seeing it drawn on screen is the
user's own check, same standing limitation as every other frontend-only change
this session (Claude-in-Chrome still not connected).
L.6 shipped same day: ManualMappingView.vue - the core deliverable of the whole
layout-mapper plan. A new routed view (/map-layout) - SourceDocumentPanel in
regionDrawMode beside a field-role toolbar (Date/Description/Debit/Credit/Amount/
Balance - click a role to arm it, drag a box, it claims that role; assigned regions
listed with a remove button each), a date-format selector (textual/dmy/mdy/
ymd), a "this statement's debit column already prints its own minus sign"
checkbox, an ignored-row-rule list, and the familiar opening/closing balance
inputs. Preview (required before Save unlocks) calls /api/process with the
assembled forced_mapping and shows the first ten transactions plus the
statement-balance check's own outcome - shown, never gating, matching the
underlying spec's own "preview before saving." Save Mapping creates the
layoutMappings record + an initial layoutMappingVersions entry, then saves the
document via the existing documentsService.saveDocument with its
layoutMappingUsed/layoutMappingVersionUsed/layoutApplied/
layoutFingerprintHash fields set.
A real File object can't survive a router navigation on its own (no way to
serialize one into a route param), so new frontend/src/stores/ layoutMapperStore.js holds exactly ONE pending file + its fingerprint in memory -
deliberately not a queue (see that store's own docstring for why) - set by
useBatchExtraction.js whenever useLayoutMapping.js's own resolveNeedsMapping()
comes back with reason: "no_match". ExtractorView.vue shows a small banner
linking to /map-layout while one is pending.
Two real bugs found while actually wiring this up and testing it end to end - not assumed safe from reading the code:
useBatchExtraction.js's ownlayoutFingerprintHashsave field was readingresult.fingerprintHashAFTERresulthad already been reassigned to the forced-mapping retry's own response - which never carries that field at all (only the 422needs_mappingresponse does, from before the retry). Would have silently leftdocuments.layoutFingerprintHashunset for every mapping-applied extraction, forever. Fixed by capturing it into its own variable before the reassignment, caught by re-reading the data flow carefully before building L.6 on top of it, not by a failing test.- A more consequential one, found by the first genuine end-to-end Preview
against real synthetic transaction data (the Equals Money PDF no longer
reaches this screen at all now that L.1's quirks module resolves it - a
deliberately-constructed gibberish-header statement with 3 real transaction rows
was needed to actually exercise this path): a forced mapping's
columnMapranges were used completely unpadded. A word's own reportedx1landed a FRACTION OF A POINT past the raw zone boundary (confirmed directly - a value that looked like416.1at a glance was actually416.14), silently excluding an entire transaction from classification with no error at all. This is exactly the failure mode a human's own imprecise mouse drag would hit even more often than a float-rounding artifact would - directly the kind of thing the "never silently exclude data" governing rule exists to catch. Fixed with a newtable_extract._FORCED_ZONE_PADDING = 3points applied to every forced zone inextract_pdf()- the same discipline the auto-detected path's own zones already use (a generous-80/+5padding there), just a smaller margin here, since this only needs to absorb imprecision, not "where does the data sit relative to the header" uncertainty.
Verified, all real, end to end - the actual proof this whole stage exists for:
a hand-built synthetic PDF (gibberish, unmatchable header labels; 3 real
transaction rows with known amounts/balances at known coordinates) confirmed to
genuinely trigger needs_mapping through the real pipeline. Driving the REAL
frontend services from Node against the rebuilt container: Preview with a
hand-assembled forcedMapping (replicating exactly what the view's own
role-toolbar would produce) correctly extracted all 3 transactions with the right
signs/balances and a passing running_balance check; Save created the mapping +
version + a documents record whose layout fields were confirmed on the
PERSISTED record (re-fetched, not the create response's own echo); a second,
completely independent upload of the identical file was then confirmed to
silently auto-apply the saved mapping via the real useLayoutMapping .resolveNeedsMapping() - the injected confirm callback was never even invoked,
true silent exact-match application - producing byte-identical transactions to
the manual Preview. A direct regression re-run of L.2's own Equals-Money
forced-mapping test confirmed the new zone padding didn't change that
already-correct result. backend/measure.py byte-identical throughout; npm run build passes; every new icon class was confirmed present in the installed
FontAwesome set before use. Not machine-verified: the actual click-and-drag
interaction, the toolbar's visual behavior, and the banner's own appearance in a
real browser - same standing limitation as every other UI stage this session.
L.7 shipped 2026-10-15: the Layouts page, drift detection wired into every
recheck, and - again - a real bug found by actually testing it end to end. New
frontend/src/views/LayoutsView.vue (routed /layouts, linked from a new
AppHeader.vue nav item): List (own + visible shared mappings, usage/failure
counts), Inspect (a read-only SourceDocumentPanel with each column drawn as a
tall, labeled vertical strip - not a row-sized box, since columnMap only ever
stores an [x0, x1] range, no vertical extent, so a full-height strip is the
honest representation of "this column," not a guess at a specific row), Test (a
real, unsaved dry run of /api/process against any of the user's own documents),
Version history + Roll back (creates a NEW version copying an old one's fields -
history stays append-only, per layoutMappingVersions' own locked rules - rather
than editing a past version in place), and Retire.
One deliberate scope deviation, decided during implementation: the plan's own
"Edit (reopens ManualMappingView pre-populated)" was dropped - columnMap has no
page/vertical position persisted at all (only [x0, x1], by design), so there's no
real data to faithfully re-populate a visual drag UI with. Inspect + version
history + rollback cover the real underlying need (see what's mapped, see what
changed, revert a bad change) without faking a "move this box" interaction with no
real position behind it.
Drift detection now also runs on every RECHECK, not just the original
extraction - useRowEditing.js's saveEdit() and TransactionRow.vue's
persistAndRecheck() both now call layoutMappingsService.recordUsage() too
(the checksPassed() helper moved from being useBatchExtraction.js's own
private copy to a shared export, so there's one definition, not three). This
required extending extractionStore.addDocument()/useDocuments.js/
useBatchExtraction.js to actually carry layoutMappingUsed/
layoutMappingVersionUsed onto the IN-MEMORY document, not just the PocketBase
record - L.6 had already saved these fields to PocketBase, but a later recheck had
no way to read them back off the Pinia object itself.
Two more real bugs, found by this stage's own end-to-end testing, in the exact same category as L.6's zone-padding fix - something computed correctly for ONE session but never actually persisted for a FUTURE auto-apply:
startPageitself was never saved anywhere.ManualMappingView.vuecomputed it correctly for that session's own Preview/Save, butcreateMapping/createVersionnever included it in what got written - meaning every future auto-applied use of a saved mapping would have silently defaulted back to page 1, reintroducing the exact cover-page bug L.2 had already found and fixed once, just one layer further up the stack. Fixed with a newstartPagefield on bothlayoutMappingsandlayoutMappingVersions(pb_migrations/ 7_add_layout_mapping_start_page.js).- A second, more consequential gap surfaced immediately after fixing the first:
start_pagealone only skips WHOLE pages before the real table - it does nothing about the real header ROW TEXT still sitting at the top of the start page itself. Confirmed for real with a 2-page synthetic test statement (a pure cover page, then the real table with its own unrecognized header on page 2): even withstart_pagecorrectly set, the header line on page 2 merged straight into the first transaction's own description - a forced mapping has noheader_topof its own the way the auto-detected path always does. This would have corrupted essentially EVERY real manually-mapped statement, not an edge case - the header row inevitably sits on the same page as the data a user draws boxes over. Fixed with a newheader_bottomparameter intable_extract.py(persisted asheaderBottom,pb_migrations/ 8_add_layout_mapping_header_bottom.js) - inferred as the topmost edge of whatever regions the user drew ON the start page, minus the same small_FORCED_ZONE_PADDINGmargin already used forx0/x1, so the exclusion boundary can never accidentally swallow the real first row it exists to protect.
Verified, all real, against the real rebuilt container - 23 + 5 assertions
across two separate test scripts, both executing the actual services/composables,
never reimplementations: a hand-built 2-page synthetic statement confirmed BOTH
bugs were real before their fixes (cover-page corruption with no startPage;
header-row corruption with startPage alone but no headerBottom), then confirmed
both fixed together; the saved mapping persists both new fields; a second,
completely independent upload of the identical file auto-applies the saved mapping
with both fields carried through, producing the correct 3 transactions;
sourceDocument is correctly backfilled right after save (what Inspect reads);
listVersions/rollbackToVersion correctly create a NEW third version rather than
editing history in place, and correctly restore the original, good column range;
retire() correctly excludes a mapping from findByFingerprintHash; a THIRD
independent user creating an equivalent mapping correctly promotes both it and an
earlier independent user's own mapping to shared via the real hook, instantly
visible to a completely unrelated fourth user. A separate, focused test confirmed
the drift-detection wiring itself: editing a row through the REAL useRowEditing .js::saveEdit() on a mapping-sourced document, deliberately breaking the running-
balance chain, correctly triggers a real /api/recheck, which correctly calls the
real recordUsage(), which correctly flips the real, persisted mapping record to
stale with failureCount: 1. backend/measure.py byte-identical throughout;
npm run build passes; every new icon class confirmed present in the installed
FontAwesome set before use. Not machine-verified: the actual List/Inspect/
Test/Retire UI click-through in a real browser - same standing limitation as
every other UI stage this session.
L.8 shipped 2026-10-15: the superuser review screen - the final stage, this
completes the full L.1-L.8 layout mapper plan. New
frontend/src/views/AdminLayoutReviewView.vue, routed at /admin/layouts, and a
new check in App.vue (route.path.startsWith('/admin'), checked FIRST, ahead
of the normal authStore.isAuthenticated gate) that renders that route's own
<RouterView> directly - no AppHeader/ProjectSidebar/AppFooter/LoginView
at all. Deliberate: a real PocketBase superuser lives in the separate
_superusers auth collection, not users - there is no "logged in as the app"
state for this screen to share or be gated by. The view has its own tiny inline
login form against pbAdmin.collection('_superusers').authWithPassword(...)
(adminLayoutsService.login()), authenticating on pbAdmin
(pocketbaseAdminRepository.js, already built in L.4) - entirely independent of
the app user's own pb.authStore on the same machine.
Once signed in, adminLayoutsService.listPending() lists every status = "private" mapping across EVERY owner in one call - no per-user filtering code
needed anywhere, since a real superuser session bypasses every PocketBase
collection rule automatically (confirmed, not assumed: the same listRule that
restricts an ordinary user to owner = @request.auth.id || status = "shared"
simply doesn't apply to a _superusers session). Each row expands into the same
Inspect pattern L.7's LayoutsView.vue already established - a read-only
SourceDocumentPanel with every columnMap field drawn as a labeled, full-height
vertical strip, plus dateFormat/signConvention/ignoredRowRules as plain
text - except the source document and file URL are resolved through two NEW
adminLayoutsService.js functions, getSourceDocument()/sourceFileUrl(),
both routed through pbAdmin rather than documentsService.js's own pb-backed
versions: the mapping's sourceDocument record belongs to its owner, not the
superuser, so the app user's own client (which may not even be logged in on this
machine at all) could never fetch it - only a real superuser session can, the
same rule-bypass reasoning as listPending(). Approve calls
adminLayoutsService.approve(id) (built in L.4 already) - sets status: "shared", promotedReason: "superuser_approved", approvedBySuperuser: <the real superuser's own email>, promotedAt: now - behind the same ConfirmModal
pattern every other consequential action in this app already uses.
No backend Python was touched this stage - this is the one layout-mapper stage
that is pure frontend routing/UI over infrastructure (fingerprinting, the schema,
the hook, pbAdmin, listPending/approve) every earlier stage already built
and proved correct.
Verified, all real, against the real rebuilt container - a hand-written Node
script executing the ACTUAL, already-committed service files (never
reimplementations: authService.js, documentsService.js,
layoutMappingsService.js, adminLayoutsService.js, both real pb/pbAdmin
client instances), 15 assertions, using the real superuser credentials already
configured via pocketbase/configure-secrets.sh: signed up a fresh app user,
saved a real source document (a real file upload, not a stub), created a
still-private mapping pointing at it; signed in as the real superuser and
confirmed listPending() surfaces that mapping; confirmed
getSourceDocument()/sourceFileUrl() fetch the owner-only document record and
its real file bytes - compared byte-for-byte against the original upload, not
just "the request succeeded"; called approve() and confirmed on the
RE-FETCHED, persisted record (not the update call's own echoed response) that
status/promotedReason/approvedBySuperuser/promotedAt are all correct, and
that the mapping no longer appears in a fresh listPending() call; signed the
superuser out and confirmed the session actually cleared; then signed up a
COMPLETELY independent third-party user and confirmed findByFingerprintHash
resolves the now-shared mapping for them immediately - proving this promotion
path works entirely on its own, independent of L.3's two-different-owner hook
path. All 15 assertions passed on the first run. Test data (the mapping, the
document, both signed-up users and their auto-created default projects) was
deleted from the real running PocketBase afterward via direct superuser REST
calls, in dependency order (mapping → document → each user's own default
project → the user), so none of it lingers as real app data.
npm run build passes; every icon class used (fa-user-shield,
fa-right-to-bracket, fa-right-from-bracket, fa-chevron-down/-right,
fa-spinner, fa-check, fa-circle-info) confirmed present in the installed
FontAwesome set before use; the app container was rebuilt and is serving the
new bundle. backend/measure.py was not re-run this stage - zero backend Python
was touched, so the standing per-stage rule (re-run after any change to
table_extract.py/extraction_service.py/pipeline_service.py) doesn't apply
here; git status confirms the only modified/new files this stage are
App.vue, router/index.js, main.css, adminLayoutsService.js, and the new
AdminLayoutReviewView.vue. Not machine-verified: the actual login form,
the expand/Inspect click-through, and the Approve confirm modal in a real
browser - same standing limitation as every other UI-only stage this session.
This closes out the full layout mapper plan (L.1-L.8). What started as one real bug report (a never-seen Equals Money statement failing extraction) now has a complete four-tier pipeline - keyword/geometry auto-detection, a code-based quirks module for mechanical oddities, fingerprint-based auto-apply with drift detection, and a manual mapping screen as the true last resort - plus a shared library two independent users' matching mappings promote into automatically, or a real PocketBase superuser can push there directly after reviewing it against the actual source document.
A real new-statement bug ("No opening and/or closing balance available"), traced to a money-format gap, then generalized into a standing fail-safe for ANY currency-wrapping format after a design discussion with the user - 2026-10-30, three stages in one day.
Stage 1 - the immediate bug. A user-uploaded EQUALS - CAD.pdf (a
CAD-denominated Equals Money account - the same product L.1's USD fixture
already generalized for) extracted ZERO transactions - page_reports showed
pdfplumber_count: 0 AND docling_count: 0, status: "ok" (both engines
"agreeing" on nothing, which is why this returned a plain 200 with
status: "Needs review" rather than erroring, and why the user's own "it
failed" report initially looked like nothing more than the ordinary, already-
documented "no printed balance" banner). Root cause, confirmed by retrieving
the user's actual uploaded file from PocketBase/R2 (via the superuser's own
file API, the same access pattern L.8's review screen already uses) and
running table_extract.extract_pdf() against it directly, not guessed from
the symptom: this statement prints every amount as "CA$386.01" - a 2-letter
currency-code prefix immediately before the $ - which _MONEY_RE (bare $
only) didn't recognize at all, so every amount fell through to plain
narrative text. First fix: widened _MONEY_RE itself to
^-?(?:[A-Z]{1,3}\$|\$)?[\d,]+\.\d{2}$ - letters accepted only when a literal
$ immediately follows (a broader letters-with-no-required-$ draft was
tried and rejected first, since it would also match a plain reference code
like "REF123.45" as money).
Stage 2 - a design conversation, not an immediate build. The user asked
whether this class of bug (new statement, new money format, silent failure
needing a developer to notice and patch) could be caught automatically on the
FIRST run - initially framed as an AI-assisted idea ("use Claude to see what
the engine expects and extract just that"). Talked through why handing this to
an LLM is the wrong fit for THIS specific codebase: it would introduce
non-determinism into a pipeline whose own measure.py regression harness
depends on determinism, and - more concretely - this exact statement's own
currency-exchange footnotes ("1 CAD = 1.0000 CAD") are also digit-plus-
decimal-plus-currency-text without being money, so an AI asked to "find
whatever looks like it's missing" would have to make the same judgment call a
human would, with a wrong guess producing a plausible-looking WRONG number
instead of a loud failure. Agreed instead on a fully deterministic
zone-scoped fallback: generalize _MONEY_RE's own narrow, one-prefix-at-a-time
fix into a standing rule that recognizes ANY currency-wrapped amount via
Unicode's own currency-symbol category, confined to columns the engine has
already geometrically proven are money columns.
Stage 3 - the general fallback, and the real regression it introduced
before shipping. Reverted _MONEY_RE back to its original bare-$-only
form and built a new _parse_money()/_money_value() pair: tries the exact
_MONEY_RE format first, then falls back to finding the one clean
[digits].[2 digits] amount in a word and requiring every OTHER character to
be either an uppercase letter or a real Unicode currency symbol (category
"Sc" - $, £, €, ¥, ₦, ₹, ₩, and effectively every other real
symbol, not a hand-maintained list), with at least one actual symbol present
- so
"REF123.45"(letters, no symbol) still correctly fails, while"CA$386.01","£386.01","-CA$50.00"etc. all correctly pass. The core regex's own trailing-digit lookahead ((?!\d)) keeps a 4-decimal exchange ratio like"1.0000"from being misread as a 2-decimal amount via its first two digits.
This alone reintroduced a real phantom-transaction bug, caught by
re-testing the ALREADY-FIXED Equals Money USD statement (L.1's own fixture)
before this ever shipped: 37 transactions instead of the documented 36, with
a broken running-balance chain. Root cause: that statement's own currency-
exchange footnotes print the CONVERTED foreign-currency amount right next to
the rate ("1 USD = 0.7104 GBP • £964.58") - a genuinely well-formed £ amount,
now correctly recognized as money shape-wise, but NOT this ledger's own money.
Because this bank's narrative continuation lines span the FULL page width
(confirmed by inspecting the real word positions), that £ token's x-position
happened to fall inside the already-resolved money column's zone purely by
coincidence of layout, and "a row is a txn if ANY money field has a value"
(table_extract.py's own existing, unrelated rule) promoted that whole
narrative line into a phantom extra transaction. Zone-scoping by x-position
alone, it turns out, isn't sufficient on this specific layout.
Fixed by adding a dominant-marker gate: _dominant_money_marker() scans
every money-shaped word on a page and tallies each one's own "marker" (the
non-numeric wrapper - "", "$", "CA$", "£", etc.), and _money_value()
now only accepts the FALLBACK path (not the strict one) when a word's own
marker matches whichever marker is most common on that page - a real
statement's own transaction amounts use the same marker dozens of times over;
a one-off foreign marker (a currency-conversion annotation) is what marks
itself as NOT the ledger's own money. This is computed once in _find_zones
(stashed into zones["_native_marker"], same pattern as the existing
_debit_self_signed flag) and threaded through to all three call sites that
used to test _MONEY_RE.match() directly - the zone-discovery clustering
step, the debit-self-signed check, and _classify_money itself - so the gate
applies everywhere a money-shaped word could ever influence the result, not
just final value extraction.
Verified, all real, across all three stages: 19 direct _money_value()
assertions (CA$/£/€/¥/₦/₹, negative amounts, trailing symbols, and the
"REF123.45"/"USD386.01"/"1.0000"/"A1B2.34" false-positive rejections).
The REGRESSION itself was confirmed real before fixing it (37 txns, broken
balance chain) by running the exact pre-dominant-marker code against the real
USD fixture, then confirmed fixed (36 txns, every running balance correct,
statement_balance/running_balance/date_sanity/structure_sanity all
pass via a real /api/process call) after adding the gate. The ORIGINAL CAD
bug was re-verified too - the original uploaded file's own PocketBase record
had since been deleted, so a hand-built synthetic PDF replicating its exact
text/structure ("CA$"-prefixed amounts, no other currency present) was run
through the real _find_zones()/extract_pdf() directly, confirming
_native_marker resolves to "CA$" and the real transaction rows classify
with the correct running-balance values. backend/measure.py re-run against
the full HSBC/RBC fixture corpus after every stage, byte-identical to the
documented baseline throughout (field accuracy 1.0, same statuses, same
transaction counts) - RBC's own CAD-denominated fixture doesn't use a
currency-code prefix at all, so it was never affected either way. The app
container was rebuilt from each stage of this change (backend edits - no hot
reload).
"Show on source" extended to every row's own click, not just the flag panel's
dedicated button, 2026-10-30. Previously this highlight (R.1's source_bbox/
showHighlight, R.2's "Show on source" button) was only reachable by opening a
flagged row's flag-detail panel first - an unflagged row (the common case on most
statements) had no way to see its own position on the source document at all.
TransactionRow.vue now calls the same showOnSource() on a click anywhere in the
row OUTSIDE its own .row-actions cell (handleRowClick) - clicking Edit/Save/
Cancel/the flag toggle/the "more actions" menu all keep their exact existing
behavior, since those live inside .row-actions and are excluded by that same
check. A no-op for a row with no real source_bbox (an OCR-sourced row), same as
the existing button's own disabled state. tr.has-position td:not(.row-actions)
(main.css) gives the clickable area cursor:pointer plus a title tooltip.
Deliberately did NOT touch toggleFlags()'s own uiStore.clearHighlightRequest()
call (fires when the flag-detail panel closes) - that click originates on the
flag-toggle button, which lives inside .row-actions, so handleRowClick's guard
already excludes it; the two behaviors don't collide.
Verified: npm run build passes; the built bundle confirmed to contain the new
has-position/handleRowClick-driven title string ("Click to highlight this row on the source document"); the app container rebuilt and the new bundle confirmed
served at /. No backend Python was touched - this is pure frontend presentation
over position data R.1 already captures - so backend/measure.py doesn't apply
(the standing per-stage rule only covers changes to table_extract.py/
extraction_service.py/pipeline_service.py); git status confirms the only
files touched are TransactionRow.vue and main.css. Not machine-verified:
the actual click-through in a real browser - same standing limitation as every
other UI-only change this project.
Transactions column reordered to align with Source Document; "Move to project" and the Flagged/Hide-Source buttons landed in a new row above the balance fields, 2026-10-30 (went through two passes - see below for what the first pass got wrong). Explicit layout request: the "Transactions" heading sat BELOW two other rows (the Results/DocumentNavBar/Accept/Download top bar, then "Move to project" on its own standalone row), while the sibling panel's "Source Document" heading was the very first thing in ITS column - the two headings never lined up horizontally.
First pass moved .txn-col-head to be the column's first element (so it aligns
with .pdf-col-head, already first in its own column - both are first children of
sibling columns under .review-grid's align-items:start, so no new CSS was needed
for the alignment itself) and dropped "Move to project" INTO that same heading row,
alongside Flagged only/Next flagged/Hide Source Doc. The user corrected this:
"Move to project" was meant to move DOWN, not up - staying at the LEFT, in a new row
of its own directly above the balance fields, with Flagged only/Next flagged/Hide
Source Doc joining it on that SAME row but right-aligned - leaving the Transactions
heading with no actions beside it at all, matching Source Document's own heading
even more closely (just the h2, nothing else).
Fixed: .txn-col-head is now just <h2>Transactions</h2>, nothing else. A new
.txn-actions-row (justify-content:space-between) sits directly above
.fields-row, with "Move to project" as its left child and a new .txn-actions-right
wrapper (Flagged only/Next flagged/Hide Source Doc) as its right child - replacing
the old .txn-col-head-actions class entirely (confirmed removed, not just
unreferenced - grepped for it after the edit). .txn-top-bar (Results/DocumentNavBar/
Accept/Download) stays second, between the heading and the new actions row, since the
user's correction didn't ask to move it again. One real slip during the first pass'
own edit, caught and fixed before ever building: moving the .txn-top-bar block up
left a stale, now-duplicate copy of that exact block still sitting further down the
file (right after the move ConfirmModal) - caught by grepping the file for
class="txn-top-bar" and DownloadChoiceModal after the edit and finding 2 and 4
hits respectively where exactly 1 and 2 (1 real + 1 import/usage) were expected;
removed the duplicate before it ever reached a build.
Verified: npm run build passes both passes; after the correction, grepped the
component for txn-top-bar/DownloadChoiceModal/move-to-project/txn-col-head/
txn-actions-row to confirm exactly one real occurrence of each (catching the
duplicate above); the app container rebuilt each time, and the served bundle
hash-matched against the local build output and confirmed to contain txn-actions-row/
txn-actions-right while txn-col-head-actions no longer appears anywhere. No
backend touched - pure template reordering + CSS, so backend/measure.py doesn't
apply.
Third pass, same day: the two headings were still a few pixels off vertically.
Root cause, reasoned through rather than guessed at a pixel offset: .pdf-col-head
is align-items:center with the zoom-control buttons (26px tall, the tallest thing
that can appear in that row) as a sibling, so "Source Document" sits vertically
CENTERED within a 26px-tall row, a few px below the row's own top edge. Once
.txn-col-head's own actions moved out (the second-pass fix above), that row had
NOTHING but its own h2 left in it - its height collapsed to the h2's own shorter
line-box, with no centering offset at all, so "Transactions" sat flush at the row's
top while "Source Document" sat a few px lower. Fixed with min-height:26px on
BOTH .pdf-col-head and .txn-col-head (not just the one that looked wrong) -
guarantees the same row height, and therefore the same centered text position, in
EVERY state, including before any file is even loaded (when .pdf-col-head's own
zoom controls aren't rendered yet either, v-if="previewUrl" - without this fix on
both sides, the two headings would have realigned differently depending on whether
a document was loaded, not just whether Transactions had actions beside it).
Verified: npm run build passes; the app container rebuilt, and the served CSS
bundle (hash-matched against the local build) confirmed to contain both new
min-height:26px rules. Not machine-verified: the actual rendered alignment in
a real browser - Claude-in-Chrome still did not connect (tried a third time) - same
standing limitation as every other UI-only change in this project.
Value-pattern mapping, backend half, 2026-10-30/31 - a new, narrower layout-mapper
tier: let a user teach the extractor to clean a raw value it can't parse, without
drawing a single column region. Follows directly from the currency-marker work
above: that fix is a good general safety net, but can never cover every future
format a new bank might print. Discussed an AI-assisted alternative with the user
and ruled it out for this pipeline specifically (non-determinism breaks
measure.py's own regression harness; a plausible-looking wrong guess from an LLM is
worse than today's loud failure). Landed on the user's own proposal instead: when the
engine finds a column's raw text but can't turn it into a value, show one
representative row's raw text per field, let the user type the corrected value,
derive a reusable strip-prefix/suffix rule from the diff, verify it against the whole
statement via the existing Preview mechanism, and save it as a mapping - reusing the
L.1-L.8 fingerprint/exact-match/near-match/versioning/sharing infrastructure outright
rather than building a second one. Full plan at
/Users/jason/.claude/plans/witty-inventing-walrus.md.
A real, pre-existing silent gap closed as part of this: a statement whose header
labels resolve fine but whose every value fails to parse (exactly the CAD bug's own
failure mode) does NOT trigger LayoutMappingRequired today - that exception's own
trigger (not any(pages_rows.values())) only fires when a page produces ZERO rows of
ANY kind; a page full of narrative-only rows (header found, no money recognized) is
non-empty, so this fell straight through to an ordinary 200 with transactions: []
and no error at all. New extraction_service.ValueRecognitionRequired (a
LayoutMappingRequired sibling) closes this: raised when pages_rows is non-empty
but zero rows are type == "txn" across every page, carrying one representative
candidate row (table_extract.value_recognition_preview(), built on the existing
header_candidate_geometry()) for the frontend to show. routes/extraction.py
catches it the same way, returning HTTP 422 with needs_value_confirmation: true +
candidateRow/fieldOrder.
A real design gap caught during PLAN REVIEW, before any code was written: a first
draft assumed _classify_money alone (stripping a learned pattern once a word's
field is known) would be enough. It wouldn't have been - _classify_money only ever
runs on a word already inside a RESOLVED zone, and money zones are resolved by
_find_zones's own clustering step, which runs on raw, unstripped text with NO field
identity known yet (field assignment happens only after clustering, via
_assign_money_columns). If the raw text defeats the existing fallback, clustering
finds nothing and no zone is ever created - a field-scoped strip pattern would never
even get a chance to run. Fixed by giving _money_value() an optional patterns list
tried at two different BREADTHS: discovery (the clustering list comprehension and
_dominant_money_marker, neither of which knows field identity yet - tried against
EVERY distinct pattern across every field, so a cluster can form at all) vs.
classification (_classify_money, which already knows the field - tried against just
that one field's own pattern, so one field's rule can never misfire on a differently-
formatted column). value_patterns threads through as a new, independent parameter
on extract_pdf()/extract_page() (composing with, not replacing, auto-detection -
confirmed by reading extract_pdf() that a forced_mapping with valuePatterns but
no columnMap already behaves identically to plain auto-detection today, since
forced_zones would be None).
A second real bug, caught by this stage's own end-to-end testing (not plan review
this time): the pattern-stripping fallback tried stripPrefix against a word's RAW
text including any leading "-", so a negative amount like "-CAD50.00" never
matched a learned stripPrefix: "CAD" pattern at all (the string literally starts
with "-", not "CAD") - every negative amount on the real synthetic test statement
that exercised this silently failed to parse (amount: null) even though the exact
same pattern worked fine on every positive one, while the running-balance numbers
themselves still happened to extract correctly (balance comes from a DIFFERENT word
than amount), making this easy to miss on a casual glance. Fixed by factoring a
shared _parse_money_with_patterns() (now the one place both _money_value and
_dominant_money_marker call) that pulls the sign off FIRST, strips the pattern from
the sign-stripped body, then re-attaches the sign before re-parsing - mirroring how
_parse_money's own strict path already separates the sign.
A third, found while building the first synthetic test: value_recognition_preview's
own rough, label-anchored fallback zone (used only when real clustering found
nothing, purely to show the user something to correct) first used the OPPOSITE
asymmetry from the real clustered zones' own convention - (anchor[0]-5, anchor[1]+60) instead of mirroring _find_zones' own (cmin-80, cmax+5) - and bled
into the very next column's own values on a real test (a right-aligned numeric
column's data starts well LEFT of its header label, essentially never further
right). Fixed to (anchor[0]-60, anchor[1]+5), matching the real convention's own
asymmetry.
Verified, all real: a hand-built synthetic statement using a bare 3-letter
currency code with NO symbol at all ("CAD50.00") - confirmed by direct test that
this genuinely defeats the existing Unicode-symbol fallback (_money_value already
correctly requires a real symbol, not letters alone, to reject "REF123.45"-style
false positives) - correctly triggers ValueRecognitionRequired with an accurate
candidateRow through a real /api/process call (HTTP 422). The same file, POSTed
with a hand-assembled {valuePatterns: {amount: {stripPrefix: "CAD"}, balance: {stripPrefix: "CAD"}}} and NO columnMap at all, now correctly extracts all 3
transactions with the right signs/balances and passes statement_balance/
running_balance/date_sanity/structure_sanity/page_coverage - proving the
discovery-breadth fix actually lets clustering succeed (confirmed this is genuinely
new: the exact same file with only the classification-breadth fix, no discovery fix,
still produced zero transactions). The earlier CA$/currency-symbol fixture
(19 direct _money_value assertions) and the real Equals Money USD statement's own
phantom-37th-transaction regression test (both from the currency-marker work above)
were re-run after this refactor and are still byte-identical/correct - confirming
this stage's restructuring of _classify_money/_money_value didn't regress either
earlier fix. backend/measure.py re-run against the full HSBC/RBC fixture corpus,
byte-identical to the documented baseline throughout every fix in this stage. One
operational note, already known but reconfirmed the hard way: docker cp-ing a fix
into the running container does NOT make the already-running Flask process reload it
- a real rebuild (
docker compose up --build -d app) is required, and skipping that step produced a confusing false negative mid-debugging (the direct Python checks via freshdocker compose execprocesses picked up the fix correctly while the HTTP route, served by the long-running process, still ran the old code) before being caught and corrected.
Value-pattern mapping, frontend half, 2026-10-31 - this closes out the plan
(/Users/jason/.claude/plans/witty-inventing-walrus.md). useBatchExtraction.js
gains an else if (result.needs_value_confirmation) branch, parallel to the
existing needs_mapping one - calls the SAME resolveNeedsMapping() first (it's
already agnostic to WHY a fingerprint needed resolving, so a value-pattern mapping
someone else already saved auto-applies or asks for confirmation exactly like a full
one does), differing only on reason: 'no_match': a new
layoutMapperStore.setPendingValueConfirmation(file, fingerprint, fingerprintHash, candidateRow, fieldOrder) (sibling state to the existing setPending, never both at
once - their backend triggers are mutually exclusive). ManualMappingView.vue tells
the two modes apart purely by whether pendingCandidateRow is set, swapping the
"Assign columns" region-drawing card for a "Confirm values" one: one row per field
(every field shown, not just the broken ones, per explicit product direction) with
the raw text as read, an editable correction defaulting to it, and an inline error
per field. forcedMapping in this mode is {valuePatterns} alone - no columnMap
at all, since that's what lets the backend's own auto-detector resolve everything
else (see the backend-half entry above).
Two more real bugs, both caught by this stage's own end-to-end testing before anything shipped (not by plan review this time - the plan itself didn't anticipate either):
hasRequiredShape(region-drawing mode's own Preview/Save gate) is derived fromcolumnMap, which stays{}for the WHOLE value-confirmation mode (there's no region-drawing there at all) - using it directly would have permanently disabled Preview the moment this mode existed, with no way to ever enable it. This one WAS flagged during plan review, fixed with a new unifiedcanPreviewcomputed (allValuesValidin value-confirmation mode,hasRequiredShapeotherwise) before any code was written - included here for completeness since it's the same category of gate-coverage bug as the next one, which review did NOT catch.- The frontend's own validation (
fieldError) and pattern-derivation (valuePatterns) both did a plainraw.includes(corrected)/raw.indexOf(corrected)substring check on the FULL text, sign included - the exact same class of bug already found and fixed on the BACKEND earlier the same day (_parse_money_with_patterns), reintroduced independently on the frontend side because the two implementations don't share code. Confirmed for real: correcting"-CAD50.00"to"-50.00"failed validation outright ("-50.00"isn't a contiguous substring of"-CAD50.00"-"CAD"sits between the sign and the digits), meaning a negative row could never be corrected at all while keeping its own sign. Fixed with abodyOf(text)helper (strips a leading"-"before the substring/diff logic, mirroring the backend's own_parse_money_with_patternsexactly) used by bothfieldErrorandvaluePatterns.
PocketBase/Inspect additions: LayoutsView.vue's own SEPARATE
forcedMappingFor() (used by its "Test" feature, a near-identical but independent
copy of useLayoutMapping.js's own - flagged during plan review as an easy-to-miss
second call site) gained the same valuePatterns key - without it, testing a saved
value-pattern mapping from the Layouts page would have silently run plain
auto-detection instead of actually exercising the saved correction. Inspect gained a
v-else ("this mapping only cleans values - no column positions recorded") for the
now-possible empty columnMap, and a new "Value corrections" card showing
mapping.valuePatterns itself (field + its stripped prefix/suffix) - previously
there was nowhere in this app that displayed the actual cleanup rule a mapping like
this exists to save.
Verified, all real, end to end, against the real running stack - a hand-written
Node script executing the ACTUAL service/composable files (never reimplementations:
authService.js, extractionService.js, documentsService.js,
layoutMappingsService.js, useLayoutMapping.js, adminLayoutsService.js), plus
ManualMappingView.vue's own validation/derivation logic verified byte-identical
against a standalone copy before testing it (17 direct assertions, including the
sign-bug case) - 19 further end-to-end assertions covering the FULL loop: a fresh
user's upload triggers needs_value_confirmation with a real, correct candidateRow;
the user's simulated correction ("-CAD50.00" → "-50.00") derives
{stripPrefix: "CAD"} for both money fields; Preview with ONLY valuePatterns (no
columnMap) correctly extracts all 3 real transactions and passes
running_balance; the mapping saves with columnMap: {} (confirming the relaxed
schema accepts it) and persists valuePatterns; the real PocketBase superuser signs
in, sees the still-private mapping in listPending() (confirming L.8's review
screen - built before this feature existed - already handles a mapping with no
columns to draw boxes over, with zero changes needed there), and approves it; a
COMPLETELY independent third-party user's own resolveNeedsMapping() then finds it
via exact fingerprint match, carries valuePatterns through, and re-applying that
resolved mapping to the same statement (simulating an unrelated fresh upload)
extracts all 3 transactions correctly again. All 19 assertions passed after both
real bugs above were fixed. npm run build passes; the served bundle (hash-matched
against the local build) confirmed to contain the new UI strings/CSS classes.
backend/measure.py re-run against the full fixture corpus, byte-identical to
baseline (no backend touched this half). Test data (mapping, version, document, both
users and their default projects) deleted from the real PocketBase afterward, in the
correct dependency order (version → mapping → document → project → user - confirmed
by testing, not assumed: deleting a mapping before its own version record, or a user
before their mapping, both correctly fail PocketBase's own required-relation check).
Not machine-verified: the actual click-through - typing into the correction
inputs, the inline errors appearing live, Preview/Save enabling - Claude-in-Chrome
still did not connect this session.
Transaction categorization, shipped 2026-10-31 - a deliberate scope expansion past
this product's own original "does not categorize transactions" boundary (see the
updated "What this is" note at the top of this file). The user asked to review
docs/bank_statement_categorizer/ - legacy categorization code ported from the
sibling eib-processor platform, placed in this repo purely as reference material,
never wired into this app's own backend/app.py - and propose how to bring real
categorization into this product, floating their own UI idea: Transactions as one tab,
Categorization as a second, switchable tab right beside it.
What the review found, and why none of the legacy code was reused as-is:
- The legacy parser (
parse_rbc_statement, hardcodedDEBIT_ZONE/CREDIT_ZONE/BALANCE_ZONEpixel ranges, RBC-only) duplicates what this app's owntable_extract.pyalready does far more robustly (bank-agnostic, dual-engine, six checks, the whole layout-mapper/value-pattern stack). Categorization here categorizes thetransactionsthis app has already extracted and verified - no second PDF pass, ever. - The legacy matching logic (
common.match_description_rule) is a black box - the sharedcommon.pymodule it imports doesn't exist anywhere in this repo at all (confirmed viafind . -iname "common.py", empty). Its behavior was inferable from the sampledescription_rules.csv(a dozen differently-suffixed "Misc Payment MC FEE..." lines all collapsing to one rule keyed on a short pattern) and from the user's own direct clarification during planning: matching is plain substring-in- description text. Reimplemented transparently rather than guessing at the missing module's exact internals. - The legacy rule storage (a flat CSV, no per-client separation) is replaced by a new,
project-scoped PocketBase collection -
documents.projectwas explicitly designed back in the original PocketBase Stage B.1 work in anticipation of exactly this feature (that migration's own comment: "a future per-project category-mapping feature needs that scoping from day one"). - The legacy "unmapped → pause → confirm → resume" flow uses an in-memory
PENDING_RUNSdict, explicitly commented in the legacy code as unsafe for concurrent use. Not needed here: categorization recomputes live from whatever rules exist right now, so resolving an unmatched description just means saving a new rule and letting the UI recompute - no server-side session/token at all.
Design decisions, each made explicit rather than assumed:
- Categorization is computed live from current rules, never persisted on the
document. Rules can change after a document was extracted; recomputing on every
view/export always reflects the latest rules, and needed zero new field on
documents.resultand zero migration for document records - only the rules themselves persist. - Matching stays entirely in the frontend - same architectural split as the layout
mapper's own near-match comparator (
layoutMappingsService.scoreNearMatch, pure JS, never duplicated in Python). The frontend already holds both the extractedtransactionsand (via PocketBase) the rules; Flask only gets involved at export time, to write one additional Excel sheet, the same wayedit_logalready flows through/api/exportuntouched.categorizationRulesService.js's ownmatchDescription(description, rules)is case-insensitive substring matching, with the longest matching pattern winning when more than one rule matches - a deterministic tie-break, no fuzzy scoring. - Rules are scoped by the active DOCUMENT's own
projectfield (extractionStore.activeDocument.project), notprojectsStore.activeProjectId- the sidebar's "All" filter can be active while a specific document (which still belongs to exactly one project) is open, and it's that document's own project whose rules apply. Called out explicitly in the plan as the same category of binding bug this file already records once, for "Move to project" (result.projectvs.activeDocument.project) - not repeated here. - No reconciliation check was added. The legacy tool's own
reconciledflag is justopening + net ≈ closing; since categorizing only relabels transactions and never drops or alters amounts, this identity is already guaranteed by the extractor's ownstatement_balancecheck - re-deriving it here would be redundant, not a safety net. - Unmatched transactions are never hidden - grouped by raw description (count + total) in both the UI and the exported Excel sheet's own "Unmatched" section, which is always written even when empty, so an export with full coverage visibly shows zero unmatched rather than silently omitting the section - the same governing rule as everywhere else in this app (see below).
- Rule management is inline in the Categorization tab, not a separate routed page.
LayoutsView.vue's own List/Inspect page is the obvious model for a future dedicated rules-management screen if this ever needs one, but the inline version (a compact rules list + an inline "add rule" form, plus a per-unmatched-group "assign a category" control) covers the actual workflow with far less surface area.
What was built: a new PocketBase collection, categorizationRules
(pb_migrations/11_add_categorization_rules.js - owner/project relations,
pattern/accountingCategory text fields, rules keyed off owner directly, same
choice documents makes despite also carrying a project relation). A new
categorizationRulesService.js (CRUD + the pure matchDescription export, same
precedent layoutMappingsService.js sets with scoreNearMatch/findBestMatch). A new
useCategorization.js composable - one pass over the active document's transactions,
bucketing each into a matched-by-category group or an unmatched-by-raw-description
group, exposing rules/matched/unmatched/summaryForExport/addRule/removeRule.
A new CategorizationPanel.vue (the tab's own body). TransactionsTable.vue's own
.txn-col-head (previously a bare "Transactions" <h2>) is now a two-item
Transactions/Categorization tab switch (activeTab, a local ref, not a route) -
everything Transactions-specific (the actions row, balance fields, mismatch note, the
table itself) is wrapped in v-show="activeTab === 'transactions'" rather than v-if,
so switching tabs never loses filter/sort state or an in-progress balance-field edit;
.txn-top-bar (Results/DocumentNavBar/Accept/Download) stays visible regardless of
tab, since it's document-level chrome, not Transactions-specific. The tab buttons
themselves needed font-size:24px to match the plain, unstyled browser-default <h2>
size/weight the heading they replaced (and "Source Document"'s own heading) both
render at with no explicit font-size rule of their own - confirmed by checking that no
global h2 rule exists in main.css before picking a size, not guessed. Backend:
extraction_schema.parse_export_request passes a new categorization field through
unchanged (same discipline as edit_log); routes/extraction.py's /api/export
merges it into the result dict; excel_service._write_categorized_summary_sheet
writes it as a new "Categorized Summary" sheet, called conditionally exactly like
_write_edits_sheet. handleDownloadCurrent (the single-document download path)
passes categorization.summaryForExport.value through; handleDownloadAll (looping
every loaded document) deliberately does NOT, since the categorization composable
instance only ever exists for the ACTIVE document - a documented, accepted scope limit
rather than a silent gap, same honesty standard as every other known limitation in
this file.
Verified, all real, at every layer, following the plan's own suggested build order (schema → pure logic → backend passthrough → UI, each verified before the next was built on top of it):
- The migration applied against the real, rebuilt PocketBase container (migrations
are baked into the image at build time via
COPY pb_migrations, not volume-mounted- confirmed a plain container restart does NOT pick up a new migration file,
only
docker compose up --build -d pocketbasedoes); the real collection's schema fetched via the REST API and confirmed to match exactly.
- confirmed a plain container restart does NOT pick up a new migration file,
only
categorizationRulesService.js(the actual file, not reimplemented) executed from a plain Node script against the live container:matchDescription's longest-pattern- wins/no-match/case-insensitive behavior (pure, no PocketBase);createRule/listForProject/deleteRuleround-tripped for real; a second, independent user's own project confirmed to see zero of a first user's rules, and a query against the FIRST user's own project (from the second user's session) correctly returns an empty list rather than an error - PocketBase'slistRulefilters rather than denies, the same behavior already documented fordocuments, reconfirmed here rather than assumed to generalize.useCategorization.js(the actual composable, not reimplemented) executed directly against REAL Vue reactivity (ref/computed/watchfrom the realvuepackage, not a mock) with real PocketBase-backed rules and synthetic transactions: longest- pattern-wins correctly distinguished "Oyster Payroll" from "Oyster Payroll - Additional"; several transactions sharing identical raw description text correctly grouped into one unmatched entry with the right count/sum;summaryForExportconfirmed plain-JSON-serializable (no strayMap/Setleaking through);addRuleimmediately re-bucketed previously-unmatched rows intomatchedwith no refetch, andremoveRulecorrectly put them back.backend/measure.pyre-run against the full HSBC/RBC/Equals-Money-adjacent fixture corpus after the backend changes - byte-identical to the documented baseline (field accuracy 1.0 on all three, same statuses) - this stage touches zero extraction/check code, confirmed rather than assumed.- A real
/api/processcall against the HSBC-Sep fixture, then two real/api/exportcalls against that actual result through the rebuilt container: one with a hand- builtcategorizationpayload (confirmed the "Categorized Summary" sheet appears with the correct matched-group row, the correct "Unmatched" header + row, and accounting-formatted amounts) and one with the field omitted entirely (confirmed no such sheet is written at all) - not assumed from the code, opened withopenpyxlinside the container and read back row by row. npm run buildpasses; the built bundle hash-matched against what the rebuiltappcontainer actually serves at/(same file hash both places, not just "the build succeeded"); grepped forCategorizationPanel/txn-tab/categorizationRulesin the built JS and confirmed present.- Test data (rules, projects, users) from every verification pass deleted from the real running PocketBase afterward via direct superuser REST calls, in dependency order (categorizationRules → project → user - confirmed by testing: deleting a project while a categorizationRules record still referenced it correctly failed with PocketBase's own required-relation error, same category of ordering this file already documents for layoutMappings/documents/users).
Not machine-verified: the actual click-through - switching tabs, typing into the inline "add rule" form, watching an unmatched group recategorize live after saving a rule - Claude-in-Chrome did not connect this session, same standing limitation as every other UI-only verification in this file.
Manual "Map" button - correcting an already-successful (but wrong) extraction,
shipped 2026-11-14. A real statement extracted without throwing any error, but got
something wrong - the wrong start page/header boundary silently pulled preamble text
into the first transaction's own description, the same category of mistake L.6/L.7's
own startPage/headerBottom work exists to prevent, just not caught by the
auto-detector this time. Until now, the ENTIRE layout-mapper//map-layout screen was
only ever reachable automatically, when extraction failed outright
(LayoutMappingRequired/ValueRecognitionRequired) - there was no way for a user to
proactively open it against a statement that technically "succeeded."
The real gap this exposed: a successful extraction never computed or returned a
fingerprint at all - only the two failure paths in extraction_service.run() did.
Fixed by computing it UNCONDITIONALLY now, right after extraction succeeds (the same
table_extract.header_candidate_geometry() + layout_fingerprint.compute_fingerprint()
call the failure paths already make, not threaded through from elsewhere) - included
in every /api/process response as fingerprint/fingerprintHash, None/None for
an OCR-sourced document (no text layer to derive one from). pipeline_service.run()
passes both straight through unchanged. This is pure addition - no existing
extraction/check behavior touched, confirmed via backend/measure.py (byte-identical
to the documented baseline before and after).
The frontend side - reusing 100% of the existing L.1-L.8 machinery, not a second
screen. TransactionsTable.vue gained a "Map" button in .txn-actions-right
(first, before "Flagged only"/"Next flagged" - btn-toggle, no new CSS needed),
enabled only when the active document's own result carries a fingerprint. Clicking it:
re-fetches the document's own sourceFile from PocketBase/R2 (the raw File object
isn't kept around once a document is loaded - see extractionStore.js's own doc
shape), wraps the fetched bytes back into a File with the original filename, and
calls layoutMapperStore.setPending(file, fingerprint, fingerprintHash, documentId) -
the EXACT same action the auto-triggered failure flow already calls, just with a new
4th argument. ManualMappingView.vue needed ZERO changes to its own region-drawing
UI, Preview, or startPage/headerBottom inference - all of that already works
identically regardless of how the screen was reached.
The one real design decision this needed: Save had to behave differently
depending on how the screen was reached. The ORIGINAL flow (a failed extraction) has
no existing document to speak of, so Save correctly creates a brand new one. Reusing
that path unchanged for a document being CORRECTED would have left the user with TWO
documents - the old, wrong one still sitting there, plus a new, duplicate, correct
one - not what "correct the mapping" means from their own perspective. Fixed with a
new layoutMapperStore.pendingDocumentId (null for the normal flow, set for this
one) - ManualMappingView.vue's handleSaveMapping() branches on it: set →
documentsService.updateDocument(pendingDocumentId, {result, layoutMappingUsed, ...})
- a new
extractionStore.replaceDocumentResult(pbId, result, {...})(finds the document by id and replaces its result/layout fields/flaggedIndexes in place, rather thanaddDocument's own append); unset → the original create-a-new-document path, byte-for-byte unchanged.
Verified, all real, against the real rebuilt container - 15 assertions, executing
the actual store/service files (never reimplementations): a real /api/process
call against the RBC fixture confirmed a successful extraction now carries a genuine
fingerprint; the document was saved normally (simulating the original, already-
"successful" upload); the exact re-fetch sequence handleMapClick() itself performs
(documentsService.getDocument → sourceFileUrl → fetch → wrap as File) was
confirmed to reproduce the ORIGINAL upload's bytes exactly, byte-for-byte; the real
layoutMapperStore.setPending(...,documentId) and extractionStore .replaceDocumentResult(...) were exercised directly, confirming exactly ONE document
record exists in PocketBase after Save (not two), exactly ONE in-memory document in
extractionStore.documents (not two), and both correctly reflect the new mapping's
id - the "update in place, don't duplicate" behavior this whole design decision
exists for. backend/measure.py re-run clean after the backend half. npm run build
passes; the app container rebuilt and confirmed serving the new bundle. Test data
(mapping, version, document, project, user) deleted from the real PocketBase
afterward in dependency order (version → mapping → document → project → user).
Not machine-verified: the actual click-through - clicking Map, drawing the correcting regions, Preview, Save, and watching the SAME document update in the Transactions tab afterward rather than a new one appearing - Claude-in-Chrome did not connect this session, same standing limitation as every other UI-only feature in this file.
Two follow-up fixes to the Map button, same day: it was disabled for every real statement, and it moved into the "Move to" row.
The real bug, found by checking the live PocketBase data directly rather than
guessing: every document the user had actually loaded predates this feature's own
backend change - their stored result JSON genuinely has no fingerprint key at
all, since it was saved by a Flask process from before that change shipped. A fresh
/api/process call, confirmed directly, already returns one correctly; the button
gating on result.fingerprint being present was therefore correct in spirit but
left every pre-existing document (which is to say, everything the user had to test
with) permanently disabled with no way out short of a full re-upload.
Fixed by making the button SELF-HEAL instead of just checking for a fingerprint:
canMap now gates only on extraction_method !== 'ocr' (the one case that's
genuinely, structurally impossible - no text layer to derive a fingerprint from,
re-extracting can't fix that). handleMapClick() re-fetches the source file as
before, but if the CURRENT result has no fingerprint, it now re-runs
extractionService.process() against that same re-fetched file first - which, on
the NOW-current backend, always returns one - before proceeding into the mapper.
Verified directly: built a document whose stored result had its fingerprint
stripped out (reproducing the exact real documents found above), confirmed it
genuinely had none after a real re-fetch from PocketBase, then confirmed the same
self-heal branch handleMapClick() runs correctly recovers a real fingerprint via
re-extraction - a document extracted before this backend change is never stuck.
Moved into the same line as "Move to project," per explicit request - the
button's own .txn-actions-right slot was the wrong spot; it now lives inside
.move-to-project itself, directly after the project <select>. "Move to project"
was shortened to "Move to" to make room on that line, and .move-to-project gained
flex-wrap:wrap so a narrow column wraps internally instead of overflowing with a
fourth child now in that row.
Corrected again, same day: the button being stuck directly beside the project
dropdown wasn't what was wanted - moved back OUT to .txn-actions-right, floating
alongside Flagged only/Next flagged/Hide Source Doc as its own independent button
rather than attached to the select. Still satisfies "same line as Move to" either
way, since .txn-actions-row is one space-between flex row regardless of which side
the button lives on. .move-to-project's own flex-wrap:wrap was reverted along
with the move (back to its original 3-child shape, no longer needed); "Move to"
(shortened from "Move to project") was left as-is - reads fine on its own regardless
of where the button ended up.
Manual layout mapping for OCR-sourced statements (scanned PDFs and raw photos), shipped 2026-11-14. The "Map" button was disabled for any OCR-sourced document on the reasoning that there's "no text layer to derive a fingerprint from." The user pushed back, correctly: OCR did produce real words and positions for these documents - that's how any transactions got extracted at all - so disabling manual correction for exactly the case where OCR's own automatic table-structure guessing is LEAST reliable was backwards. A human drawing boxes over an image is strictly MORE trustworthy than an OCR model's own structural inference, not less.
What was actually missing, confirmed by reading the code rather than assumed:
extraction_service.run() checked _needs_ocr(file_path) FIRST and returned
_run_ocr_only(file_path, docling_url) immediately - before the if forced_mapping:
branch was ever reached, and _run_ocr_only() didn't even accept a forced_mapping
parameter. POSTing a forced_mapping for a file that needed OCR silently discarded
it entirely and ran plain auto-detect instead - no error, just quietly ignored.
Separately, raw_ocr_extract.py (the module that already reuses table_extract.py's
own _find_zones/_classify_money for OCR'd words) had no forced-zone parameter at
all - zone resolution there was 100% auto-derived from OCR'd header-label text
matching, with zero manual-override hook.
The frontend needed almost nothing - confirmed by research before writing any
code: useRegionDraw.js has zero PDF-specific logic (driven purely by whatever
zoomRef the caller supplies); useImageZoom.js already exposes the identical
showHighlights/highlights/boxStyle shape usePdfViewer.js does, with drawn
regions landing in the image's own natural pixel space; SourceDocumentPanel.vue
already wires regionDrawMode/region-drawn to BOTH viewers via one shared
useRegionDraw instance (page: null for a bare image, a real 1-based page number
for a scanned-but-textless PDF, which pdf.js renders identically to any other PDF);
ManualMappingView.vue's own startPage/headerBottom computeds already handle a
null page gracefully (r.page || 1). Only TransactionsTable.vue's own canMap
gate needed to change - result.extraction_method !== 'ocr' dropped entirely, now
just computed(() => !!result.value) - its existing self-heal logic (re-extract to
recover a missing fingerprint, already built for an old pre-fingerprint PDF document)
covers an OCR document exactly the same way, now that the backend can produce one.
Design decision: a forced OCR mapping bypasses Docling's table-structure call
entirely, going straight through raw_ocr_extract.py - the same module that
already stands in whenever Docling's own TableFormer recognition fails.
docling_parser.ocr_table_to_rows() operates on Docling's own row/COLUMN-INDEX grid
with no x-coordinate concept at all - structurally incompatible with the point-range
{field: (x0, x1)} zones forced_zones already is everywhere else in this app.
Building a second, parallel forced-zone mechanism for Docling's own grid shape was
never on the table; there was no reason to run TableFormer at all once the user has
already overridden its entire job.
layout_fingerprint.compute_fingerprint() needed zero changes - confirmed by
reading it closely before assuming otherwise: its own field_positions are
normalized ratios (center / page_width), unit-agnostic by construction, so it works
on OCR-derived, point-scaled words exactly as well as pdfplumber's. Only a NEW
geometry-gathering function was needed - raw_ocr_extract.header_candidate_geometry (file_path, is_image), the OCR-side equivalent of table_extract .header_candidate_geometry() (which is hard-wired to pdfplumber.open()/
page.extract_words() and can't be reused directly) - same scoring algorithm (the
page/image whose lines match the most distinct vocabulary fields wins), built on this
module's own existing word-extraction + pixel-to-point scaling. extraction_service .py gained _ocr_header_candidate_geometry() (resolves is_image the same way
_try_raw_ocr_fallback already distinguishes a real, if textless, PDF container from
a bare image file) and _ocr_fingerprint() (the OCR-side equivalent of the
fingerprint computation run() already does for the pdfplumber path) - both new
helpers, not changes to the fingerprint module itself.
_run_ocr_only(file_path, docling_url, forced_mapping=None) now branches: when
forced_mapping carries a columnMap, it skips Docling entirely and dispatches to
raw_ocr_extract.extract_pdf/.extract_image (try-as-PDF-first, same dispatch
_try_raw_ocr_fallback already uses) with the forced zones applied; when every page
comes back empty under plain auto-detect, it now raises the EXISTING
LayoutMappingRequired (no new exception type needed - its own shape was already
generic) with a real OCR-derived fingerprint, instead of a bare, unrecoverable
ValueError - a never-seen OCR statement gets the same auto-triggered "needs
mapping" banner a never-seen PDF statement already does. Every successful return
path (auto-detect success, forced-mapping success) now includes a real
fingerprint/fingerprintHash too, removing the old hardcoded None/None.
A real bug caught by this stage's own end-to-end testing, not by review:
raw_ocr_extract.extract_image() had no header_bottom parameter at all - the
reasoning that "a bare image has no page concept, so no start_page" had wrongly
also dropped header_bottom, which is a SEPARATE concept (where WITHIN the one page
to start reading, not WHICH page) that's just as necessary for a single image as for
a PDF's own start page. Confirmed for real: a forced mapping against a rasterized
version of the existing docs/unrecognized_layout_test.pdf fixture, with no
header_bottom supplied, correctly reproduced the exact same bug class this whole
mechanism exists to prevent on the pdfplumber side - the statement's own company-name/
"Opening balance" preamble text merged straight into the first transaction's
description. Fixed by adding header_bottom to extract_image()'s own signature and
threading it through from extraction_service.py's forced-mapping branch (which had
only been passing it to the extract_pdf call, not the extract_image fallback) -
confirmed fixed by re-running the identical test and getting a clean "Coffee Shop
Purchase" description instead of the whole preamble.
Verified, all real, against the real rebuilt container: the existing
docs/unrecognized_layout_test.pdf fixture (gibberish headers, 3 real transaction-
shaped rows, already proven for the PDF-based manual-mapping flow) was rasterized via
pdftoppm into both a bare PNG and a textless PDF (via PIL), covering BOTH OCR
dispatch paths (extract_image's own fallback branch, and extract_pdf's own direct
branch for a real-but-textless PDF container). A fresh, unmapped upload of either
variant correctly raised needs_mapping with a real, non-null fingerprint - and
remarkably, the IDENTICAL fingerprint hash the original vector PDF itself produces
(1e4fa05e...), confirming the ratio-based normalization genuinely makes a
fingerprint comparable across engines, not just within one - a saved mapping from a
PDF would auto-apply to a scan of the same statement, and vice versa, an unplanned
but welcome consequence of the unit-agnostic design. The SAME forced_mapping, applied
to both the PNG and the textless-PDF variant, produced identical, correct results
(3/3 transactions, correct signs/balances, running_balance and statement_balance
both passing once opening/closing balances were supplied) - confirming both dispatch
branches work identically. The pre-existing scanned-statement fixture
(docs/scanned_statement_2page.pdf) was re-run and still produces its documented
17/17 transactions with the same per-page engine attribution, now ALSO carrying a
real fingerprint where it previously carried none - confirming zero regression on
the already-working OCR auto-detect path, including the date-handling substitution
(_normalize_date_text() → normalize_date(..., date_format="textual"), confirmed
by inspection to be a guaranteed no-op change when date_format stays at its
default). backend/measure.py re-run against the full PDF fixture corpus, byte-
identical to the documented baseline throughout every stage of this work - this
touches zero pdfplumber-path code. npm run build passes; the app container
rebuilt and confirmed serving the new bundle.
Not machine-verified: the actual click-through - clicking Map on an OCR-sourced document, drawing the correcting regions over an image instead of a PDF, Preview, Save - Claude-in-Chrome did not connect this session, same standing limitation as every other UI-only feature in this file. The backend mechanism and the frontend's own already-generic region-drawing plumbing are both independently confirmed correct; only their actual connection through a real mouse drag is unverified.
Per-document mapping queue for batch uploads, shipped 2026-11-15 - fixes a real
reported bug where mapping the first of several needs-mapping statements made the
rest vanish with no way back. The auto-triggered mapping flow (needs_mapping/
needs_value_confirmation) held its "statement waiting to be mapped" state in
layoutMapperStore's own pendingFile/pendingFingerprint/etc - a single slot,
by original design (see that store's own prior docstring: "mapping them one at a
time... is the simpler, honest v1 behavior"). The user correctly pushed back on
that tradeoff once it actually hit them: uploading several statements at once where
MORE THAN ONE needed manual mapping meant every useBatchExtraction.js call for a
needs-mapping file overwrote that single slot - only whichever statement happened
to be there when the user clicked "Map it now" was ever reachable; once that one
was saved and the slot cleared, every other needs-mapping statement in the same
batch was gone, with nothing in the UI even hinting one had ever existed. The
user's own proposed fix was explicit: stop surfacing a single global "Map now"
button under the upload area at all, and instead let each needs-mapping statement
stay visible in the document queue (so DocumentNavBar's prev/next already reaches
it), with the actual "map this" reminder + button shown in the Transactions panel
for whichever one is currently active - "that seems like the simplest approach
instead of building some other queue logic after the extraction stage."
Implemented close to literally that, not a bigger queue abstraction. The
"queue" is just the EXISTING extractionStore.documents array - no new store, no
new list. Each needs-mapping file in a batch becomes a PLACEHOLDER document there
(extractionStore.addPendingMappingDocument()) with result: null and a new
pendingMapping field ({file, fingerprint, fingerprintHash, needsValueConfirmation, candidateRow, fieldOrder}) carrying everything needed to
launch the mapper later - the raw File object included, since (same as the old
single-slot design) it can never be persisted anywhere until the user actually
maps it. useBatchExtraction.js's own reason === 'no_match' branches (both the
needs_mapping and needs_value_confirmation ones) now call this instead of
layoutMapperStore.setPending(...), and no longer push the file into the batch's
own failures list either - a statement waiting on manual mapping isn't a
failure, it's queued work, and reporting it as an error alongside genuine extraction
failures would have been misleading now that it's actually recoverable.
layoutMapperStore itself shrank in scope rather than growing - it's now purely
the short-lived bridge across ONE /map-layout navigation (set right before the
screen opens, cleared when it's done), never where "which statements need mapping"
lives. It gained one new field, pendingDocKey, set when the mapper was launched
from a queued placeholder (as opposed to the existing pendingDocumentId, used
when correcting an already-successful document via the separate "Map" button) -
ManualMappingView.vue's handleSaveMapping() checks pendingDocKey to decide
whether to call the new extractionStore.replacePendingMappingDocument() (replaces
the placeholder's own queue slot IN PLACE, preserving the user's position while
cycling through several queued statements) instead of addDocument()'s normal
append-a-new-document path.
ExtractorView.vue's banner under the upload area is now purely informational - a
count ("N statements need manual mapping...") with no button at all, per the
user's own explicit ask to move the action, not just relocate the button text.
TransactionsTable.vue gained the actual trigger: its existing !result empty-
state branches on whether the active document's own pendingMapping is set,
showing a reminder + "Map now" button scoped to THAT document when it is (a NEW
handleMapPendingClick(), distinct from the existing "Map" button/handleMapClick
which corrects an already-SUCCESSFUL extraction and needs to re-fetch its source
file from PocketBase/R2 - a placeholder's file is already sitting in memory on
pendingMapping.file, nothing to fetch).
One real gap caught while implementing this, before it ever shipped: a
placeholder document has no pbId (nothing was ever saved for it), but
DocumentNavBar.vue's rename/delete unconditionally called
documentsService.updateDocument(doc.pbId, ...)/deleteDocument(doc.pbId) -
clicking either on a placeholder would have PATCHed/DELETEd PocketBase record id
null, not crashed outright (caught by the existing try/catch) but silently
wrong. Fixed by guarding both on doc.pbId being truthy: a placeholder renames
purely in-memory (extractionStore.setActiveDocumentFileName, no remote call),
and deletes via a new extractionStore.removePendingMappingDocument(docKey) (looked
up by docKey, the one stable identifier a placeholder actually has) rather than
removeDocument(pbId). Factored the shared splice-and-resettle-activeIndex logic
both deletion paths need into one private _removeDocumentAt(idx) helper, rather
than duplicating it a third time.
Verified: npm run build passes; the built bundle confirmed to contain the new
store action/property names (addPendingMappingDocument,
replacePendingMappingDocument, removePendingMappingDocument, pendingDocKey).
Not machine-verified: the actual click-through - uploading a batch where more than
one statement needs mapping, cycling between the resulting placeholders via
DocumentNavBar, mapping each one in turn and confirming the others stay reachable
throughout - Claude-in-Chrome did not connect this session, same standing
limitation as every other UI-only change in this file.
Confirm step before remapping a statement that already has a result, shipped
2026-11-15. The existing "Map" button (TransactionsTable.vue's handleMapClick,
for correcting an already-successful extraction - distinct from the per-document
mapping queue's own "Map now" reminder above, which has no existing result to warn
about overwriting) used to launch straight into /map-layout on click, with no
warning that saving a new mapping there replaces the statement's current result.
Explicit request: add the same kind of confirm step the document-delete flow
already has before this one too, since it's the same category of "about to change
something that already exists" action.
Reused the existing ConfirmModal outright (same component/props as "Move
document?"/"Delete document?" - no new modal component, matching the "re-wire a
button's click handler through a confirm step" pattern already established twice
in this file) rather than building a one-off dialog. The button's own
@click="handleMapClick" became @click="requestMapClick" (just opens the modal
if canMap); a new confirmMapClick() runs the real handleMapClick() and closes
the modal once it resolves - handleMapClick() itself needed zero changes, since
it already owns mappingDoc, now also bound to the modal's own busy prop so it
stays open with a spinner during the re-fetch/self-heal/navigation the same way
the delete modal stays open during its own network call. Not marked danger (red)
- replacing a mapping is recoverable (re-extracting or remapping again undoes it), not a permanent deletion, the same judgment call "Move document?" already makes for an analogous "changes existing state but isn't destructive" action.
Verified: npm run build passes; the built bundle's message string
("Remap this statement?"/the confirm text) confirmed present. The app container
was rebuilt and confirmed serving the new bundle (hash-matched against the local
build output). No backend touched - pure frontend, so backend/measure.py doesn't
apply. Not machine-verified: the actual click-through (does the modal appear, does
Cancel correctly leave the existing result untouched, does Continue still reach
the mapper) - Claude-in-Chrome did not connect this session.
Pending-mapping notice made clickable, 2026-11-15 - a real discoverability gap
found right after the per-document mapping queue shipped, not a data-loss bug.
Reported as "the 2 [needs-mapping statements] were never added to the general
project or shown in the document navigator... it appears it was dropped." Investigated
by executing the REAL extractionStore.js directly (not assumed from reading the
code) via a plain Node script, simulating the exact sequence useBatchExtraction.js
produces for "1 success + 2 needs-mapping" in both possible upload orders: in every
case, all 3 documents ended up in extractionStore.documents (confirmed
documents.length === 3), DocumentNavBar's own next() correctly cycled onto
each placeholder with result === null, and the banner's own pending count matched
reality. Nothing was dropped - the store/queue logic from the prior stage is
correct. The two actual, real things going on:
- "Never added to the general project" is CORRECT, not a bug - a needs-mapping placeholder has nothing saved to PocketBase yet (there's no real document to add to a project's cache), so it was never going to appear in ProjectSidebar's per-project list - that list only ever reflects what's actually persisted.
- "Never shown in the document navigator" was a real, if more forgivable, gap:
the only way to actually REACH one of several queued placeholders was
DocumentNavBar's small "◀ (1 of 3) ▶" prev/next controls, easy to miss entirely if nothing draws the eye to them - especially right after the notice banner already told you something needs attention, with no obvious link from that notice to where to go next.
Fixed by making the notice itself the navigation, rather than leaving
discovery to the small nav arrows: ExtractorView.vue's pendingMappingCount
(a bare number) became pendingMappingDocs ({docKey, fileName}[]), and the
banner now renders each queued statement's own filename as a clickable
.banner-link button (new, main.css) - jumpToPendingMapping(docKey) looks
up that document's CURRENT index by its stable docKey (not a precomputed
index, which could drift if the list is ever mutated between render and click)
and calls the existing extractionStore.setActiveIndex(idx) - the exact same
action DocumentNavBar's own prev/next already use, just invoked directly
rather than requiring several clicks to arrive at the right one. .banner
gained flex-wrap:wrap so several filenames don't force the banner to overflow
on a narrow screen.
Verified: the Node-script reproduction above confirmed the underlying queue was
never actually broken, in both possible upload orderings; npm run build
passes; the built bundle confirmed to contain banner-link. The app container
was rebuilt and confirmed serving the new bundle. No backend touched.
Not machine-verified: whether clicking a filename in the notice actually lands
on the right document and shows its "Map now" reminder in a real browser -
Claude-in-Chrome did not connect this session, same standing limitation as
every other UI-only change in this file.
Persisted pending-mapping statements, shipped 2026-11-16 - a statement still
waiting on manual mapping now survives a page reload. Explicit report: a
needs-mapping placeholder (the per-document mapping queue above) lived ONLY in
memory - the raw File and fingerprint data sat on the in-memory document
entry's own pendingMapping field, nothing was ever saved to PocketBase for it.
Reloading the page mid-session (or just navigating away and back) lost it
completely, forcing a full re-upload - the exact same category of gap the
earlier "Excel exports moved to R2"/"PocketBase Stage B.1" work already solved
for every OTHER kind of in-progress state in this app, just not yet for this one.
Schema (pb_migrations/12_add_pending_mapping_fields.js): documents.result
relaxed to optional (a placeholder genuinely has no result yet - the same
"PocketBase's required:true rejects a missing/empty value" gap migration 10
already found for layoutMappings.columnMap, confirmed again here rather than
assumed to generalize). Six new fields: needsMapping/needsValueConfirmation
(bool - the umbrella flag and its narrower sub-flag, the same distinction
pendingMapping.needsValueConfirmation already makes in memory) and
pendingFingerprint/pendingFingerprintHash/pendingCandidateRow/
pendingFieldOrder (the raw data LayoutMappingRequired/
ValueRecognitionRequired already computed, saved so the mapper doesn't need
to re-run extraction after a reload just to get it back). Deliberately NOT
reusing the existing layoutFingerprintHash field - that one means "the hash
of whichever mapping was actually APPLIED," a different thing from "the hash
of an UNRESOLVED fingerprint still waiting on one."
New documentsService.savePendingMappingDocument() - the same multipart-
upload shape saveDocument() already uses (real sourceFile, same as any
other document), just with no result and the six new fields set instead.
useBatchExtraction.js's own reason === 'no_match' branches (both
needs_mapping and needs_value_confirmation) now call this - via a new shared
addPendingMappingDoc() helper - BEFORE adding the placeholder to
extractionStore's queue, so every placeholder in the queue already has a real
PocketBase id and a cached project-sidebar entry from the moment it appears,
the same as a normal successful extraction already gets.
The placeholder having a REAL pbId now simplified three things that used to be special-cased for "nothing's been saved yet":
ManualMappingView.vue'spendingDocKeybranch (resolving a queued placeholder) now UPDATES the existing record in place (documentsService.updateDocument, clearing all six pending fields so a future reload doesn't keep reading it as unresolved) instead of CREATING a second one - the earlier version, written before persistence existed, mistakenly still calledsaveDocument()here, which would have left a duplicate document behind the moment this landed; caught and fixed before it ever shipped, not after.DocumentNavBar.vue's delete flow already branched ondoc.pbId(added in the per-document-queue work, defensively, for what was then the common case) - that branch is now the NORMAL path for a placeholder too (delete the real record, same as any other document); the oldelsebranch (local-only removal) is kept only as a fallback for the rare case a placeholder's own save never actually went through.useDocuments.js'sloadDocuments()now recognizes aneedsMappingrecord on reload and reconstructs it as a placeholder (addPendingMappingDocument) instead of an ordinary one -pendingMapping.fileisnullin this case (there's no raw File to restore from a PocketBase record, only its ownsourceFile), which is the one real asymmetry the rest of this work had to account for.
TransactionsTable.vue's "Map now" handler had to become async to cover
that asymmetry - a placeholder created fresh THIS session still has its raw
pendingMapping.file in memory (no fetch needed, same as before); one
restored from a reload does not, so handleMapPendingClick() now re-fetches
it from PocketBase/R2 first via a new shared fetchSourceFileAsFile(pbId)
helper - factored out of the existing "Map" button's own handleMapClick(),
which already did exactly this for a different reason (correcting an
already-successful document, whose raw File is never kept once saved).
Verified, all real, against the real running stack - a hand-written Node
script executing the ACTUAL, already-committed files (never
reimplementations: authService.js, documentsService.js,
projectsService.js, useDocuments.js, extractionStore.js), 7 assertions
covering the full loop: savePendingMappingDocument creates a real record
with needsMapping: true and a real sourceFile for both the plain and
value-confirmation flavors; a RE-FETCHED record (not the create response's own
echo) matches what was saved; loadDocuments() reconstructs both as
placeholders with the real pbId, pendingMapping.file === null, and the
correct fingerprint/candidateRow data; resolving one
(documentsService.updateDocument + extractionStore .replacePendingMappingDocument, the exact sequence ManualMappingView.vue's
own pendingDocKey branch now runs) clears pendingMapping and sets the real
result IN PLACE; the PERSISTED record (re-fetched again) confirms
needsMapping: false and the real result, not just in-memory state; a SECOND
reload loads the resolved document normally while the other statement still
shows as pending. All 7 passed on the real running PocketBase container; test
data (both documents, the project, the user) deleted afterward via direct
superuser REST calls. pb_migrations/12 confirmed applied against the real
rebuilt pocketbase container (the new fields and result's relaxed
required both read back via the REST API, not assumed from the migration
file). npm run build passes; the app container rebuilt and confirmed
serving the new bundle. backend/measure.py re-run against the full fixture
corpus, byte-identical to the documented baseline (no backend Python touched
this stage).
Not machine-verified: the actual click-through - uploading a batch, seeing the notice, reloading the page before mapping anything, and confirming the placeholders are still there with working "Map now" buttons - Claude-in-Chrome did not connect this session, same standing limitation as every other UI-only feature in this file.
Flagged rows' edit pencil visually disappearing - a real <colgroup>/CSS
width mismatch, not a logic gate, shipped 2026-11-15. Reported as "I can't
edit flagged transactions after accepting them." Investigated the full edit
path first - TransactionRow.vue's pencil button, useRowEditing.js,
extractionStore.js - and confirmed by reading AND by directly executing the
real composables (acknowledge a flag, accept the document, then
startEdit()/saveEdit() on that row) that nothing anywhere gates editing
on accepted/acknowledgedFlags state at all; TransactionRow.vue doesn't
even receive an isAccepted prop. Asked the user a direct follow-up
(AskUserQuestion) rather than keep guessing once code-reading ruled out the
obvious theory - "the pencil icon is missing/hidden" pointed at a rendering
problem, not a logic one.
The real bug: .row-actions's own CSS width grew TWICE over this
project's history - 34px→54px (R.2, 2026-10-13, to fit the new flag-toggle
icon) →74px (R.4, same day, for the "more actions" menu) - but
TransactionsTable.vue's <colgroup> (<col style="width:34px"> for that
column) was never updated either time, and neither was the table{min-width: 664px} rule's own "fixed columns sum to 504px" comment/math. Under
table-layout:fixed, a table's actual column widths come from the
<colgroup>, not from a <td>'s own CSS width - so the real rendered
column stayed stuck at the original 34px the whole time, regardless of what
.row-actions itself claimed. An ordinary row (edit + "more" = 2 icons,
~46px needed) was narrow enough to mostly get away with this; a FLAGGED row
(flag-toggle + edit + "more" = 3 icons, ~67px needed) overflowed the real
34px column badly enough that the later icons - the edit pencil among them -
ended up visually covered by the Date column's own input, painted on top of
them in DOM order. This is exactly why the user saw it specifically on
flagged rows, and exactly why "missing/hidden" was the right description
rather than "disabled" - no code ever hid it, the layout did.
Fixed by updating the colgroup's first <col> to 74px (matching
.row-actions's own already-correct CSS) and recalculating table's
min-width from 664px to 704px (74+120+120+135+95 fixed columns = 544, +160px
Description floor) - both now actually consistent with what the CSS has
claimed since R.4. Computed the real fit before calling it done, not just
matching numbers: .row-btn is padding:4px at font-size:13px (~21px per
icon), so 3 icons + .row-actions's own 4px left padding = ~67px, comfortably
under the corrected 74px column.
Verified: npm run build passes; the built CSS bundle confirmed to contain
both corrected values (width:74px on the colgroup's own rule, width:704px
on table). The app container was rebuilt and confirmed serving the new
bundle (hash-matched against the local build output). No backend touched -
pure frontend CSS/markup, so backend/measure.py doesn't apply.
Not machine-verified: whether the pencil is actually visible on a flagged row now in a real browser - Claude-in-Chrome did not connect this session, same standing limitation as every other UI-only change in this file. This one is worth the user's own quick look before considering it closed, since the original report was a direct visual symptom.
"Download All" bundles into a single zip instead of N separate browser
downloads, shipped 2026-11-16. Previously handleDownloadAll()
(TransactionsTable.vue) looped every loaded document and triggered its own
<a download> click per document - functional, but some browsers prompt to
allow multiple downloads from one click, flagged in this file as "a known,
minor wrinkle" since the original multi-document work shipped. Explicit
request to fix it properly.
Added jszip as a real npm dependency (same offline-build reasoning as
pdfjs-dist/@fortawesome/fontawesome-free - a real package, not a CDN
script, keeps the Docker build reproducible without network access).
downloadOne() was split into two pieces: a new buildExport() (builds one
document's workbook via the existing /api/export call and best-effort
persists it to R2, same as before - just no longer ALSO triggers its own
browser download) and a new, tiny triggerBrowserDownload(blob, fileName)
(the actual <a> click mechanics, factored out so both a single-document
download and the final zip bundle share identical download code, not two
near-duplicate copies). handleDownloadCurrent() calls buildExport() then
downloads that one file directly, unchanged in effect. handleDownloadAll()
now calls buildExport() per document (R2 persistence per document is
unchanged) but adds each resulting blob to one JSZip archive instead of
downloading it immediately, then triggers exactly ONE browser download of the
finished zip (Statements_Export_<date>.zip) once every document's been
processed.
One real collision case handled deliberately, not left to chance: two
documents can produce the same derived filename (neither has a real title,
both falling back to "Statement_Extraction.xlsx") - a zip archive technically
allows duplicate entry names, but silently letting one export clobber another
inside the archive would be exactly the kind of silent data loss this app's
own governing rule exists to prevent. A collision gets " (2)", " (3)", etc.
appended before the extension instead, same pattern a browser's own
"file already exists" rename uses.
Verified: a hand-written Node script exercised the REAL jszip package (not
a mock) with the EXACT dedupe algorithm written into handleDownloadAll() -
confirmed 4 documents including two genuine filename collisions produce 4
distinct zip entry names, then round-tripped the actual generated zip bytes
back through JSZip.loadAsync() and confirmed all 4 entries exist with the
correct, un-clobbered content (not just that zip.file() was called without
error - a real archive, read back and checked byte-for-byte). npm run build
passes; the built JS bundle confirmed to contain the real jszip/
generateAsync code. The app container was rebuilt and confirmed serving
the new bundle. No backend touched - Flask already builds each workbook in
memory per-document exactly as before; only the frontend's own
bundling/download step changed.
Not machine-verified: the actual click-through - does the zip genuinely download as one file in a real browser, does it open correctly and contain every statement's own correctly-named workbook - Claude-in-Chrome did not connect this session, same standing limitation as every other UI-only change in this file.
Usage tracking foundation, shipped 2026-11-16 - the first piece of a stated future billing model (free tier, one-time page packs, three subscription tiers with pause/resume), scoped down to exactly what was asked for: a visible pages-extracted counter and the raw data recording behind it, NOT plan enforcement, payment processing, or the pause/resume billing-cycle logic itself - none of that exists yet and wasn't built. The user's own framing was explicit about scope: "the foundation I want to focus on now is a visible page(s) extracted counter... and recording these stats."
Schema (pb_migrations/13_add_usage_events.js): a new usageEvents
collection - owner (relation, required), document (relation, optional -
traceability, not every future usage event will necessarily have one), pages
(number, required), created (autodate). Deliberately append-only and
immutable (updateRule/deleteRule both null, superuser-only) - the same
pattern layoutMappingVersions already established for history that must
never be editable by its own owner, which matters MORE here than anywhere
else in this schema: a usage record a user could edit or delete is a free-
tier limit that's trivially gameable.
What counts as "a page extracted," and where it's recorded: one event
per successfully DELIVERED extraction - not a ManualMappingView.vue Preview
click, which costs the same real backend compute (OCR/Docling) but isn't a
billable deliverable the user actually walks away with. Recorded at the two
places a real result gets persisted as a document's own current result:
useBatchExtraction.js's normal save path (auto-detected or mapping-applied),
and all three of ManualMappingView.vue's own save branches - including the
pendingDocumentId correction case (re-mapping an already-successful
document still re-runs real extraction and delivers a new result, so it
counts again, deliberately not special-cased out). pages comes from
result.page_reports.length - the one field populated identically across
every extraction path (dual-engine text PDF, OCR-only, forced-mapping retry),
confirmed by checking extraction_service.py directly rather than assumed.
A /api/recheck call (editing a row, acknowledging a flag, accepting a
document) never re-runs extraction at all, so correctly never records usage.
New usageService.js (recordUsage/getPagesSince, thin PocketBase
wrappers, same shape as every other service in this app) and new
usageStore.js (Pinia - pagesThisPeriod, loadUsage(),
recordExtraction() with an optimistic local bump so the header updates
instantly without re-querying after every single extraction in a batch).
Named recordExtraction, not recordUsage, specifically to avoid colliding
with layoutMappingsService.recordUsage - an entirely unrelated, pre-existing
concept (a saved MAPPING's own pass/fail drift-detection history) that
happens to live in the exact same file (useBatchExtraction.js) this new
call was added to; flagged with an inline comment at the one spot both
appear together, so the name collision can't read as the same thing later.
"This period" is explicitly a placeholder - the current CALENDAR month,
not the real billing-cycle semantics the user has described (a
subscription period that can be paused mid-month and resumes counting from
where it left off, rather than resetting to a fresh calendar month). That
needs a real subscription/plan record to anchor a custom cycle against,
which doesn't exist yet - documented directly in usageStore.js's own
docstring as the one place this logic will need to change once that exists;
nothing else in the app needs to know how "the current period" is actually
defined, by design.
The visible counter lives in AppHeader.vue - a plain pill, "{N} pages this month", no quota/limit shown alongside it since no plan system exists
yet to compare against. Loaded once on mount (the one place in the app this
value is currently shown). Originally placed top-left (right after the logo,
per the first explicit ask); moved top-right the same day, replacing the
/layouts nav link (.app-nav-link/.app-nav-link-active removed from
main.css as genuinely dead CSS once nothing referenced them) - a second,
separate explicit request. The Layouts page itself (LayoutsView.vue,
routed at /layouts) was NOT removed, only its one header entry point - it's
still reachable by direct URL, just no longer linked from anywhere in the
app's own navigation chrome.
A real bug found by this stage's own end-to-end testing, not assumed safe
from the filter syntax alone: getPagesSince's first draft built its
PocketBase filter from a plain Date.toISOString() value (a "T" separator,
e.g. "2026-11-16T12:13:00.000Z") - but PocketBase's own stored created
format uses a literal SPACE instead ("2026-11-16 12:13:00.000Z", confirmed
directly via the REST API, not assumed). Bisected the real failure (cutoffs
of 1 minute/1 hour/1 day ago, and the exact stored value, each tried against
the real running PocketBase) before guessing at a fix: a same-CALENDAR-DAY
cutoff with the mismatched "T" separator silently matched ZERO events even
when the cutoff was chronologically well in the past, while a cutoff on a
DIFFERENT day still worked - consistent with PocketBase comparing the filter
value against the stored one as a plain STRING when the two formats differ,
where " " (space) sorts lexicographically before "T", so same-day
comparisons silently broke while cross-day ones (where an earlier character
already differs) happened to still work by coincidence. This would have
made the counter read 0 for literally the entire current month, every month,
until the month rolled over - a foundational feature shipping completely
broken in its own single most common case. Fixed by normalizing since
(.replace('T', ' ')) inside getPagesSince itself, protecting every future
caller, not just the one call site this was first found on.
Verified, all real, against the real running PocketBase - a hand-written
Node script executing the ACTUAL, already-committed files (authService.js,
usageService.js, usageStore.js, never reimplementations), 6 assertions:
recordUsage creates a real, owner-scoped event; a RE-FETCHED record (not
the create response's own echo) confirms it's genuinely persisted; a plain
owner session cannot UPDATE or DELETE their own usage event (the immutability
rule actually enforced, not just declared in the migration); getPagesSince
correctly sums real events across a genuine same-day window (the exact case
the date-filter bug broke) and correctly excludes a future cutoff; and
usageStore.recordExtraction's optimistic bump plus a completely FRESH
store instance's own loadUsage() (simulating a page reload) both
independently arrive at the same real persisted total. The date-filter bug
itself was confirmed real BEFORE being fixed (bisecting cutoffs against the
broken code, reproducing the exact 0-results symptom) and confirmed fixed
after (the same bisection, now all passing) - not fixed speculatively.
npm run build passes; pb_migrations/13 confirmed applied against the
real rebuilt pocketbase container (the collection's own fields/rules read
back via the REST API, not assumed from the migration file). The app
container was rebuilt and confirmed serving the new bundle.
backend/measure.py re-run against the full fixture corpus, byte-identical
to the documented baseline (no backend Python touched - this is entirely a
new PocketBase collection plus frontend code). All test users/events/
projects created during this verification pass deleted afterward via direct
superuser REST calls, in dependency order (usageEvents -> project -> user).
Not machine-verified: the actual counter rendering correctly in a real browser, and updating live immediately after a real extraction completes - Claude-in-Chrome did not connect this session, same standing limitation as every other UI-only piece of this change.
Manual mapper no longer requires a Balance column, shipped 2026-11-16 - a
real statement with none couldn't be mapped at all before this. Reported
directly: some real statements genuinely don't print a running balance per
row, and ManualMappingView.vue's own hasRequiredShape gate unconditionally
required date AND balance (plus Amount or Debit+Credit) before Preview/
Save would even enable - with no real balance column to draw a box over, the
only way past the gate was drawing one over BLANK page space, which then fed
whatever that blank region's own text happened to be into the balance field
instead of correctly leaving it empty.
Traced before touching anything, not assumed: hasRequiredShape's own
comment claimed it mirrored layout_rules.has_required_shape (Python,
REQUIRED_FIELDS = ("date", "balance")) - true, but for the wrong code path.
Reading table_extract.extract_pdf() directly confirmed its forced_zones
branch never calls has_required_shape at all - that check only ever runs
for AUTO-DETECTION, where requiring balance is a real signal a genuine table
was actually found. A forced mapping has already been told exactly where the
columns are by a human; there's nothing left for a balance requirement to
validate. Every money field, balance included, is read via money.get(...)
in _build_rows, so an unassigned balance zone already correctly produces
balance: None for every row with zero code changes needed there.
Fixed by dropping balance from hasRequiredShape's own requirement (now
just date + amount or debit+credit) - updated its own stale comment,
the Preview-disabled hint text, and relabeled the Balance role button itself
"Balance (optional)" so this is visible before a user ever hits the gate,
not just after.
Verified against the REAL backend, not assumed safe from reading the checks
code alone: the existing docs/unrecognized_layout_test.pdf fixture (a real,
already-proven gibberish-header/3-transaction-row statement) forced through
/api/process with a columnMap that deliberately OMITS balance entirely -
all 3 transactions extracted correctly (right dates/descriptions/signs/
amounts), every balance field null as expected (not garbage), and
running_balance correctly reports "pass" with zero mismatches - vacuously
correct, since _walk_balance_chain only ever compares rows that both HAVE a
printed balance (confirmed by reading it directly: running only updates
when t["balance"] is not None, so an all-None statement produces no
contradictions to find, not a crash and not a false failure).
statement_balance correctly reports "not_available" (no closing balance
typed or printed) rather than guessing one. npm run build passes; the app
container was rebuilt and confirmed serving the new bundle.
backend/measure.py re-run against the full fixture corpus, byte-identical
to the documented baseline - no backend code was touched, since the backend
never needed a change for this.
Not machine-verified: the actual click-through - drawing regions with no Balance box, confirming Preview enables and produces the right result in a real browser - Claude-in-Chrome did not connect this session, same standing limitation as every other UI-only change in this file.
Parenthesized negative amounts recognized, shipped 2026-11-16 - a real
statement using this standard accounting convention produced a fully blank
manual-mapping Preview. Reported alongside a question about how to draw a
mapper region - the region-drawing was fine; the real cause was that
_parse_money() had no concept of "(25.00)" as a negative amount at all,
only a leading "-". On a single-amount-column statement (exactly the case
reported) this is consequential in a way it isn't for split Debit/Credit
columns - the ONLY way that layout expresses a negative value is the
wrapper itself, so every row using it failed money classification entirely.
Reproduced against the real backend before touching any code, not
assumed from reading _parse_money alone: built a synthetic single-
amount-column statement (reusing the existing gibberish-header test-PDF
technique) with parenthesized negatives, forced it through /api/process
with an Amount-only mapping - confirmed the two parenthesized rows produced
NO transaction at all (money classification failed on both), their own text
instead absorbed as narrative into the one row that DID parse (the
un-parenthesized positive amount), which is exactly the "garbled, mostly
missing" shape a real "blank" report would come from once a statement's
negatives (debits) are the parenthesized ones and its positives
(credits) aren't.
Fixed in table_extract.py's _parse_money() (shared by the
auto-detection path, the forced-mapping path, AND raw_ocr_extract.py's own
OCR path, which imports _classify_money directly - one fix covers all
three, not a mapper-specific patch): a new _split_sign() helper recognizes
either a leading "-" or a full "(...)" wrap as negative, used by BOTH
_parse_money() and _parse_money_with_patterns() (factored out rather
than duplicated, so the two can't quietly drift apart on which negative
forms they each recognize). _MONEY_RE itself simplified to just the BODY
shape (^\$?[\d,]+\.\d{2}$) now that sign/parens stripping happens once,
up front, before either the exact-match or currency-fallback check runs -
so a parenthesized CURRENCY-WRAPPED value like "(CA$386.01)" is handled
for free by the existing fallback logic, not as a separate case. The
existing false-positive guards ("REF123.45", "1.0000" exchange-rate
ratios, "USD386.01") are unaffected, confirmed directly rather than
assumed - none of them start with "-" or are parenthesized, so _split_sign
is a no-op for all of them and they hit the exact same rejection path as
before.
Verified: 16 direct _parse_money() assertions against the real rebuilt
container (10 pre-existing cases re-confirmed unchanged: plain/negative/
$/CA$-prefixed amounts, plus the "1.0000"/"REF123.45"/"USD386.01"/
"A1B2.34" false-positive rejections; 6 new: "(25.00)", "(1,234.56)",
"($150.00)", "(CA$386.01)", and confirming "()"/"(REF123.45)" still
correctly reject). The real synthetic reproduction re-run after the fix:
all 3 transactions now extract with correct signs and a passing
running_balance check (previously 1 garbled row). backend/measure.py
re-run against the full fixture corpus, byte-identical to the documented
baseline. The existing docs/scanned_statement_2page.pdf OCR fixture
re-verified too (still 17/17, same per-page engine attribution) - confirms
the OCR path, which reuses this same function, has zero regression either.
The app container was rebuilt and these checks run against the real
running instance throughout, not a separate dev process.
Not machine-verified: the actual manual-mapper click-through with a real single-amount-column statement using parentheses - Claude-in-Chrome did not connect this session, same standing limitation as every other UI-adjacent change in this file (though this particular fix is backend-only; nothing in the mapper's own frontend code changed).
Two real bugs found investigating a specific real-world statement report,
shipped 2026-11-16 - a low-resolution photo's OCR read almost nothing, AND
every image-sourced manual mapping was sending column zones in the wrong
coordinate system entirely. Reported directly: a real Bank of America
statement (a phone photo/screenshot, uploaded as a bare .jpg) returned a
blank manual-mapping Preview, with the user explicitly noting its negatives
use a plain "-" (ruling out the parentheses bug fixed earlier the same
day). Investigated by fetching the user's own actual uploaded file (via the
superuser's own file API, same access pattern the admin-review screen
already uses) and running the real extraction code directly against it,
not guessed at from the symptom.
Bug 1 - OCR couldn't read the statement at all at its native resolution.
The real image is only 480x800px. Running raw_ocr_extract._extract_words()
on it directly found only 26 words total - almost entirely large header/
status-bar text (a phone's clock, battery icon, app title bar), NONE of the
actual financial table body. Confirmed by bisecting upscale factors against
the real image before fixing anything: 2x-4x upscaling (960-1920px wide)
found 180-191 words instead - a roughly 7x improvement, plateauing around
3x, with the real transaction dates/descriptions/amounts finally present.
Nothing anywhere in this pipeline upscaled a low-resolution bare-image
upload before handing it to tesserocr - extract_image()'s own pixel-to-
point SCALE factor (_REFERENCE_PAGE_WIDTH_PT / image.width) is a
coordinate-space conversion, not an image resize, and a scanned PDF page
(rendered via pdfplumber at resolution=200, ~1700px wide for a US-Letter
page) was already well above any reasonable OCR floor - only a genuinely
small bare photo/screenshot upload was ever exposed to this.
Fixed in raw_ocr_extract._extract_words() itself (the one place every OCR
path funnels through - auto-detection, forced-mapping, AND
header_candidate_geometry's own fingerprinting, since all three call this
same function): upscales a working copy to _MIN_OCR_WIDTH_PX = 1600 before
running tesserocr if the image is narrower than that (never downscales an
already-adequate one), then divides the returned word coordinates back down
by that same factor before returning - so every caller's own existing
pixel-to-point scale math (computed from the ORIGINAL image's own width)
stays correct unchanged, with no caller needing to know this ever happened.
Bug 2 - a real, systemic coordinate-space mismatch for EVERY image-
sourced manual mapping, not specific to this one statement. Traced while
confirming bug 1's own fix actually produced real transactions: the FIRST
reproduction attempt (zones built directly from the real OCR'd words' own
raw pixel positions) still came back blank. Reading useRegionDraw.js/
useImageZoom.js directly revealed why: a region drawn over a PDF page is
already correctly in PDF POINTS the moment it's reported (pdf.js's own
zoom ref IS a points-per-pixel ratio, confirmed by this file's own R.1
entry) - but a region drawn over a bare IMAGE is reported in that image's
own NATURAL PIXEL space instead (useImageZoom.js's own zoom is a plain
CSS display scale, unrelated to points), and ManualMappingView.vue's
columnMap/headerBottom sent that raw value straight through with NO
conversion - while raw_ocr_extract.extract_image() scales every OCR'd
WORD position to points via that exact _REFERENCE_PAGE_WIDTH_PT / image.width factor before ever comparing it against a zone. The zones and
the words were being compared in two different coordinate systems for
every single image upload this feature has ever supported, confirmed
directly: forcing the real statement's own words through zones built from
unconverted raw pixel coordinates matched NOTHING (every real amount word's
own point-scaled x-position landed far outside a zone whose boundaries were
still expressed in pixels) - the exact same mistake independently confirmed
by hand first, before realizing the shipped frontend code made it too.
Fixed with a new imagePointScale in ManualMappingView.vue - loads the
pending image's own real naturalWidth (a plain Image() probe against
the same previewUrl blob, since this view doesn't own SourceDocumentPanel .vue's internal useImageZoom instance to read it from there instead),
mirrors the backend's own _REFERENCE_PAGE_WIDTH_PT / naturalWidth
conversion exactly, and multiplies every columnMap/headerBottom value by
it before the forced mapping is ever sent - a no-op for a PDF (isImage
false, scale stays 1), so that path is provably unaffected. The drawn
regions' own ON-SCREEN highlight boxes (highlightBoxes/regions.value
itself) deliberately stay in natural-pixel space unchanged - only the
OUTGOING forced_mapping payload needed the conversion.
Verified, all real, against the real running backend and the user's own
actual uploaded file (fetched via the superuser file API, not a synthetic
stand-in) - confirmed both bugs were real BEFORE fixing either (26 OCR
words at native resolution; a hand-built zone set using unconverted pixel
coordinates matching nothing even with the OCR fix alone applied), then
confirmed fixed: forcing the exact formula now baked into columnMap
(raw pixel region coordinates x 612/naturalWidth) through the real
/api/process produced 5 real transactions with correct dates
(forward-filled across an OCR line-split, the same mechanism that already
covers RBC's own blank-after-first-row date convention) and mostly-correct
signed amounts. npm run build passes; backend/measure.py re-run against
the full fixture corpus, byte-identical to the documented baseline (the OCR-
path change is upscale-only, a no-op for every already-adequate-resolution
fixture); the existing docs/scanned_statement_2page.pdf OCR fixture
re-verified too (still 17/17, zero regression - that scan was already well
above the new resolution floor). The app container was rebuilt and these
checks run against the real running instance throughout.
An honest, residual limitation this does NOT fix, confirmed directly rather than glossed over: this specific photo's own OCR quality is still genuinely poor even after upscaling - two of the seven real transaction rows visible in it still extract imperfectly for reasons no code change can recover: one row's minus sign was OCR'd as entirely missing (tesserocr simply never output that character, producing a wrongly-POSITIVE amount for a real withdrawal), and another's amount lost its decimal point entirely ("262.50" read as "26250," which fails money-shape outright and drops that row as narrative text instead of a transaction). Both are genuine OCR misreads on a low-quality source image, not a parsing or coordinate bug - no further fix was attempted for either, consistent with this file's own standing, already-documented position on OCR reliability depending on the external model's own behavior on a given image.
Low-resolution image upload warning, shipped 2026-11-16 - a direct follow- up to the real Bank of America photo investigated above. Explicit request: detect a low-resolution image at upload time and tell the user plainly that the app will try to correct for it, but data quality may still suffer and the result will likely need manual review - and let them choose between picking a clearer file or proceeding anyway, rather than only discovering the problem after a confusing Preview.
Deliberately an inline warning, not a blocking confirm modal - a
judgment call, not what was literally specified. This is a quality heads-up,
not a destructive or hard-to-reverse action (every other ConfirmModal in
this app guards something consequential - delete, move, overwrite an
existing mapping); both choices the user actually needs are already sitting
right there in the existing UI the moment the warning appears - the staged
file's own × (pick a different file) and the Extract button (proceed
accepting the risk) - so a modal would have added an extra click without
adding a real choice that wasn't already available. It also avoids a pile-
up of sequential modals if someone drops several low-res files at once.
useFileUpload.js gained LOW_RESOLUTION_WIDTH_PX = 1600 - deliberately
the EXACT SAME threshold raw_ocr_extract._MIN_OCR_WIDTH_PX uses to decide
whether to upscale before OCR (see the entry above), so the frontend's own
warning and the backend's own correction trigger agree on what "low
resolution" means, not two independently-chosen numbers that could quietly
drift apart. A new probeImageWidth(file) reads a bare image's own real
naturalWidth/naturalHeight (a plain Image() load against an object
URL, same technique ManualMappingView.vue's own imagePointScale probe
added the same day uses) - fired, not awaited, the moment an image is
staged in setFiles(), so staging itself stays synchronous and instant;
the warning (keyed by the same name:size string chosenFiles' own dedup
already uses) just appears a moment later once the probe resolves. A PDF is
never probed at all - a scanned PDF page is rendered server-side at a fixed
resolution regardless of the original scan's own resolution, so there's
nothing meaningful to read client-side for it the way a bare image's own
naturalWidth directly is one. removeChosenFile/clearChosenFiles both
clean up the matching warning entry/entries too, so removing a flagged file
doesn't leave a stale warning behind for a DIFFERENT file that happens to
reuse the same list position.
FileUploadZone.vue renders the warning inline, directly under the
flagged file's own name (restructured that <li> into two stacked rows -
the existing name+remove-button row, now .staged-file-row, plus the new
conditional warning row beneath it) - amber .staged-file-warning, the same
"needs review, not an error" visual language .status-banner.Needs-review/
.tag.needs_review already use elsewhere in this app, not red/error
styling, since nothing has actually failed yet.
Verified: a hand-written Node script exercised the REAL, already-committed
useFileUpload.js directly (not a reimplementation) with a minimal,
honest mock of the two browser APIs it actually touches (Image,
URL.createObjectURL/revokeObjectURL - the same "mock only the
irreducible browser-only piece" discipline useRegionDraw.js's own earlier
verification already established), 5 assertions: staging is synchronous
with warnings starting empty; after the mocked probes resolve, only the
genuinely low-resolution image is flagged (a high-res image and a PDF are
both correctly left unflagged); an image exactly AT the threshold is
correctly NOT flagged (strictly below, not at-or-below); removing a
flagged file removes its warning too; and clearChosenFiles() wipes both.
npm run build passes; the built bundle confirmed to contain
lowResolutionWarnings/LOW_RESOLUTION_WIDTH_PX. The app container was
rebuilt and confirmed serving the new bundle. No backend touched.
Not machine-verified: the actual warning rendering correctly under a real low-resolution file drop/pick in a real browser - Claude-in-Chrome did not connect this session, same standing limitation as every other UI-only change in this file.
QBO export (QuickBooks/Quicken-compatible bank-feed file), shipped 2026-11-19 - the first accounting-software integration this app supports, built in two deliberately separated parts. Explicit request: let users download a QBO of their extracted transactions alongside the existing Excel download, starting with QBO (Xero's own formats are a stated future follow-on, not built). The user also specifically asked how to avoid making someone re-enter their bank's routing number/account number/ account type on every single export if they're doing several a month from the same real account - the answer shipped is a reusable, project-scoped profile, set up once.
Part 1 - the bank account profile foundation. New bankAccountProfiles
PocketBase collection (pb_migrations/14) - project-scoped, same pattern
categorizationRules already established (no sharing/promotion concept;
a bank account has no cross-user "two independent confirmations"
scenario). Fields: name (the user's own label), bankId (OFX BANKID -
the real routing number), accountId (OFX ACCTID), accountType
(CHECKING/SAVINGS/MONEYMRKT/CREDITLINE - OFX's own fixed vocabulary). A
new documents.bankAccountProfile relation remembers which profile a
given document last used, so re-exporting the SAME statement never asks
again. A deliberate security choice baked into the schema itself, not
just UI copy: accountId is NOT labeled or treated as "the real account
number" anywhere - QBO/Quicken only need it to be a stable, unique string
per account for matching, not literal banking PII; the creation form's own
helper text explicitly suggests a last-4-digits form or an internal
reference code instead of a real full account number.
New bankAccountProfilesService.js (thin PocketBase CRUD, same shape as
categorizationRulesService.js) and useBankAccountProfiles.js (a
composable mirroring useCategorization.js's own rules-loading half -
reactive, project-scoped, auto-reloads when the active document's project
changes). New BankAccountProfileModal.vue - shown only when the active
document has no remembered profile yet: a dropdown of the project's
existing profiles (newest-first, defaulting to the most recently created -
the common "second+ export from the same account" case needs exactly one
click) plus a "+ Add a new bank account" inline create form. Purely
presentational (emits use-existing/create-new/cancel, never calls
PocketBase itself), same "parent owns every service call" convention
DocumentOptionsModal.vue already established.
Part 2 - the actual QBO generation. New backend/services/ qbo_service.py - writes OFX 1.x SGML text directly (QBO is Intuit's own
variant; OFX 1.x has no closing tags on leaf elements, so this isn't
well-formed XML and a generic XML library would be the wrong tool).
Reuses this pipeline's own existing result["transactions"] entirely -
no new extraction logic, same data excel_service.py already consumes.
Two real design problems solved, not glossed over:
- FITID (OFX's own stable transaction id) - this pipeline's extracted data has no native bank transaction id to reuse, so one is derived by hashing date+description+amount+balance (NOT the bare list index, which shifts if a row is later inserted/deleted via a review-screen structural edit - hashing on content instead means the SAME transaction re-exported after an unrelated edit elsewhere in the statement still gets the same FITID, which is the whole point of a stable id for QBO's own dedup logic). The row's own index is still mixed into the hash as a tie- breaker for the one real case content-hashing alone can't resolve - two genuinely identical transactions (same date/description/amount/balance, not rare on a real statement) would otherwise collide onto the same FITID and one would be silently dropped by QBO's own dedup - exactly the "never silently exclude data" failure this app's own governing rule exists to prevent.
- OFX 1.x text safety - a transaction description can't safely carry a
literal
<,&, or a newline into an SGML field with no closing tag to bound it (one stray character would corrupt every field after it) - a small_escape()strips/replaces these before any text reaches the output, confirmed directly against a deliberately adversarial test description containing all three.
A real bug found by this stage's own route-level testing, not caught by
a code read alone: extraction_schema.parse_qbo_export_request is the
FIRST schema function in this whole file that genuinely raises
ValidationError on a required-but-missing JSON field (every existing
schema function either has no required fields or only validates a
multipart form, where /api/process's own route already catches this) -
the new /api/export/qbo route's first draft, copied from /api/export's
own shape, had no matching try/except around it, so a missing/malformed
bank_account 500'd with no useful message instead of a clean 400.
Confirmed broken via a real curl call before fixing it, confirmed fixed
the same way after. A second real gap, found while building
qbo_service.py itself: this export route's own result dict has NO
top-level closing_balance key at all (confirmed by reading
excel_service.py, which never references one either) - <LEDGERBAL>
is built from the last transaction's own printed balance instead, the
same "final balance" value the Excel export's own last row already shows.
Verified, all real, against the real running stack - a hand-written Node
script executing the ACTUAL, already-committed files (authService.js,
documentsService.js, projectsService.js, bankAccountProfilesService .js, useBankAccountProfiles.js, extractionService.js,
useDocuments.js, never reimplementations), 5 assertions covering the
full loop: bankAccountProfilesService creates and lists a real,
persisted profile; the real composable auto-loads it reactively and adds
a second one newest-first with no refetch; extractionService.exportQbo
produces a real QBO file from the REAL running Flask backend, containing
the right bank id/account id/transaction amounts (not a mock response);
the chosen profile is genuinely persisted on the document (confirmed via
a RE-FETCH, not the update call's own echo); and - simulating a page
reload via the real useDocuments.js::loadDocuments() - the remembered
profile survives it, so a user's second export of the same statement
after closing the tab still skips the picker. Separately: three real curl
calls against the rebuilt container confirmed a real, hand-inspected QBO
file's own structure is correct (STMTTRN/BANKACCTFROM/LEDGERBAL blocks
present and populated), that a missing bank_account and an invalid
accountType both now correctly 400 with a real message (not 500), and
that a transaction with no parseable date is correctly SKIPPED from the
output rather than crashing or writing a malformed <STMTTRN> block.
backend/measure.py re-run against the full fixture corpus, byte-
identical to the documented baseline (no extraction code touched).
npm run build passes; pb_migrations/14 confirmed applied against the
real rebuilt pocketbase container (the new collection's fields and
documents.bankAccountProfile both read back via the REST API). Both
app and pocketbase containers rebuilt and confirmed serving the new
code. All test data (profiles, document, project, user) deleted from the
real running PocketBase afterward via direct superuser REST calls, in
dependency order.
Known, deliberate scope limits, not oversights: a QBO export is NOT
persisted to PocketBase/R2 the way an Excel export is (exportFile) -
that field is specifically for the workbook; conflating a QBO file into
it would silently overwrite a user's own Excel backup with a different
file type, so this first cut just triggers the browser download and
nothing more. "Download All" (the zip bundle) has no QBO equivalent yet -
a bank account profile is resolved per DOCUMENT, and asking which account
applies to every statement in a multi-document batch at once is a real
UI design question this first cut doesn't guess at. Xero's own export
formats (OFX variant, QIF, or CSV) are not built - explicitly the
user's own stated "starting with QBO" scope.
Not machine-verified: the actual click-through - clicking "QuickBooks (.qbo)", the picker modal appearing, filling in a new bank account, confirming the downloaded file opens correctly in real QuickBooks/ Quicken software - Claude-in-Chrome did not connect this session, and no real QBO/Quicken instance was available to import the generated file into; the file's own structural correctness was verified against OFX's published spec shape, not a real import.
IMPORTANT retroactive correction to the entry above: the entry above
has been edited in place (originally written describing a feature named
"QFX") to use this feature's current, correct name - but the ACTUAL file
this stage originally produced was never a real QFX/QBO file: it was
missing <INTU.BID> entirely, the one field that distinguishes an
Intuit-variant OFX file (QBO/QFX) from plain generic OFX. See the next
entry, ".qbo export - corrected and renamed, 2026-11-19", for the real
fix and the research that found this gap, done the same day as the
original build above, before any of it reached the user as a finished
feature.
.qbo export - corrected and renamed, 2026-11-19 (same day as the
entry above - this closes out that gap before it ever shipped as
"done"). User's explicit, aggressively-scoped request: "I want to have
the .qbo file extension so that it perfectly matches what quickbooks
online will accept and it can also be used for quickbooks desktop. Check
the requirements aggressively so you don't make any errors."
Research, cross-checked across multiple independent sources before writing any code - not assumed from a single search result:
- QBO (QuickBooks "Web Connect") and QFX (Quicken) are structurally the
SAME thing - OFX 1.x SGML plus one addition,
<INTU.BID>(Intuit's own internal bank-id directory lookup) inside the sign-on<FI>block - differing only in which Intuit product/extension convention they target. **This app's own file, confirmed via a directgrepagainst the then-existingqfx_service.pybefore writing anything new, had NEITHER- no
<INTU.BID>line existed anywhere in it.** What that module produced was, structurally, always plain generic OFX with a.qfxextension slapped on - never a real QFX file at all.
- no
- QuickBooks Online's own official upload UI (fetched directly) lists
.csv, .txt, .qbo, or .ofx as supported - not .qfx by name.
QuickBooks Desktop's own Web Connect import also expects
.qbo. So.qbo- not.qfx- is the extension that actually matches both of this app's stated targets. - The missing
<INTU.BID>value, confirmed from ProperSoft's own official support documentation (fetched directly as a primary source, not a search snippet), quoted directly: "If your bank is not listed, use 3000 (Wells Fargo), which allows every account type, or 2 for QuickBooks Canada." Confirmed this value is purely cosmetic - it only controls which bank-name label QuickBooks Desktop shows during import, never which real account the transactions land in (the user always picks the destination account manually regardless) - so it's hardcoded inqbo_service.pyas a constant, not something abankAccountProfilesrecord needs to carry or a user needs to see. This specific guidance is scoped to QuickBooks Desktop in the source document itself (the strict one - it validates a bank id against Intuit's own closed/registered list and rejects an unrecognized one outright; QuickBooks Online does only minimal validation of this field regardless, per a separate technical source cross-checked the same day) -3000satisfies both. - Confirmed registered MIME type:
application/vnd.intu.qbo(parallel to.qfx's ownapplication/vnd.intu.qfx), mirroring the existingapplication/vnd.openxmlformats...precedent this app's own Excel export already uses for a format-specific MIME type rather than a generic fallback. - Re-checked this app's own ALREADY-correct logic before assuming
anything needed fixing there too: FITID's own index tie-breaker
(avoids a same-day-duplicate-transaction collision) and
_escape()'s own</>/&/newline stripping were both confirmed still correct and left untouched - the fix is additive (one new field), not a rewrite.
The fix, not just a rename: qfx_service.py → qbo_service.py
(build_qfx → build_qbo), with one new line added to the <FI> block:
<INTU.BID>3000 - placed inside <FI>, alongside the existing <ORG>,
not after </FI> (an OFX's own sign-on block has exactly one <FI>
element per the spec; <INTU.BID> is one of its children, same as
<ORG>/<FID>). extraction_schema.parse_qfx_export_request →
parse_qbo_export_request (same validation, same required
bank_account fields, only the name and its own error-message text
changed from "QFX" to "QBO"). file_repository.new_qfx_output_filename
→ new_qbo_output_filename (.qfx → .qbo). The route itself:
POST /api/export/qfx → POST /api/export/qbo, mimetype
application/vnd.intu.qfx → application/vnd.intu.qbo. Frontend,
mirroring every backend rename one-for-one:
extractionRepository.exportStatementQfx → exportStatementQbo,
extractionService.exportQfx → exportQbo, and in
TransactionsTable.vue every qfx*-named ref/handler (qfxDownloading,
handleDownloadQfxClick, proceedQfxExport) → its qbo* equivalent,
plus the dropdown's own button label, "QuickBooks (.qfx)" →
"QuickBooks (.qbo)". The OLD /api/export/qfx route no longer exists at
all (confirmed: a POST to it now returns a plain 405, the same response
any unmatched POST path gets from this app's own SPA catch-all, not a
leftover route in disguise).
Verified, all real, against the real rebuilt container - not assumed
from the diff: a real /api/process call against the HSBC-Sep fixture,
then a real /api/export/qbo call against that actual result (bank
account {bankId: "021000021", accountId: "TESTACCT123", accountType: "CHECKING"}) confirmed, by inspecting the real response headers and
file content directly: Content-Type: application/vnd.intu.qbo,
Content-Disposition naming a real .qbo file, and the file's own text
containing <INTU.BID>3000 correctly placed inside <FI> (between
<ORG> and </FI>), all 32 real transactions present as <STMTTRN>
blocks, and a correct <LEDGERBAL> matching the statement's own real
closing balance. Confirmed the schema's own validation still correctly
400s with a real message ("bank_account is required for a QBO export")
on a request missing bank_account. backend/measure.py re-run against
the full fixture corpus, byte-identical to the documented baseline (this
touches zero extraction/check code). npm run build passes; the built
JS bundle confirmed to contain the new /api/export/qbo route string and
the "QuickBooks (.qbo)" button label, and confirmed to contain ZERO
remaining case-insensitive "qfx" references anywhere in the minified
output. Both the app container (backend + frontend bundle) rebuilt and
confirmed serving the corrected code - the actual served JS asset,
fetched directly from the running container, re-confirmed to contain the
new label and zero stale "qfx" strings.
Not machine-verified (same standing limitation as the original build above): an actual import of the corrected file into real QuickBooks Online or Desktop software - still no real instance available this session to confirm against. The file's structure now matches every documented requirement found across every cross-checked source, which is the strongest confirmation available without that software in hand.
Xero export, shipped 2026-11-19 - the second accounting-software integration, immediately following QBO the same day. Explicit request, with the user's own earlier framing establishing the direction: QBO first, Xero second.
**Researched Xero's own actual import requirements before building anything
- found genuinely different from QBO's, not assumed to match.** Two
independent sources were checked, since they disagreed on one real detail
(whether Xero maps CSV columns by name or by position) - rather than
picking one and risking the other being right, the builder writes a real
header row in the documented recommended order (
Date, Amount, Payee, Description), which is correct under either reading. Confirmed separately, directly from Xero's own documented requirements: only Date and Amount are actually required; Amount is a SINGLE signed column (no separate debit/credit, unlike this app's own Excel export); no currency symbols/thousands separators/parenthesized negatives; UTF-8, comma- delimited. Most importantly: Xero's own CSV import has NO equivalent of OFX's<BANKACCTFROM>block at all - which bank account a statement imports INTO is chosen inside Xero's own UI at import time, not embedded in the file. This made the Xero build genuinely simpler than QBO, not just a reskin of it: no bank-account picker, nobankAccountProfileslookup, no extra required field on the export request at all - confirmed by research, not assumed to mirror QBO's own shape out of consistency for its own sake.
One real, worth-noting fit, not a coincidence worth re-deriving:
Xero's own documented accepted date formats include "D MMM YYYY"/
"DD MMM YYYY" (e.g. "3 May 2026") - which is ALREADY this pipeline's own
canonical transaction-date text ("DD Mon YYYY", e.g. "03 Jan 2027").
So the export needs zero date reformatting, and more importantly
sidesteps Xero's own documented #1 CSV silent-failure mode entirely: a
locale-ambiguous numeric date like "03/04/2026" parses differently
depending on the importing organization's own regional settings, with no
warning - this pipeline's own date text was never ambiguous in the first
place, so that whole failure class doesn't apply here.
New backend/services/xero_csv_service.py - build_csv(result, title),
same in-memory, no-disk discipline as excel_service.build_workbook/
qbo_service.build_qbo, using Python's stdlib csv module (not a manual
string join, unlike QBO's own hand-written SGML - a real description
containing a comma is safely quoted BY CONSTRUCTION this way, confirmed
directly rather than assumed, see below) to write the header + one row
per transaction, skipping a transaction with no parseable date/amount the
same way build_qbo() already does, never inventing a value this
pipeline never resolved. Payee and Description both carry the same
transaction description text - this pipeline has no separate payee-
name extraction (would mean guessing a clean counterparty name out of
noisy bank text, which this app's own "never silently correct" rule
prohibits), so rather than inventing a new, different judgment call for
Xero alone, this reuses the EXACT SAME NAME/MEMO duality qbo_service.py's
own build_qbo() already established for the identical reason - kept
deliberately consistent across both export formats. A newline embedded in
a description is collapsed to a space before writing (same conservative
choice QBO's own _escape() makes, for the same reason: Xero's own
documentation doesn't confirm how its importer handles an embedded raw
newline inside a quoted CSV field, even though it would be valid per RFC
4180, so this doesn't rely on that leniency).
New route POST /api/export/xero-csv - reuses the EXISTING
extraction_schema.parse_export_request as-is (no new schema function
needed at all, unlike QBO's own parse_qbo_export_request, since there's
no extra required field to validate). New extractionRepository .exportStatementXeroCsv/extractionService.exportXeroCsv (no
bankAccount parameter, mirroring the backend's own simpler shape) and a
new "Xero (.csv)" button beside "QuickBooks (.qbo)" in
TransactionsTable.vue's own top bar - downloads directly on click, no
picker modal, since there's nothing to pick.
Verified, all real: three direct curl calls against the rebuilt
container confirmed a comma inside a real description is correctly
quoted ("Coffee Shop Purchase, with a comma"), a newline inside another
is correctly collapsed to a space, and a transaction with no date is
correctly skipped rather than writing a malformed row - all from the
REAL route, not the function in isolation. A hand-written Node script
then executed the ACTUAL extractionService.exportXeroCsv (never a
reimplementation) against the real running Flask backend and confirmed
the full file - header row, both real transaction rows, correct signed
amounts - comes back exactly as expected. backend/measure.py re-run
against the full fixture corpus, byte-identical to the documented
baseline (no extraction code touched). npm run build passes; both
app containers rebuilt and confirmed serving the new bundle/code (no
PocketBase migration was needed for this stage at all - the genuinely
simpler design needs no new collection or document field).
Not machine-verified: the actual click-through, and whether the generated CSV imports cleanly into a real Xero account - no real Xero instance was available to test an actual import into, same honest limitation the QBO entry above already states for QuickBooks/Quicken; the file's own structure was verified against Xero's documented requirements, not a real import.
Four export formats consolidated into one Download dropdown, plus a new generic CSV export, shipped 2026-11-19 - the three separate download buttons (Excel, QuickBooks, Xero) were a real reported UI problem, crowding the top bar. Explicit request: nest all formats behind one "Download" trigger with a chevron, detect multiple loaded documents for Excel's own current-vs-all choice the same way it already did, and add a plain CSV option (distinct from Xero's own import-specific CSV) that ALSO supports the current-vs-all choice.
UI restructure. The three .txn-download-btn buttons became one
trigger + dropdown, reusing the Results toggle's own exact hover-sticky,
zero-dead-zone structure (.download-trigger-wrap/.download-dropdown/
.download-dropdown-inner, anchored right:0 instead of left:0 since
this trigger sits at the row's right end) rather than inventing a new
hover pattern - this project already found and fixed a real slow-drag
dead-zone bug building the Results dropdown (padding-top on the invisible
outer hit-box, not a positioning gap), so the new dropdown copies that
exact structure rather than risking the same bug a second time. Dropdown
order, per the explicit ask: QuickBooks (.qbo), Xero (.csv), CSV, Excel
(.xlsx) - CSV directly above Excel.
The real generalization: Excel's own single/all download logic
(buildExport/handleDownloadCurrent/handleDownloadAll/the choice-
modal handlers) was parameterized by format ('xlsx' | 'csv') instead of
duplicated a second time for CSV - a DOWNLOAD_FORMATS lookup table
holds each format's own build() call and file extension;
DownloadChoiceModal (unchanged itself - already fully generic) now
serves both formats, with a new pendingDownloadFormat ref remembering
which one a shown choice-modal is actually for. The zip-collision-naming
logic ( (2), (3), etc. for two documents sharing a derived filename -
see "Download All bundles into a single zip" under Key decisions &
lessons for the original Excel-only version) now builds its own regex
from the format's own extension instead of a hardcoded \.xlsx$, so it
correctly handles both - verified directly, not assumed, see below.
Deliberately NOT generalized to QBO/Xero - both stayed single-
document-only, exactly as already documented (a bank account profile is
resolved per document for QBO; multi-download wasn't asked for either
format this time) - only Excel and the new CSV got the multi-document
treatment, matching exactly what was asked.
New backend/services/csv_service.py - a plain, generic transactions
CSV, distinct from xero_csv_service.py's own import-specific Date/
Amount/Payee/Description shape: this one writes the SAME Date/
Description/Amount/Balance/Status/Check-flags columns excel_service.py's
own Transactions sheet already writes, reusing that module's own
_flagged_row_indexes() directly rather than re-deriving the same "which
checks flagged which row" logic a second time (same cross-module-reuse
precedent qbo_service.py/pipeline_service.py already set with
checks_service._parse_date). A real, deliberate behavioral
difference from xero_csv_service.py, not an oversight: this writes
EVERY transaction row regardless of whether its own date/amount
resolved - a plain data dump has no structural requirement a blank field
would violate (unlike an accounting-import file, which genuinely can't
use a transaction with no date), so nothing is silently skipped here,
confirmed directly with a transaction carrying amount: null and
confirming it's still written (with its own real structure_sanity flag
intact in the Check flags column) rather than dropped. New route POST /api/export/csv reuses parse_export_request as-is, same as Xero's own
route - no bank-account field needed here either.
One real, deliberate scope boundary, same reasoning already documented
for QBO/Xero: neither new download path persists anywhere other than
the browser's own download - DOWNLOAD_FORMATS.csv.persistToR2 is
explicitly false, since the EXISTING exportFile field on a document
is Excel-specific; a second format writing to that same field would
silently overwrite a user's own Excel backup with a different file type.
Excel alone keeps persistToR2: true, unchanged.
Verified, all real: curl calls against the rebuilt container confirmed
the new /api/export/csv route - a comma in a description is correctly
quoted, a transaction with amount: null/balance: null is written (not
skipped) with its own real check-flag intact, matching the deliberate
difference from Xero's own CSV documented above. A hand-written Node
script then executed the ACTUAL, already-committed
extractionService.exportCsv/exportWorkbook (never reimplementations)
against the real running backend, confirming both still produce correct
files through the new DOWNLOAD_FORMATS indirection - and separately
exercised the EXACT zip-collision-naming algorithm now live in
TransactionsTable.vue's own handleDownloadAll() (the same code, not a
reimplementation) against both .xlsx and .csv extensions, confirming
the switch from a hardcoded regex to a dynamic one still resolves
" (2)"/" (3)" collisions correctly for either - then round-tripped a
real zip built with the new CSV naming through JSZip's own loadAsync()
to confirm it's a genuinely valid archive, not just that the naming
strings looked right. backend/measure.py re-run against the full
fixture corpus, byte-identical to the documented baseline (no extraction
code touched). npm run build passes; every new FontAwesome icon
(fa-download, fa-file-csv) confirmed present in the installed set
before use. The app container was rebuilt and confirmed serving the new
bundle.
Not machine-verified: the actual click-through - does the dropdown open/close correctly on hover and click, does it render in the right position without overflowing the card's own edge, does each menu item trigger the right flow - Claude-in-Chrome did not connect this session, same standing limitation as every other UI-only change in this file. This one is worth a real look given how much UI structure changed in one pass.
Per-transaction "include in downloads" checkbox, shipped 2026-11-19 - the explicit "exclude" half of this product's own "Full Data Control" claim ("Review, edit, or exclude any individual transaction on your screen before converting"). Deleting a row (the existing R.4 "Delete row" structural action) already covers this, but it's destructive and permanent - it removes the transaction from the on-screen data entirely and re-runs every check against the smaller set. The ask here was for a lighter, reversible alternative: a checkbox beside the edit button that controls only whether a transaction ends up in the NEXT download, with zero effect on the live review screen.
Deliberately a separate column, not crammed into .row-actions. That
cell already came close to overflowing once this session (see "Flagged
rows' edit pencil visually disappearing" above - a real <colgroup>/CSS
width mismatch, not a logic gate) once a flagged+editing row needs flag-
toggle + save + cancel + more = 4 icons in a cell originally sized for
3. Adding a 5th, semantically different kind of control (selection, not
an action) into that same crowded cell would have made that exact class
of bug more likely to recur, not less. A checkbox is a different
category of control than an action button, so it got its own 34px
.row-select column instead - recomputed the full fixed-column-width
math from scratch (578px fixed + 160px Description floor = 738px
min-width) rather than patching the old 704px number, the same
discipline that earlier bug fix itself called out as the thing to get
right next time this changes.
Deliberately non-destructive and export-time-only, not wired into
/api/recheck or the live UI at all. excludedFromExport (an array of
original transaction indices) lives directly on doc.result, the same
arbitrary-JSON-blob pattern acknowledgedFlags/editLog already use -
no new PocketBase migration needed. Unlike every R.4 structural action,
toggling it never calls persistAndRecheck() - the on-screen
transactions/checks/status are completely unaffected; the array is only
ever READ at the moment a download is actually built
(TransactionsTable.vue's own resultForExport(r)), which filters
r.transactions down before handing the result to whichever export
function is about to run. This single helper is applied at all four
single-document export call sites (handleDownloadCurrent,
proceedQboExport, handleDownloadXeroCsvClick) and inside
handleDownloadAll's own per-document loop (using THAT document's own
excludedFromExport, not the active document's) - covering every
format (QBO/Xero/CSV/Excel) and both single/all download paths with one
function, not four near-duplicate copies.
One real consequence of filtering before the backend's own recheck
call, confirmed deliberate rather than papered over: /api/export*
re-runs pipeline_service.recheck() against whatever transactions
array it's handed, same as it always has - so excluding a transaction
can genuinely change the exported file's own embedded check status
(e.g. a CSV's per-row "Check flags" column, or Excel's Summary sheet) if
removing that row changes the running-balance chain. This is intentional,
not a bug to fix: the export's own checks describing the ACTUAL exported
content is more honest than showing stale checks computed against data
that isn't in the file, and it's the user's own deliberate, visible
choice (an unchecked box), not a silent omission - the same distinction
this file's own governing rule (below) already draws between a
deliberate, visible user action and a silent auto-correction.
Header "select all / deselect all" checkbox, tri-state via direct DOM
property manipulation. Operates on the currently VISIBLE rows
(useTransactionFilters.js's own visibleRows), not every transaction
in the document - the standard data-table convention, and the one that
lets a filtered view (e.g. "Flagged only") be selected/deselected as its
own subset without affecting rows currently hidden by a filter. Checked
when every visible row is included, unchecked when every visible row is
excluded, indeterminate when mixed - clicking it excludes all visible
rows if they're all currently included, otherwise includes all of them
(the standard "select all" toggle). The indeterminate DOM property has
no reflected HTML attribute, so Vue's own v-bind attribute-vs-property
heuristics can't be trusted to set it correctly from a template
binding alone - set directly via a template ref + watchEffect
(selectAllCheckboxRef.value.indeterminate = ...) rather than risking a
silently-no-op :indeterminate binding.
Excluded rows get a plain visual cue (tr.excluded td:not(.row-select) :not(.row-actions){opacity:.5}) - dims the row's own data cells so it's
visibly different from an included one, while deliberately NOT dimming
the checkbox or the action-icons cell, so both stay fully legible/
clickable even on an excluded row (re-including it, or still editing/
flagging/deleting it, should never require fighting a half-opacity
control to do so).
Verified: 12 direct assertions against the REAL, already-committed
extractionStore.js (not a reimplementation) executed via a plain Node
script against real Pinia - default state (nothing excluded), a single
toggle on/off, bulk exclude/include over a set of indices (confirming a
bulk re-include only touches the indices actually passed, leaving
others alone), and idempotency (excluding an already-excluded index
doesn't duplicate the stored array). 5 further assertions against the
exact resultForExport() logic now living in TransactionsTable.vue
(copied byte-for-byte into the test, not re-derived) confirmed: the
no-exclusions case returns the SAME object reference (a cheap no-op,
not a wasted copy on every download); excluding one transaction removes
exactly that one, in the right order, with every other field passed
through unchanged; excluding every transaction correctly produces an
empty list rather than erroring. Confirmed directly from checks_service .py that nothing in check_page_coverage/check_engine_agreement
(both page_reports-only) or check_structure_sanity (transactions-only)
cross-references transaction COUNT against page_reports in a way a
shorter, filtered list could break - a smaller transactions array
changes what the checks CONCLUDE, never causes an error. npm run build
passes; the app container was rebuilt and the actual served JS bundle
(fetched directly from the running container, not just the local build
output) confirmed to contain excludedFromExport/row-select as real,
unminified string literals (property keys and a CSS class name survive
minification; local function/variable names like toggleSelectAllVisible
don't, and correctly didn't show up in the same grep). backend/ measure.py re-run, byte-identical to the documented baseline (zero
backend Python touched - this is entirely frontend state plus an
export-time filter over data the backend already accepts in any length).
Not machine-verified: the actual click-through - checking/unchecking individual rows, the header checkbox's tri-state behavior across a filtered view, confirming an unchecked transaction genuinely doesn't appear in a real downloaded file for all four formats - Claude-in-Chrome did not connect this session, same standing limitation as every other UI-only feature in this file.
Governing rule: never silently correct or exclude data. This shows up in several concrete places, not just as an abstract principle:
- A row with an unusual status (e.g. HSBC's "Cancelled" wires) stays in the output and is allowed to break the running-balance chain, surfaced as a flag — the earlier in-app categorizer tool used to silently drop these rows before running checks; this product deliberately does not repeat that.
- An ambiguous narrative-attachment gap (see below) is flagged (
ambiguous_indices), not guessed toward whichever direction seems more likely. - Engine disagreement between Docling and pdfplumber is flagged with specifics, never auto-resolved by picking one engine's result.
- The opening/closing balance input fields never auto-fill — a separate read-only "Calculated" readout shows the auto-detected value instead, so the UI never shows a number in an editable field that the user didn't actually type themselves.
Narrative-direction detection went through a real debugging cycle worth knowing about
if this logic needs to change again. The first approach — counting blank lines to guess
which transaction a wrapped description belongs to — was wrong for RBC (confirmed via an
Oyster payroll example where text was misattributed to the preceding fee transaction
instead of the correct following one). The fix was a per-gap hybrid in _decide_gap():
an explicit column label (e.g. "Narrative") is the primary, always-confident signal when
present; geometric vertical-proximity is the fallback when no label exists. A second bug
surfaced during this fix: HSBC's narrative label line usually has no text after the label
word itself, so filtering empty-text rows before checking their label flag silently
dropped the label signal. Fixed by tracking saw_label as its own boolean, updated
regardless of whether that row's own text is empty, independent of the buffer list
(which only holds non-empty entries).
RBC page-4 footer absorbed into the last transaction's description, fixed 2026-10-12.
The permanent regression case the RBC fixture's ground truth was built to catch (see
"Outstanding before Phase 1" above): RBC prints Account Fees: $48.75 directly under
"Closing balance" on the statement's last page - a real summary line, not transaction
data, but one extract_page() had no reason to recognize as anything special. It isn't
a money token by this module's own definition ($48.75, not 48.75 - the $ fails
_MONEY_RE), has no reference-number prefix, and isn't a page-number footer, so it fell
through to plain narrative text; being the very last row on the statement with no
following transaction to lead into, rows_to_transactions's own trailing-leftover-buffer
rule (correctly, by its own logic - nothing here was buggy in isolation) attached it to
the last real transaction above it. The fix treats the closing-balance line the same way
the header row is already treated: a position-based boundary, not a text pattern to
special-case. extract_page() now sets after_closing_balance = True the moment it
recognizes that line (same spot it already captures the figure for
extract_statement_facts) and skips every subsequent line on the page outright, before
it ever reaches the money/narrative classification that swept the footer in originally.
Confirmed safe for HSBC, which never emits a closing_balance row at all (its balance
prints outside the table, already excluded by the header-top preamble filter) - the flag
simply never flips there, so this is a pure no-op on that bank's own path. Verified via
measure.py (RBC's field accuracy went from 0.9977 to 1.0, HSBC unaffected) and a real
/api/process call against the running container (last transaction's description is now
just "Misc Payment VSA FEE11112299", transaction count still 108). RBC's overall
status is still "Failed" after this fix - a separate, pre-existing, already-documented
engine_agreement disagreement on page 4 (see "Docling spike finding" and the column-
collision note in the Architecture section), not something this fix touched or was ever
meant to resolve.
Balance-chain and date-ordering direction are auto-detected, not hardcoded per bank —
checks.py tries both forward and backward (and both newest-first and oldest-first) and
keeps whichever has fewer violations, because RBC and HSBC don't share a convention and a
third bank is unlikely to either.
UI iteration has mostly been many small, specific, explicitly-approved requests — the
one explicit correction worth remembering: an early request to fix the Date/Amount/Balance
column widths was initially (wrongly) read as "remove the side-by-side resizer layout
entirely." The correct scope was much narrower (fixed-width columns via <colgroup> +
table-layout:fixed, Description column left flexible) and the resizer/side-by-side
structure was never meant to change. When a UI request could be read either as a small,
scoped fix or a larger structural change, confirm before assuming the larger one.
OCR / scanned statements (added 2026-10-11, routing built; real-world reliability
unresolved). pdfplumber has zero OCR capability — confirmed by building an image-only
PDF (no text layer, same as a real scan) from a real statement page and watching
extract_text() return nothing. Before this work, the pipeline's own guard clause
(if not any(pages_rows.values())) caught that and raised a misleading error — "could
not recognize this statement's column layout," which is the message written for a
different problem (a text PDF whose bank layout isn't supported yet), not "no text layer
at all." reconcile._needs_ocr() now distinguishes the two: a raw image upload or a
scanned/photographed PDF routes to _run_ocr_only() (Docling's OCR as the sole canonical
source, correctly worded error if even OCR fails), while a text PDF this extractor just
doesn't recognize still gets the original, differently-worded error.
An OCR-sourced extraction can never reach "Verified" — checks.check_ocr_source() always
reports needs_review, by design: there is no second engine to cross-check Docling's OCR
against, so the core safety property every other check result rests on (two independent
engines, never trust one alone) doesn't hold here. This is enforced by construction (the
check's own outcome), not a bolted-on status override.
The honest limitation this surfaced, confirmed empirically, not assumed: Docling's own
table-structure recognition is meaningfully less reliable on rasterized/OCR'd input than
on a native PDF's text layer — this was already known from the original Docling spike (see
above) on the clean text-PDF path; this work reconfirmed it's worse again once OCR is
also in the loop. Four real test renders this session, same real HSBC statement, different
pages/settings: page 1 alone → Docling merged the account-summary preamble block in
above the real header row into one table (fixed here — ocr_table_to_rows now searches
for the header row via the same pattern table_extract._find_header_row already uses for
pdfplumber, rather than assuming row 0); that same render also merged "Credit amount" and
"Debit amount" into a single cell, which can't be safely split back into two columns after
the fact (the column-collision detector correctly refuses to guess, leaving debit
unresolved) — not fixed, and not safely fixable by reshaping alone. Page 2 alone, at both
200 and 300 DPI, wasn't recognized as a table at all (flat OCR text instead, same failure
mode the original spike documented on page 4 of the clean PDF). So: the routing and
row-reshaping infrastructure is built and unit-verified correct (confirmed end-to-end
through the real running app for both a text-PDF upload and a raw-image upload), but
whether a given real scan or photo actually extracts anything still depends on Docling's
own, inconsistent table-structure call on that specific image — not something this session
resolved, and not something straightforward to fix from this repo's side (it's the
external model's own behavior, not a parsing bug in this codebase). Test images from this
session are kept at docs/scanned_statement.pdf and docs/scan_test_page-1.png for
whoever picks this up next.
PaddleOCR (PP-StructureV3) was benchmarked and rejected, 2026-10-11. Built as a
standalone adapter (own venv — paddlepaddle has no wheel for the main app's Python
version), reshaping its table output into the same canonical row format Docling's OCR
path uses and run through the real table_extract.rows_to_transactions/checks.run_all
pipeline — not just a raw-OCR-text comparison. Against the same problem image Docling
struggled with (docs/scan_test_page-1.png), PP-StructureV3 did worse, not better: its
table-structure HTML was more severely corrupted (mismatched colspans, cell content from
different real rows jumbled together), and while its best candidate header row recovered
status/date/credit/debit correctly, the "Balance" column header was lost entirely
with no recoverable cell anywhere — one field short of usable, 0 transactions extracted.
One data point against one hard image, not a broad verdict, but enough to not pursue it
further here — the adapter code was removed rather than kept unused.
raw_ocr_extract.py (now backend/services/extraction/raw_ocr_extract.py) — a working
fallback for Docling's OCR-structure failures, shipped 2026-10-11. Also benchmarked: Docling's own alternate OCR engines (tesseract,
rapidocr) and table_mode: fast against the same problem image — all produced the
identical grid (same merges, same failure) or worse; neither the OCR engine nor the table
mode was ever the actual bottleneck. The real fix came from a different idea: don't trust
ANY table-structure model's row/column grouping at all. Run OCR directly (tesserocr) to
get raw per-word text + pixel position, then reuse table_extract.py's own column-
geometry logic (_find_zones/_classify_money/etc. — the same code already proven
correct for HSBC and RBC's real pdfplumber path) to derive columns from word geometry
itself, same as it already does for a native PDF.
Two adaptations beyond the pdfplumber path, both confirmed necessary by testing against real rendered pages, not assumed:
- Pixel-to-point scaling.
_assign_money_columns'smax_distance=60is tuned for PDF points (72/inch), meaningless for raw pixel coordinates. For a scanned PDF the exact scale is knowable (pdfplumber reports a page's real point-dimensions even with no text layer) and used directly. For a bare photo with no PDF page to anchor against, there's no way to know true scale, so the image's own pixel width is treated as if it were a standard portrait US Letter page (612pt) — a real, documented assumption, not a fact; wrong for a landscape photo or non-Letter paper. - Cross-page zone sharing. A single page with one-sided data (e.g. zero debit
transactions, confirmed for real on HSBC's own page 1) makes its own column-clustering
genuinely ambiguous — its lone value cluster can get assigned to the wrong field purely
by which header word sits pixel-closer, a geometric coin-flip with no data on that page
able to correct it (confirmed for real: this exact case resolved correctly in one test
run and would plausibly resolve wrong in another — it is NOT reliably fixed when only
one page exists, see below).
table_extract.py's owncarry_zonesonly carries FORWARD; this instead resolves zones on every page first, keeps whichever page resolved the MOST complete shape (both credit and debit present), and applies that single zone definition across every page. Confirmed fixing a real case: HSBC page 1 (all credits) alone always mis-signed every amount as a negative debit; processed together with page 2 (which has real debits, resolves cleanly on its own), page 1's 7 transactions came back with correct positive amounts, deterministically, every time — verified through the actual running app, not just the extraction function in isolation.
Wired into reconcile._run_ocr_only as a per-page fallback, not document-level —
confirmed necessary for real: on an actual 2-page scan, Docling succeeded on page 1 but
missed page 2's table entirely in the SAME conversion call; a document-level "did ANY page
get rows" check would have silently kept page 2 empty (10 real transactions, including
both debits, would have vanished with no error) since page 1 alone made the overall result
non-empty. The fallback runs the whole document through raw_ocr_extract whenever any
page comes back empty from Docling (so its cross-page zone-sharing can still use a good
page), then only replaces the specific pages Docling actually failed — a page Docling got
right is never second-guessed. page_reports[].status is "ocr_only" or "ocr_raw_words"
per page so it's visible which engine produced which page. Verified end-to-end through the
real running app on a genuine 2-page scanned test file
(docs/scanned_statement_2page.pdf, built from real HSBC pages 1+2): 17/17 transactions,
correct signs, correct balances; date_sanity correctly flagged the one real OCR date
misread rather than hiding it. measure.py confirms zero regression on the existing
text-PDF corpus.
Known, honest limitation, not glossed over: the one-sided-data edge case above is only
reliably fixed when a SECOND page with both debits and credits exists to borrow zones from.
A genuine single-page photo upload with only one-sided data on it has no second page to
borrow from — the geometric assignment stays a close call, and which way it resolves isn't
guaranteed. New dependencies: tesserocr, pypdfium2, pillow, plus tesseract-ocr/
libtesseract-dev/libleptonica-dev at the OS level (Dockerfile) — TESSDATA_PREFIX must
be set explicitly (/usr/share/tesseract-ocr/5/tessdata); tesserocr does not reliably
auto-discover Debian's tessdata location on its own (confirmed for real: failed with
"invalid tessdata path: ./" without it).
Phase 4 dropped, 2026-11-24 - explicit user decision, not a Claude judgment call. Phase 4 (the spec's own multi-tenant practice/client model, a real Frappe-style tenant entity sitting above a plain user account) is no longer "not started" - it's removed from this product's roadmap entirely. The user's own framing: "a user would be able to use the projects feature as a way of handling different clients [on] their account." A bookkeeper or accountant with several clients creates one project per client inside their own single account - already fully built (PocketBase Stage B.1-B.3, 2026-10-13) - rather than this product ever growing a second, separate tenant/organization layer above the account itself.
This resolves, permanently rather than provisionally, a gap this file already
flagged honestly at the time the layout mapper was built (see "A real gap flagged
explicitly" under the Layout mapper entry above): the spec's own data model (§9)
ties a Layout Mapping to a Practice/Client, and several already-shipped features -
the layout mapper's own cross-user sharing/promotion hook, the admin review screen,
categorization rules, bank account profiles - were all built using "a different
users account" as the honest stand-in for "a different practice," with this file's
own language explicitly saying to revisit that once Phase 4's real model existed.
That revisit will not happen - a users account is now this product's permanent,
final unit of isolation, and "client" maps onto project, not onto any account/
tenant boundary. Nothing in the already-built schema or code needed to change for
this decision itself (every one of those features already used exactly this model);
this entry exists so the "stand-in, revisit later" framing scattered through this
file's own history reads correctly going forward - a few of the more load-bearing
mentions were updated in place to point here, but older verification notes
describing a specific past test (e.g. "a second, different users account" in a
layout-mapper verification paragraph) were left as the accurate historical record of
what was tested, not rewritten.
One real, concrete consequence worth naming, not just a renaming of the status column: this means a layout mapping, a categorization rule set, or a bank account profile can never be shared automatically across two of one bookkeeper's own DIFFERENT clients (two projects under the same account) the way they already are shared automatically across two independent USERS who happen to upload the same statement layout - project-level sharing was never built and isn't implied by this decision. If that turns out to matter in practice (e.g. the same new bank layout showing up for two of one bookkeeper's own clients), it's a new, separate feature request to design later, not something this decision already covers.
Real fixtures removed from git history, replaced with a synthetic corpus,
2026-11-24 - ahead of this repo's first push to a remote. Before this repo had
ever been pushed anywhere, a check of what it actually tracks found that
fixtures/HSBC-USD-Sep2026.pdf/HSBC-USD-August2026.pdf/RBC-CAD-Aug26.pdf (plus
their own _ground_truth.xlsx siblings) and a handful of docs/ files
(docs/HSBC-USD-Sep2026.pdf, docs/RBC-CAD-Aug26.pdf, docs/scanned_statement.pdf,
docs/scanned_statement_2page.pdf, docs/scan_test_page-1.png,
docs/bank_statement_categorizer/description_rules.csv) all contain REAL financial
data, not synthetic test material - a real account name ("PLANETERRA INTERNATIONAL
FOUNDATION"), a real account number, and a real Royal Bank of Canada business
account statement, confirmed by actually reading the PDFs' own extracted text
(pdftotext), not assumed from the filenames. These had been sitting in this
repo's git history since the very first commits this file documents, entirely
unflagged at the time - this repo's own "no DB, no PII" framing never actually
applied to its own test fixtures.
Fixed in two parts, both completed BEFORE the first push: all of those files were
removed from EVERY commit in git history (not just the latest) via git-filter-repo --invert-paths, confirmed clean afterward (git log --all -- <path> returns
nothing for any of them); the real files themselves were then restored to disk from
a backup and re-added to .gitignore by EXACT filename (not a blanket fixtures/
ignore, which would have hidden a future synthetic replacement fixture too) -
measure.py and manual local testing keep working off the real files, they just
never reach the remote.
This left backend/measure.py's whole regression corpus empty from a fresh
clone - fixtures/ had nothing else in it, so removing those three pairs left
nothing committed for measure.py to discover at all; a clone on another machine
(or a different environment, like the one that built the fix below) would see zero
fixtures. Fixed the same day with fixtures/generate_synthetic_fixtures.py
(reportlab + openpyxl) - two invented bank statements (fake org names, fake account
numbers), each built from one shared Python list of transaction data used to write
BOTH the PDF and its own _ground_truth.xlsx, so the two can never drift apart by a
transcription mistake the way a hand-verified real fixture's ground truth could.
Deliberately keeps every description on a single line with its amount on the same
line - no attempt to replicate HSBC's trailing-"Narrative"-label convention or
RBC's leading-wrap convention; that row-grouping complexity is already proven
elsewhere in this file's own history and isn't this corpus's job to re-prove, and
skipping it is what makes the ground truth exactly derivable from the generator's
own data rather than needing a human to re-verify it page by page the way the real
fixtures' own ground truth was built.
Two genuinely different column shapes, still exercising the "bank-agnostic" claim
this harness exists to prove: Fake-Bank-A-Synthetic (split Debit/Credit columns,
newest-first order, no in-table opening/closing balance - HSBC-style, debit printed
as a plain positive magnitude rather than self-signed) and Fake-Bank-B-Synthetic
(a single signed Amount column, oldest-first order, WITH in-table Opening
balance/Closing balance rows - RBC-style). Column x-positions were tuned against
real reportlab.pdfbase.pdfmetrics.stringWidth measurements and a real
_find_zones() debug run, not hand-calculated and trusted blind - a first draft's
description column sat close enough to the date zone's own computed upper bound
that every row's description bled its own first word into the date field (and, for
Fixture B specifically, broke the exact-phrase match its Opening/Closing balance
rows depend on) - caught by actually running the real extractor against the
generated PDF before ever treating it as finished, the same discipline this file's
own history already insists on everywhere else.
Verified, all real: python3 backend/measure.py against the full 5-fixture
corpus (the two new ones alongside the three real, still-local ones) - both new
fixtures report field_accuracy=1.0, zero count mismatches, and correct
opening/closing balance matches (None/None for Fixture A, matching
extract_statement_facts' own real behavior for a layout with no in-table balance;
the real printed figures for Fixture B). Neither reaches "Verified" in THIS
environment specifically because the Docling container isn't running here - every
page degrades to pdfplumber-only (engine_agreement = needs_review), which is
measure.py's own already-documented degraded mode ("Works with or without the
Docling container up... same behavior as the live app"), not a defect in either
fixture - confirmed by running every other check directly and seeing
statement_balance/running_balance/date_sanity/structure_sanity/
page_coverage/narrative_direction all pass cleanly for both. The three real
fixtures were re-measured in the same run and are unaffected (same field accuracy,
same statuses modulo the one expected Docling-unavailability difference: RBC reads
"Needs review" here rather than its documented "Failed", since reproducing that
real page-4 engine MISMATCH needs Docling to actually respond and disagree, not
just be unreachable - HSBC-Aug's own "Failed" is untouched, since that one comes
from a real running-balance break, not engine agreement at all).
Frontend / UI state (as of 2026-10-13)
Theme is enterprise-light, not the Bettersight brand default. UI_DESIGN_THEME.md
specifies a dark-first brand system (deep navy base, single lime-green accent) — that's
the default for Bettersight-family products. This app was explicitly converted away from
that default, on direct user request, to match a specific enterprise-SaaS reference
screenshot (light background, standard blue #2563EB accent, white cards, 8px radii). The
conversion kept the same set of CSS custom properties defined in UI_DESIGN_THEME.md
(same names, same count) and only changed their values — including reusing that doc's own
already-specified "light surface" and "text on light surfaces" token values where they
existed, rather than inventing new ones. This lives in frontend/src/assets/main.css now
(moved verbatim in the Vue restructure — see Key decisions & lessons — not rewritten). If
asked to touch the theme again, preserve this token-value-only discipline rather than
restructuring the :root block or hardcoding colors inline.
Key current UI behaviors, each the result of an explicit, specific user request (don't "simplify" these away without asking first) — implementation pointers reflect the Vue restructure; the behavior itself predates it and is unchanged:
- The upload zone accepts
.pdf,.jpg/.jpeg, and.png(added 2026-10-11 for OCR support — see "OCR / scanned statements" above). A PDF renders via pdf.js as of 2026-10-13 (usePdfViewer.js— one<canvas>per page, stacked in a scrollable column; the browser's own native viewer/toolbar is no longer used, since the review screen needs to draw a highlight box on a specific row, which an<iframe>has no hook for — see "Review screen" under Key decisions & lessons); an image gets its own dedicated zoomable/scrollable panel (useImageZoom.js) — both expose the same −/+/Fit controls, both open at fit-width by default, and both now support drawing a highlight box at a givensource_bbox(showHighlight/clearHighlight, exposed bySourceDocumentPanel.vue— not called from anywhere yet, that's the review screen's still-unbuilt R.2). - Multiple files can be picked/dropped at once (
FileUploadZone.vue's file input now hasmultiple, added 2026-10-13), extracted SEQUENTIALLY (useBatchExtraction.js, one/api/processcall at a time) with "Extracting N/M: filename — " progress. The very first document to finish becomes the active one shown on screen; every document after that is added without moving focus away from whatever the user currently has active, since they may already be reviewing or editing it (see "Multi-document upload..." under Key decisions & lessons for the full reasoning).DocumentNavBar.vue(visible once there's more than one document) provides ◀/▶ to browse completed results, swapping the Transactions table, the Source Document preview, and the visible document name together as one unit - all three readextractionStore.activeDocument/activeIndex, soDocumentNavBaris the only component that needs to know navigation exists at all. Lives INSIDETransactionsTable.vuenow (moved there 2026-10-13, per explicit request - it started as its own standalone bar aboveResizablePanels, spanning the whole page) - rendered first, across the top of the transactions card, above the Hide/Show Source Doc row, with no border/background box of its own since it's already inside the card's (just a bottom border separating it from the "Transactions" title beneath). Picking/dropping ADDS to the staged list (useFileUpload.js'schosenFiles) rather than replacing it (fixed 2026-10-13 - the first version replaced it, so picking a second file after a first lost the first entirely, reported by the user as "I select one document and start again to select another, the first one is replaced") - a batch can be built up across several separate picks/drops, not just one multi-select dialog. Each staged file shows with an × to remove it before Extract is ever clicked (FileUploadZone.vue's.staged-fileslist); an exact duplicate (same name+size as something already staged) is silently skipped rather than appearing twice. The staging list is cleared the moment Extract is clicked (not after the batch finishes) so an already-handed-off file can't sit there and get accidentally re-processed (and duplicated inextractionStore.documents, which has no dedup of its own) by a later click. - PDF/image ("Source Document") and Transactions sit side-by-side with a draggable resizer
(
ResizablePanels.vue, the handle styled as a vertical grip-knob), both wrapped in one sticky flex row so they scroll as one unit (not the source-doc column alone)..txn-colhascontainer-type:inline-size/container-name:txncol(added 2026-10-12) so layout rules that need to react to this column's own width — not the viewport's — can use@container txncol (...)instead of@media. This matters because the resizer can narrow this column well below a comfortable width on an otherwise-wide screen, a case a@mediabreakpoint never sees at all (confirmed as a real bug: the balance fields + Recheck Balance button used to only switch to a stacked, narrow-friendly layout under an actual narrow viewport — dragging the resizer narrow on a wide screen left them overflowing the column's right edge instead, since no rule was watching the column's own width). The@container txncol (max-width:520px)rule that replaced the old@media (max-width:640px)one covers both cases now with one mechanism — real mobile included, since.txn-colis just as narrow as the viewport there too (see the 860px breakpoint below). Same root cause nearly broke the transactions table's own Description column:table-layout:fixed+width:100%shrinks EVERY column proportionally (including the fixed-pixel ones) to fit whatever width it's given, which would otherwise squeeze Description unreadable long before the column hit its absolute 260px floor. Fixed withmin-width:664pxon the<table>itself (the fixed columns' own widths sum to 504px; 160px is a legible floor for Description) — below that,.table-wrap's ownoverflow-x:autotakes over and the table scrolls horizontally instead of compressing further, while at or above 664pxwidth:100%still governs exactly as before. Both panels' own fixed height (.pdf-col/.txn-col) is102.5vh(raised 25% from the original82vhper request, 2026-10-13) - both still track each other exactly, same "fixed total card height, same pattern" relationship documented where each rule lives. - A Hide/Show toggle in the Transactions header (
TransactionsTable.vue, driven byuiStore.pdfColHidden, labeled "Hide Source Doc"/"Show Source Doc") collapses the source-doc column so Transactions fills the row. - The Transactions column's own vertical order, as of 2026-10-30:
.txn-col-head(JUST the "Transactions" h2, no actions beside it) is the FIRST thing in the column, so it aligns horizontally withSourceDocumentPanel.vue's own "Source Document" heading on the sibling panel - both are simply the first child of a sibling flex column under.review-grid'salign-items:start, so no extra CSS was needed once each was literally first. Second is the former top bar (Results dropdown/DocumentNavBar/Accept/Download,.txn-top-bar- see the next bullet for what it contains). Third is a new.txn-actions-row, directly above the balance fields: "Move to project" at the LEFT, and a.txn-actions-rightgroup (Flagged only/Next flagged/Hide Source Doc) at the RIGHT, one space-between row rather than three things stacked across two different rows the way an earlier same-day pass had it (that pass put "Move to project" up in the title row instead - corrected per explicit feedback once it shipped wrong). TransactionsTable.vue's own top bar (replacing the old standaloneResultCard.vue, deleted 2026-10-13) is a 3-part row: a "Results" toggle on the left opens a hover-sticky dropdown (click to open; closes automatically once the mouse leaves the trigger+panel area, viauiStore.resultsOpen/toggleResultsOpen/closeResultsOpen) showing the status banner + checks list;DocumentNavBarsits truly centered in the middle (CSS Grid, not flexspace-between); the Download button is on the right. Every fresh extraction starts with the dropdown closed. With more than one document loaded (and no batch still running), Download opensDownloadChoiceModal- "current document" vs. "all N documents" - instead of a permanently-visible second "Download All" button; with exactly one document it downloads immediately. "All" builds every loaded document's own export and bundles them into ONE zip download (Statements_Export_<date>.zip, via thejszippackage - see "Download All bundles into a single zip" under Key decisions & lessons for the full record and the real filename-collision case it handles), not N separate browser downloads - fixed 2026-11-16, since some browsers prompt to allow multiple downloads from one click. Every document's own export is still persisted individually to PocketBase/R2 (documentsService.saveExportFile, best-effort - a failure there is reported but never blocks the download itself) - the latest export only, overwritten each time, not a history (no retention policy has been decided yet).DocumentNavBar.vue's filename is clickable (a hover state + trailing muted ellipsis icon signal it, since it looks like plain text otherwise) - opensDocumentOptionsModalto rename it, or hands off to a secondConfirmModalto delete it (red confirm button, stays open with a spinner until the request resolves). Renders for any loaded document, not just once there's more than one - deleting a single loaded document before downloading it doesn't require a second document to exist first.- Opening/closing balance inputs always start blank (never auto-filled) — a separate
read-only "Calculated: $X" readout below each one shows the auto-detected or typed value,
turning green when the
statement_balancecheck outcome is "pass". Deliberate, to reduce confusion about what's user-entered vs. auto-detected. One real asymmetry worth knowing if this is ever touched: the opening readout is a snapshot of the ORIGINAL extraction's ownopening_balance(the backend never returns a new one on recheck, only status/checks change) while the closing readout recomputes live on every recheck — confirmed by reading the original vanilla-JS implementation closely before the Vue rewrite, and reproduced deliberately rather than "fixed" as an inconsistency (seeTransactionsTable.vue's own comment). - An explicit "Recheck Balance" button (
TransactionsTable.vue) re-runs just the checks (via/api/recheck, no re-extraction) against whichever balance values are currently effective —extractionStore.effectiveOpeningBalance/effectiveClosingBalance: the typed input if non-blank, else that frozen originalopening_balance/closing_balancefrom the initial extraction — so clearing a typed value and clicking Recheck restores the statement's own original figures, same check as the first run. Added so a user who forgot to type a balance before Extract can still run the full check afterward (typing alone was never wired to a recheck, same as the original vanilla-JS version — only a row Save or Download triggered one). Below the fields, anerror-notesurfaces the check's owndetailtext whenever the outcome isn't "pass": a leading "Balance doesn't match the statement — " prefix for "fail" (its own detail is just the raw math), no prefix for "not_available" (its detail — "No opening and/or closing balance available..." — already reads as a complete sentence) — both outcomes used to leave the readout silently grey with no explanation; "not_available"'s case was only noticed and fixed 2026-10-12, after "fail" already had it. On wide viewports the button is wrapped in.recheck-wrapwith an invisible.recheck-spacerlabel above it mirroring.fields label's own box (same font-size/margin-bottom) — this lines the button's top edge up with the balance inputs' own top edge rather than the row's labels. Matching the top edge alone turned out not to be enough (confirmed by the user after the first pass):.btn-toggle's own padding makes a button naturally shorter than a balance input (which has more vertical padding plus a 1px border), so top-aligning two boxes of different heights still reads as slightly off-center. Fixed by giving both an explicit, equalheight:36px(flex- centering the button's own text inside it) instead of leaving either height to the browser's own font-metric-driven "auto" — a hardcoded pixel offset would have been fragile to any future font-size/padding change, but equal explicit heights on both elements can't drift apart from each other even if those values are ever touched. The spacer is hidden at the 640px mobile breakpoint, where the button drops below the fields instead (see above). - Sort + filter/search on the transactions table (
TransactionsTable.vue+useTransactionFilters.js, added 2026-10-12) — purely client-side display state, no backend involvement, same scope asuseImageZoom.js. Each sortable header (Date, Description, Amount, Balance, Status) gets its own up/down arrow pair (.sort-arrows/.sort-arrow) rather than one toggle arrow, so both directions stay visible; the active column+direction turns blue. A second<tr class="filter-row">sits inside<thead>, directly beneath the header row (so it inherits the samecolgroupwidths viatable-layout:fixed) — free-text filter inputs per column (Description's doubles as the search box), Status as an exact-match<select>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/useRowEditingread and writecurrentResult.transactionsby its own ORIGINAL index, not by position in whatever's currently displayed — sovisibleRowsis 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, eachposition: sticky) — these used to be ONE rule matching everythead thwithtop: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 owntopby 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) — nowuiStore.layoutVersionbumps on that toggle (and on a resize-drag ending) and every row's own textarea watches it to re-measure. - Every row, not just a flagged one, highlights its own printed position on the
source document when clicked (added 2026-10-30) - clicking anywhere in a
TransactionRowoutside its own action buttons (handleRowClick, which excludes.row-actionsso Edit/Save/Cancel/the flag toggle/the "more actions" menu all keep their existing behavior untouched) calls the sameshowOnSource()the flag panel's dedicated button already called - one definition either path uses. A no-op for a row with no realsource_bbox(an OCR-sourced row).tr.has-position td:not(.row- actions)getscursor:pointerplus atitletooltip as the visual affordance. - A flagged row (added 2026-10-13, review screen R.2) gets its own amber flag-icon
toggle in the row-actions cell, opening a second table row beneath it with a
plain-language explanation for every check that flagged it (what/why/what-to-do -
flagCatalogService.js) and its OWN "Show on source" button (same highlight, now one of two ways to trigger it) that boxes the row's own printed position on the source document (disabled when no position data exists for that row - see R.1'ssource_bbox).TransactionsTable.vue's own header gets "Flagged only" (filters the table to just flagged rows) and "Next flagged" (cycles through flagged rows, scrolling each into view) once anything is actually flagged. Arunning_balance-flagged row may also show a suggested fix (added 2026-10-13, review screen R.3) in that same panel - evidence text plus an "Apply fix" button; note the fix can apply to a DIFFERENT row than the one the panel was opened from (the balance-chain check's own bridging logic means the row that's actually wrong isn't always the one the mismatch is reported against - see R.3's own entry). - Every row also has a "more actions" popover (added 2026-10-13, review screen R.4,
row-btn.more) with structural edits: flip debit/credit, insert a row after (blank, for one the extractor missed), split this row (duplicates the row's own values into a new one right after - the user divides them manually, nothing is auto-split), merge with the next row, delete this row. Delete and merge each confirm via the sameConfirmModalpattern every other destructive action in this app uses. - Every row also has its own "include in downloads" checkbox (added 2026-11-19, its
own
.row-selectcolumn beside.row-actions) - unchecking it leaves the row fully intact and editable on screen, it's just left out of every download format (QBO/ Xero/CSV/Excel) the next time one is built. A header checkbox selects/deselects every currently-VISIBLE (filtered) row at once, tri-state when mixed. Deliberately separate from "Delete row" above - that one is permanent and re-runs every check on a smaller dataset; this one changes nothing about the live review screen at all. - Every mutation above (manual cell edit, suggested-fix apply, every structural
action) also appends an entry to the document's own edit log (added 2026-10-14,
review screen R.5 -
extractionStore.appendEditLogEntry), included as an optional "Edits" sheet in the downloaded Excel workbook. Each flag in a row's flag-detail panel (R.2) also gets its own "Mark as checked"/"Acknowledged" toggle - reviewing a flag doesn't change any data, it just records that a human looked at it (e.g. a genuine Cancelled-wire balance break that's correct as-is, nothing to fix). A new "Accept"/"Accepted" button inTransactionsTable.vue's top bar, beside Download, is enabled once the statement is "Verified" or every flagged row has been acknowledged. - All numeric displays are comma-formatted (
formatService.js'sfmtMoney/fmtNum). - Edits persist to PocketBase (
documentsService.js'ssaveDocument/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'sloadDocuments(), 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/processis 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
- Write
measure.py(the harness from the plan's step 10) and actually run it. Lives atbackend/measure.py, run aspython3 backend/measure.pyfrom the repo root (or inside theappcontainer). Auto-discovers its corpus: everyfixtures/*.pdfwith a matching<name>_ground_truth.xlsxsibling is measured for both of section 11's measures (untouched pass rate, field accuracy on date/description/amount/balance, position-matched); a fixture with no ground truth still gets an untouched-pass reading but is reported as "no ground truth" for field accuracy, never silently skipped. Writes a dated JSON report toresults/(gitignored — each run produces a new file, not meant to be committed) and prints a console summary. Confirmed working against the real dual-engine pipeline (Docling + pdfplumber, not a fallback stub) as of 2026-10-11. - Commit an RBC fixture + hand-derived ground truth —
fixtures/RBC-CAD-Aug26.pdf(copied fromdocs/RBC-CAD-Aug26.pdf, which the user had placed there) plusfixtures/RBC-CAD-Aug26_ground_truth.xlsx, hand-verified by reading all 4 statement pages visually (viapdftoppm/poppler) against the extractor's own output — all 108 transactions, the opening balance ($66,857.70), and the closing balance ($90,569.13) matched exactly. One real extraction bug was caught in the process and became a permanent regression case, since-fixed (2026-10-12, see below): the last transaction on page 4 absorbed the page's trailingAccount Fees: $48.75footer line into its own description.fixtures/HSBC-USD-Sep2026_ground_truth.xlsxwas built and verified the same way (all 32 transactions visually confirmed page-by-page); HSBC's own opening/closing ground truth isNone/None, matchingextract_statement_facts— HSBC genuinely doesn't print these within the table (confirmed visually: the only balance figures on the statement are a "Closing ledger balance brought forward" and "Current ledger balance" dated 01–02 Oct, outside the Sep 1–30 statement period, not this statement's own opening/ closing).fixtures/HSBC-USD-August2026_ground_truth.xlsxwas 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 therunning_balanceflag (alsoNone/Noneopening/closing, same reason as Sep). These three real fixtures were removed from git history outright on 2026-11-24 and replaced with a fully-synthetic corpus - see "Real fixtures removed from git history, replaced with a synthetic corpus" under Key decisions & lessons. This bullet is kept as the accurate historical record of what was originally built and verified, not as a description of whatfixtures/currently holds in git. git initthis repo — done 2026-10-11, initial commit16f74f7.- Decide whether a
README.mdis wanted — yes; added 2026-10-12. Short: what the product is,docker compose up, project layout,measure.pyusage, and a pointer to this file for the deeper architecture/decision record. Doesn't duplicate anything CLAUDE.md already covers in depth. fixtures/ground_truth_sep_reference.xlsxwas discovered to be mismatched (a bank-description→accounting-category mapping from the separatebank_statement_categorizertool, 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.- The HSBC-Aug
running_balance/engine_agreementand RBCengine_agreementissuesmeasure.pysurfaces — investigated 2026-10-12, not extraction bugs. HSBC-Aug's singlerunning_balancemismatch 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_agreementon 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'sdocling_parser.pynote) is the architecture working as designed - Docling missed a table, pdfplumber's own result was used instead, correctly flaggedneeds_review/failfor 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 <this-repo-path> (session-only) or add it to permissions.additionalDirectories
in ~/.claude/settings.json (persistent). The cleanest setup for sustained work on this
project specifically is to run a Claude Code session rooted directly in this directory
(cd here, then claude) — this file loads automatically when that session starts.