Lays the backend groundwork for the layout mapper (no UI/PocketBase yet): when both
the keyword detector and the layout_quirks fallback fail on every page,
extraction_service.run() now raises LayoutMappingRequired with a computed fingerprint
instead of a dead-end error; routes/extraction.py returns this as a 422 with
{needs_mapping, fingerprint, fingerprintHash}. run()/pipeline_service.run() gained a
forced_mapping parameter that extracts directly from given column positions, bypassing
auto-detection entirely - the entry point a future manual mapping screen will use.
Two real gaps surfaced by testing against the actual problem statement, not assumed:
header_candidate_geometry() scans every page for the best candidate rather than just
page 1 (this statement's own page 1 is a pure cover page); a forced mapping had no
page-boundary concept, so a cover page's own letterhead merged into the first real
transaction - fixed with a new start_page field.
Verified: a synthetic unrecognizable PDF correctly triggers the 422 contract through
the real running container; the real problem statement, forced through a hand-built
mapping, now extracts 36/36 transactions with every check passing, matching the
auto-detected L.1 result exactly; measure.py byte-identical on HSBC/RBC throughout.
Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
L.1 of the layout-mapper plan (docs at /Users/jason/.claude/plans/witty-inventing-walrus.md):
a new backend/services/extraction/layout_quirks.py runs as a zero-friction fallback after
the keyword/geometry header detector fails, fixing mechanical geometric oddities (here, a
header label wrapped across physical lines) without requiring a manual mapping step. Also
generalizes money-token recognition to accept a leading "$" and date recognition to accept
an unambiguous YYYY/MM/DD shape - both real gaps surfaced by the same new statement once its
header was fixed. Relocates table_extract.py's private header-matching helpers into
layout_rules.py as public functions to avoid a circular import with the new module.
Verified: measure.py byte-identical on HSBC/RBC (every change is a provable no-op there);
the real statement that prompted this now extracts 36/36 transactions through the live
container with statement_balance/running_balance/date_sanity/structure_sanity all passing,
every row spot-checked against the source PDF; the existing scanned-statement OCR fixture
re-verified with zero regression.
Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
Completes the R.1-R.5 review screen plan. editLog/acknowledgedFlags/accepted all
live on the existing result JSON blob, no new PocketBase migration needed. Every
row mutation (manual edit, suggested-fix apply, structural edits) now logs a
field-level edit log entry; flags can be individually acknowledged; a document
can be Accepted once Verified or fully acknowledged; exports gain an optional
Edits sheet when edit_log is non-empty.
Verified: measure.py byte-identical to the pre-R.5 baseline, real curl round trip
through the rebuilt container confirming the Edits sheet appears/omits correctly,
extractionStore's new getters/actions run directly against real Pinia, and
useRowEditing's edit-log capture confirmed against a document actually persisted
on the live PocketBase container.
Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
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 needed).
Three patterns, tried in order so a row already explained by a sign
flip isn't also offered a digit-level fix: debit/credit swapped,
transposed digits, OCR digit misread. Each is tested empirically -
apply the candidate value to a copy of the real transactions and
re-run the actual check_running_balance - rather than hand-derived
from that check's own bridging/direction math, which is both safer
and simpler than tracing which row a bridged, auto-direction-detected
mismatch is "really" about.
"Date format swapped" was investigated and found not to apply to this
pipeline's data at all, documented directly in the new module's own
docstring rather than silently skipped: by the time a transaction
reaches this module its date is already normalized to "DD Mon YYYY"
(month already a name, not a number), so the raw numeric day/month
ambiguity that pattern addresses was already resolved upstream at
extraction time.
A real bug, found by the first end-to-end test and not by reading the
code: the running-balance check's own bridging logic means a mismatch
recorded at row i can be caused by row i or row i-1's amount - the
backend already tried both as fix candidates, but the frontend matched
a suggestion to a row by the fix target's own index, while the flag
icon only ever appears on the row the mismatch itself is reported
against. Confirmed for real: corrupting row 5 surfaced the mismatch on
row 6, so the correct suggestion (fix row 5) was completely unreachable
from the UI. Fixed by adding flag_index (the row shown flagged)
alongside index (the row the fix applies to) - TransactionRow.vue now
looks up by flag_index and always applies to suggestion.index.
TransactionRow.vue's suggestion UI lives in R.2's same flag-detail
panel; "Apply fix" runs the same save->persist->recheck pipeline a
manual edit already uses. extractionStore.applyCheckResults now
re-applies suggestions on every recheck, not just once, so a stale one
a manual edit already resolved disappears on its own.
Verified: three corruption patterns run through the real container via
curl against a known-good fixture, each detected and correctly
reverse-fixed at the right index. The real HSBC-Aug Cancelled-wire
mismatch (a genuine non-error case) correctly produces zero
suggestions. The full apply->persist->recheck->restore round trip
executed directly against real Pinia plus the real running PocketBase,
confirming the persisted record (not just local state) reflects the
fix. measure.py unaffected.
Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
R.1 (backend half) of the staged review-screen plan (Phase 2). Every
transaction now carries source_page/source_bbox - purely additive, so
the frontend's upcoming pdf.js viewer can box the exact printed row a
flagged transaction came from.
Traced extraction_service.py first: the canonical transactions list for
a normal text PDF always comes from pdfplumber (table_extract.py);
Docling's own extract_transactions() only feeds the cross-check
confidence signal, never the returned data. So this only needed to
touch table_extract.py and raw_ocr_extract.py (the OCR pixel-position
fallback), zero changes to engine-selection/cross-check logic.
One shared helper, table_extract._line_bbox(), used by both files
(mirrors how raw_ocr_extract.py already reuses _classify_money/_REF_RE
rather than re-implementing them) instead of two separate
implementations that could drift apart. A new _union_bbox() grows a
transaction's box as narrative lines merge into it, both the trailing
direction (HSBC) and leading direction (RBC).
Docling's own OCR-table-structure path doesn't get a real bbox (a
synthetic row-index, not a pixel position) - those transactions get
source_bbox: null, a graceful no-highlight rather than an error.
Verified: measure.py run before/after, byte-identical pass rate and
field accuracy on all three fixtures. A real /api/process call against
both HSBC and RBC fixtures confirmed every existing field unchanged.
Then the check measure.py can't make at all: rendered both fixtures'
pages for real and drew the reported source_bbox on the actual page
image - every box landed on exactly the right printed row, including
HSBC's trailing-narrative merge correctly widening the box.
Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
The actual request was simple (store exports in R2 like source files,
pending a retention-duration decision), but investigating where
exports were written surfaced something worse: /api/process built and
saved a full workbook to disk on EVERY extraction, and nothing in the
frontend ever called /api/download/<filename> to retrieve it (confirmed
by grep - no reference anywhere). Every extraction was silently
orphaning an .xlsx file for no reason; 91 had already accumulated
locally from this session's own testing alone.
Removed the dead work entirely: /api/process no longer builds or saves
a workbook at all. /api/download/<filename>, file_repository.
save_workbook/resolve_output_path, and OUTPUT_FOLDER (env var, volume,
directory) are all gone - confirmed nothing else referenced any of
them before removing. outputs/ deleted, including its 91 accumulated
files.
/api/export (the only path actually used - Download Excel/All) now
builds the workbook into an in-memory BytesIO and streams it straight
from there - never touches disk, not even temporarily. The frontend
persists it long-term instead: documentsService.saveExportFile uploads
the same Blob the browser download already used to a new exportFile
field (pb_migrations/3_add_export_file.js), stored in R2 same as
sourceFile. Overwrites the previous export rather than keeping a
history - no retention policy has been decided yet, and keeping every
version would just relocate the same unbounded-growth problem from the
VPS to R2 instead of fixing it. Best-effort from ResultCard.vue - a
save failure is reported but never blocks the browser download itself.
Verified for real: /api/process's response no longer has `filename`
(title still does); /api/export still streams a valid, correctly-typed
.xlsx; /app/outputs no longer exists in the rebuilt container; the old
/api/download URL now falls through to the ordinary SPA catch-all, not
a leftover route. documentsService.saveExportFile run against the REAL
bytes /api/export produced, fetched back through the R2-backed URL,
confirmed byte-for-byte - and confirmed a second export overwrites
rather than creating a second record. measure.py unaffected; npm run
build passes.
RBC prints "Account Fees: $48.75" directly under "Closing balance" on
the statement's last page - not a money token this module recognizes
("$48.75", not "48.75"), no reference-number prefix, no page-number
pattern, so it fell through to plain narrative text and landed on the
last real transaction's description via the trailing-leftover-buffer
rule (correct behavior for a GENUINE trailing narrative line, wrong
for this one).
Fixed by treating the closing-balance line as a position-based
boundary, the same way the header row already is: once extract_page()
recognizes it, every subsequent line on that page is skipped outright
rather than reaching money/narrative classification at all. A no-op
for HSBC, which never emits a closing_balance row in the first place.
measure.py: RBC field accuracy 0.9977 -> 1.0, HSBC unaffected. RBC's
overall status is still "Failed" after this - a separate, pre-existing
engine_agreement disagreement on page 4, not touched by this fix.
ocr_only detection only matched page_reports status "ocr_only", not
"ocr_raw_words" - if every page of a recheck needed the per-page
raw-OCR-words fallback (Docling failed on all of them), this incorrectly
treated the recheck as non-OCR-sourced, letting it reach "Verified" when
there was no second engine to earn that on. Now checks membership in
("ocr_only", "ocr_raw_words").
Verified directly (not just via measure.py, which never exercises
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; a normal dual-engine case is unaffected - confirmed
both as a direct function call and through /api/recheck on the real
running app. measure.py confirms zero regression elsewhere.
Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
Three small UI fixes from earlier testing, never committed:
- Pencil edit icon now uses the same blue accent token the Save button
already does (.row-btn.edit), instead of the default muted gray.
- Description textarea boxes left stale blank space after hiding the
Source Document panel - the drag-resizer already re-measures box
height on resize (autoGrowAll()), but the Hide/Show toggle never did,
so widening the transactions column left every description box at its
old height until something else happened to trigger a re-measure.
Added the missing call.
- Images shown in the Source Document panel had no zoom controls at all
(unlike PDFs, which get the browser's native viewer toolbar for free).
Added a dedicated zoomable/scrollable image panel with -/+/Fit
controls, width-based zoom (not CSS transform, so the panel's
overflow:auto actually produces real scrollbars when zoomed in),
opening at fit-width by default.
Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>