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
@@ -0,0 +1,217 @@
/**
* gnubok_match_batch_allocate: the already-explained guard at stage time
* (issue #2294).
*
* The dashboard door refuses a batch allocation with
* BATCH_TX_POSSIBLE_DUPLICATE when posted, unlinked vouchers on the row's
* settlement account sum exactly to the row (gecko's Bankgirot aggregate, PR
* #2300). The MCP door used to stage straight past that, so an agent could
* book the aggregate a second time. Now the same detector runs before
* staging: the refusal names the vouchers and the link call that resolves
* the row, and force is bound to exactly those ids.
*/
import { describe, it, expect, vi, beforeEach } from 'vitest'
import { createQueuedMockSupabase } from '@/tests/helpers'
const { mockDetectSet } = vi.hoisted(() => ({ mockDetectSet: vi.fn() }))
vi.mock('@/lib/invoices/duplicate-payment-detection', () => ({
detectExplainingVoucherSetForTransaction: mockDetectSet,
detectDuplicatePaymentVoucher: vi.fn(async () => null),
}))
import { tools } from '../server'
const allocate = tools.find((t) => t.name === 'gnubok_match_batch_allocate')!
const TX_ID = '11111111-1111-4111-8111-111111111111'
const INV_ID = '22222222-2222-4222-8222-222222222222'
const JE_A = '55555555-5555-4555-8555-555555555555'
const JE_B = '66666666-6666-4666-8666-666666666666'
const txRow = {
id: TX_ID,
description: 'BGGIRERING',
merchant_name: null,
amount: 88250,
currency: 'SEK',
amount_sek: null,
exchange_rate: null,
cash_account_id: 'ca-1',
date: '2026-07-31',
journal_entry_id: null,
}
const explainingSet = {
vouchers: [
{ journal_entry_id: JE_A, voucher_label: 'A57', entry_date: '2026-07-31', description: 'Inbetalning kundfaktura 063', source_type: 'invoice_paid', amount: 62500, bank_account_number: '1930' },
{ journal_entry_id: JE_B, voucher_label: 'A58', entry_date: '2026-07-31', description: 'Inbetalning kundfaktura 064', source_type: 'invoice_paid', amount: 25750, bank_account_number: '1930' },
],
total: 88250,
bank_account_number: '1930',
same_date: true,
}
const args = (extra: Record<string, unknown> = {}) => ({
transaction_id: TX_ID,
allocations: [{ kind: 'customer_invoice', invoice_id: INV_ID, amount: 88250 }],
...extra,
})
function run(supabase: unknown, extra: Record<string, unknown> = {}) {
return allocate.execute(args(extra), 'company-1', 'user-1', supabase as never, { type: 'api_key' } as never)
}
/** tx fetch + invoice tenant pre-check: everything the tool reads before the guard. */
function enqueuePreGuard(enqueue: (r: { data?: unknown; error?: unknown }) => void) {
enqueue({ data: txRow, error: null })
enqueue({ data: [{ id: INV_ID, document_type: 'invoice' }], error: null })
}
/** period_status lookups + the pending_operations insert. */
function enqueueStage(enqueue: (r: { data?: unknown; error?: unknown }) => void) {
enqueue({ data: { bookkeeping_locked_through: null }, error: null }) // company_settings
enqueue({ data: { id: 'fp-1', is_closed: false, locked_at: null }, error: null }) // fiscal_periods
enqueue({ data: { id: 'op-batch-1' }, error: null }) // pending_operations insert
}
beforeEach(() => {
vi.clearAllMocks()
mockDetectSet.mockResolvedValue(null)
})
describe('gnubok_match_batch_allocate: already-explained guard at stage time', () => {
it('refuses to stage, coded BATCH_TX_POSSIBLE_DUPLICATE, naming the vouchers, the link call and the force binding', async () => {
mockDetectSet.mockResolvedValue(explainingSet)
const { supabase, enqueue } = createQueuedMockSupabase()
enqueuePreGuard(enqueue)
const err = await run(supabase).then(() => null, (e: Error & { code?: string }) => e)
expect(err).toBeInstanceOf(Error)
expect(err!.code).toBe('BATCH_TX_POSSIBLE_DUPLICATE')
expect(err!.message).toContain('A57 + A58')
expect(err!.message).toContain('gnubok_reconcile_match')
expect(err!.message).toContain('bank:ca-1')
expect(err!.message).toContain(`expected_journal_entry_ids=${JSON.stringify([JE_A, JE_B])}`)
// The row the tool already holds goes to the detector: no second fetch.
expect(mockDetectSet).toHaveBeenCalledWith(supabase, 'company-1', expect.objectContaining({ id: TX_ID, cash_account_id: 'ca-1' }))
// Nothing was staged.
const tables = (supabase.from as ReturnType<typeof vi.fn>).mock.calls.map((c) => c[0])
expect(tables).not.toContain('pending_operations')
})
it('points a single explaining voucher at the 1:1 link tool too', async () => {
mockDetectSet.mockResolvedValue({ ...explainingSet, vouchers: [explainingSet.vouchers[0]] })
const { supabase, enqueue } = createQueuedMockSupabase()
enqueuePreGuard(enqueue)
await expect(run(supabase)).rejects.toThrow(/gnubok_link_transaction_to_journal_entry/)
})
it('stages with a compliance warning when force names exactly the detected set, and persists the binding', async () => {
mockDetectSet.mockResolvedValue(explainingSet)
const { supabase, enqueue, findCall } = createQueuedMockSupabase()
enqueuePreGuard(enqueue)
enqueueStage(enqueue)
const result = (await run(supabase, { force: true, expected_journal_entry_ids: [JE_B, JE_A] })) as {
staged: boolean
operation_id?: string
message: string
preview: Record<string, unknown>
}
expect(result.staged).toBe(true)
expect(result.operation_id).toBe('op-batch-1')
expect(result.preview.compliance_warning).toContain('A57 + A58')
expect(result.message).toContain('WARNING')
// The commit executor re-validates against the set detected at commit,
// so the binding must travel with the op.
const inserted = findCall('pending_operations', 'insert')?.[0] as { params: Record<string, unknown> }
expect(inserted.params).toMatchObject({
transaction_id: TX_ID,
force: true,
expected_journal_entry_ids: [JE_B, JE_A],
})
})
it('refuses force whose ids are not exactly the set detected now', async () => {
mockDetectSet.mockResolvedValue(explainingSet)
const { supabase, enqueue } = createQueuedMockSupabase()
enqueuePreGuard(enqueue)
const err = await run(supabase, { force: true, expected_journal_entry_ids: [JE_A] }).then(
() => null,
(e: Error & { code?: string }) => e,
)
expect(err!.code).toBe('BATCH_TX_POSSIBLE_DUPLICATE')
expect(err!.message).toMatch(/^force=true avvisad/)
const tables = (supabase.from as ReturnType<typeof vi.fn>).mock.calls.map((c) => c[0])
expect(tables).not.toContain('pending_operations')
})
it('rejects force without expected_journal_entry_ids before any query runs', async () => {
const { supabase } = createQueuedMockSupabase()
const err = await run(supabase, { force: true }).then(() => null, (e: Error & { code?: string }) => e)
expect(err!.code).toBe('VALIDATION_ERROR')
expect(err!.message).toContain('expected_journal_entry_ids is required when force=true')
expect(supabase.from).not.toHaveBeenCalled()
})
it('rejects a malformed expected_journal_entry_ids at the boundary instead of silently filtering it', async () => {
// No host validates inputSchema at runtime: a string, an empty array, a
// non-string element and more than 10 ids are each a validation error,
// never a filtered list that then reads as a force mismatch.
for (const bad of [JE_A, [], [JE_A, 42], [JE_A, ''], Array.from({ length: 11 }, () => JE_A)]) {
const { supabase } = createQueuedMockSupabase()
const err = await run(supabase, { force: true, expected_journal_entry_ids: bad }).then(
() => null,
(e: Error & { code?: string }) => e,
)
expect(err?.code, JSON.stringify(bad)).toBe('VALIDATION_ERROR')
expect(err!.message).toContain('array of 1 to 10 journal_entry_id strings')
expect(supabase.from).not.toHaveBeenCalled()
}
})
it('does not persist a binding on a plain stage', async () => {
const { supabase, enqueue, findCall } = createQueuedMockSupabase()
enqueuePreGuard(enqueue)
enqueueStage(enqueue)
const result = (await run(supabase)) as { staged: boolean; preview: Record<string, unknown> }
expect(result.staged).toBe(true)
expect(result.preview.compliance_warning).toBeUndefined()
const inserted = findCall('pending_operations', 'insert')?.[0] as { params: Record<string, unknown> }
expect(inserted.params).not.toHaveProperty('force')
expect(inserted.params).not.toHaveProperty('expected_journal_entry_ids')
})
it('fails open when the detector throws without force, but the approval card says the check did not run', async () => {
mockDetectSet.mockRejectedValue(new Error('ledger scan timed out'))
const { supabase, enqueue, findCall } = createQueuedMockSupabase()
enqueuePreGuard(enqueue)
enqueueStage(enqueue)
const result = (await run(supabase)) as { staged: boolean; message: string; preview: Record<string, unknown> }
expect(result.staged).toBe(true)
expect(result.preview.compliance_warning).toContain('Dubblettkontrollen kunde inte köras')
expect(result.message).toContain('WARNING')
// Persisted with the op, so /pending (GenericPreview) renders the same warning.
const inserted = findCall('pending_operations', 'insert')?.[0] as { preview_data: Record<string, unknown> }
expect(inserted.preview_data.compliance_warning).toContain('Dubblettkontrollen kunde inte köras')
})
it('refuses force=true when the detector throws: an override that cannot be re-verified is never staged', async () => {
mockDetectSet.mockRejectedValue(new Error('ledger scan timed out'))
const { supabase, enqueue } = createQueuedMockSupabase()
enqueuePreGuard(enqueue)
const err = await run(supabase, { force: true, expected_journal_entry_ids: [JE_A, JE_B] }).then(
() => null,
(e: Error & { code?: string }) => e,
)
expect(err!.code).toBe('BATCH_TX_EXPLAINED_CHECK_FAILED')
const tables = (supabase.from as ReturnType<typeof vi.fn>).mock.calls.map((c) => c[0])
expect(tables).not.toContain('pending_operations')
})
})
@@ -0,0 +1,207 @@
/**
* gnubok_match_transaction_to_invoice: the soft-duplicate guard at stage time
* (issue #2294, parity with the dashboard match-invoice route's
* MATCH_INVOICE_POSSIBLE_DUPLICATE / MATCH_INVOICE_FORCE_CANDIDATE_MISMATCH).
*
* A manual verifikation that already books the receipt is surfaced before
* anything is staged, with the voucher named and the link call that resolves
* it; force is bound to that exact candidate and travels with the op so the
* commit executor can re-validate it.
*/
import { describe, it, expect, vi, beforeEach } from 'vitest'
import { createQueuedMockSupabase } from '@/tests/helpers'
const { mockDetectCandidate } = vi.hoisted(() => ({ mockDetectCandidate: vi.fn() }))
vi.mock('@/lib/invoices/duplicate-payment-detection', () => ({
detectDuplicatePaymentVoucher: mockDetectCandidate,
detectExplainingVoucherSetForTransaction: vi.fn(async () => null),
}))
import { tools } from '../server'
const match = tools.find((t) => t.name === 'gnubok_match_transaction_to_invoice')!
const TX_ID = '11111111-1111-4111-8111-111111111111'
const INV_ID = '22222222-2222-4222-8222-222222222222'
const JE_MANUAL = '55555555-5555-4555-8555-555555555555'
const JE_OTHER = '66666666-6666-4666-8666-666666666666'
const txRow = {
id: TX_ID,
description: 'SWISH INBET',
merchant_name: null,
amount: 1000,
currency: 'SEK',
amount_sek: null,
exchange_rate: null,
date: '2026-05-15',
invoice_id: null,
}
const invoiceRow = {
id: INV_ID,
invoice_number: 'F-2026001',
status: 'sent',
document_type: 'invoice',
total: 1000,
currency: 'SEK',
invoice_date: '2026-05-01',
customer: { name: 'Kund AB' },
}
const candidate = {
journal_entry_id: JE_MANUAL,
voucher_label: 'A12',
entry_date: '2026-05-15',
description: 'Inbetalning faktura',
amount: 1000,
bank_account_number: '1930',
reason: 'exact_amount_same_date',
amount_verified: true,
unverified_reason: null,
}
function run(supabase: unknown, extra: Record<string, unknown> = {}) {
return match.execute(
{ transaction_id: TX_ID, invoice_id: INV_ID, ...extra },
'company-1',
'user-1',
supabase as never,
{ type: 'api_key' } as never,
)
}
function enqueuePreGuard(enqueue: (r: { data?: unknown; error?: unknown }) => void) {
enqueue({ data: txRow, error: null })
enqueue({ data: invoiceRow, error: null })
}
function enqueueStage(enqueue: (r: { data?: unknown; error?: unknown }) => void) {
enqueue({ data: { bookkeeping_locked_through: null }, error: null }) // company_settings
enqueue({ data: { id: 'fp-1', is_closed: false, locked_at: null }, error: null }) // fiscal_periods
enqueue({ data: { id: 'op-match-1' }, error: null }) // pending_operations insert
}
beforeEach(() => {
vi.clearAllMocks()
mockDetectCandidate.mockResolvedValue(null)
})
describe('gnubok_match_transaction_to_invoice: soft-duplicate guard at stage time', () => {
it('refuses to stage, coded MATCH_INVOICE_POSSIBLE_DUPLICATE, naming the voucher, the link tool and the force binding', async () => {
mockDetectCandidate.mockResolvedValue(candidate)
const { supabase, enqueue } = createQueuedMockSupabase()
enqueuePreGuard(enqueue)
const err = await run(supabase).then(() => null, (e: Error & { code?: string }) => e)
expect(err).toBeInstanceOf(Error)
expect(err!.code).toBe('MATCH_INVOICE_POSSIBLE_DUPLICATE')
expect(err!.message).toContain('verifikat A12')
expect(err!.message).toContain('gnubok_link_transaction_to_journal_entry')
expect(err!.message).toContain(`expected_journal_entry_id="${JE_MANUAL}"`)
expect(mockDetectCandidate).toHaveBeenCalledWith(
supabase,
expect.objectContaining({ companyId: 'company-1', transactionId: TX_ID, transactionAmount: 1000, transactionCurrency: 'SEK' }),
)
const tables = (supabase.from as ReturnType<typeof vi.fn>).mock.calls.map((c) => c[0])
expect(tables).not.toContain('pending_operations')
})
it('stages with a compliance warning when force echoes the detected candidate, and persists the binding', async () => {
mockDetectCandidate.mockResolvedValue(candidate)
const { supabase, enqueue, findCall } = createQueuedMockSupabase()
enqueuePreGuard(enqueue)
enqueueStage(enqueue)
const result = (await run(supabase, { force: true, expected_journal_entry_id: JE_MANUAL })) as {
staged: boolean
operation_id?: string
preview: Record<string, unknown>
}
expect(result.staged).toBe(true)
expect(result.operation_id).toBe('op-match-1')
expect(result.preview.compliance_warning).toContain('A12')
const inserted = findCall('pending_operations', 'insert')?.[0] as { params: Record<string, unknown> }
expect(inserted.params).toMatchObject({
transaction_id: TX_ID,
invoice_id: INV_ID,
force: true,
expected_journal_entry_id: JE_MANUAL,
})
})
it('refuses a stale force id as MATCH_INVOICE_FORCE_CANDIDATE_MISMATCH', async () => {
mockDetectCandidate.mockResolvedValue(candidate)
const { supabase, enqueue } = createQueuedMockSupabase()
enqueuePreGuard(enqueue)
const err = await run(supabase, { force: true, expected_journal_entry_id: JE_OTHER }).then(
() => null,
(e: Error & { code?: string }) => e,
)
expect(err!.code).toBe('MATCH_INVOICE_FORCE_CANDIDATE_MISMATCH')
expect(err!.message).toContain(JE_OTHER)
expect(err!.message).toContain(JE_MANUAL)
})
it('refuses force when no candidate is detected any more (force is moot)', async () => {
const { supabase, enqueue } = createQueuedMockSupabase()
enqueuePreGuard(enqueue)
await expect(run(supabase, { force: true, expected_journal_entry_id: JE_MANUAL })).rejects.toMatchObject({
code: 'MATCH_INVOICE_FORCE_CANDIDATE_MISMATCH',
})
})
it('rejects force without expected_journal_entry_id before any query runs', async () => {
const { supabase } = createQueuedMockSupabase()
await expect(run(supabase, { force: true })).rejects.toMatchObject({ code: 'VALIDATION_ERROR' })
expect(supabase.from).not.toHaveBeenCalled()
})
it('rejects a non-string expected_journal_entry_id at the boundary instead of silently dropping it', async () => {
for (const bad of [42, '', [JE_MANUAL]]) {
const { supabase } = createQueuedMockSupabase()
await expect(run(supabase, { expected_journal_entry_id: bad })).rejects.toMatchObject({ code: 'VALIDATION_ERROR' })
expect(supabase.from).not.toHaveBeenCalled()
}
})
it('fails open when the detector throws without force, but the approval card says the check did not run', async () => {
mockDetectCandidate.mockRejectedValue(new Error('scan failed'))
const { supabase, enqueue, findCall } = createQueuedMockSupabase()
enqueuePreGuard(enqueue)
enqueueStage(enqueue)
const result = (await run(supabase)) as { staged: boolean; preview: Record<string, unknown> }
expect(result.staged).toBe(true)
expect(result.preview.compliance_warning).toContain('Dubblettkontrollen kunde inte köras')
// Persisted with the op: MatchTransactionInvoicePreview renders it on /pending.
const inserted = findCall('pending_operations', 'insert')?.[0] as { preview_data: Record<string, unknown> }
expect(inserted.preview_data.compliance_warning).toContain('Dubblettkontrollen kunde inte köras')
})
it('refuses force=true when the detector throws: an override that cannot be re-verified is never staged', async () => {
mockDetectCandidate.mockRejectedValue(new Error('scan failed'))
const { supabase, enqueue } = createQueuedMockSupabase()
enqueuePreGuard(enqueue)
await expect(run(supabase, { force: true, expected_journal_entry_id: JE_MANUAL })).rejects.toMatchObject({
code: 'MATCH_INVOICE_FORCE_CANDIDATE_MISMATCH',
})
const tables = (supabase.from as ReturnType<typeof vi.fn>).mock.calls.map((c) => c[0])
expect(tables).not.toContain('pending_operations')
})
it('stages a clean match without a binding or a warning', async () => {
const { supabase, enqueue, findCall } = createQueuedMockSupabase()
enqueuePreGuard(enqueue)
enqueueStage(enqueue)
const result = (await run(supabase)) as { staged: boolean; preview: Record<string, unknown> }
expect(result.staged).toBe(true)
expect(result.preview.compliance_warning).toBeUndefined()
const inserted = findCall('pending_operations', 'insert')?.[0] as { params: Record<string, unknown> }
expect(inserted.params).toEqual({ transaction_id: TX_ID, invoice_id: INV_ID })
})
})
@@ -390,6 +390,20 @@ describe('tools/list payload size guard', () => {
// description, no example; the lookup itself now goes through the
// shared resolver with the cache, so the case is also rarer.
//
// * Held at 60K with the force binding on the two match tools
// (2026-09-06, #2294): force + expected_journal_entry_ids on
// gnubok_match_batch_allocate and force + expected_journal_entry_id on
// gnubok_match_transaction_to_invoice, the override an agent needs
// once the already-explained guard refuses at stage time (the refusal
// message carries the exact ids to echo, so the property descriptions
// are one clause each). ~100 tokens against 93 of headroom, paid for
// inside the same two tools: the two "UUID of ..." property
// descriptions on the single tool dropped (names are the contract, as
// on the batch tool), and the batch tool's "Use when ..." sentence
// folded into its first sentence. Measured 59 988 on the accounted
// projection after the trims; headroom is 12, so the next addition
// demotes a read first.
//
// Long-term answer to growth is no longer a ceiling bump. gnubok_call_tool
// makes `catalogVisibility: 'search'` usable for READ tools on hosts that
// can only invoke what tools/list showed them, which is the constraint that