* fix(bookkeeping): allow creating a fiscal year that fills an interior gap Fiscal-period creation only allowed chaining a new räkenskapsår before the earliest or after the latest existing period, so a company with a gap between years (e.g. 2024 + 2026 from an SIE import, missing 2025) could not create the missing year — it failed with "New period must chain before the earliest or after the latest existing period". Generalise forward chaining onto the new period's immediate predecessor, which covers both appending a new latest year and filling an interior gap. The "prior year must be locked" guard now applies only to true appends, not gap fills (a backfill, like backward chaining). previous_period_id is set to the predecessor and the successor is relinked so the BFNAR 2013:2 continuity chain stays intact. The create dialog suggests the missing year (capped so it never overlaps the next period), the settings page seeds the dialog at the earliest gap, and the default suggested name is now "Räkenskapsår <year>". Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com> * fix(bookkeeping): omföra föregående års resultat (2099 → 2098) at year-end Year-end closing posts the result to 2099 "Årets resultat" and the opening balance carried it forward on 2099 every year, so 2099 accumulated across years and the prior result never moved off "Årets resultat". executeYearEndClosing now posts a separate "Omföring av föregående års resultat" verifikat (Dr 2099 / Cr 2098 for a profit, reversed for a loss) into the new period after the continuity check passes, so 2099 starts each year at zero. Kept as a standalone entry rather than folded into the opening balance so the IB stays a faithful mirror of the prior UB and IB/UB continuity still holds. Aktiebolag only; idempotent; no-op when 2099 is flat. The 2098 → 2091/2898 disposition (bolagsstämma decision) is intentionally left to a separate step. - new source_type 'result_appropriation' (migration + type + Zod enum) - generateResultAppropriation helper (planner + poster) wired as step 11 - ResultStep surfaces the omföring voucher - unit tests + pg-real invariant - scripts/repair-result-appropriation.ts: retroactive catch-up (dry-run default) Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com> * feat(transactions): shadow-detect date-drift duplicate bank transactions The content-dedup bridge buckets on exact (date, ore), so the same transaction re-imported with a booking date that drifted a day lands in a different bucket and slips past every dedup layer. Add a measure-only ("shadow") detector that flags would-be +/-1-day duplicates and counts them, without changing what is inserted - so the gap can be validated on real data before any enforcement, mirroring the scope-drift shadow. - shiftIsoDate(): pure, deterministic adjacent-date helper - ingest: DEDUP_DATE_DRIFT_MODE flag (default on), pre-loop bucket snapshot, per-row gate with desc-bridge + cross-channel-symmetry signals; logs shadow_date_drift_candidates, never alters inserts - fail-safe date guard so the measurement can never abort an import - regression tests for both signals, account/window/distinct guards, no-double-count, and the malformed-date fail-safe Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com> * test(bookkeeping): anonymize a customer reference in fiscal-period tests Remove a real customer name ("AXMD AB") from regression-test comments; no logic change. Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com> * fix(workflows): enhance Docker image scanning and caching mechanisms * fix(bookkeeping): enhance year-end result appropriation handling and error reporting --------- Co-authored-by: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
269 lines
9.1 KiB
TypeScript
269 lines
9.1 KiB
TypeScript
/**
|
|
* Tests for gnubok_get_agent_briefing — session-bootstrap context for the
|
|
* specialized accountant agent over MCP.
|
|
*/
|
|
import { describe, it, expect, vi, beforeEach } from 'vitest'
|
|
import { tools } from '../server'
|
|
|
|
vi.mock('@/lib/supabase/server', () => ({
|
|
createClient: vi.fn(),
|
|
createServiceClient: vi.fn(),
|
|
}))
|
|
|
|
vi.mock('@/lib/auth/api-keys', async (importOriginal) => {
|
|
const actual = await importOriginal<typeof import('@/lib/auth/api-keys')>()
|
|
return {
|
|
...actual,
|
|
extractBearerToken: vi.fn().mockReturnValue('test-token'),
|
|
validateApiKey: vi.fn().mockResolvedValue({
|
|
userId: 'user-1',
|
|
companyId: 'company-1',
|
|
scopes: ['agent:read'],
|
|
}),
|
|
createServiceClientNoCookies: vi.fn(),
|
|
}
|
|
})
|
|
|
|
/** Builds a supabase mock whose three relevant tables resolve to canned data. */
|
|
function mockSupabase(opts: {
|
|
profile?: {
|
|
profile_summary: string | null
|
|
horizontal_atoms: string[] | null
|
|
vertical_atoms: string[] | null
|
|
modifier_atoms: string[] | null
|
|
} | null
|
|
memoryRows?: Array<{
|
|
id: string
|
|
kind: string
|
|
content: string
|
|
relevance_score: number | null
|
|
}>
|
|
atomRows?: Array<{
|
|
id: string
|
|
tier: string
|
|
title: string | null
|
|
description: string
|
|
}>
|
|
// profiles.full_name for the signed-in user. undefined → no profile row.
|
|
userFullName?: string | null
|
|
errors?: { profile?: string; memory?: string; atoms?: string }
|
|
}) {
|
|
const profile = opts.profile === undefined ? null : opts.profile
|
|
const memoryRows = opts.memoryRows ?? []
|
|
const atomRows = opts.atomRows ?? []
|
|
const errors = opts.errors ?? {}
|
|
|
|
return {
|
|
from: vi.fn((table: string) => {
|
|
if (table === 'profiles') {
|
|
return {
|
|
select: vi.fn(() => ({
|
|
eq: vi.fn(() => ({
|
|
maybeSingle: vi.fn().mockResolvedValue({
|
|
data:
|
|
opts.userFullName === undefined ? null : { full_name: opts.userFullName },
|
|
error: null,
|
|
}),
|
|
})),
|
|
})),
|
|
}
|
|
}
|
|
if (table === 'agent_profiles') {
|
|
return {
|
|
select: vi.fn(() => ({
|
|
eq: vi.fn(() => ({
|
|
maybeSingle: vi.fn().mockResolvedValue({
|
|
data: profile,
|
|
error: errors.profile ? new Error(errors.profile) : null,
|
|
}),
|
|
})),
|
|
})),
|
|
}
|
|
}
|
|
if (table === 'agent_memory') {
|
|
return {
|
|
select: vi.fn(() => ({
|
|
eq: vi.fn(() => ({
|
|
eq: vi.fn(() => ({
|
|
order: vi.fn(() => ({
|
|
order: vi.fn(() => ({
|
|
limit: vi.fn().mockResolvedValue({
|
|
data: memoryRows,
|
|
error: errors.memory ? new Error(errors.memory) : null,
|
|
}),
|
|
})),
|
|
})),
|
|
})),
|
|
})),
|
|
})),
|
|
}
|
|
}
|
|
if (table === 'agent_atom_registry') {
|
|
return {
|
|
select: vi.fn(() => ({
|
|
in: vi.fn(() => ({
|
|
eq: vi.fn().mockResolvedValue({
|
|
data: atomRows,
|
|
error: errors.atoms ? new Error(errors.atoms) : null,
|
|
}),
|
|
})),
|
|
})),
|
|
}
|
|
}
|
|
throw new Error(`Unexpected table in test mock: ${table}`)
|
|
}),
|
|
}
|
|
}
|
|
|
|
describe('gnubok_get_agent_briefing tool', () => {
|
|
beforeEach(() => {
|
|
vi.clearAllMocks()
|
|
})
|
|
|
|
it('is registered with readOnly + idempotent annotations', () => {
|
|
const tool = tools.find((t) => t.name === 'gnubok_get_agent_briefing')
|
|
expect(tool).toBeDefined()
|
|
expect(tool?.annotations.readOnlyHint).toBe(true)
|
|
expect(tool?.annotations.idempotentHint).toBe(true)
|
|
expect(tool?.annotations.destructiveHint).toBe(false)
|
|
})
|
|
|
|
it('inputSchema declares no required args (no inputs)', () => {
|
|
const tool = tools.find((t) => t.name === 'gnubok_get_agent_briefing')!
|
|
const input = tool.inputSchema as { properties?: Record<string, unknown>; required?: string[]; additionalProperties: boolean }
|
|
expect(input.additionalProperties).toBe(false)
|
|
expect(input.required).toBeUndefined()
|
|
})
|
|
|
|
it('returns null summary, empty atoms, empty memory, null user_name when nothing exists', async () => {
|
|
const tool = tools.find((t) => t.name === 'gnubok_get_agent_briefing')!
|
|
const supabase = mockSupabase({ profile: null })
|
|
const result = (await tool.execute(
|
|
{},
|
|
'company-1',
|
|
'user-1',
|
|
supabase as never,
|
|
{ type: 'api_key' }
|
|
)) as {
|
|
user_name: string | null
|
|
profile_summary: string | null
|
|
atoms: unknown[]
|
|
memory: unknown[]
|
|
}
|
|
expect(result.profile_summary).toBeNull()
|
|
expect(result.atoms).toEqual([])
|
|
expect(result.memory).toEqual([])
|
|
expect(result.user_name).toBeNull()
|
|
})
|
|
|
|
it('returns only the first name (tilltalsnamn) — data minimisation, not the full legal name', async () => {
|
|
const tool = tools.find((t) => t.name === 'gnubok_get_agent_briefing')!
|
|
const supabase = mockSupabase({ profile: null, userFullName: 'Peter Bennet' })
|
|
const result = (await tool.execute(
|
|
{},
|
|
'company-1',
|
|
'user-1',
|
|
supabase as never,
|
|
{ type: 'api_key' }
|
|
)) as { user_name: string | null }
|
|
// GDPR Art.5(1)(c): the surname never enters the LLM prompt.
|
|
expect(result.user_name).toBe('Peter')
|
|
})
|
|
|
|
it('treats a blank full_name as no name (null)', async () => {
|
|
const tool = tools.find((t) => t.name === 'gnubok_get_agent_briefing')!
|
|
const supabase = mockSupabase({ profile: null, userFullName: ' ' })
|
|
const result = (await tool.execute(
|
|
{},
|
|
'company-1',
|
|
'user-1',
|
|
supabase as never,
|
|
{ type: 'api_key' }
|
|
)) as { user_name: string | null }
|
|
expect(result.user_name).toBeNull()
|
|
})
|
|
|
|
it('returns profile + atom metadata + memory when populated', async () => {
|
|
const tool = tools.find((t) => t.name === 'gnubok_get_agent_briefing')!
|
|
const supabase = mockSupabase({
|
|
profile: {
|
|
profile_summary: 'Du driver Acme AB som IT-konsult …',
|
|
horizontal_atoms: ['horizontal/swedish-vat'],
|
|
vertical_atoms: ['vertical/konsult-it'],
|
|
modifier_atoms: ['modifier/single-shareholder-ab-fmb'],
|
|
},
|
|
atomRows: [
|
|
{ id: 'horizontal/swedish-vat', tier: 'horizontal', title: 'Swedish VAT', description: 'Moms compliance' },
|
|
{ id: 'vertical/konsult-it', tier: 'vertical', title: 'IT-konsult', description: 'SNI 62' },
|
|
{ id: 'modifier/single-shareholder-ab-fmb', tier: 'modifier', title: 'Fåmansbolag', description: 'AB single shareholder' },
|
|
],
|
|
memoryRows: [
|
|
{ id: 'mem-1', kind: 'fact', content: 'Hyresavtal löper t.o.m. 2027', relevance_score: 0.9 },
|
|
{ id: 'mem-2', kind: 'preference', content: 'Föredrar månadsslut den 25:e', relevance_score: 0.7 },
|
|
],
|
|
})
|
|
const result = (await tool.execute(
|
|
{},
|
|
'company-1',
|
|
'user-1',
|
|
supabase as never,
|
|
{ type: 'api_key' }
|
|
)) as {
|
|
profile_summary: string | null
|
|
atoms: Array<{ id: string; tier: string; title: string; description: string }>
|
|
memory: Array<{ id: string; kind: string; content: string; relevance_score: number | null }>
|
|
}
|
|
expect(result.profile_summary).toContain('Acme AB')
|
|
expect(result.atoms).toHaveLength(3)
|
|
expect(result.atoms.map((a) => a.id).sort()).toEqual([
|
|
'horizontal/swedish-vat',
|
|
'modifier/single-shareholder-ab-fmb',
|
|
'vertical/konsult-it',
|
|
])
|
|
expect(result.memory).toHaveLength(2)
|
|
expect(result.memory[0].id).toBe('mem-1') // top-ranked
|
|
expect(result.memory[0].relevance_score).toBe(0.9)
|
|
})
|
|
|
|
it('handles profile present but no atoms loaded yet', async () => {
|
|
const tool = tools.find((t) => t.name === 'gnubok_get_agent_briefing')!
|
|
const supabase = mockSupabase({
|
|
profile: {
|
|
profile_summary: 'Composer ran but selected nothing.',
|
|
horizontal_atoms: null,
|
|
vertical_atoms: null,
|
|
modifier_atoms: null,
|
|
},
|
|
})
|
|
const result = (await tool.execute(
|
|
{},
|
|
'company-1',
|
|
'user-1',
|
|
supabase as never,
|
|
{ type: 'api_key' }
|
|
)) as {
|
|
profile_summary: string | null
|
|
atoms: unknown[]
|
|
memory: unknown[]
|
|
}
|
|
expect(result.profile_summary).toBe('Composer ran but selected nothing.')
|
|
expect(result.atoms).toEqual([])
|
|
})
|
|
|
|
it('surfaces a structured error if the profile query fails', async () => {
|
|
const tool = tools.find((t) => t.name === 'gnubok_get_agent_briefing')!
|
|
const supabase = mockSupabase({ profile: null, errors: { profile: 'pg-down' } })
|
|
await expect(
|
|
tool.execute({}, 'company-1', 'user-1', supabase as never, { type: 'api_key' })
|
|
).rejects.toThrow(/Failed to load agent profile.*pg-down/)
|
|
})
|
|
|
|
it('surfaces a structured error if the memory query fails', async () => {
|
|
const tool = tools.find((t) => t.name === 'gnubok_get_agent_briefing')!
|
|
const supabase = mockSupabase({ profile: null, errors: { memory: 'rls-denied' } })
|
|
await expect(
|
|
tool.execute({}, 'company-1', 'user-1', supabase as never, { type: 'api_key' })
|
|
).rejects.toThrow(/Failed to load agent memory.*rls-denied/)
|
|
})
|
|
})
|