feat(mcp): already-explained voucher guard at stage and commit for match_batch_allocate (#2294) (#2346)

* feat(mcp): already-explained voucher guard at stage and commit for match_batch_allocate

The dashboard match-batch route refused BATCH_TX_POSSIBLE_DUPLICATE when
posted, unlinked vouchers already summed to the bank row (PR #2300), but the
MCP door (gnubok_match_batch_allocate staging + commitMatchBatchAllocate)
called the RPC with no guard, so an agent could book a Bankgirot aggregate a
second time. The detector existed once; the guard lived in one door.

One shared decision helper, lib/invoices/already-explained-guard.ts, now
sits on top of the existing detectors (no fork) and is called by the
dashboard route, the MCP staging tools and the commit executors:

- gnubok_match_batch_allocate refuses to stage, coded
  BATCH_TX_POSSIBLE_DUPLICATE, naming the vouchers, the reconcile_match /
  link_transaction_to_journal_entry call that resolves the row, and the
  exact force + expected_journal_entry_ids binding.
- commitMatchBatchAllocate runs the same guard before the RPC and
  re-validates a staged force binding against the set detected at commit,
  so a stale approval cannot book a duplicate; 409 auto-rejects with the
  vouchers in result_data.
- force + expected_journal_entry_ids on the tool mirror MatchBatchSchema;
  an honoured override stages with a compliance_warning and, after the
  booking succeeds, writes BankTransactionDuplicateDismissed to
  behandlingshistorik (dashboard route included; it only logged before).
- gnubok_match_transaction_to_invoice and commitMatchTransactionInvoice get
  the dashboard's 1:1 soft-duplicate guard (MATCH_INVOICE_POSSIBLE_DUPLICATE
  / MATCH_INVOICE_FORCE_CANDIDATE_MISMATCH) with force +
  expected_journal_entry_id; at commit it runs before the storno.
- Registry: both duplicate codes gain retryable: false and a remediation.

Catalog payload held under the 60K ceiling by trimming the two tools' own
descriptions (59 988 measured, ledger entry in payload-size.bench.test.ts).

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_019SaJfqNi4VmsG8FMKq99G6

* docs(decisions): record the 2026-09-06 ten-issue batch's first-principles choices

Carries the DECISIONS.md lines for PRs #2337 #2339 #2340 #2341 #2342 #2343 #2344 #2345 #2346 #2347 in one place so the ten branches do not conflict on this file.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_019SaJfqNi4VmsG8FMKq99G6

* fix(mcp): refuse an unverifiable forced override, surface a failed duplicate check, validate the binding (#2294 review)

Review round on PR #2346 (CodeRabbit + compliance):

- guardAlreadyExplained returned 'clear' when the detector threw even with
  force=true, so a forced 1:N override could book without re-validating
  expected_journal_entry_ids and left no behandlingshistorik record. It now
  returns a distinct 'unverifiable' outcome under force (mirrors
  guardDuplicatePaymentVoucher); the dashboard route, the MCP staging tool
  and the commit executor all refuse it with the new registry code
  BATCH_TX_EXPLAINED_CHECK_FAILED (409, retryable, remediation). Regression
  tests on every caller.
- A detector failure without force still fails open at stage time, but no
  longer silently: the tools track onDetectError and stage a
  complianceNote, so preview_data.compliance_warning is set on both
  match_batch_allocate (GenericPreview renders it) and
  match_transaction_invoice (MatchTransactionInvoicePreview now renders
  data.compliance_warning through AttnLine).
- expected_journal_entry_ids / expected_journal_entry_id are validated at
  the MCP boundary (array of 1 to 10 non-empty strings / non-empty string)
  and refused with VALIDATION_ERROR instead of being silently filtered.
  No schema description text added: catalog payload unchanged.
- RoPA: .compliance/ropa.yaml gains bookkeeping.duplicate_dismissal_history
  for the BankTransactionDuplicateDismissed record (Art. 6(1)(c), BFNAR
  2013:2 p. 9.16, retention per BFL 7 kap, stored in processing_history).

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>

---------

Co-authored-by: Jakob Wennberg <311770904+jakobwennberg-oss@users.noreply.github.com>
Co-authored-by: Claude Fable 5.1 <noreply@anthropic.com>
This commit is contained in:
Jakob Wennberg
2026-09-06 18:56:36 +02:00
committed by GitHub
co-authored by Claude Fable 5.1 Jakob Wennberg
parent 39d409d257
commit cce0de5704
17 changed files with 1970 additions and 40 deletions
+113
View File
@@ -94,6 +94,15 @@ import {
import { linkInvoiceToVoucher, type LinkInvoiceToVoucherResult } from '@/lib/invoices/voucher-matching'
import { planInvoicePayment } from '@/lib/invoices/apply-invoice-payment'
import { findDuplicatePaymentCandidatesForInvoice } from '@/lib/invoices/duplicate-payment-candidates'
import {
alreadyExplainedDetails,
describeExplainingSet,
guardAlreadyExplained,
guardDuplicatePaymentVoucher,
recordDuplicateCandidateOverride,
recordExplainedOverride,
type ExplainedOverride,
} from '@/lib/invoices/already-explained-guard'
import {
linkSupplierInvoiceToVoucher,
type LinkSupplierInvoiceToVoucherResult,
@@ -3306,6 +3315,45 @@ async function commitMatchTransactionInvoice(
return { error: 'Invoice is not in a matchable state', status: 409 }
}
// Soft-duplicate guard: parity with the dashboard and v1 match routes
// (MATCH_INVOICE_POSSIBLE_DUPLICATE), which this path bypassed. A manual
// verifikation that already books this receipt means the approved match
// would double-book it. Runs BEFORE the irreversible storno below, and
// re-binds force to the candidate detected NOW: an approval staged before
// the manual voucher was posted cannot slip through (issue #2294).
const duplicate = await guardDuplicatePaymentVoucher(
supabase,
companyId,
transaction,
{
force: params.force === true,
expected_journal_entry_id:
typeof params.expected_journal_entry_id === 'string' ? params.expected_journal_entry_id : undefined,
},
{ onDetectError: (err) => log.warn('match_transaction_invoice: duplicate detection failed (continuing)', err) },
)
if (duplicate.status === 'blocked') {
const entry = getErrorEntry('MATCH_INVOICE_POSSIBLE_DUPLICATE')
return {
error: `${entry?.message_sv ?? 'Det finns redan en bokförd verifikation på samma belopp och datum.'} (verifikat ${duplicate.candidate.voucher_label}, ${duplicate.candidate.entry_date})`,
errorCode: 'MATCH_INVOICE_POSSIBLE_DUPLICATE',
status: 409,
data: { candidate: duplicate.candidate },
}
}
if (duplicate.status === 'mismatch') {
const entry = getErrorEntry('MATCH_INVOICE_FORCE_CANDIDATE_MISMATCH')
return {
error: entry?.message_sv ?? 'Verifikationen som dubblettkontrollen visade matchar inte längre.',
errorCode: 'MATCH_INVOICE_FORCE_CANDIDATE_MISMATCH',
status: 409,
data: {
expected_journal_entry_id: duplicate.expected_journal_entry_id,
detected_journal_entry_id: duplicate.detected_journal_entry_id,
},
}
}
// FX resolution: parity with the dashboard and v1 match routes. paidAmount
// MUST be denominated in the INVOICE's currency (the unit of
// invoices.paid_amount / remaining_amount and invoice_payments.amount).
@@ -3583,6 +3631,18 @@ async function commitMatchTransactionInvoice(
})
}
// The override was acted on: durable behandlingshistorik record (BFNAR
// 2013:2 p. 9.16), same event the categorize guard writes.
if (duplicate.status === 'overridden') {
await recordDuplicateCandidateOverride(
companyId,
transactionId,
duplicate.candidate,
{ actor: { type: 'user', id: userId }, via: 'pending_operation_force' },
(err) => log.warn('match_transaction_invoice: failed to record override behandlingshistorik', err),
)
}
// The invoice is now settled, so every OTHER transaction still carrying a
// suggestion pointer at it is dead: retire them (issue #1259). This
// operation's own row is cleared by the update just below.
@@ -6638,6 +6698,47 @@ async function commitMatchBatchAllocate(
if (!Array.isArray(allocations) || allocations.length === 0) {
return { error: 'allocations is required (non-empty array)', status: 400 }
}
// Already-explained guard: the RPC only knows the invoices in the request,
// so posted vouchers that already book this bank row (each invoice marked
// paid by hand, a Bankgirot aggregate) are invisible to it and the money
// gets booked a second time. Same detector + force binding as the
// dashboard route and the staging tool (lib/invoices/already-explained-
// guard.ts). Commit is the last gate: the binding is re-validated against
// the set detected NOW, so an approval staged before a voucher was posted
// cannot slip through (issue #2294). 409 auto-rejects the op with the
// vouchers in result_data.
const override: ExplainedOverride = {
force: params.force === true,
expected_journal_entry_ids: Array.isArray(params.expected_journal_entry_ids)
? (params.expected_journal_entry_ids as unknown[]).filter((v): v is string => typeof v === 'string')
: undefined,
}
const explained = await guardAlreadyExplained(supabase, companyId, txId, override, {
onDetectError: (err) => log.warn('match_batch_allocate: explaining-voucher detection failed (continuing)', err),
})
if (explained.status === 'blocked') {
const entry = getErrorEntry('BATCH_TX_POSSIBLE_DUPLICATE')
return {
error: `${entry?.message_sv ?? 'Transaktionen ser redan ut att vara bokförd.'} (${describeExplainingSet(explained.set)})`,
errorCode: 'BATCH_TX_POSSIBLE_DUPLICATE',
status: 409,
data: alreadyExplainedDetails(explained) as unknown as Record<string, unknown>,
}
}
if (explained.status === 'unverifiable') {
// force=true but the check could not run at commit: the staged binding
// cannot be re-verified, so the op is refused (auto-rejected), never
// waved through on the strength of an earlier review.
const entry = getErrorEntry('BATCH_TX_EXPLAINED_CHECK_FAILED')
return {
error: entry?.message_sv ?? 'Dubblettkontrollen kunde inte köras, så "bokför ändå" avvisades.',
errorCode: 'BATCH_TX_EXPLAINED_CHECK_FAILED',
status: 409,
data: { reason: 'detector_failed', force_rejected: true },
}
}
const { data, error } = await supabase.rpc('match_batch_allocate', {
p_tx_id: txId,
p_allocations: allocations,
@@ -6673,6 +6774,18 @@ async function commitMatchBatchAllocate(
// (app/api/transactions/[id]/match-batch/route.ts) so the two cannot drift.
await clearSettledBatchAllocationSuggestions(supabase, companyId, result.allocations ?? [], txId)
// The override was acted on: durable behandlingshistorik record (BFNAR
// 2013:2 p. 9.16), same event the categorize guard writes.
if (explained.status === 'overridden') {
await recordExplainedOverride(
companyId,
txId,
explained.set,
{ actor: { type: 'user', id: userId }, via: 'pending_operation_force' },
(err) => log.warn('match_batch_allocate: failed to record override behandlingshistorik', err),
)
}
// Structured audit-trail entry on success (compliance-swarm V16). Tx
// count + JE id + the source tx id only: no amounts, no
// counterparty identifiers, no descriptions. txId is included