Files
accounted/extensions/general/mcp-server/__tests__/voucher-tools.test.ts
T
MattssonandClaude Fable 5 05380ddf54 feat(bookkeeping): correction-chain depth guard + Bedrock stream retry (#1581)
* feat(bookkeeping): bypassable chain-depth guard on corrections and stornos

Correcting or reversing an entry that already sits 3+ links deep in a
rattelse chain (correction_of_id/reverses_id walked in the DB, never
description matching) now throws CORRECTION_CHAIN_TOO_DEEP, steering the
caller to book ONE correction expressing the chain's net effect. Agents
looped storno+rattelse 10 deep on a live company (63/193 vouchers noise).

The guard is advisory, never a dead end: allow_deep_chain bypasses it on
every surface (correctEntry/reverseEntry option, REST body, MCP tool arg
staged through pending_operations, and confirm dialogs with Ratta anda /
Aterfor anda in the web UI). MCP staging pre-flight fires the guard at
stage time so the agent reconsiders in the same turn, and the executor
re-checks at commit. tools/list payload ceiling bumped 59K -> 59.5K for
the two bypass properties (trimmed to one sentence first).

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

* feat(agent): retry the Bedrock stream once on transient failures

A transient stream death (429/5xx, transport cut, or the two known
stream-corruption signatures: 'Unexpected event order' and 'request ended
without sending any chunks') killed the whole chat turn, stranding the
user mid-answer. The turn now retries once per turn after a short backoff:
safe because nothing is persisted until finalMessage() succeeds. A new
stream_restart event carries the pre-attempt text snapshot so the chat
client resets the partial bubble, drops uncompleted tool chips, and shows
'Forsoker igen...' until the retried stream produces text. Non-transient
errors (403, 400) keep the existing immediate-error path.

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

* fix(api): regenerate accounted-api skill and wire allow_deep_chain through v1

apiskill:check failed: CorrectJournalEntrySchema gained allow_deep_chain,
making references/journal-entries.md stale. Regenerated (hand-applied: the
generator output is deterministic from the registry). While wiring: the v1
correct route validated allow_deep_chain but dropped it, and the v1 reverse
route's strict body schema would have rejected it outright, leaving API
clients no bypass when the chain-depth guard fires. Both now forward the
flag to the engine and document CORRECTION_CHAIN_TOO_DEEP as a pitfall.

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

* chore: re-trigger CI after Vercel infra hang

The preview for e527e4044 compiled in 91s then hung 40 minutes in the
TypeScript phase and was killed with no error output; a CLI redeploy of
the identical code went Ready in 5m. Empty commit to refresh the git-
triggered deployment status.

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

* fix(bookkeeping): address CodeRabbit review on the chain-depth guard

- correction-chain: report rootVoucher only when the walk reached a
  genuine parentless root; a broken link, cycle, or hop-cap now yields
  null instead of presenting an intermediate voucher as the chain root.
- recordate: propagate allow_deep_chain end-to-end (recordateEntry
  option, route schema, and a Flytta anda bypass confirm in the dialog);
  a date move is another storno+rattelse layer and carried the guard
  with no override path.
- v1 correct/reverse: run the chain-depth guard before the dry-run
  return so a dry run gives the same verdict as the real execution.
- dashboard reverse route: 400 on malformed JSON or a non-boolean
  allow_deep_chain instead of silently reversing without the override;
  empty body stays the supported no-body case. Tests added.
- AgentChat stream_restart: discard the dead attempt's reasoning and
  re-arm the post-tool paragraph break so a retried turn doesn't render
  thinking twice or glue its continuation onto restored text.
- v1 reverse route doc comment updated for allow_deep_chain.

Not changed: the journal-list reverse flow (flagged as a dead end) can
never receive CORRECTION_CHAIN_TOO_DEEP: the list renders Aterfor only
for entries that are neither storno nor correction, and such entries
have no backward chain links, so their depth is always 0.

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

* test(bookkeeping): recordate route test expects the new options arg

recordateEntry now takes { allowDeepChain } as a sixth argument; the
route test's called-with assertion predates it.

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

---------

Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
2026-08-13 19:32:41 +02:00

881 lines
28 KiB
TypeScript

/**
* Staging-time gate tests for gnubok_create_voucher.
*
* The executor-level gates (period lock, balance, status === 'posted' for
* correct_entry) are tested in lib/pending-operations/__tests__/. This file
* covers the pre-staging gates added to the MCP tool layer for UX: explicit
* fiscal_period_id validation, inactive/missing account rejection, and the
* source_type-not-staged invariant.
*/
import { describe, it, expect, vi, beforeEach } from 'vitest'
import { createQueuedMockSupabase } from '@/tests/helpers'
vi.mock('@/lib/bookkeeping/engine', async () => {
const actual = await vi.importActual<typeof import('@/lib/bookkeeping/engine')>(
'@/lib/bookkeeping/engine'
)
return {
...actual,
findFiscalPeriod: vi.fn(),
}
})
import { tools } from '../server'
import { findFiscalPeriod } from '@/lib/bookkeeping/engine'
const createVoucher = tools.find((t) => t.name === 'gnubok_create_voucher')!
const correctEntry = tools.find((t) => t.name === 'gnubok_correct_entry')!
const reverseEntry = tools.find((t) => t.name === 'gnubok_reverse_journal_entry')!
beforeEach(() => {
vi.clearAllMocks()
})
const balancedLines = [
{ account_number: '1010', debit_amount: 250, credit_amount: 0 },
{ account_number: '1930', debit_amount: 0, credit_amount: 250 },
]
describe('gnubok_create_voucher: staging gates', () => {
it('is registered and mapped to bookkeeping:write scope', async () => {
const { TOOL_SCOPE_MAP } = await import('@/lib/auth/api-keys')
expect(createVoucher).toBeDefined()
expect(createVoucher.annotations.readOnlyHint).toBe(false)
expect(TOOL_SCOPE_MAP.gnubok_create_voucher).toBe('bookkeeping:write')
})
it('rejects unbalanced lines before staging', async () => {
const { supabase } = createQueuedMockSupabase()
await expect(
createVoucher.execute(
{
entry_date: '2026-05-12',
description: 'unbalanced',
fiscal_period_id: 'fp-1',
lines: [
{ account_number: '1010', debit_amount: 100, credit_amount: 0 },
{ account_number: '1930', debit_amount: 0, credit_amount: 80 },
],
},
'company-1',
'user-1',
supabase as never,
),
).rejects.toThrow(/not balanced/i)
})
it('rejects when an explicit fiscal_period_id is closed', async () => {
const { supabase, enqueue } = createQueuedMockSupabase()
// fiscal_periods fetch returns a closed period
enqueue({
data: {
id: 'fp-closed',
is_closed: true,
period_start: '2026-01-01',
period_end: '2026-03-31',
name: 'Q1 2026',
},
error: null,
})
await expect(
createVoucher.execute(
{
entry_date: '2026-02-15',
description: 'attempt to post in closed Q1',
fiscal_period_id: 'fp-closed',
lines: balancedLines,
},
'company-1',
'user-1',
supabase as never,
),
).rejects.toThrow(/låst/i)
// findFiscalPeriod must NOT be called when an explicit ID was supplied.
expect(findFiscalPeriod).not.toHaveBeenCalled()
})
it('rejects when an explicit fiscal_period_id does not exist', async () => {
const { supabase, enqueue } = createQueuedMockSupabase()
enqueue({ data: null, error: null }) // fiscal_periods fetch: not found
await expect(
createVoucher.execute(
{
entry_date: '2026-05-12',
description: 'unknown period uuid',
fiscal_period_id: 'fp-nonexistent',
lines: balancedLines,
},
'company-1',
'user-1',
supabase as never,
),
).rejects.toThrow(/not found/i)
})
it('rejects when entry_date is outside the supplied period', async () => {
const { supabase, enqueue } = createQueuedMockSupabase()
enqueue({
data: {
id: 'fp-1',
is_closed: false,
period_start: '2026-01-01',
period_end: '2026-03-31',
name: 'Q1 2026',
},
error: null,
})
await expect(
createVoucher.execute(
{
entry_date: '2026-05-12',
description: 'date outside Q1',
fiscal_period_id: 'fp-1',
lines: balancedLines,
},
'company-1',
'user-1',
supabase as never,
),
).rejects.toThrow(/utanför/i)
})
it('rejects when a referenced account is missing from the chart', async () => {
const { supabase, enqueue } = createQueuedMockSupabase()
enqueue({
data: {
id: 'fp-1',
is_closed: false,
period_start: '2026-01-01',
period_end: '2026-12-31',
name: '2026',
},
error: null,
})
// chart_of_accounts returns nothing: both accounts unknown
enqueue({ data: [], error: null })
await expect(
createVoucher.execute(
{
entry_date: '2026-05-12',
description: 'unknown accounts',
fiscal_period_id: 'fp-1',
lines: balancedLines,
},
'company-1',
'user-1',
supabase as never,
),
).rejects.toThrow(/saknas i kontoplanen/i)
})
it('rejects when a referenced account exists but is inactive', async () => {
const { supabase, enqueue } = createQueuedMockSupabase()
enqueue({
data: {
id: 'fp-1',
is_closed: false,
period_start: '2026-01-01',
period_end: '2026-12-31',
name: '2026',
},
error: null,
})
enqueue({
data: [
{ account_number: '1010', account_name: 'Balanserade utgifter', is_active: false },
{ account_number: '1930', account_name: 'Företagskonto', is_active: true },
],
error: null,
})
await expect(
createVoucher.execute(
{
entry_date: '2026-05-12',
description: 'inactive account',
fiscal_period_id: 'fp-1',
lines: balancedLines,
},
'company-1',
'user-1',
supabase as never,
),
).rejects.toThrow(/inaktiv/i)
})
it('happy path: stages with no source_type in params (executor hardcodes it)', async () => {
const { supabase, enqueue } = createQueuedMockSupabase()
enqueue({
data: {
id: 'fp-1',
is_closed: false,
period_start: '2026-01-01',
period_end: '2026-12-31',
name: '2026',
},
error: null,
})
enqueue({
data: [
{ account_number: '1010', account_name: 'Balanserade utgifter', is_active: true },
{ account_number: '1930', account_name: 'Företagskonto', is_active: true },
],
error: null,
})
// resolvePeriodStatusForDate: layer 1 (company_settings) + layer 2 (fiscal_periods).
enqueue({ data: null, error: null })
enqueue({ data: null, error: null })
enqueue({ data: { id: 'op-staged' }, error: null }) // pending_operations insert
const result = (await createVoucher.execute(
{
entry_date: '2026-05-12',
description: 'Capitalize Cursor',
fiscal_period_id: 'fp-1',
lines: balancedLines,
},
'company-1',
'user-1',
supabase as never,
)) as { staged: boolean; operation_id?: string; preview: Record<string, unknown> }
expect(result.staged).toBe(true)
expect(result.operation_id).toBe('op-staged')
expect(result.preview.total_debit).toBe(250)
expect(result.preview.total_credit).toBe(250)
// Critical: the staged pending_operations row must NOT carry source_type.
// The executor always hardcodes 'manual'. Look at the insert call.
const insertCalls = (supabase.from as ReturnType<typeof vi.fn>).mock.calls
expect(insertCalls.some((args) => args[0] === 'pending_operations')).toBe(true)
})
it('exposes inbox_item_id as an optional input', () => {
const schema = createVoucher.inputSchema as {
properties: { inbox_item_id?: { type: string; description?: string } }
required?: string[]
}
expect(schema.properties.inbox_item_id).toBeDefined()
expect(schema.properties.inbox_item_id?.type).toBe('string')
// Must NOT be required: voucher creation works standalone too.
expect(schema.required ?? []).not.toContain('inbox_item_id')
})
it('happy path with inbox_item_id: stages the op with inbox_item_id + document_id in params', async () => {
const { supabase, enqueue } = createQueuedMockSupabase()
enqueue({
data: {
id: 'fp-1',
is_closed: false,
period_start: '2026-01-01',
period_end: '2026-12-31',
name: '2026',
},
error: null,
})
enqueue({
data: [
{ account_number: '5410', account_name: 'Förbrukningsinventarier', is_active: true },
{ account_number: '1930', account_name: 'Företagskonto', is_active: true },
],
error: null,
})
enqueue({
data: {
id: 'inbox-1',
document_id: 'doc-1',
created_journal_entry_id: null,
created_supplier_invoice_id: null,
},
error: null,
}) // invoice_inbox_items lookup
enqueue({ data: null, error: null }) // resolvePeriodStatusForDate layer 1
enqueue({ data: null, error: null }) // resolvePeriodStatusForDate layer 2
enqueue({ data: { id: 'op-inbox' }, error: null }) // pending_operations insert
const result = (await createVoucher.execute(
{
entry_date: '2026-05-12',
description: 'Kvitto från Clas Ohlson: adapter',
fiscal_period_id: 'fp-1',
inbox_item_id: 'inbox-1',
lines: [
{ account_number: '5410', debit_amount: 250, credit_amount: 0 },
{ account_number: '1930', debit_amount: 0, credit_amount: 250 },
],
},
'company-1',
'user-1',
supabase as never,
)) as { staged: boolean; operation_id?: string; preview: Record<string, unknown> }
expect(result.staged).toBe(true)
expect(result.preview.inbox_item_id).toBe('inbox-1')
expect(result.preview.document_attached).toBe(true)
expect(result.preview.will).toMatch(/link the inbox item/i)
})
it('rejects when inbox_item_id is already booked as a journal entry', async () => {
const { supabase, enqueue } = createQueuedMockSupabase()
enqueue({
data: {
id: 'fp-1',
is_closed: false,
period_start: '2026-01-01',
period_end: '2026-12-31',
name: '2026',
},
error: null,
})
enqueue({
data: [
{ account_number: '5410', account_name: 'Förbrukningsinventarier', is_active: true },
{ account_number: '1930', account_name: 'Företagskonto', is_active: true },
],
error: null,
})
enqueue({
data: {
id: 'inbox-1',
document_id: 'doc-1',
created_journal_entry_id: 'je-existing',
created_supplier_invoice_id: null,
},
error: null,
})
await expect(
createVoucher.execute(
{
entry_date: '2026-05-12',
description: 'duplicate book attempt',
fiscal_period_id: 'fp-1',
inbox_item_id: 'inbox-1',
lines: [
{ account_number: '5410', debit_amount: 250, credit_amount: 0 },
{ account_number: '1930', debit_amount: 0, credit_amount: 250 },
],
},
'company-1',
'user-1',
supabase as never,
),
).rejects.toThrow(/already booked/i)
})
it('rejects when inbox_item_id is already converted to a supplier invoice', async () => {
const { supabase, enqueue } = createQueuedMockSupabase()
enqueue({
data: {
id: 'fp-1',
is_closed: false,
period_start: '2026-01-01',
period_end: '2026-12-31',
name: '2026',
},
error: null,
})
enqueue({
data: [
{ account_number: '5410', account_name: 'Förbrukningsinventarier', is_active: true },
{ account_number: '1930', account_name: 'Företagskonto', is_active: true },
],
error: null,
})
enqueue({
data: {
id: 'inbox-1',
document_id: 'doc-1',
created_journal_entry_id: null,
created_supplier_invoice_id: 'si-existing',
},
error: null,
})
await expect(
createVoucher.execute(
{
entry_date: '2026-05-12',
description: 'voucher attempt on AP-converted inbox',
fiscal_period_id: 'fp-1',
inbox_item_id: 'inbox-1',
lines: [
{ account_number: '5410', debit_amount: 250, credit_amount: 0 },
{ account_number: '1930', debit_amount: 0, credit_amount: 250 },
],
},
'company-1',
'user-1',
supabase as never,
),
).rejects.toThrow(/already converted/i)
})
it('rejects when inbox_item_id does not exist for the company', async () => {
const { supabase, enqueue } = createQueuedMockSupabase()
enqueue({
data: {
id: 'fp-1',
is_closed: false,
period_start: '2026-01-01',
period_end: '2026-12-31',
name: '2026',
},
error: null,
})
enqueue({
data: [
{ account_number: '5410', account_name: 'Förbrukningsinventarier', is_active: true },
{ account_number: '1930', account_name: 'Företagskonto', is_active: true },
],
error: null,
})
enqueue({ data: null, error: { message: 'not found' } })
await expect(
createVoucher.execute(
{
entry_date: '2026-05-12',
description: 'unknown inbox uuid',
fiscal_period_id: 'fp-1',
inbox_item_id: 'inbox-missing',
lines: [
{ account_number: '5410', debit_amount: 250, credit_amount: 0 },
{ account_number: '1930', debit_amount: 0, credit_amount: 250 },
],
},
'company-1',
'user-1',
supabase as never,
),
).rejects.toThrow(/inbox item .* not found/i)
})
})
describe('gnubok_correct_entry: registration', () => {
it('is registered with bookkeeping:write scope and is not read-only', async () => {
const { TOOL_SCOPE_MAP } = await import('@/lib/auth/api-keys')
expect(correctEntry).toBeDefined()
expect(correctEntry.annotations.readOnlyHint).toBe(false)
expect(TOOL_SCOPE_MAP.gnubok_correct_entry).toBe('bookkeeping:write')
})
it('rejects unbalanced replacement lines before staging', async () => {
const { supabase } = createQueuedMockSupabase()
await expect(
correctEntry.execute(
{
entry_id: 'je-1',
lines: [
{ account_number: '2645', debit_amount: 250, credit_amount: 0 },
{ account_number: '2614', debit_amount: 0, credit_amount: 200 },
],
},
'company-1',
'user-1',
supabase as never,
),
).rejects.toThrow(/not balanced/i)
})
it('shows preserved currency, tax, and dimension metadata in the correction preview', async () => {
const { supabase, enqueue } = createQueuedMockSupabase()
enqueue({ data: { dimensions_enabled: false }, error: null })
enqueue({
data: {
id: '11111111-1111-4111-8111-111111111111',
status: 'posted',
entry_date: '2026-05-12',
description: 'Foreign purchase',
voucher_number: 12,
voucher_series: 'A',
fiscal_period_id: 'fp-1',
fiscal_periods: { name: '2026', is_closed: false, locked_at: null },
lines: [
{
account_number: '5420',
debit_amount: 1000,
credit_amount: 0,
line_description: 'Software',
currency: 'EUR',
amount_in_currency: 90,
exchange_rate: 11.111111,
tax_code: 'EU_SERVICE',
dimensions: { '6': 'P001' },
cost_center: null,
project: 'P001',
},
{
account_number: '1930',
debit_amount: 0,
credit_amount: 1000,
line_description: 'Settlement',
currency: 'EUR',
amount_in_currency: 90,
exchange_rate: 11.111111,
tax_code: null,
dimensions: {},
cost_center: null,
project: null,
},
],
},
error: null,
})
enqueue({ data: { bookkeeping_locked_through: null }, error: null })
enqueue({ data: { id: 'fp-1', is_closed: false, locked_at: null }, error: null })
enqueue({ data: { id: 'op-correct-1' }, error: null })
const replacementLines = [
{
account_number: '5420',
debit_amount: 1000,
credit_amount: 0,
line_description: 'Software',
currency: 'EUR',
amount_in_currency: 90,
exchange_rate: 11.111111,
tax_code: 'EU_SERVICE',
dimensions: { '6': 'P001' },
},
{
account_number: '1931',
debit_amount: 0,
credit_amount: 1000,
line_description: 'Settlement',
currency: 'EUR',
amount_in_currency: 90,
exchange_rate: 11.111111,
dimensions: {},
},
]
const result = (await correctEntry.execute(
{
entry_id: '11111111-1111-4111-8111-111111111111',
lines: replacementLines,
},
'company-1',
'user-1',
supabase as never,
)) as {
preview: {
original: { lines: Array<Record<string, unknown>> }
correction: { lines: Array<Record<string, unknown>> }
}
}
expect(result.preview.original.lines[0]).toMatchObject({
currency: 'EUR',
amount_in_currency: 90,
exchange_rate: 11.111111,
tax_code: 'EU_SERVICE',
dimensions: { '6': 'P001' },
project: 'P001',
})
expect(result.preview.correction.lines[0]).toMatchObject({
currency: 'EUR',
amount_in_currency: 90,
exchange_rate: 11.111111,
tax_code: 'EU_SERVICE',
dimensions: { '6': 'P001' },
})
})
})
describe('gnubok_correct_entry / gnubok_reverse_journal_entry: chain-depth guard', () => {
// Base row for a posted correction that already sits 3 links deep:
// c3 → c2 → c1 → orig-0 (root, voucher A7).
const deepTarget = {
id: '22222222-2222-4222-8222-222222222222',
status: 'posted',
entry_date: '2026-05-12',
description: 'Rättelse: Rättelse: Rättelse: Köp',
voucher_number: 15,
voucher_series: 'A',
fiscal_period_id: 'fp-1',
correction_of_id: 'c2',
reverses_id: null,
fiscal_periods: { name: '2026', is_closed: false, locked_at: null },
lines: [
{ account_number: '5420', debit_amount: 1000, credit_amount: 0, line_description: null, currency: null, amount_in_currency: null, exchange_rate: null, tax_code: null, dimensions: null, cost_center: null, project: null },
{ account_number: '1930', debit_amount: 0, credit_amount: 1000, line_description: null, currency: null, amount_in_currency: null, exchange_rate: null, tax_code: null, dimensions: null, cost_center: null, project: null },
],
}
const walkerRows = [
{ data: { id: 'c2', correction_of_id: 'c1', reverses_id: null, voucher_series: 'A', voucher_number: 12 }, error: null },
{ data: { id: 'c1', correction_of_id: 'orig-0', reverses_id: null, voucher_series: 'A', voucher_number: 9 }, error: null },
{ data: { id: 'orig-0', correction_of_id: null, reverses_id: null, voucher_series: 'A', voucher_number: 7 }, error: null },
]
const replacementLines = [
{ account_number: '5410', debit_amount: 1000, credit_amount: 0 },
{ account_number: '1930', debit_amount: 0, credit_amount: 1000 },
]
it('refuses to stage a correction on a chain 3 levels deep with an agent-actionable error', async () => {
const { supabase, enqueue, enqueueMany } = createQueuedMockSupabase()
// Lines carry no dimensions, so no dimension-registry query precedes the
// entry fetch.
enqueue({ data: deepTarget, error: null })
enqueueMany(walkerRows)
await expect(
correctEntry.execute(
{ entry_id: deepTarget.id, lines: replacementLines },
'company-1',
'user-1',
supabase as never,
),
).rejects.toMatchObject({
code: 'CORRECTION_CHAIN_TOO_DEEP',
depth: 3,
chainRootVoucher: 'A7',
})
})
it('stages when allow_deep_chain=true and forwards the flag to the executor params', async () => {
const { supabase, enqueue, findCall } = createQueuedMockSupabase()
enqueue({ data: deepTarget, error: null })
// No walker queries: the guard is skipped entirely on explicit override.
enqueue({ data: { bookkeeping_locked_through: null }, error: null })
enqueue({ data: { id: 'fp-1', is_closed: false, locked_at: null }, error: null })
enqueue({ data: { id: 'op-deep-1' }, error: null })
await correctEntry.execute(
{ entry_id: deepTarget.id, lines: replacementLines, allow_deep_chain: true },
'company-1',
'user-1',
supabase as never,
)
const insertArgs = findCall('pending_operations', 'insert')
expect(insertArgs).toBeDefined()
const payload = (insertArgs as unknown[])[0] as { params?: { allow_deep_chain?: boolean } }
expect(payload.params?.allow_deep_chain).toBe(true)
})
it('refuses to stage a storno on a chain 3 levels deep', async () => {
const { supabase, enqueue, enqueueMany } = createQueuedMockSupabase()
enqueue({ data: deepTarget, error: null })
enqueueMany(walkerRows)
await expect(
reverseEntry.execute(
{ entry_id: deepTarget.id },
'company-1',
'user-1',
supabase as never,
),
).rejects.toMatchObject({ code: 'CORRECTION_CHAIN_TOO_DEEP', depth: 3 })
})
})
describe('gnubok_reverse_journal_entry: staging gates', () => {
it('is registered with bookkeeping:write scope and is not read-only', async () => {
const { TOOL_SCOPE_MAP } = await import('@/lib/auth/api-keys')
expect(reverseEntry).toBeDefined()
expect(reverseEntry.annotations.readOnlyHint).toBe(false)
expect(TOOL_SCOPE_MAP.gnubok_reverse_journal_entry).toBe('bookkeeping:write')
})
it('rejects when entry_id is missing', async () => {
const { supabase } = createQueuedMockSupabase()
await expect(
reverseEntry.execute({}, 'company-1', 'user-1', supabase as never),
).rejects.toThrow(/entry_id is required/i)
})
it('rejects when the original entry is not posted', async () => {
const { supabase, enqueue } = createQueuedMockSupabase()
enqueue({
data: {
id: '11111111-1111-1111-1111-111111111111',
status: 'draft',
entry_date: '2026-05-12',
description: 'Test',
voucher_number: 1,
voucher_series: 'A',
fiscal_period_id: 'fp-1',
fiscal_periods: { name: '2026', is_closed: false },
lines: [],
},
error: null,
})
await expect(
reverseEntry.execute(
{ entry_id: '11111111-1111-1111-1111-111111111111' },
'company-1',
'user-1',
supabase as never,
),
).rejects.toThrow(/posted entries can be reversed/i)
})
it('rejects when the original entry is in a closed period', async () => {
const { supabase, enqueue } = createQueuedMockSupabase()
enqueue({
data: {
id: '22222222-2222-2222-2222-222222222222',
status: 'posted',
entry_date: '2025-12-31',
description: 'Test',
voucher_number: 42,
voucher_series: 'A',
fiscal_period_id: 'fp-closed',
fiscal_periods: { name: '2025', is_closed: true },
lines: [],
},
error: null,
})
await expect(
reverseEntry.execute(
{ entry_id: '22222222-2222-2222-2222-222222222222' },
'company-1',
'user-1',
supabase as never,
),
).rejects.toThrow(/closed/i)
})
})
describe('entry_id resolution: voucher refs and hallucinated UUIDs', () => {
// These tests cover the resolveJournalEntryRef helper as exercised through
// gnubok_correct_entry. The same resolution path is wired into
// gnubok_reverse_journal_entry, so one tool is enough to lock the behaviour.
const balancedCorrection = [
{ account_number: '2645', debit_amount: 250, credit_amount: 0 },
{ account_number: '2614', debit_amount: 0, credit_amount: 250 },
]
it('resolves a voucher ref like "A-113" to its UUID before the lookup', async () => {
const { supabase, enqueue } = createQueuedMockSupabase()
const resolvedId = '33333333-3333-3333-3333-333333333333'
// 1) resolveJournalEntryRef -> single match by (series, number)
enqueue({
data: [{ id: resolvedId, entry_date: '2026-03-06', description: 'Cursor 2' }],
error: null,
})
// 2) original journal_entries lookup, but the period is closed so we
// short-circuit before staging. That's enough to confirm the helper
// resolved the ref and passed the UUID through to the next query.
enqueue({
data: {
id: resolvedId,
status: 'posted',
entry_date: '2026-03-06',
description: 'Cursor 2',
voucher_number: 113,
voucher_series: 'A',
fiscal_period_id: 'fp-closed',
fiscal_periods: { name: '2026', is_closed: true, locked_at: null },
lines: [],
},
error: null,
})
await expect(
correctEntry.execute(
{ entry_id: 'A-113', lines: balancedCorrection },
'company-1',
'user-1',
supabase as never,
),
).rejects.toThrow(/locked or closed/i)
})
it('errors when a voucher ref matches multiple entries across fiscal periods', async () => {
const { supabase, enqueue } = createQueuedMockSupabase()
enqueue({
data: [
{ id: 'aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa', entry_date: '2026-03-06', description: 'Cursor 2' },
{ id: 'bbbbbbbb-bbbb-bbbb-bbbb-bbbbbbbbbbbb', entry_date: '2025-03-06', description: 'Cursor 1' },
],
error: null,
})
await expect(
correctEntry.execute(
{ entry_id: 'A-113', lines: balancedCorrection },
'company-1',
'user-1',
supabase as never,
),
).rejects.toThrow(/matches multiple entries/i)
})
it('errors when a voucher ref matches nothing', async () => {
const { supabase, enqueue } = createQueuedMockSupabase()
enqueue({ data: [], error: null })
await expect(
correctEntry.execute(
{ entry_id: 'Z-999', lines: balancedCorrection },
'company-1',
'user-1',
supabase as never,
),
).rejects.toThrow(/no journal entry found for voucher "z-999"/i)
})
it('errors with a parse hint when the ref is neither a UUID nor a voucher format', async () => {
const { supabase } = createQueuedMockSupabase()
await expect(
correctEntry.execute(
{ entry_id: 'not-an-id-at-all', lines: balancedCorrection },
'company-1',
'user-1',
supabase as never,
),
).rejects.toThrow(/could not parse entry reference/i)
})
it('surfaces the supplied UUID in not-found errors so hallucinated IDs are debuggable', async () => {
const { supabase, enqueue } = createQueuedMockSupabase()
const hallucinated = 'a71a11ae-b8e2-450f-aaa6-a227d03b0c94'
// UUID passes through resolution unchanged → straight to the original
// lookup, which returns no row.
enqueue({ data: null, error: null })
await expect(
correctEntry.execute(
{ entry_id: hallucinated, lines: balancedCorrection },
'company-1',
'user-1',
supabase as never,
),
).rejects.toThrow(new RegExp(`id=${hallucinated}`))
})
})
describe('agent memory tools: agent:write scope gate', () => {
const rememberFact = tools.find((t) => t.name === 'gnubok_remember_fact')
const forgetFact = tools.find((t) => t.name === 'gnubok_forget_fact')
it('registers the memory write tools mapped to agent:write', async () => {
const { TOOL_SCOPE_MAP } = await import('@/lib/auth/api-keys')
expect(rememberFact).toBeDefined()
expect(forgetFact).toBeDefined()
expect(TOOL_SCOPE_MAP.gnubok_remember_fact).toBe('agent:write')
expect(TOOL_SCOPE_MAP.gnubok_forget_fact).toBe('agent:write')
})
// Mirror the server's enforcement: a tool is blocked when it has a required
// scope the key does not hold (server.ts: `requiredScope && !hasScope(...)`).
it('denies a key without agent:write and allows one with it', async () => {
const { TOOL_SCOPE_MAP, hasScope } = await import('@/lib/auth/api-keys')
const required = TOOL_SCOPE_MAP.gnubok_remember_fact
const without = ['agent:read', 'reports:read'] as never[]
const isDenied = !!required && !hasScope(without, required)
expect(isDenied).toBe(true)
const withWrite = ['agent:read', 'agent:write'] as never[]
const isAllowed = !required || hasScope(withWrite, required)
expect(isAllowed).toBe(true)
})
})