e-arveldaja-mcp 0.42.1 → 0.43.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (32) hide show
  1. package/CHANGELOG.md +16 -0
  2. package/CLAUDE.md +2 -2
  3. package/README.md +1 -1
  4. package/dist/banking/reconciliation/executor.d.ts.map +1 -1
  5. package/dist/banking/reconciliation/executor.js +29 -1
  6. package/dist/banking/reconciliation/executor.js.map +1 -1
  7. package/dist/document-parser.d.ts +2 -2
  8. package/dist/document-parser.d.ts.map +1 -1
  9. package/dist/document-parser.js +4 -4
  10. package/dist/document-parser.js.map +1 -1
  11. package/dist/document-reading-card.d.ts +2 -29
  12. package/dist/document-reading-card.d.ts.map +1 -1
  13. package/dist/document-reading-card.js +5 -28
  14. package/dist/document-reading-card.js.map +1 -1
  15. package/dist/document-reading-lost-value.d.ts +2 -51
  16. package/dist/document-reading-lost-value.d.ts.map +1 -1
  17. package/dist/document-reading-lost-value.js +18 -237
  18. package/dist/document-reading-lost-value.js.map +1 -1
  19. package/dist/documents/lost-value-ocr.d.ts +1 -37
  20. package/dist/documents/lost-value-ocr.d.ts.map +1 -1
  21. package/dist/documents/lost-value-ocr.js +7 -84
  22. package/dist/documents/lost-value-ocr.js.map +1 -1
  23. package/dist/documents/reading-operations.d.ts +6 -37
  24. package/dist/documents/reading-operations.d.ts.map +1 -1
  25. package/dist/documents/reading-operations.js +18 -160
  26. package/dist/documents/reading-operations.js.map +1 -1
  27. package/dist/guided/process-accounting-document.d.ts +2 -18
  28. package/dist/guided/process-accounting-document.d.ts.map +1 -1
  29. package/dist/guided/process-accounting-document.js +4 -34
  30. package/dist/guided/process-accounting-document.js.map +1 -1
  31. package/package.json +6 -6
  32. package/server.json +2 -2
package/CHANGELOG.md CHANGED
@@ -2,6 +2,22 @@
2
2
 
3
3
  ## [Unreleased]
4
4
 
5
+ ## [0.43.1] - 2026-11-28
6
+
7
+ ### Changed
8
+
9
+ - **PDF reader updated to liteparse 2.21.4; nothing you see changes.** This version fixes a crash on some ruled-table cells and repairs PDFs whose text layer is in the wrong code page or in visual order, and adds a second OCR pass for pages of small print. On the 75-document owner corpus, compared with 2.21.3, every extracted field, every hold and the reading-packet text are identical. Details: @llamaindex/liteparse 2.21.4 (floor `^2.21.4`, upstream #649/#650/#652/#654/#661/#664); the liteparse version diagnostic names `^2.21.4`.
10
+
11
+ ## [0.43.0] - 2026-11-27
12
+
13
+ ### Changed
14
+
15
+ - **Google Cloud invoices now come with their invoice date read straight from the PDF, and their invoice date is no longer taken as the due date.** Before, the PDF reader lost the date and number printed after a dotted line on these invoices, so the date had to be typed (or read from a picture of the row), and the invoice date was sometimes taken as the due date. The PDF reader now keeps those values. Details: @llamaindex/liteparse 2.21.3 (floor `^2.21.3`; upstream #622 / #623, "Keep values next to dotted leaders", in 2.21.2). On the 75-document owner corpus, compared with 2.19.0: the 7 Google Cloud invoices lose their `text_layer_value_lost` hold and gain `invoice_date` from the text layer (each checked against the printed date), their former `due_date` (which was the invoice date) is no longer extracted, and every other extracted field (supplier, numbers, dates, amounts, VAT, currency, IBAN) is unchanged; the remaining 2 held documents are held as before. Only descriptions and OCR confidence moved: Telia's "Ä Telia" → "Telia", a Wise statement's "jwise" → "Wise Assets Europe AS", one hash in a payment-reference description now reads `bf5actid…` instead of `bf5ac9d…` (a description, which can become an invoice line's title; never an amount, date, number or reference), and a Google Play receipt no longer raises a false "buyer not verified" flag (cleaner OCR).
16
+ - **The "read the lost value from a picture" step of the verified-reading mode is removed; a value the text loses is typed by you, as before that step existed.** It only ever helped the Google Cloud invoices above, which no longer need it, and it was the most complex part of the reading path. If a PDF loses a value behind a dotted line again, the invoice is still held and the card asks you to type the date or number. Details: `process_accounting_document` `mode="read"` no longer returns image blocks, `lost_value_images`, `lost_value_instructions` or `lost_value_images_omitted`; `mode="verify"` no longer takes `lost_value_reading` (now refused as an undeclared argument) or returns `lost_values`; the verified-reading plan no longer carries `image_agreed`, the card has no image-agreed rows, and the create audit no longer writes `image_ocr_agreed_fields`. Removed: `matchLostValue`, `parseLostValueReading`, `locateLostValueRects`, `buildLostValueCrops`, `ocrLostValueLine` and the `image_agreed` re-check source. Kept unchanged: the `text_layer_value_lost` hold, the blank signature-line proof (`blank_leader_lines`, still switched off by `EARVELDAJA_READING_LOST_VALUE_IMAGES=0` or `EARVELDAJA_LITEPARSE_OCR_ENABLED=false`) and the header-number confirm row (`text_layer_number_kept_under_label`). The synthetic leader-overlay integration test is now a tripwire that fails if liteparse drops such values again. Only affects `EARVELDAJA_DOCUMENT_READING=1`; with the flag off the tool surface is unchanged.
17
+ - **An invoice whose number the PDF lost but whose date it kept now reaches your review card.** Before, it was blocked before the card, so you could not type the number. Details: with `text_layer_value_lost` and a null number, `verify` drops only the `booking_field_mismatch` on `number`; `create` binds the booking again on the typed number and runs every duplicate scan. Also: a CropBox in a PDF with several page sizes now refuses the signature-line band crop (`crop_box_ambiguous`; the row stays held), and the liteparse version diagnostic names `^2.21.3`.
18
+ - **Bank matching now suggests the right month's invoice for a repeating subscription.** Before, two unpaid invoices of the same amount from one supplier (e.g. monthly Google Workspace 13.60) scored equally and both payments were suggested against the same invoice. Now the invoice dated nearest on or before the payment is suggested, and the row says the scores were tied so you check the period. Details: `reconcile_bank_transactions` `mode="suggest"` orders equal-confidence candidates by invoice date (on/before the payment first, then nearest) and adds a `manual_review_required` note on a tie; scores, thresholds and auto-confirm are unchanged. Found in the 2026-11-27 live delete-and-rebook test.
19
+ - **Developer dependency updates.** Details: @babel/parser 8.1.3, @types/node 26.6.11, vite 8.4.0, vitest 5.1.2, with declared floors equal to the tested versions; `npm audit` clean.
20
+
5
21
  ## [0.42.1] - 2026-11-15
6
22
 
7
23
  ### Fixed
package/CLAUDE.md CHANGED
@@ -274,11 +274,11 @@ The guided surface is sized for routing clarity, not token cost (per-tool measur
274
274
 
275
275
  `EARVELDAJA_DOCUMENT_READING=1` is not an exposure flag: it adds the opt-in verified-reading modes `read` / `verify` to `process_accounting_document` (create and confirm route on the reading-domain handle), so no tool count and no profile changes (guided stays 19). Off, the tool's schema and description are byte-identical. The workflow guidance for the reading path is carried by the flag-gated tool description and the `read` / `verify` / `create` outputs, not by `workflows/book-invoice.md` (prompt feature sections are tool-gated, and the flag adds no tool).
276
276
 
277
- Lost dot-leader values (`text_layer_value_lost`, a liteparse overlay bug): with the reading flag on, `read` also returns one PNG crop per lost leader row (300 dpi, label included; ≤ 6 crops, 64 KB each, 256 KB total, else `lost_value_images_omitted`) after fixed instructions that the pixels are untrusted. The client transcribes only `invoice_date` / `invoice_number` into `verify`'s `lost_value_reading` (`{field: {line, printed}}`), keeping them null in `document_reading`. `verify` (`src/documents/reading-operations.ts` `resolveLostValues`) accepts a value only when the field is null with no other hold, the cited line is a lost line cited once, the re-rendered crop's server OCR (`src/documents/lost-value-ocr.ts`, `src/document-reading-lost-value.ts` `matchLostValue`) shows exactly one candidate equal to it at confidence ≥ 0.6 on the same OCR row as the cell's label, with only leader glyphs and punctuation besides, and a second full checker pass raises no new hold (`image_agreed` allow-list: evidence/proof codes only). A date is not applied while the number stays lost. Every agreed value gets a mandatory confirm row and is re-checked at create; the audit records `image_ocr_agreed_fields`. Any failure leaves today's typed row (`lost_values` says why). A read invoice number whose evidence line starts with a lost cell's own label of at least two words followed by the number (Google's header `Arve number: …`; `printedUnderLostLabel`), with no other hold on the field, gets a confirm row instead of the typed row (audit `text_layer_number_kept_under_label`); the date never takes this route. Signature lines: before the hold is raised, `readingPacketOf` (`src/tools/document-text-hazards.ts`, used by every path that checks the hold) renders each lost row's full-width band and OCRs it. The band comes from `leaderRowBand`: the row is unique on its page, the band runs from two row heights (the tallest row item) above it to 0.4·h below, at most 6 rows on 2 pages, and each lost cell is bound to its own label item. `ocrItemsOnPage` maps OCR words to page points using the OCR's extent (`OcrPngResult.size`) over the crop's real rect (`croppedPixels`). `leaderRowIsBlank` clears the row only when both hold:
277
+ Lost dot-leader values (`text_layer_value_lost`): liteparse < 2.21.2 dropped the value painted after a dot leader (Google Cloud invoices; upstream #622, fixed in 2.21.2; floor `^2.21.4`). The hold stays as the safety net: whichever cell lost its value (a date, number, billing ID or total), the card asks the owner to type the invoice date and the invoice number (§5.3); a lost amount is still caught by the amount checks, not typed. With the number lost and the date printed, `verify` skips only the number binding; `create` binds the booking again on the typed number and runs every duplicate scan on it. The image-crop transcription path (`lost_value_reading`, crops on `read`, server-OCR agreement) was removed in 0.43.0; the synthetic tripwire `src/__integration__/lost-value-image.test.ts` fails loudly if liteparse loses such values again. A read invoice number whose evidence line starts with a lost cell's own label of at least two words followed by the number (Google's header `Arve number: …`; `printedUnderLostLabel`), with no other hold on the field, gets a confirm row instead of the typed row (audit `text_layer_number_kept_under_label`); the date never takes this route. Signature lines: before the hold is raised, `readingPacketOf` (`src/tools/document-text-hazards.ts`, used by every path that checks the hold) renders each lost row's full-width band and OCRs it. The band comes from `leaderRowBand`: the row is unique on its page, the band runs from two row heights (the tallest row item) above it to 0.4·h below, at most 6 rows on 2 pages, and each lost cell is bound to its own label item. `ocrItemsOnPage` maps OCR words to page points using the OCR's extent (`OcrPngResult.size`) over the crop's real rect (`croppedPixels`). `leaderRowIsBlank` clears the row only when both hold:
278
278
  - OCR read each cell's last label word on that label item, on the row;
279
279
  - every OCR item is accounted for. Host = the item under the OCR item's centre; a number keeps its sign and punctuation and gets no slack. "On the leader" means the host holds a leader run (a combined label+leader item counts wholly), the box reaches into such an item, or there is no host. On the leader, only the host's label words (counted) pass; a number, any other word, or punctuation other than leader glyphs holds, unless the item is a smudge (< 0.2·h, confidence < 0.5, no digit). Off the leader, a word must be the host's word (counted), or have no digit and not be only look-alikes. Each lost cell is bound to its own leader run (`lostLeaderRunIndex`); the row's items must hold the line's runs one for one.
280
280
 
281
- Cleared rows go to `blank_leader_lines`. The digest is unchanged, but the reading plan binds the set: a different set at create is `packet_changed`, and the audit records `blank_leader_lines`. Any failure keeps the hold. Owner-accepted gaps: a digit-free lost value over printed text can be cleared, and OCR that skips a value entirely while reading every label is not detected. Off with `EARVELDAJA_READING_LOST_VALUE_IMAGES=0` or `EARVELDAJA_LITEPARSE_OCR_ENABLED=false`; a remote OCR server (`EARVELDAJA_LITEPARSE_OCR_SERVER_URL`) is accepted as the server check (owner decision). Unusual page geometry (`/Rotate`, `/UserUnit`, a non-zero MediaBox origin, a CropBox differing from the MediaBox, an indirect box, encryption, more than 256 or 32 MB of object streams; `pdfPageBoxRefusal`, name escapes decoded) and a page over 40 Mpx at 300 dpi get no crop.
281
+ Cleared rows go to `blank_leader_lines`. The digest is unchanged, but the reading plan binds the set: a different set at create is `packet_changed`, and the audit records `blank_leader_lines`. Any failure keeps the hold. Owner-accepted gaps: a digit-free lost value over printed text can be cleared, and OCR that skips a value entirely while reading every label is not detected. Off with `EARVELDAJA_READING_LOST_VALUE_IMAGES=0` (the name is kept from the removed image path) or `EARVELDAJA_LITEPARSE_OCR_ENABLED=false`; a remote OCR server (`EARVELDAJA_LITEPARSE_OCR_SERVER_URL`) is accepted as the server check (owner decision). Unusual page geometry (`/Rotate`, `/UserUnit`, a non-zero MediaBox origin, a CropBox differing from the MediaBox or any CropBox in a PDF with several page sizes, an indirect box, encryption, more than 256 or 32 MB of object streams; `pdfPageBoxRefusal`, name escapes decoded) and a page over 40 Mpx at 300 dpi get no band crop (the row stays held).
282
282
 
283
283
  Payment reference on the reading path: `ref_number` and `notes` are refused arguments; `verify` derives the viitenumber from the packet (`src/document-reading-reference.ts` `printedPaymentReference`: an Estonian label `Viitenumber`/`Viitenr` followed on the same line by a whole-token 2–20-digit number with a valid 7-3-1 check digit, `isValidEstonianReferenceNumber` in `src/ref-number.ts`; English `Reference` labels are not read). Exactly one distinct value is bound as the booking's `ref_number` (`bank_ref_number` on the draft, covered by the fingerprint, drift and readback checks); several distinct values bind nothing and `verify` returns `payment_reference_note`.
284
284
 
package/README.md CHANGED
@@ -4,7 +4,7 @@
4
4
 
5
5
  MCP server for the Estonian e-arveldaja (RIK e-Financials) REST API. 130 tools on the standard profile, 16 workflow prompts, 15 resources. Works with any MCP client — Claude Code, Codex CLI, Gemini CLI, Cursor, Windsurf, Cline, and others.
6
6
 
7
- > **Telia supplier fix and dependency updates (0.42.1).** With the newer PDF reader (liteparse 2.19), which fresh installs of 0.42.0 already pick up, Telia invoices lost their supplier; this is fixed, and the reader floor now matches the tested version. Dependencies are updated and `npm audit` is clean. See the [changelog](CHANGELOG.md) for details.
7
+ > **Google Cloud invoice dates read from the PDF (0.43.0).** The newer PDF reader (liteparse 2.21) keeps the date and number printed after a dotted line, so Google Cloud invoices no longer need the date typed; the verified-reading picture step that worked around it is removed. See the [changelog](CHANGELOG.md) for details.
8
8
 
9
9
  > **Rules and company state follow the company; export and import (0.42.0).** Your booking rules and saved state (statement balances, receipt checks, limited-VAT records, Lightyear USD pool) are now kept per company, identified by its registry code from the EMTA VAT register or the business register, so they survive an API key change; existing folders are copied over once, the old ones are kept. The new `accounting_data_transfer` tool exports a company's rules and state to one file and imports it on another computer after a preview and your approval. `save_annual_report_account_rule` saves a cash-flow (operating/investing/financing) or liability (current/non-current) account choice from the conversation, and rule saves now say whether the rule applies to this company only or to every company sharing the rules folder. See the [changelog](CHANGELOG.md) for details.
10
10
 
@@ -1 +1 @@
1
- {"version":3,"file":"executor.d.ts","sourceRoot":"","sources":["../../../src/banking/reconciliation/executor.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,UAAU,EAAE,MAAM,4BAA4B,CAAC;AAuB7D,OAAO,KAAK,EAAE,oBAAoB,EAAE,MAAM,iCAAiC,CAAC;AAuE5E,OAAO,KAAK,EAEV,qBAAqB,EACrB,0BAA0B,EAC1B,iBAAiB,EAGjB,mBAAmB,EAGnB,qBAAqB,EACrB,0BAA0B,EAC1B,iBAAiB,EACjB,uBAAuB,EAEvB,mBAAmB,EAInB,yBAAyB,EAOzB,mBAAmB,EACpB,MAAM,YAAY,CAAC;AAkBpB,eAAO,MAAM,+BAA+B,KAAK,CAAC;AAUlD,MAAM,MAAM,YAAY,GACpB;IAAE,IAAI,EA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0BAA0B,GAChC,OAAO,CAAC,eAAe,CAAC,qBAAqB,CAAC,CAAC,CA2SjD"}
@@ -83,6 +83,13 @@ export const SUGGEST_DEFAULT_MIN_CONFIDENCE = 50;
83
83
  */
84
84
  const DOCUMENT_REFERENCE_POINTS = 30;
85
85
  const DOCUMENT_REFERENCE_CONFIDENCE_CAP = 85;
86
+ /** Days from an invoice date to the payment date (positive when the invoice is earlier); undefined if unreadable. */
87
+ function signedDayGap(invoiceDate, paymentDate) {
88
+ const parse = (value) => (value && /^\d{4}-\d{2}-\d{2}/.test(value) ? Date.parse(`${value.slice(0, 10)}T00:00:00Z`) : NaN);
89
+ const a = parse(invoiceDate);
90
+ const b = parse(paymentDate);
91
+ return Number.isNaN(a) || Number.isNaN(b) ? undefined : Math.round((b - a) / 86_400_000);
92
+ }
86
93
  export async function runSuggestMatches(api, input) {
87
94
  const threshold = input.minConfidence ?? SUGGEST_DEFAULT_MIN_CONFIDENCE;
88
95
  const documentReferenceCandidates = [];
@@ -123,12 +130,15 @@ export async function runSuggestMatches(api, input) {
123
130
  let matchedDateTo;
124
131
  for (const tx of unconfirmed) {
125
132
  const candidates = [];
133
+ // Invoice date per candidate, for the tie-break below (not part of the payload).
134
+ const invoiceDateOf = new Map();
126
135
  const documentReferenceByInvoiceId = new Map();
127
136
  const { allowSaleInvoices, allowPurchaseInvoices } = getInvoiceMatchEligibility(tx);
128
137
  if (allowSaleInvoices) {
129
138
  for (const inv of getIndexedCandidates(saleIndex, tx.ref_number, tx.amount, tx.base_amount)) {
130
139
  const { confidence, reasons, partiallyPaidWarning } = matchScore(tx, inv, tx.amount);
131
140
  if (confidence >= threshold) {
141
+ invoiceDateOf.set(`sale_invoice:${inv.id}`, inv.create_date ?? undefined);
132
142
  candidates.push({
133
143
  type: "sale_invoice",
134
144
  id: inv.id,
@@ -160,6 +170,7 @@ export async function runSuggestMatches(api, input) {
160
170
  if (confidence >= threshold) {
161
171
  if (matchedReference !== undefined)
162
172
  documentReferenceByInvoiceId.set(inv.id, { inv, matchedReference });
173
+ invoiceDateOf.set(`purchase_invoice:${inv.id}`, inv.create_date ?? undefined);
163
174
  candidates.push({
164
175
  type: "purchase_invoice",
165
176
  id: inv.id,
@@ -177,8 +188,21 @@ export async function runSuggestMatches(api, input) {
177
188
  }
178
189
  }
179
190
  if (candidates.length > 0) {
180
- candidates.sort((a, b) => b.confidence - a.confidence);
191
+ // Equal scores (e.g. a monthly subscription of one amount) are ordered by the invoice date: one dated on or
192
+ // before the payment beats a later one, then the nearest date wins. The tie is still reported for review.
193
+ const dateRank = (candidate) => {
194
+ const days = tx.date ? signedDayGap(invoiceDateOf.get(`${candidate.type}:${candidate.id}`), tx.date) : undefined;
195
+ return days === undefined ? [2, 0] : [days >= 0 ? 0 : 1, Math.abs(days)];
196
+ };
197
+ candidates.sort((a, b) => {
198
+ if (b.confidence !== a.confidence)
199
+ return b.confidence - a.confidence;
200
+ const [ra, da] = dateRank(a);
201
+ const [rb, db] = dateRank(b);
202
+ return ra - rb || da - db;
203
+ });
181
204
  const bestMatch = candidates[0];
205
+ const tiedWithBest = candidates.filter((candidate) => candidate.confidence === bestMatch.confidence).length;
182
206
  // A document-reference invoice that did not win this row is listed
183
207
  // separately so it is not hidden behind the chosen best match.
184
208
  for (const candidate of candidates.slice(1)) {
@@ -239,6 +263,10 @@ export async function runSuggestMatches(api, input) {
239
263
  if (bestMatch.partially_paid_warning) {
240
264
  manualReviewNotes.push("Invoice is PARTIALLY_PAID; verify the remaining open balance before confirming.");
241
265
  }
266
+ if (tiedWithBest > 1) {
267
+ manualReviewNotes.push(`${tiedWithBest} invoices score equally; the one dated nearest on or before the payment is suggested. `
268
+ + "Check the invoice number or period before confirming.");
269
+ }
242
270
  if (ambiguousForeignBase) {
243
271
  manualReviewNotes.push(`ambiguous_foreign_invoice_base: ${candidates.map(c => `${c.type} #${c.id}`).join(", ")} `
244
272
  + "compete on a foreign-currency invoice base amount; pick the invoice manually.");