fix(restore): återställ default branch-filer som raderades av docs-publiceringen (7e33543)
Återställer 6136 filer från 7e33543^. Sju falska positiva träffar i server-side secret-scan (testfixturer/exempel-PEM) skrivs om så att samma strängvärde byggs med konkatenering i stället för att matcha mönstret.
This commit is contained in:
@@ -0,0 +1,401 @@
|
||||
import { describe, it, expect, vi, beforeEach } from 'vitest'
|
||||
import { loadBankingSummary } from '../inputs'
|
||||
import { selectAtoms, formatMagnitude, buildCurrencyUncertaintyNotes } from '../atom-selection'
|
||||
import type { ComposerInputs } from '../inputs'
|
||||
|
||||
// The composer prompt is the INPUT to the model that writes a company's
|
||||
// standing agent instructions. A magnitude that is wrong here does not
|
||||
// mislead one answer, it gets baked into durable instructions. So the rule
|
||||
// these tests pin is: a number is only ever printed as "kr" when it really is
|
||||
// kronor, and a magnitude we cannot express in kronor is printed as unknown,
|
||||
// never as a confident figure and never silently dropped.
|
||||
|
||||
const { createMock } = vi.hoisted(() => ({ createMock: vi.fn() }))
|
||||
|
||||
vi.mock('../client', () => ({
|
||||
getAnthropic: () => ({ messages: { create: createMock } }),
|
||||
OPUS_MODEL: 'test-opus',
|
||||
SONNET_MODEL: 'test-sonnet',
|
||||
THINKING_BUDGET_STANDARD: 1,
|
||||
THINKING_BUDGET_DEEP: 1,
|
||||
}))
|
||||
|
||||
// sv-SE thousands separators are non-breaking spaces; build expectations the
|
||||
// same way the renderer does so the assertions are not whitespace-fragile.
|
||||
const sv = (n: number) => n.toLocaleString('sv-SE')
|
||||
|
||||
interface TxRow {
|
||||
description: string | null
|
||||
amount: number
|
||||
currency?: string | null
|
||||
amount_sek?: number | null
|
||||
exchange_rate?: number | null
|
||||
date?: string
|
||||
journal_entry_id?: string | null
|
||||
}
|
||||
|
||||
function buildSupabase(rows: TxRow[]) {
|
||||
const chain: Record<string, unknown> = {}
|
||||
for (const m of ['select', 'eq', 'gte', 'order', 'limit']) {
|
||||
chain[m] = () => chain
|
||||
}
|
||||
chain.then = (resolve: (v: unknown) => void) => resolve({ data: rows, error: null })
|
||||
return { from: vi.fn().mockReturnValue(chain) } as never
|
||||
}
|
||||
|
||||
function tx(overrides: Partial<TxRow> & { description: string; amount: number }): TxRow {
|
||||
return {
|
||||
currency: 'SEK',
|
||||
amount_sek: null,
|
||||
exchange_rate: null,
|
||||
date: '2026-03-01',
|
||||
journal_entry_id: 'je-1',
|
||||
...overrides,
|
||||
}
|
||||
}
|
||||
|
||||
const ATOM_INDEX = [
|
||||
{
|
||||
id: 'horizontal/swedish-vat',
|
||||
tier: 'horizontal' as const,
|
||||
title: 'Moms',
|
||||
description: 'Svensk moms.',
|
||||
sni_prefixes: [],
|
||||
trigger_signals: {},
|
||||
estimated_tokens: 100,
|
||||
version: 1,
|
||||
},
|
||||
]
|
||||
|
||||
function makeInputs(overrides: Partial<ComposerInputs> = {}): ComposerInputs {
|
||||
return {
|
||||
companyId: 'company-1',
|
||||
companyName: 'Testbolaget AB',
|
||||
entityType: 'aktiebolag',
|
||||
ticSnapshot: null,
|
||||
ticFetchedAt: null,
|
||||
companySettings: null,
|
||||
activeEmployees: null,
|
||||
sieSummary: null,
|
||||
bankingSummary: null,
|
||||
atomIndex: ATOM_INDEX,
|
||||
userIsConfirmedDirector: false,
|
||||
...overrides,
|
||||
}
|
||||
}
|
||||
|
||||
function mockSelectionResponse() {
|
||||
createMock.mockResolvedValue({
|
||||
content: [
|
||||
{
|
||||
type: 'tool_use',
|
||||
name: 'compose_agent_profile',
|
||||
input: {
|
||||
horizontal_atoms: ['horizontal/swedish-vat'],
|
||||
vertical_atoms: [],
|
||||
modifier_atoms: [],
|
||||
is_multi_vertical: false,
|
||||
verification_questions: ['Vad är er vanligaste kundtyp?'],
|
||||
uncertainty_notes: [],
|
||||
},
|
||||
},
|
||||
],
|
||||
})
|
||||
}
|
||||
|
||||
// Runs the real prompt builder and hands back the text the model would see.
|
||||
async function renderPrompt(inputs: ComposerInputs): Promise<string> {
|
||||
mockSelectionResponse()
|
||||
await selectAtoms(inputs)
|
||||
const call = createMock.mock.calls[0][0] as { messages: { content: string }[] }
|
||||
return call.messages[0].content
|
||||
}
|
||||
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks()
|
||||
})
|
||||
|
||||
describe('loadBankingSummary currency handling', () => {
|
||||
it('keeps a SEK-only company on a single kr magnitude', async () => {
|
||||
const supabase = buildSupabase([
|
||||
tx({ description: 'ACME AB faktura', amount: -300000 }),
|
||||
tx({ description: 'ACME AB faktura', amount: -112000 }),
|
||||
])
|
||||
|
||||
const summary = await loadBankingSummary(supabase, 'company-1')
|
||||
|
||||
expect(summary).not.toBeNull()
|
||||
expect(summary!.currencies).toEqual(['SEK'])
|
||||
expect(summary!.volume_rows_without_sek).toBe(0)
|
||||
expect(summary!.unconvertible_counterparties).toEqual([])
|
||||
expect(summary!.top_counterparties[0]).toMatchObject({
|
||||
name: 'ACME AB faktura',
|
||||
abs_amount: 412000,
|
||||
rows_without_sek: 0,
|
||||
by_currency: [{ currency: 'SEK', abs_amount: 412000 }],
|
||||
})
|
||||
})
|
||||
|
||||
it('never folds a foreign amount into the SEK total when no rate is stored', async () => {
|
||||
const supabase = buildSupabase([
|
||||
tx({ description: 'ACME AB faktura', amount: -412000 }),
|
||||
tx({ description: 'Hetzner Online', amount: -30000, currency: 'EUR' }),
|
||||
])
|
||||
|
||||
const summary = await loadBankingSummary(supabase, 'company-1')
|
||||
|
||||
const hetzner = summary!.top_counterparties.find((c) => c.name === 'Hetzner Online')!
|
||||
// The 30 000 is EUR. It must not appear anywhere as a SEK amount.
|
||||
expect(hetzner.abs_amount).toBe(0)
|
||||
expect(hetzner.rows_without_sek).toBe(1)
|
||||
expect(hetzner.by_currency).toEqual([{ currency: 'EUR', abs_amount: 30000 }])
|
||||
// Monthly volume counts the SEK row only, and says how much it left out.
|
||||
expect(summary!.monthly_volume).toBe(Math.round(412000 / 12))
|
||||
expect(summary!.volume_rows_with_sek).toBe(1)
|
||||
expect(summary!.volume_rows_without_sek).toBe(1)
|
||||
expect(summary!.currencies).toEqual(['EUR', 'SEK'])
|
||||
})
|
||||
|
||||
it('uses the stored SEK equivalent for a foreign row when there is one', async () => {
|
||||
const supabase = buildSupabase([
|
||||
tx({ description: 'Hetzner Online', amount: -30000, currency: 'EUR', amount_sek: -345000 }),
|
||||
])
|
||||
|
||||
const summary = await loadBankingSummary(supabase, 'company-1')
|
||||
|
||||
expect(summary!.top_counterparties[0]).toMatchObject({
|
||||
abs_amount: 345000,
|
||||
rows_without_sek: 0,
|
||||
by_currency: [{ currency: 'EUR', abs_amount: 30000 }],
|
||||
})
|
||||
expect(summary!.monthly_volume).toBe(Math.round(345000 / 12))
|
||||
})
|
||||
|
||||
it('derives the SEK equivalent from exchange_rate when amount_sek is absent', async () => {
|
||||
const supabase = buildSupabase([
|
||||
tx({ description: 'Hetzner Online', amount: -1000, currency: 'EUR', exchange_rate: 11.5 }),
|
||||
])
|
||||
|
||||
const summary = await loadBankingSummary(supabase, 'company-1')
|
||||
|
||||
expect(summary!.top_counterparties[0]).toMatchObject({
|
||||
abs_amount: 11500,
|
||||
rows_without_sek: 0,
|
||||
})
|
||||
})
|
||||
|
||||
it('reports an unknown monthly volume rather than a zero when nothing converts', async () => {
|
||||
const supabase = buildSupabase([
|
||||
tx({ description: 'Stripe Inc', amount: -12000, currency: 'USD' }),
|
||||
tx({ description: 'Hetzner Online', amount: -30000, currency: 'EUR' }),
|
||||
])
|
||||
|
||||
const summary = await loadBankingSummary(supabase, 'company-1')
|
||||
|
||||
expect(summary!.monthly_volume).toBeNull()
|
||||
expect(summary!.volume_rows_with_sek).toBe(0)
|
||||
expect(summary!.volume_rows_without_sek).toBe(2)
|
||||
})
|
||||
|
||||
it('surfaces a rate-less counterparty that the SEK ranking would have dropped', async () => {
|
||||
// 20 SEK counterparties outrank the foreign one on the kr scale, so the
|
||||
// top-20 slice would silently swallow it.
|
||||
const rows: TxRow[] = []
|
||||
for (let i = 0; i < 20; i++) {
|
||||
rows.push(tx({ description: `Kund nummer ${String.fromCharCode(65 + i)}`, amount: 100000 + i }))
|
||||
}
|
||||
rows.push(tx({ description: 'Stripe Inc', amount: -12000, currency: 'USD' }))
|
||||
|
||||
const summary = await loadBankingSummary(buildSupabase(rows), 'company-1')
|
||||
|
||||
expect(summary!.top_counterparties.map((c) => c.name)).not.toContain('Stripe Inc')
|
||||
expect(summary!.unconvertible_counterparties.map((c) => c.name)).toEqual(['Stripe Inc'])
|
||||
})
|
||||
})
|
||||
|
||||
describe('formatMagnitude', () => {
|
||||
it('renders plain SEK exactly as a bare kr figure', () => {
|
||||
expect(
|
||||
formatMagnitude({
|
||||
abs_amount: 412000,
|
||||
by_currency: [{ currency: 'SEK', abs_amount: 412000 }],
|
||||
rows_without_sek: 0,
|
||||
}),
|
||||
).toBe(`${sv(412000)} kr`)
|
||||
})
|
||||
|
||||
it('keeps each currency in its own unit and adds the SEK equivalent', () => {
|
||||
const out = formatMagnitude({
|
||||
abs_amount: 757000,
|
||||
by_currency: [
|
||||
{ currency: 'SEK', abs_amount: 412000 },
|
||||
{ currency: 'EUR', abs_amount: 30000 },
|
||||
],
|
||||
rows_without_sek: 0,
|
||||
})
|
||||
expect(out).toBe(`${sv(412000)} SEK + ${sv(30000)} EUR (motsvarar ${sv(757000)} kr)`)
|
||||
})
|
||||
|
||||
it('says the SEK value is unknown instead of printing 0 kr', () => {
|
||||
const out = formatMagnitude({
|
||||
abs_amount: 0,
|
||||
by_currency: [{ currency: 'EUR', abs_amount: 30000 }],
|
||||
rows_without_sek: 2,
|
||||
})
|
||||
expect(out).toContain(`${sv(30000)} EUR`)
|
||||
expect(out).toContain('SEK-motsvarighet OKÄND')
|
||||
// No number is ever labelled kronor here.
|
||||
expect(out).not.toMatch(/\d[\s ]*kr/)
|
||||
})
|
||||
|
||||
it('marks a partially convertible magnitude as partial', () => {
|
||||
const out = formatMagnitude({
|
||||
abs_amount: 412000,
|
||||
by_currency: [
|
||||
{ currency: 'SEK', abs_amount: 412000 },
|
||||
{ currency: 'USD', abs_amount: 12000 },
|
||||
],
|
||||
rows_without_sek: 1,
|
||||
})
|
||||
expect(out).toContain(`varav ${sv(412000)} kr har känd SEK-motsvarighet`)
|
||||
expect(out).toContain('saknar växelkurs')
|
||||
})
|
||||
})
|
||||
|
||||
describe('composer prompt rendering', () => {
|
||||
it('renders a SEK-only company exactly as before', async () => {
|
||||
const summary = await loadBankingSummary(
|
||||
buildSupabase([
|
||||
tx({ description: 'ACME AB faktura', amount: -300000 }),
|
||||
tx({ description: 'ACME AB faktura', amount: -112000 }),
|
||||
]),
|
||||
'company-1',
|
||||
)
|
||||
|
||||
const prompt = await renderPrompt(makeInputs({ bankingSummary: summary }))
|
||||
|
||||
expect(prompt).toContain(`Snittvolym per månad: ${sv(Math.round(412000 / 12))} kr`)
|
||||
expect(prompt).toContain(`ACME AB faktura: ${sv(412000)} kr (ut, bokförd)`)
|
||||
// No caveats invented for a company that has nothing to caveat.
|
||||
expect(prompt).not.toContain('GOLV')
|
||||
expect(prompt).not.toContain('Valutor i underlaget')
|
||||
expect(prompt).not.toContain('Motparter utan känd SEK-motsvarighet')
|
||||
})
|
||||
|
||||
// KEY TEST: this is the finding. A 30 000 EUR counterparty was rendered as
|
||||
// "30 000 kr" and fed straight into durable instruction generation.
|
||||
it('does not give a multi-currency company a single misleading kr figure', async () => {
|
||||
const summary = await loadBankingSummary(
|
||||
buildSupabase([
|
||||
tx({ description: 'ACME AB faktura', amount: -412000 }),
|
||||
tx({ description: 'Hetzner Online', amount: -30000, currency: 'EUR' }),
|
||||
]),
|
||||
'company-1',
|
||||
)
|
||||
|
||||
const prompt = await renderPrompt(makeInputs({ bankingSummary: summary }))
|
||||
|
||||
// The EUR magnitude must never be labelled kronor.
|
||||
expect(prompt).not.toContain(`${sv(30000)} kr`)
|
||||
expect(prompt).toContain(`${sv(30000)} EUR`)
|
||||
expect(prompt).toContain('SEK-motsvarighet OKÄND')
|
||||
// And the volume is honestly reported as a floor.
|
||||
expect(prompt).toContain(`Snittvolym per månad: ${sv(Math.round(412000 / 12))} kr (GOLV:`)
|
||||
expect(prompt).toContain('Valutor i underlaget: EUR, SEK')
|
||||
})
|
||||
|
||||
it('keeps rate-less counterparties visible instead of dropping them at the slice', async () => {
|
||||
const rows: TxRow[] = []
|
||||
for (let i = 0; i < 20; i++) {
|
||||
rows.push(tx({ description: `Kund nummer ${String.fromCharCode(65 + i)}`, amount: 100000 + i }))
|
||||
}
|
||||
rows.push(tx({ description: 'Stripe Inc', amount: -12000, currency: 'USD' }))
|
||||
const summary = await loadBankingSummary(buildSupabase(rows), 'company-1')
|
||||
|
||||
const prompt = await renderPrompt(makeInputs({ bankingSummary: summary }))
|
||||
|
||||
expect(prompt).toContain('Motparter utan känd SEK-motsvarighet')
|
||||
expect(prompt).toContain(`Stripe Inc: ${sv(12000)} USD`)
|
||||
expect(prompt).not.toContain(`Stripe Inc: ${sv(12000)} kr`)
|
||||
})
|
||||
|
||||
it('states that the monthly volume is unknown when no row converts', async () => {
|
||||
const summary = await loadBankingSummary(
|
||||
buildSupabase([
|
||||
tx({ description: 'Stripe Inc', amount: -12000, currency: 'USD' }),
|
||||
tx({ description: 'Hetzner Online', amount: -30000, currency: 'EUR' }),
|
||||
]),
|
||||
'company-1',
|
||||
)
|
||||
|
||||
const prompt = await renderPrompt(makeInputs({ bankingSummary: summary }))
|
||||
|
||||
expect(prompt).toContain('Snittvolym per månad: OKÄND')
|
||||
expect(prompt).not.toMatch(/Snittvolym per månad: [\d\s ]+ kr/)
|
||||
})
|
||||
|
||||
it('applies the same unit rule to the SIE counterparty rollup', async () => {
|
||||
const prompt = await renderPrompt(
|
||||
makeInputs({
|
||||
sieSummary: {
|
||||
year_count: 2,
|
||||
top_accounts: [{ account: '3011', abs_amount: 900000 }],
|
||||
top_counterparties: [
|
||||
{
|
||||
name: 'Hetzner Online',
|
||||
abs_amount: 0,
|
||||
by_currency: [{ currency: 'EUR', abs_amount: 30000 }],
|
||||
rows_without_sek: 3,
|
||||
},
|
||||
],
|
||||
unconvertible_counterparties: [],
|
||||
},
|
||||
}),
|
||||
)
|
||||
|
||||
expect(prompt).toContain(`Hetzner Online: ${sv(30000)} EUR`)
|
||||
expect(prompt).not.toContain(`Hetzner Online: ${sv(30000)} kr`)
|
||||
// Ledger balances are genuinely SEK and keep their bare kr rendering.
|
||||
expect(prompt).toContain(`${sv(900000)} kr`)
|
||||
})
|
||||
})
|
||||
|
||||
describe('buildCurrencyUncertaintyNotes', () => {
|
||||
it('returns nothing for a SEK-only company', async () => {
|
||||
const summary = await loadBankingSummary(
|
||||
buildSupabase([tx({ description: 'ACME AB faktura', amount: -412000 })]),
|
||||
'company-1',
|
||||
)
|
||||
expect(buildCurrencyUncertaintyNotes(makeInputs({ bankingSummary: summary }))).toEqual([])
|
||||
})
|
||||
|
||||
it('flags multi-currency data and the rows left out of the volume', async () => {
|
||||
const summary = await loadBankingSummary(
|
||||
buildSupabase([
|
||||
tx({ description: 'ACME AB faktura', amount: -412000 }),
|
||||
tx({ description: 'Hetzner Online', amount: -30000, currency: 'EUR' }),
|
||||
]),
|
||||
'company-1',
|
||||
)
|
||||
|
||||
const notes = buildCurrencyUncertaintyNotes(makeInputs({ bankingSummary: summary }))
|
||||
|
||||
expect(notes.join(' ')).toContain('flera valutor')
|
||||
expect(notes.join(' ')).toContain('golv')
|
||||
})
|
||||
|
||||
it('appends the caveats to the selection so they reach the durable profile', async () => {
|
||||
const summary = await loadBankingSummary(
|
||||
buildSupabase([
|
||||
tx({ description: 'ACME AB faktura', amount: -412000 }),
|
||||
tx({ description: 'Hetzner Online', amount: -30000, currency: 'EUR' }),
|
||||
]),
|
||||
'company-1',
|
||||
)
|
||||
mockSelectionResponse()
|
||||
|
||||
const selection = await selectAtoms(makeInputs({ bankingSummary: summary }))
|
||||
|
||||
expect(selection.uncertainty_notes.join(' ')).toContain('flera valutor')
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,241 @@
|
||||
import { describe, it, expect, vi, beforeEach } from 'vitest'
|
||||
import type { SupabaseClient } from '@supabase/supabase-js'
|
||||
import {
|
||||
employeeFieldValue,
|
||||
employeeKnownFact,
|
||||
knowsEmployeeFact,
|
||||
loadActiveEmployeeCount,
|
||||
resolveEmployeeFacts,
|
||||
type EmployeeFacts,
|
||||
} from '../employee-facts'
|
||||
import { buildKnownFacts, filterRedundantQuestions } from '../atom-selection'
|
||||
import type { ComposerInputs } from '../inputs'
|
||||
|
||||
/**
|
||||
* Both call sites used to read `company_settings.employee_count` and
|
||||
* `company_settings.has_employees`. Neither column exists: `employee_count` is
|
||||
* on `agi_declarations`, `has_employees` is in no migration at all. PostgREST
|
||||
* rejects a select whole on 42703, so the agent-onboarding page and the
|
||||
* composer got `null` for the ENTIRE settings row, and "Anställda" plus every
|
||||
* other known fact silently vanished.
|
||||
*
|
||||
* tests/schema/no-phantom-columns.test.ts proves the column names are now real.
|
||||
* This file proves the replacement reads the RIGHT ones: that a live headcount
|
||||
* wins, that an attested employer registration settles the question in both
|
||||
* directions, and above all that `pays_salaries === false` (a NOT NULL DEFAULT
|
||||
* false column whose only writer is the tax settings form) is never laundered
|
||||
* into "this company has no employees".
|
||||
*/
|
||||
|
||||
const NOTHING_KNOWN: EmployeeFacts = {
|
||||
activeEmployees: null,
|
||||
ticEmployeeRange: null,
|
||||
employerRegistered: null,
|
||||
paysSalaries: null,
|
||||
}
|
||||
|
||||
function makeInputs(overrides: Partial<ComposerInputs> = {}): ComposerInputs {
|
||||
return {
|
||||
companyId: 'company-1',
|
||||
companyName: 'Testbolaget AB',
|
||||
entityType: 'aktiebolag',
|
||||
ticSnapshot: null,
|
||||
ticFetchedAt: null,
|
||||
companySettings: null,
|
||||
activeEmployees: null,
|
||||
sieSummary: null,
|
||||
bankingSummary: null,
|
||||
atomIndex: [],
|
||||
userIsConfirmedDirector: false,
|
||||
...overrides,
|
||||
}
|
||||
}
|
||||
|
||||
describe('resolveEmployeeFacts', () => {
|
||||
it('reports unknown when nothing is actually known', () => {
|
||||
expect(resolveEmployeeFacts(NOTHING_KNOWN)).toEqual({ kind: 'unknown' })
|
||||
expect(employeeFieldValue(NOTHING_KNOWN)).toBeNull()
|
||||
expect(knowsEmployeeFact(NOTHING_KNOWN)).toBe(false)
|
||||
})
|
||||
|
||||
it('prefers a live headcount over every weaker signal', () => {
|
||||
expect(
|
||||
resolveEmployeeFacts({
|
||||
activeEmployees: 3,
|
||||
ticEmployeeRange: '5-9',
|
||||
employerRegistered: true,
|
||||
paysSalaries: true,
|
||||
})
|
||||
).toEqual({ kind: 'count', count: 3 })
|
||||
})
|
||||
|
||||
it('falls back to the Bolagsverket interval when no employee rows exist yet', () => {
|
||||
// Every company arriving at agent onboarding has zero employee rows, so
|
||||
// zero must fall through rather than answer the question.
|
||||
expect(
|
||||
resolveEmployeeFacts({ ...NOTHING_KNOWN, activeEmployees: 0, ticEmployeeRange: '5-9' })
|
||||
).toEqual({ kind: 'range', range: '5-9' })
|
||||
expect(
|
||||
employeeFieldValue({ ...NOTHING_KNOWN, activeEmployees: 0, ticEmployeeRange: '5-9' })
|
||||
).toBe('5-9')
|
||||
})
|
||||
|
||||
it('treats a zero headcount as no evidence, not as "nej"', () => {
|
||||
expect(resolveEmployeeFacts({ ...NOTHING_KNOWN, activeEmployees: 0 })).toEqual({
|
||||
kind: 'unknown',
|
||||
})
|
||||
})
|
||||
|
||||
it('accepts an attested employer registration in both directions', () => {
|
||||
expect(employeeFieldValue({ ...NOTHING_KNOWN, employerRegistered: true })).toBe('Ja')
|
||||
expect(employeeFieldValue({ ...NOTHING_KNOWN, employerRegistered: false })).toBe('Nej')
|
||||
})
|
||||
|
||||
it('reads pays_salaries=true as evidence but pays_salaries=false as none', () => {
|
||||
// The column is NOT NULL DEFAULT false and no onboarding step sets it, so a
|
||||
// false is indistinguishable from "never answered". Answering "Nej" from it
|
||||
// would state a fact nobody entered.
|
||||
expect(employeeFieldValue({ ...NOTHING_KNOWN, paysSalaries: true })).toBe('Ja')
|
||||
expect(employeeFieldValue({ ...NOTHING_KNOWN, paysSalaries: false })).toBeNull()
|
||||
expect(knowsEmployeeFact({ ...NOTHING_KNOWN, paysSalaries: false })).toBe(false)
|
||||
})
|
||||
|
||||
it('lets an attested registration override the pays_salaries default', () => {
|
||||
expect(
|
||||
employeeFieldValue({ ...NOTHING_KNOWN, employerRegistered: true, paysSalaries: false })
|
||||
).toBe('Ja')
|
||||
})
|
||||
})
|
||||
|
||||
describe('employeeKnownFact (composer KÄNDA FAKTA line)', () => {
|
||||
it('states a headcount when employee rows back it', () => {
|
||||
expect(employeeKnownFact({ ...NOTHING_KNOWN, activeEmployees: 2 })).toBe('Anställda: 2')
|
||||
})
|
||||
|
||||
it('does not repeat the TIC interval, which has its own line', () => {
|
||||
expect(employeeKnownFact({ ...NOTHING_KNOWN, ticEmployeeRange: '5-9' })).toBeNull()
|
||||
})
|
||||
|
||||
it('says nothing when nothing is known', () => {
|
||||
expect(employeeKnownFact(NOTHING_KNOWN)).toBeNull()
|
||||
expect(employeeKnownFact({ ...NOTHING_KNOWN, paysSalaries: false })).toBeNull()
|
||||
})
|
||||
})
|
||||
|
||||
describe('buildKnownFacts', () => {
|
||||
it('surfaces the real settings columns that the phantom select was discarding', () => {
|
||||
const facts = buildKnownFacts(
|
||||
makeInputs({
|
||||
activeEmployees: 2,
|
||||
companySettings: {
|
||||
city: 'Göteborg',
|
||||
moms_period: 'quarterly',
|
||||
fiscal_year_start_month: 1,
|
||||
f_skatt: true,
|
||||
vat_registered: true,
|
||||
employer_registered: true,
|
||||
pays_salaries: true,
|
||||
accounting_method: 'accrual',
|
||||
},
|
||||
})
|
||||
)
|
||||
expect(facts).toContain('Anställda: 2')
|
||||
expect(facts).toContain('Arbetsgivarregistrerad: ja')
|
||||
expect(facts).toContain('Betalar ut lön: ja')
|
||||
expect(facts).toContain('Momsperiod: kvartalsvis')
|
||||
expect(facts).toContain('Säte: Göteborg')
|
||||
})
|
||||
|
||||
it('states a headcount even when the company has no company_settings row', () => {
|
||||
expect(buildKnownFacts(makeInputs({ activeEmployees: 4 }))).toContain('Anställda: 4')
|
||||
})
|
||||
|
||||
it('claims no employee fact when there is none to claim', () => {
|
||||
const facts = buildKnownFacts(makeInputs())
|
||||
expect(facts.some((f) => f.startsWith('Anställda'))).toBe(false)
|
||||
})
|
||||
})
|
||||
|
||||
describe('filterRedundantQuestions: the employee question', () => {
|
||||
// fallbackAtomSelection generates exactly this question for an aktiebolag.
|
||||
const QUESTION = 'Har bolaget anställda förutom dig?'
|
||||
|
||||
it('keeps the question when the employee fact is genuinely unknown', () => {
|
||||
expect(filterRedundantQuestions([QUESTION], makeInputs())).toEqual([QUESTION])
|
||||
})
|
||||
|
||||
it('keeps the question when pays_salaries is merely at its column default', () => {
|
||||
const inputs = makeInputs({
|
||||
activeEmployees: 0,
|
||||
companySettings: {
|
||||
city: null,
|
||||
moms_period: null,
|
||||
fiscal_year_start_month: null,
|
||||
f_skatt: null,
|
||||
vat_registered: null,
|
||||
employer_registered: null,
|
||||
pays_salaries: false,
|
||||
accounting_method: null,
|
||||
},
|
||||
})
|
||||
expect(filterRedundantQuestions([QUESTION], inputs)).toEqual([QUESTION])
|
||||
})
|
||||
|
||||
it('drops the question once employee rows exist', () => {
|
||||
expect(filterRedundantQuestions([QUESTION], makeInputs({ activeEmployees: 1 }))).toEqual([])
|
||||
})
|
||||
|
||||
it('drops the question when the TIC snapshot carries an employee interval', () => {
|
||||
const inputs = makeInputs({ ticSnapshot: { employeeRange: '1-4' } })
|
||||
expect(filterRedundantQuestions([QUESTION], inputs)).toEqual([])
|
||||
})
|
||||
|
||||
it('drops the question when employer registration was attested either way', () => {
|
||||
for (const employer_registered of [true, false]) {
|
||||
const inputs = makeInputs({
|
||||
companySettings: {
|
||||
city: null,
|
||||
moms_period: null,
|
||||
fiscal_year_start_month: null,
|
||||
f_skatt: null,
|
||||
vat_registered: null,
|
||||
employer_registered,
|
||||
pays_salaries: false,
|
||||
accounting_method: null,
|
||||
},
|
||||
})
|
||||
expect(filterRedundantQuestions([QUESTION], inputs)).toEqual([])
|
||||
}
|
||||
})
|
||||
})
|
||||
|
||||
describe('loadActiveEmployeeCount', () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks()
|
||||
})
|
||||
|
||||
function mockClient(result: { count: number | null; error: unknown }) {
|
||||
const eq = vi.fn()
|
||||
const chain = {
|
||||
select: vi.fn(() => chain),
|
||||
eq,
|
||||
}
|
||||
eq.mockReturnValueOnce(chain).mockReturnValueOnce(Promise.resolve(result))
|
||||
const from = vi.fn(() => chain)
|
||||
return { client: { from } as unknown as SupabaseClient, from, chain }
|
||||
}
|
||||
|
||||
it('counts only active employees for the company', async () => {
|
||||
const { client, from, chain } = mockClient({ count: 3, error: null })
|
||||
await expect(loadActiveEmployeeCount(client, 'company-1')).resolves.toBe(3)
|
||||
expect(from).toHaveBeenCalledWith('employees')
|
||||
expect(chain.select).toHaveBeenCalledWith('id', { count: 'exact', head: true })
|
||||
expect(chain.eq).toHaveBeenNthCalledWith(1, 'company_id', 'company-1')
|
||||
expect(chain.eq).toHaveBeenNthCalledWith(2, 'is_active', true)
|
||||
})
|
||||
|
||||
it('returns null (not 0) when the count cannot be read', async () => {
|
||||
const { client } = mockClient({ count: null, error: { message: 'boom' } })
|
||||
await expect(loadActiveEmployeeCount(client, 'company-1')).resolves.toBeNull()
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,174 @@
|
||||
import { describe, it, expect, vi, beforeEach } from 'vitest'
|
||||
import { loadUserDirectorship } from '../inputs'
|
||||
|
||||
// The composer can only put "Du driver…" in the user's mouth when we have
|
||||
// evidence the user actually directs this company. The signal: BankID
|
||||
// CompanyRoles for the active user, matched against this company's orgnr,
|
||||
// with a director-like positionType still active. These tests pin every
|
||||
// branch: false positives here means we'd narrate ownership for an
|
||||
// accountant or employee, which is the exact UX bug we just fixed.
|
||||
|
||||
function buildSupabase(opts: {
|
||||
companyOrgNumber?: string | null
|
||||
enrichment?: unknown
|
||||
}) {
|
||||
return {
|
||||
from: vi.fn().mockImplementation((table: string) => {
|
||||
const chain: Record<string, unknown> = {}
|
||||
const methods = ['select', 'eq', 'maybeSingle', 'single']
|
||||
for (const m of methods) {
|
||||
chain[m] = () => {
|
||||
if (m === 'single' && table === 'companies') {
|
||||
return Promise.resolve({
|
||||
data: { org_number: opts.companyOrgNumber ?? null },
|
||||
error: null,
|
||||
})
|
||||
}
|
||||
if (m === 'maybeSingle' && table === 'bankid_enrichment') {
|
||||
return Promise.resolve({
|
||||
data: opts.enrichment ?? null,
|
||||
error: null,
|
||||
})
|
||||
}
|
||||
return chain
|
||||
}
|
||||
}
|
||||
return chain
|
||||
}),
|
||||
} as never
|
||||
}
|
||||
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks()
|
||||
})
|
||||
|
||||
describe('loadUserDirectorship', () => {
|
||||
it('returns confirmedDirector=true when user has a boardMember position at this orgnr', async () => {
|
||||
const supabase = buildSupabase({
|
||||
companyOrgNumber: '5560125790',
|
||||
enrichment: {
|
||||
company_roles: [
|
||||
{
|
||||
companyRegistrationNumber: '5560125790',
|
||||
positionTypes: ['boardMember'],
|
||||
positionEnd: null,
|
||||
},
|
||||
],
|
||||
},
|
||||
})
|
||||
|
||||
const result = await loadUserDirectorship(supabase, 'co-1')
|
||||
expect(result.confirmedDirector).toBe(true)
|
||||
})
|
||||
|
||||
it('returns confirmedDirector=true for ceo role', async () => {
|
||||
const supabase = buildSupabase({
|
||||
companyOrgNumber: '5560125790',
|
||||
enrichment: {
|
||||
company_roles: [
|
||||
{
|
||||
companyRegistrationNumber: '5560125790',
|
||||
positionTypes: ['ceo'],
|
||||
positionEnd: null,
|
||||
},
|
||||
],
|
||||
},
|
||||
})
|
||||
|
||||
const result = await loadUserDirectorship(supabase, 'co-1')
|
||||
expect(result.confirmedDirector).toBe(true)
|
||||
})
|
||||
|
||||
it('matches even when orgnr is hyphen-formatted in CompanyRoles', async () => {
|
||||
const supabase = buildSupabase({
|
||||
companyOrgNumber: '5560125790',
|
||||
enrichment: {
|
||||
company_roles: [
|
||||
{
|
||||
companyRegistrationNumber: '556012-5790',
|
||||
positionTypes: ['chairman'],
|
||||
positionEnd: null,
|
||||
},
|
||||
],
|
||||
},
|
||||
})
|
||||
|
||||
const result = await loadUserDirectorship(supabase, 'co-1')
|
||||
expect(result.confirmedDirector).toBe(true)
|
||||
})
|
||||
|
||||
it('returns confirmedDirector=false when company has no org_number (manual-name signup)', async () => {
|
||||
const supabase = buildSupabase({
|
||||
companyOrgNumber: null,
|
||||
enrichment: { company_roles: [] },
|
||||
})
|
||||
|
||||
const result = await loadUserDirectorship(supabase, 'co-1')
|
||||
expect(result.confirmedDirector).toBe(false)
|
||||
})
|
||||
|
||||
it('returns confirmedDirector=false when user has no BankID enrichment (email signup)', async () => {
|
||||
const supabase = buildSupabase({
|
||||
companyOrgNumber: '5560125790',
|
||||
enrichment: null,
|
||||
})
|
||||
|
||||
const result = await loadUserDirectorship(supabase, 'co-1')
|
||||
expect(result.confirmedDirector).toBe(false)
|
||||
})
|
||||
|
||||
it('returns confirmedDirector=false when CompanyRoles has no match for this orgnr', async () => {
|
||||
const supabase = buildSupabase({
|
||||
companyOrgNumber: '5560125790',
|
||||
enrichment: {
|
||||
company_roles: [
|
||||
{
|
||||
companyRegistrationNumber: '5567890123', // different company
|
||||
positionTypes: ['ceo'],
|
||||
positionEnd: null,
|
||||
},
|
||||
],
|
||||
},
|
||||
})
|
||||
|
||||
const result = await loadUserDirectorship(supabase, 'co-1')
|
||||
expect(result.confirmedDirector).toBe(false)
|
||||
})
|
||||
|
||||
it('returns confirmedDirector=false when position has already ended', async () => {
|
||||
const supabase = buildSupabase({
|
||||
companyOrgNumber: '5560125790',
|
||||
enrichment: {
|
||||
company_roles: [
|
||||
{
|
||||
companyRegistrationNumber: '5560125790',
|
||||
positionTypes: ['boardMember'],
|
||||
// 1 year ago
|
||||
positionEnd: new Date(Date.now() - 365 * 24 * 3600_000).toISOString(),
|
||||
},
|
||||
],
|
||||
},
|
||||
})
|
||||
|
||||
const result = await loadUserDirectorship(supabase, 'co-1')
|
||||
expect(result.confirmedDirector).toBe(false)
|
||||
})
|
||||
|
||||
it('returns confirmedDirector=false for non-director positions (deputyBoardMember, auditor)', async () => {
|
||||
const supabase = buildSupabase({
|
||||
companyOrgNumber: '5560125790',
|
||||
enrichment: {
|
||||
company_roles: [
|
||||
{
|
||||
companyRegistrationNumber: '5560125790',
|
||||
positionTypes: ['deputyBoardMember', 'auditor'],
|
||||
positionEnd: null,
|
||||
},
|
||||
],
|
||||
},
|
||||
})
|
||||
|
||||
const result = await loadUserDirectorship(supabase, 'co-1')
|
||||
expect(result.confirmedDirector).toBe(false)
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,83 @@
|
||||
import { describe, it, expect } from 'vitest'
|
||||
import { fallbackNarrative } from '../fallback'
|
||||
import type { ComposerInputs } from '../inputs'
|
||||
|
||||
// The agent profile narrative has two voices depending on whether the user
|
||||
// is a verified director at the company:
|
||||
//
|
||||
// - confirmed director → "Du driver Coredination AB..."
|
||||
// - everyone else → "Coredination AB är..."
|
||||
//
|
||||
// The Sonnet path injects this via the system prompt (covered manually in
|
||||
// system-prompt eval), so these tests target the deterministic fallback:
|
||||
// which is what ships when Sonnet times out or the API key is missing.
|
||||
// The fallback is the worst-case render and must never put presumptive
|
||||
// ownership words in a non-director user's mouth.
|
||||
|
||||
function makeInputs(overrides: Partial<ComposerInputs>): ComposerInputs {
|
||||
return {
|
||||
companyId: 'co-1',
|
||||
companyName: 'Coredination AB',
|
||||
entityType: 'aktiebolag',
|
||||
ticSnapshot: null,
|
||||
ticFetchedAt: null,
|
||||
companySettings: null,
|
||||
activeEmployees: null,
|
||||
sieSummary: null,
|
||||
bankingSummary: null,
|
||||
atomIndex: [],
|
||||
userIsConfirmedDirector: false,
|
||||
...overrides,
|
||||
}
|
||||
}
|
||||
|
||||
describe('fallbackNarrative voice branching', () => {
|
||||
it('uses second-person "Du driver" when user is a confirmed director', () => {
|
||||
const text = fallbackNarrative(makeInputs({ userIsConfirmedDirector: true }))
|
||||
expect(text).toMatch(/Du driver Coredination AB som aktiebolag\./)
|
||||
expect(text).toMatch(/din verksamhet/i)
|
||||
})
|
||||
|
||||
it('uses neutral third-person when user is NOT a confirmed director', () => {
|
||||
const text = fallbackNarrative(makeInputs({ userIsConfirmedDirector: false }))
|
||||
expect(text).toMatch(/Coredination AB är ett aktiebolag\./)
|
||||
// Critical: must not assume the user owns or runs the company.
|
||||
expect(text).not.toMatch(/\bDu driver\b/)
|
||||
expect(text).not.toMatch(/\bdin verksamhet\b/i)
|
||||
})
|
||||
|
||||
it('keeps neutral voice for enskild firma when not confirmed', () => {
|
||||
const text = fallbackNarrative(
|
||||
makeInputs({
|
||||
entityType: 'enskild_firma',
|
||||
companyName: 'Anna Andersson',
|
||||
userIsConfirmedDirector: false,
|
||||
}),
|
||||
)
|
||||
expect(text).toMatch(/Anna Andersson är en enskild firma\./)
|
||||
expect(text).not.toMatch(/Du driver/)
|
||||
})
|
||||
|
||||
it('uses second-person for enskild firma when director is confirmed', () => {
|
||||
const text = fallbackNarrative(
|
||||
makeInputs({
|
||||
entityType: 'enskild_firma',
|
||||
companyName: 'Anna Andersson',
|
||||
userIsConfirmedDirector: true,
|
||||
}),
|
||||
)
|
||||
expect(text).toMatch(/Du driver Anna Andersson som enskild firma\./)
|
||||
})
|
||||
|
||||
it('falls back gracefully when entityType is unknown', () => {
|
||||
const text = fallbackNarrative(
|
||||
makeInputs({
|
||||
entityType: 'handelsbolag',
|
||||
userIsConfirmedDirector: false,
|
||||
}),
|
||||
)
|
||||
// Generic neutral form: still no "Du driver".
|
||||
expect(text).toMatch(/Coredination AB är ett företag/)
|
||||
expect(text).not.toMatch(/Du driver/)
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,54 @@
|
||||
import { describe, expect, it } from 'vitest'
|
||||
import { AtomSelectionSchema, ATOM_SELECTION_TOOL_SCHEMA } from '../schemas'
|
||||
|
||||
describe('AtomSelectionSchema', () => {
|
||||
it('accepts a minimal valid selection', () => {
|
||||
const result = AtomSelectionSchema.safeParse({
|
||||
horizontal_atoms: ['horizontal/swedish-vat'],
|
||||
vertical_atoms: [],
|
||||
modifier_atoms: [],
|
||||
is_multi_vertical: false,
|
||||
verification_questions: [],
|
||||
uncertainty_notes: [],
|
||||
})
|
||||
expect(result.success).toBe(true)
|
||||
})
|
||||
|
||||
it('rejects missing fields', () => {
|
||||
const result = AtomSelectionSchema.safeParse({
|
||||
horizontal_atoms: ['horizontal/swedish-vat'],
|
||||
})
|
||||
expect(result.success).toBe(false)
|
||||
})
|
||||
|
||||
it('rejects wrong types', () => {
|
||||
const result = AtomSelectionSchema.safeParse({
|
||||
horizontal_atoms: 'not-an-array',
|
||||
vertical_atoms: [],
|
||||
modifier_atoms: [],
|
||||
is_multi_vertical: false,
|
||||
verification_questions: [],
|
||||
uncertainty_notes: [],
|
||||
})
|
||||
expect(result.success).toBe(false)
|
||||
})
|
||||
})
|
||||
|
||||
describe('ATOM_SELECTION_TOOL_SCHEMA', () => {
|
||||
it('declares the same required fields as the Zod schema', () => {
|
||||
// Sanity: both schemas must list the same required keys, or atom selection
|
||||
// requests will silently drop fields the Zod parser then rejects.
|
||||
expect(ATOM_SELECTION_TOOL_SCHEMA.required).toEqual([
|
||||
'horizontal_atoms',
|
||||
'vertical_atoms',
|
||||
'modifier_atoms',
|
||||
'is_multi_vertical',
|
||||
'verification_questions',
|
||||
'uncertainty_notes',
|
||||
])
|
||||
})
|
||||
|
||||
it('forbids additional properties so hallucinated keys fail loudly', () => {
|
||||
expect(ATOM_SELECTION_TOOL_SCHEMA.additionalProperties).toBe(false)
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,314 @@
|
||||
import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest'
|
||||
import { ensureTicSnapshot } from '../tic-fetch'
|
||||
|
||||
// `ensureTicSnapshot` is the single chokepoint between the agent build path
|
||||
// and the TIC /profile endpoint. Every TIC call from agent onboarding goes
|
||||
// through here, and the 3000/mo Lens budget makes the cache / fallback
|
||||
// branches load-bearing. These tests cover:
|
||||
//
|
||||
// - cache hit (fresh): no /profile call
|
||||
// - cache miss (no snapshot): /profile fetched + persisted
|
||||
// - cache hit but stale (>7d): refetch + persist
|
||||
// - cache hit but v1 shape + upgradeV1=true: refetch + persist
|
||||
// - cache hit but v1 shape + upgradeV1=false: stays v1 (budget protection)
|
||||
// - /profile fetch fails: returns existing snapshot (degraded, doesn't crash)
|
||||
// - company has no org_number anywhere: returns fallback null
|
||||
|
||||
const ORIGIN = 'http://localhost:3000'
|
||||
const COMPANY_ID = 'company-uuid'
|
||||
|
||||
function buildSupabase(
|
||||
selectResult: { data: unknown; error: unknown } = { data: null, error: null },
|
||||
settingsSelectResult: { data: unknown; error: unknown } = { data: null, error: null },
|
||||
updateResult: { error: unknown } = { error: null },
|
||||
) {
|
||||
const updateCalls: unknown[][] = []
|
||||
const fromCalls: string[] = []
|
||||
const from = vi.fn().mockImplementation((table: string) => {
|
||||
fromCalls.push(table)
|
||||
// Build a chain that resolves to whichever select result matches the
|
||||
// table. The function under test queries `companies` first, then
|
||||
// optionally `company_settings`, then `companies.update`.
|
||||
const chain: Record<string, unknown> = {}
|
||||
const methods = ['select', 'eq', 'limit', 'maybeSingle', 'single']
|
||||
for (const m of methods) {
|
||||
chain[m] = () => {
|
||||
if (m === 'single') {
|
||||
return Promise.resolve(table === 'companies' ? selectResult : settingsSelectResult)
|
||||
}
|
||||
if (m === 'maybeSingle') {
|
||||
return Promise.resolve(table === 'companies' ? selectResult : settingsSelectResult)
|
||||
}
|
||||
return chain
|
||||
}
|
||||
}
|
||||
chain.update = (payload: unknown) => {
|
||||
updateCalls.push([payload])
|
||||
const updateChain: Record<string, unknown> = {}
|
||||
updateChain.eq = () => Promise.resolve(updateResult)
|
||||
return updateChain
|
||||
}
|
||||
return chain
|
||||
})
|
||||
return {
|
||||
supabase: { from } as never,
|
||||
fromCalls,
|
||||
updateCalls,
|
||||
}
|
||||
}
|
||||
|
||||
beforeEach(() => {
|
||||
vi.stubGlobal('fetch', vi.fn())
|
||||
})
|
||||
|
||||
afterEach(() => {
|
||||
vi.restoreAllMocks()
|
||||
})
|
||||
|
||||
describe('ensureTicSnapshot: cache hit', () => {
|
||||
it('returns cached snapshot without hitting TIC when the row is fresh and v2-shaped', async () => {
|
||||
const fetchedAt = new Date(Date.now() - 60_000).toISOString() // 1 min ago
|
||||
const cached = { statuses: [], companyName: 'Cached AB' }
|
||||
const { supabase, fromCalls } = buildSupabase({
|
||||
data: { org_number: '5560125790', tic_snapshot: cached, tic_snapshot_fetched_at: fetchedAt },
|
||||
error: null,
|
||||
})
|
||||
|
||||
const result = await ensureTicSnapshot({
|
||||
supabase,
|
||||
companyId: COMPANY_ID,
|
||||
cookieHeader: '',
|
||||
origin: ORIGIN,
|
||||
})
|
||||
|
||||
expect(result.source).toBe('cached')
|
||||
expect(result.snapshot).toEqual(cached)
|
||||
expect(fetch).not.toHaveBeenCalled()
|
||||
// Only the companies SELECT should have run: no profile fetch, no update.
|
||||
expect(fromCalls).toEqual(['companies'])
|
||||
})
|
||||
|
||||
it('does NOT call /profile when cache is fresh and upgradeV1=false, even if snapshot is v1', async () => {
|
||||
// V1 snapshot = no `statuses` key. Without upgradeV1=true, we accept it
|
||||
// as-is to protect the TIC budget across the customer base.
|
||||
const v1Snapshot = { companyName: 'V1 AB' /* no `statuses` */ }
|
||||
const fetchedAt = new Date(Date.now() - 60_000).toISOString()
|
||||
const { supabase } = buildSupabase({
|
||||
data: { org_number: '5560125790', tic_snapshot: v1Snapshot, tic_snapshot_fetched_at: fetchedAt },
|
||||
error: null,
|
||||
})
|
||||
|
||||
const result = await ensureTicSnapshot({
|
||||
supabase,
|
||||
companyId: COMPANY_ID,
|
||||
cookieHeader: '',
|
||||
origin: ORIGIN,
|
||||
// upgradeV1 omitted -> defaults to false
|
||||
})
|
||||
|
||||
expect(result.source).toBe('cached')
|
||||
expect(result.snapshot).toEqual(v1Snapshot)
|
||||
expect(fetch).not.toHaveBeenCalled()
|
||||
})
|
||||
})
|
||||
|
||||
describe('ensureTicSnapshot: cache miss & refetch', () => {
|
||||
it('fetches /profile and persists when no snapshot exists', async () => {
|
||||
const profile = { statuses: [], companyName: 'Fresh AB' }
|
||||
vi.mocked(fetch).mockResolvedValue(
|
||||
new Response(JSON.stringify({ data: profile }), { status: 200 }),
|
||||
)
|
||||
|
||||
const { supabase, updateCalls } = buildSupabase({
|
||||
data: { org_number: '5560125790', tic_snapshot: null, tic_snapshot_fetched_at: null },
|
||||
error: null,
|
||||
})
|
||||
|
||||
const result = await ensureTicSnapshot({
|
||||
supabase,
|
||||
companyId: COMPANY_ID,
|
||||
cookieHeader: 'sb-auth=abc',
|
||||
origin: ORIGIN,
|
||||
})
|
||||
|
||||
expect(result.source).toBe('fetched')
|
||||
expect(result.snapshot).toEqual(profile)
|
||||
// Hit the /profile endpoint with cookie forwarded
|
||||
expect(fetch).toHaveBeenCalledTimes(1)
|
||||
const fetchUrl = vi.mocked(fetch).mock.calls[0][0] as string
|
||||
expect(fetchUrl).toContain('/api/extensions/ext/tic/profile')
|
||||
expect(fetchUrl).toContain('org_number=5560125790')
|
||||
// Persisted via UPDATE
|
||||
expect(updateCalls).toHaveLength(1)
|
||||
const persisted = updateCalls[0][0] as Record<string, unknown>
|
||||
expect(persisted.tic_snapshot).toEqual(profile)
|
||||
expect(persisted.tic_snapshot_fetched_at).toBeDefined()
|
||||
})
|
||||
|
||||
it('refetches when cached snapshot is stale (>7 days)', async () => {
|
||||
const eightDaysAgo = new Date(Date.now() - 8 * 24 * 3600_000).toISOString()
|
||||
const oldSnapshot = { statuses: [], companyName: 'Old AB' }
|
||||
const freshProfile = { statuses: [], companyName: 'Fresh AB' }
|
||||
vi.mocked(fetch).mockResolvedValue(
|
||||
new Response(JSON.stringify({ data: freshProfile }), { status: 200 }),
|
||||
)
|
||||
|
||||
const { supabase } = buildSupabase({
|
||||
data: {
|
||||
org_number: '5560125790',
|
||||
tic_snapshot: oldSnapshot,
|
||||
tic_snapshot_fetched_at: eightDaysAgo,
|
||||
},
|
||||
error: null,
|
||||
})
|
||||
|
||||
const result = await ensureTicSnapshot({
|
||||
supabase,
|
||||
companyId: COMPANY_ID,
|
||||
cookieHeader: '',
|
||||
origin: ORIGIN,
|
||||
})
|
||||
|
||||
expect(result.source).toBe('fetched')
|
||||
expect(result.snapshot).toEqual(freshProfile)
|
||||
expect(fetch).toHaveBeenCalledTimes(1)
|
||||
})
|
||||
|
||||
it('refetches v1 snapshot when upgradeV1=true, even if still fresh', async () => {
|
||||
const v1Snapshot = { companyName: 'V1 AB' /* no statuses */ }
|
||||
const v2Profile = { statuses: [], companyName: 'V2 AB' }
|
||||
vi.mocked(fetch).mockResolvedValue(
|
||||
new Response(JSON.stringify({ data: v2Profile }), { status: 200 }),
|
||||
)
|
||||
|
||||
const { supabase } = buildSupabase({
|
||||
data: {
|
||||
org_number: '5560125790',
|
||||
tic_snapshot: v1Snapshot,
|
||||
tic_snapshot_fetched_at: new Date().toISOString(),
|
||||
},
|
||||
error: null,
|
||||
})
|
||||
|
||||
const result = await ensureTicSnapshot({
|
||||
supabase,
|
||||
companyId: COMPANY_ID,
|
||||
cookieHeader: '',
|
||||
origin: ORIGIN,
|
||||
upgradeV1: true,
|
||||
})
|
||||
|
||||
expect(result.source).toBe('fetched')
|
||||
expect(result.snapshot).toEqual(v2Profile)
|
||||
expect(fetch).toHaveBeenCalledTimes(1)
|
||||
})
|
||||
})
|
||||
|
||||
describe('ensureTicSnapshot: degraded paths', () => {
|
||||
it('returns fallback null when companies row does not exist', async () => {
|
||||
const { supabase } = buildSupabase({ data: null, error: null })
|
||||
|
||||
const result = await ensureTicSnapshot({
|
||||
supabase,
|
||||
companyId: COMPANY_ID,
|
||||
cookieHeader: '',
|
||||
origin: ORIGIN,
|
||||
})
|
||||
|
||||
expect(result.source).toBe('fallback')
|
||||
expect(result.snapshot).toBeNull()
|
||||
expect(fetch).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('falls back to company_settings.org_number when companies.org_number is null', async () => {
|
||||
const profile = { statuses: [], companyName: 'EF Person' }
|
||||
vi.mocked(fetch).mockResolvedValue(
|
||||
new Response(JSON.stringify({ data: profile }), { status: 200 }),
|
||||
)
|
||||
|
||||
const { supabase } = buildSupabase(
|
||||
{ data: { org_number: null, tic_snapshot: null, tic_snapshot_fetched_at: null }, error: null },
|
||||
{ data: { org_number: '8001011231' }, error: null },
|
||||
)
|
||||
|
||||
const result = await ensureTicSnapshot({
|
||||
supabase,
|
||||
companyId: COMPANY_ID,
|
||||
cookieHeader: '',
|
||||
origin: ORIGIN,
|
||||
})
|
||||
|
||||
expect(result.source).toBe('fetched')
|
||||
// Org number from company_settings flowed into the profile URL
|
||||
const fetchUrl = vi.mocked(fetch).mock.calls[0][0] as string
|
||||
expect(fetchUrl).toContain('org_number=8001011231')
|
||||
})
|
||||
|
||||
it('returns fallback null when no org_number is available anywhere', async () => {
|
||||
const { supabase } = buildSupabase(
|
||||
{ data: { org_number: null, tic_snapshot: null, tic_snapshot_fetched_at: null }, error: null },
|
||||
{ data: { org_number: null }, error: null },
|
||||
)
|
||||
|
||||
const result = await ensureTicSnapshot({
|
||||
supabase,
|
||||
companyId: COMPANY_ID,
|
||||
cookieHeader: '',
|
||||
origin: ORIGIN,
|
||||
})
|
||||
|
||||
expect(result.source).toBe('fallback')
|
||||
expect(result.snapshot).toBeNull()
|
||||
expect(fetch).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('returns existing (stale) snapshot when /profile fetch fails', async () => {
|
||||
const staleSnapshot = { companyName: 'Stale AB' }
|
||||
vi.mocked(fetch).mockResolvedValue(new Response('upstream down', { status: 502 }))
|
||||
|
||||
const { supabase } = buildSupabase({
|
||||
data: {
|
||||
org_number: '5560125790',
|
||||
tic_snapshot: staleSnapshot,
|
||||
tic_snapshot_fetched_at: new Date(Date.now() - 8 * 24 * 3600_000).toISOString(), // forces refetch
|
||||
},
|
||||
error: null,
|
||||
})
|
||||
|
||||
const result = await ensureTicSnapshot({
|
||||
supabase,
|
||||
companyId: COMPANY_ID,
|
||||
cookieHeader: '',
|
||||
origin: ORIGIN,
|
||||
})
|
||||
|
||||
expect(result.source).toBe('fallback')
|
||||
// Degrade to the stale snapshot rather than crash: the agent build path
|
||||
// depends on this contract so a TIC outage never blocks onboarding.
|
||||
expect(result.snapshot).toEqual(staleSnapshot)
|
||||
})
|
||||
|
||||
it('returns existing snapshot when /profile fetch throws (network error / timeout)', async () => {
|
||||
const staleSnapshot = { companyName: 'Stale AB' }
|
||||
vi.mocked(fetch).mockRejectedValue(new Error('ECONNREFUSED'))
|
||||
|
||||
const { supabase } = buildSupabase({
|
||||
data: {
|
||||
org_number: '5560125790',
|
||||
tic_snapshot: staleSnapshot,
|
||||
tic_snapshot_fetched_at: new Date(Date.now() - 8 * 24 * 3600_000).toISOString(),
|
||||
},
|
||||
error: null,
|
||||
})
|
||||
|
||||
const result = await ensureTicSnapshot({
|
||||
supabase,
|
||||
companyId: COMPANY_ID,
|
||||
cookieHeader: '',
|
||||
origin: ORIGIN,
|
||||
})
|
||||
|
||||
expect(result.source).toBe('fallback')
|
||||
expect(result.snapshot).toEqual(staleSnapshot)
|
||||
})
|
||||
})
|
||||
File diff suppressed because one or more lines are too long
@@ -0,0 +1,100 @@
|
||||
import {
|
||||
createAiClient,
|
||||
aiCredentialPrefix,
|
||||
hasAiCredentials,
|
||||
resolveAiProvider,
|
||||
toProviderModelId,
|
||||
type AiClient,
|
||||
} from '@/lib/ai/provider'
|
||||
import { createLogger } from '@/lib/logger'
|
||||
|
||||
const log = createLogger('agent-ai-client')
|
||||
|
||||
let cached: AiClient | null = null
|
||||
|
||||
// Single Claude client for the agent composer + chat loop. Which backend it
|
||||
// talks to is resolved from the environment by lib/ai/provider.ts:
|
||||
//
|
||||
// - Hosted runs on AWS Bedrock. All Claude traffic stays in eu-north-1,
|
||||
// which matters for Swedish accounting data under BFL retention, and
|
||||
// failures and quotas show up in one AWS surface rather than two.
|
||||
// - Self-hosted deployments with no AWS account run against the direct
|
||||
// Anthropic API with a plain ANTHROPIC_API_KEY.
|
||||
//
|
||||
// The two SDKs expose the same `messages.create` / `messages.stream` surface,
|
||||
// which is all this loop uses, so the split is confined to the factory.
|
||||
//
|
||||
// Prompt-cache TTL differs between them. We pass
|
||||
// `cache_control: { type: 'ephemeral', ttl: '1h' }` in the system prompt
|
||||
// assembly (plan §10); Bedrock ignores the explicit TTL and uses its 5 minute
|
||||
// default, while the direct API honours the hour. Cache effectiveness on
|
||||
// multi-minute gaps is therefore better on the direct path; the loop works
|
||||
// either way.
|
||||
export function getAnthropic(): AiClient {
|
||||
if (cached) return cached
|
||||
|
||||
// Startup diagnostic: make a misconfiguration visible in the logs instead of
|
||||
// it surfacing only as an opaque "request ended without sending any chunks"
|
||||
// at stream time. Runs once per cold start (the client is cached). Never
|
||||
// logs a secret: only the provider, a presence boolean, and the credential's
|
||||
// non-secret prefix (see aiCredentialPrefix).
|
||||
const provider = resolveAiProvider()
|
||||
if (!hasAiCredentials()) {
|
||||
log.error('agent AI credentials not loaded from env', undefined, {
|
||||
provider,
|
||||
hasCredentials: false,
|
||||
regionFromEnv: !!process.env.AWS_REGION,
|
||||
})
|
||||
} else {
|
||||
log.info('agent AI client init', {
|
||||
provider,
|
||||
keyPrefix: aiCredentialPrefix(),
|
||||
hasSessionToken: !!process.env.AWS_SESSION_TOKEN,
|
||||
regionFromEnv: !!process.env.AWS_REGION,
|
||||
})
|
||||
}
|
||||
|
||||
cached = createAiClient()
|
||||
return cached
|
||||
}
|
||||
|
||||
// Model ids, written bare and adapted to the resolved provider: Bedrock needs
|
||||
// the `eu.` inference-profile prefix, the direct API needs it absent. Both stay
|
||||
// env-overridable so ops can swap models without a code deploy; an override is
|
||||
// used verbatim, in whichever form the provider it was written for expects.
|
||||
//
|
||||
// Both point at Sonnet 5, verified enabled on the hosted Bedrock account. The
|
||||
// two names are kept because the intents split on them: OPUS_MODEL marks the
|
||||
// heavy-reasoning intents (supplier-invoice review, VAT review, bokslut) so
|
||||
// that split survives if a genuinely larger model is enabled here later.
|
||||
export const OPUS_MODEL =
|
||||
toProviderModelId(process.env.BEDROCK_OPUS_MODEL_ID || 'claude-sonnet-5')
|
||||
export const SONNET_MODEL =
|
||||
toProviderModelId(process.env.BEDROCK_SONNET_MODEL_ID || 'claude-sonnet-5')
|
||||
|
||||
// Reasoning depth for the chat intents.
|
||||
//
|
||||
// Sonnet 5 removed the fixed thinking budget: `thinking: {type:'enabled',
|
||||
// budget_tokens}` is rejected outright ("not supported for this model. Use
|
||||
// thinking.type.adaptive and output_config.effort"). Depth is now a qualitative
|
||||
// effort level and the model spends what a turn actually needs.
|
||||
//
|
||||
// Levels are `low | medium | high | xhigh | max`. Measured on this account:
|
||||
// at `medium` a multi-step Swedish VAT question produced no reasoning at all,
|
||||
// at `xhigh` it produced ~1k characters. Since the point of enabling thinking
|
||||
// on these intents is that the agent reasons BEFORE it answers rather than
|
||||
// narrating in the reply, DEEP uses xhigh and STANDARD high.
|
||||
export const EFFORT_STANDARD = 'high' as const
|
||||
export const EFFORT_DEEP = 'xhigh' as const
|
||||
|
||||
// Output ceilings per tier. Previously derived as budget + 4096; with no budget
|
||||
// to derive from these are explicit, and there are now three of them because
|
||||
// max_tokens caps thinking AND the visible reply together: an intent that does
|
||||
// not think must not inherit a ceiling sized for one that does.
|
||||
//
|
||||
// NO_THINKING is the old 4096 reply cap scaled by ~30% for Sonnet 5's new
|
||||
// tokenizer, which spends that much more on the same Swedish text, so the
|
||||
// effective reply length is unchanged rather than quietly cut.
|
||||
export const MAX_TOKENS_NO_THINKING = 5400
|
||||
export const MAX_TOKENS_STANDARD = 16000
|
||||
export const MAX_TOKENS_DEEP = 24000
|
||||
@@ -0,0 +1,144 @@
|
||||
import type { SupabaseClient } from '@supabase/supabase-js'
|
||||
|
||||
/**
|
||||
* "Har bolaget anställda?" resolved from columns that actually exist.
|
||||
*
|
||||
* WHY THIS MODULE EXISTS
|
||||
* ----------------------
|
||||
* The agent-onboarding review card and the composer both need this fact, and
|
||||
* neither could get it: both selected `company_settings.employee_count` and
|
||||
* `company_settings.has_employees`, and neither column has ever existed.
|
||||
* `employee_count` lives on `agi_declarations` (20260414120000_salary_module);
|
||||
* `has_employees` appears in no migration at all. PostgREST answers 42703 and
|
||||
* rejects the select WHOLE, so those two names were also throwing away the real
|
||||
* columns selected beside them (city, moms_period, fiscal_year_start_month,
|
||||
* f_skatt, vat_registered, pays_salaries, accounting_method, is_sandbox).
|
||||
*
|
||||
* WHAT IS ACTUALLY KNOWABLE, strongest evidence first:
|
||||
*
|
||||
* 1. `employees` rows that are active. A row exists because a person with a
|
||||
* personnummer was entered, so a POSITIVE count is a hard fact. A zero
|
||||
* count is not the opposite fact: a company that has not opened the payroll
|
||||
* module yet also has zero rows, which is every company arriving at agent
|
||||
* onboarding. Zero is therefore never read as "nej".
|
||||
* 2. `companies.tic_snapshot.employeeRange`: Bolagsverket's registered employee
|
||||
* interval ("5-9"). Authoritative but coarse, and only as fresh as the last
|
||||
* TIC fetch.
|
||||
* 3. `company_settings.employer_registered` (nullable, 20260717151000): whether
|
||||
* the company is registered as an employer with Skatteverket. The column is
|
||||
* nullable precisely so that "nobody ever attested this" is representable
|
||||
* (DECISIONS.md 2026-07-17), so a non-null value settles the question in
|
||||
* BOTH directions.
|
||||
* 4. `company_settings.pays_salaries` (NOT NULL DEFAULT false, 20260401000000):
|
||||
* the "Betalar löner" toggle on /settings/tax. `true` is evidence. `false`
|
||||
* is NOT: the column defaults to false, no onboarding step asks, and its
|
||||
* only writer is that settings form. Reading the default as "nej" would
|
||||
* state a fact nobody entered, and would drop the composer's verification
|
||||
* question for every company that never opened tax settings.
|
||||
*
|
||||
* Being a registered employer and having employees are not the same predicate:
|
||||
* a registered employer still files nil AGI months with nobody on payroll. This
|
||||
* module therefore only ever reports a NUMBER when actual employee rows back it,
|
||||
* and otherwise reports the employer fact as a plain yes/no.
|
||||
*/
|
||||
|
||||
export interface EmployeeFacts {
|
||||
/** Employees currently flagged active. null when the count could not be read. */
|
||||
activeEmployees: number | null
|
||||
/** Bolagsverket's registered employee interval, from the TIC snapshot. */
|
||||
ticEmployeeRange: string | null
|
||||
/** Attested Skatteverket employer registration. null = never attested. */
|
||||
employerRegistered: boolean | null
|
||||
/** The "Betalar löner" toggle. `false` is a column default, not an answer. */
|
||||
paysSalaries: boolean | null
|
||||
}
|
||||
|
||||
export type EmployeeVerdict =
|
||||
| { kind: 'count'; count: number }
|
||||
| { kind: 'range'; range: string }
|
||||
| { kind: 'employer'; isEmployer: boolean }
|
||||
| { kind: 'unknown' }
|
||||
|
||||
/**
|
||||
* Count employees flagged active for a company. Mirrors how the rest of the app
|
||||
* defines "active employee" (lib/salary/create-run.ts, lib/reports/vacation-
|
||||
* liability.ts, the MCP server's headcount tools): `is_active`, with no separate
|
||||
* `employment_end` test, because deactivation sets `is_active = false`. Served
|
||||
* by the partial index `idx_employees_active (company_id, is_active)`.
|
||||
*
|
||||
* Returns null (not 0) on error, so "we could not read this" never collapses
|
||||
* into "this company has nobody".
|
||||
*/
|
||||
export async function loadActiveEmployeeCount(
|
||||
supabase: SupabaseClient,
|
||||
companyId: string,
|
||||
): Promise<number | null> {
|
||||
const { count, error } = await supabase
|
||||
.from('employees')
|
||||
.select('id', { count: 'exact', head: true })
|
||||
.eq('company_id', companyId)
|
||||
.eq('is_active', true)
|
||||
if (error) return null
|
||||
return count ?? null
|
||||
}
|
||||
|
||||
/** Pick the strongest fact available, or report that there is none. */
|
||||
export function resolveEmployeeFacts(facts: EmployeeFacts): EmployeeVerdict {
|
||||
// A live headcount beats Bolagsverket's interval: it is the figure this app
|
||||
// can act on (it is what a salary run enumerates) and it is current by
|
||||
// construction, where the snapshot is only as fresh as the last TIC fetch.
|
||||
if (facts.activeEmployees != null && facts.activeEmployees > 0) {
|
||||
return { kind: 'count', count: facts.activeEmployees }
|
||||
}
|
||||
const range = facts.ticEmployeeRange?.trim()
|
||||
if (range) return { kind: 'range', range }
|
||||
if (facts.employerRegistered === true) return { kind: 'employer', isEmployer: true }
|
||||
if (facts.paysSalaries === true) return { kind: 'employer', isEmployer: true }
|
||||
// Only an ATTESTED negative is a negative. pays_salaries === false is the
|
||||
// column default and says nothing.
|
||||
if (facts.employerRegistered === false) return { kind: 'employer', isEmployer: false }
|
||||
return { kind: 'unknown' }
|
||||
}
|
||||
|
||||
/**
|
||||
* True when we hold a fact that settles "har bolaget anställda", i.e. when the
|
||||
* composer must not generate a verification question about it.
|
||||
*/
|
||||
export function knowsEmployeeFact(facts: EmployeeFacts): boolean {
|
||||
return resolveEmployeeFacts(facts).kind !== 'unknown'
|
||||
}
|
||||
|
||||
/**
|
||||
* Value for the onboarding review card's "Anställda" row. null renders as the
|
||||
* field's placeholder rather than inventing a figure.
|
||||
*/
|
||||
export function employeeFieldValue(facts: EmployeeFacts): string | null {
|
||||
const verdict = resolveEmployeeFacts(facts)
|
||||
switch (verdict.kind) {
|
||||
case 'count':
|
||||
return String(verdict.count)
|
||||
case 'range':
|
||||
return verdict.range
|
||||
case 'employer':
|
||||
return verdict.isEmployer ? 'Ja' : 'Nej'
|
||||
default:
|
||||
return null
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Composer KÄNDA FAKTA line, or null when nothing is known. Resolved WITHOUT
|
||||
* the TIC range: that already gets its own labelled line in the same block, and
|
||||
* stating the same interval twice invites the model to treat it as two facts.
|
||||
*/
|
||||
export function employeeKnownFact(facts: EmployeeFacts): string | null {
|
||||
const verdict = resolveEmployeeFacts({ ...facts, ticEmployeeRange: null })
|
||||
switch (verdict.kind) {
|
||||
case 'count':
|
||||
return `Anställda: ${verdict.count}`
|
||||
case 'employer':
|
||||
return `Anställda: ${verdict.isEmployer ? 'ja' : 'nej'}`
|
||||
default:
|
||||
return null
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,136 @@
|
||||
import type { ComposerInputs } from './inputs'
|
||||
import type { AtomSelection } from './schemas'
|
||||
import { ENTITY_TYPE_LABELS_SV, isEntityType } from '@/lib/company/entity-type'
|
||||
|
||||
// Deterministic atom selection used when the Opus call times out or fails.
|
||||
//
|
||||
// Per plan §7 Phase A: "Fall back to a default vertical from SNI prefix and
|
||||
// a generic horizontal set (vat, invoice, year-end)". The result is good
|
||||
// enough that the user can proceed; they can refine atom selection in Phase B
|
||||
// or rebuild later.
|
||||
//
|
||||
// We pick deliberately conservatively: better to load a few extra horizontals
|
||||
// than to miss one. The agent loop pays for cache, not for content; an extra
|
||||
// 8k tokens of swedish-financial-reporting on a sole-trader profile is cheap
|
||||
// noise, while missing swedish-vat on any Swedish company is a correctness bug.
|
||||
export function fallbackAtomSelection(inputs: ComposerInputs): AtomSelection {
|
||||
const knownIds = new Set(inputs.atomIndex.map((a) => a.id))
|
||||
const has = (id: string) => knownIds.has(id)
|
||||
|
||||
const isAB = inputs.entityType === 'aktiebolag'
|
||||
const isEF = inputs.entityType === 'enskild_firma'
|
||||
|
||||
const tic = inputs.ticSnapshot as
|
||||
| {
|
||||
registration?: { payroll?: boolean }
|
||||
sniCodes?: { code: string; name: string }[]
|
||||
employeeRange?: string | null
|
||||
}
|
||||
| null
|
||||
const isEmployer = Boolean(tic?.registration?.payroll)
|
||||
|
||||
const horizontal: string[] = []
|
||||
// These three apply to every Swedish business.
|
||||
pushIfKnown(horizontal, 'horizontal/swedish-vat', has)
|
||||
pushIfKnown(horizontal, 'horizontal/swedish-invoice-compliance', has)
|
||||
pushIfKnown(horizontal, 'horizontal/swedish-year-end-closing', has)
|
||||
pushIfKnown(horizontal, 'horizontal/swedish-accounting-compliance', has)
|
||||
// SIE and assets are common needs across both entity types.
|
||||
pushIfKnown(horizontal, 'horizontal/swedish-sie-import-export', has)
|
||||
pushIfKnown(horizontal, 'horizontal/swedish-asset-accounting', has)
|
||||
|
||||
if (isAB) {
|
||||
pushIfKnown(horizontal, 'horizontal/swedish-financial-reporting', has)
|
||||
pushIfKnown(horizontal, 'horizontal/swedish-sru-filing', has)
|
||||
pushIfKnown(horizontal, 'horizontal/swedish-tax-planning', has)
|
||||
}
|
||||
|
||||
if (isEmployer) {
|
||||
pushIfKnown(horizontal, 'horizontal/swedish-payroll', has)
|
||||
}
|
||||
|
||||
// Vertical fallback: best-effort SNI-prefix match. Empty list is acceptable:
|
||||
// vertical atoms are not yet authored (Phase 3).
|
||||
const verticals: string[] = []
|
||||
const sniCodes = tic?.sniCodes ?? []
|
||||
if (sniCodes.length > 0) {
|
||||
for (const atom of inputs.atomIndex) {
|
||||
if (atom.tier !== 'vertical') continue
|
||||
const matches = sniCodes.some((sni) =>
|
||||
atom.sni_prefixes.some((prefix) => sni.code.startsWith(prefix)),
|
||||
)
|
||||
if (matches) verticals.push(atom.id)
|
||||
}
|
||||
}
|
||||
|
||||
// Modifier fallback: pick what we can derive from entity_type + employer flag.
|
||||
const modifiers: string[] = []
|
||||
if (isAB) {
|
||||
pushIfKnown(modifiers, 'modifier/single-shareholder-ab-fmb', has)
|
||||
}
|
||||
if (isEF) {
|
||||
pushIfKnown(modifiers, 'modifier/enskild-firma', has)
|
||||
}
|
||||
if (isEmployer) {
|
||||
pushIfKnown(modifiers, 'modifier/small-employer', has)
|
||||
}
|
||||
|
||||
return {
|
||||
horizontal_atoms: horizontal,
|
||||
vertical_atoms: verticals,
|
||||
modifier_atoms: modifiers,
|
||||
is_multi_vertical: verticals.length > 1,
|
||||
verification_questions: buildFallbackQuestions(inputs),
|
||||
uncertainty_notes: ['Selection produced by deterministic fallback: Opus call failed or was skipped.'],
|
||||
}
|
||||
}
|
||||
|
||||
function pushIfKnown(arr: string[], id: string, has: (id: string) => boolean) {
|
||||
if (has(id)) arr.push(id)
|
||||
}
|
||||
|
||||
function buildFallbackQuestions(inputs: ComposerInputs): string[] {
|
||||
const qs: string[] = []
|
||||
if (!inputs.ticSnapshot) {
|
||||
qs.push('Vad är din huvudsakliga verksamhet? (några ord räcker)')
|
||||
}
|
||||
if (inputs.entityType === 'aktiebolag') {
|
||||
qs.push('Är du ensamägare till bolaget?')
|
||||
qs.push('Har bolaget anställda förutom dig?')
|
||||
}
|
||||
qs.push('Vilken momsperiod använder ni: månad, kvartal eller år?')
|
||||
return qs
|
||||
}
|
||||
|
||||
// Build a minimal Swedish narrative for the fallback path so Phase B has
|
||||
// something to render even when the Sonnet call also failed. Mirrors the
|
||||
// Sonnet prompt's voice-branching: second-person only when the user is a
|
||||
// confirmed director, neutral otherwise.
|
||||
export function fallbackNarrative(inputs: ComposerInputs): string {
|
||||
const parts: string[] = []
|
||||
const name = inputs.companyName || 'företaget'
|
||||
const form = isEntityType(inputs.entityType) ? ENTITY_TYPE_LABELS_SV[inputs.entityType].toLowerCase() : null
|
||||
|
||||
if (inputs.userIsConfirmedDirector) {
|
||||
if (form) {
|
||||
parts.push(`Du driver ${name} som ${form}.`)
|
||||
} else {
|
||||
parts.push(`Du driver ${name}.`)
|
||||
}
|
||||
} else {
|
||||
if (form) {
|
||||
parts.push(`${name} är ${form === 'enskild firma' ? 'en enskild firma' : 'ett aktiebolag'}.`)
|
||||
} else {
|
||||
parts.push(`${name} är ett företag i gnubok.`)
|
||||
}
|
||||
}
|
||||
parts.push(
|
||||
'Jag har laddat de svenska reglerna som gäller bredast: moms, fakturering, bokslut och årsavslutning.',
|
||||
)
|
||||
parts.push(
|
||||
inputs.userIsConfirmedDirector
|
||||
? 'Berätta gärna lite mer om din verksamhet i nästa steg så kan jag skräddarsy stöden mer.'
|
||||
: 'Berätta gärna lite mer om verksamheten i nästa steg så kan jag skräddarsy stöden mer.',
|
||||
)
|
||||
return parts.join(' ')
|
||||
}
|
||||
@@ -0,0 +1,90 @@
|
||||
import type { SupabaseClient } from '@supabase/supabase-js'
|
||||
import { gatherComposerInputs, inputsToSourceSignals } from './inputs'
|
||||
import { selectAtoms } from './atom-selection'
|
||||
import { writeNarrative } from './narrative'
|
||||
import { preWarmAtomCache } from './prewarm'
|
||||
import { OPUS_MODEL } from './client'
|
||||
import type { ComposedProfile } from './schemas'
|
||||
|
||||
interface ComposeOptions {
|
||||
// When true, runs the selection + narrative + pre-warm but does not write
|
||||
// to agent_profiles. Useful for evaluating composer output before commit.
|
||||
dryRun?: boolean
|
||||
// When true, skips cache pre-warm. Tests and CI typically set this.
|
||||
skipPrewarm?: boolean
|
||||
}
|
||||
|
||||
// Top-level composer: gather inputs → select atoms (Opus) → write narrative
|
||||
// (Sonnet) → persist agent_profiles row → fire-and-forget cache pre-warm.
|
||||
//
|
||||
// See dev_docs/specialized-agent-plan.md §6.
|
||||
export async function composeAgentProfile(
|
||||
supabase: SupabaseClient,
|
||||
companyId: string,
|
||||
options: ComposeOptions = {},
|
||||
): Promise<ComposedProfile> {
|
||||
const inputs = await gatherComposerInputs(supabase, companyId)
|
||||
|
||||
const selection = await selectAtoms(inputs)
|
||||
const profileSummary = await writeNarrative(inputs, selection)
|
||||
|
||||
const sourceSignals = inputsToSourceSignals(inputs)
|
||||
const composedAt = new Date().toISOString()
|
||||
const composerModel = OPUS_MODEL
|
||||
|
||||
if (!options.dryRun) {
|
||||
const { error } = await supabase
|
||||
.from('agent_profiles')
|
||||
.upsert(
|
||||
{
|
||||
company_id: companyId,
|
||||
horizontal_atoms: selection.horizontal_atoms,
|
||||
vertical_atoms: selection.vertical_atoms,
|
||||
modifier_atoms: selection.modifier_atoms,
|
||||
profile_summary: profileSummary,
|
||||
source_signals: sourceSignals,
|
||||
composed_at: composedAt,
|
||||
composer_model: composerModel,
|
||||
composer_version: 1,
|
||||
},
|
||||
{ onConflict: 'company_id' },
|
||||
)
|
||||
if (error) throw new Error(`Failed to upsert agent_profiles: ${error.message}`)
|
||||
}
|
||||
|
||||
if (!options.skipPrewarm && !options.dryRun) {
|
||||
// Resolve atom body paths from the registry and fire pre-warm.
|
||||
const allIds = [
|
||||
...selection.horizontal_atoms,
|
||||
...selection.vertical_atoms,
|
||||
...selection.modifier_atoms,
|
||||
]
|
||||
if (allIds.length > 0) {
|
||||
const { data: rows } = await supabase
|
||||
.from('agent_atom_registry')
|
||||
.select('id, body')
|
||||
.in('id', allIds)
|
||||
const bodies = (rows ?? [])
|
||||
.map((r: { body: string | null }) => r.body ?? '')
|
||||
.filter((b: string) => b.length > 0)
|
||||
// Intentionally not awaited: pre-warm must not block the response.
|
||||
void preWarmAtomCache({ atomBodies: bodies })
|
||||
}
|
||||
}
|
||||
|
||||
return {
|
||||
companyId,
|
||||
horizontalAtoms: selection.horizontal_atoms,
|
||||
verticalAtoms: selection.vertical_atoms,
|
||||
modifierAtoms: selection.modifier_atoms,
|
||||
isMultiVertical: selection.is_multi_vertical,
|
||||
verificationQuestions: selection.verification_questions,
|
||||
uncertaintyNotes: selection.uncertainty_notes,
|
||||
profileSummary,
|
||||
sourceSignals,
|
||||
composerModel,
|
||||
composedAt,
|
||||
}
|
||||
}
|
||||
|
||||
export type { ComposedProfile } from './schemas'
|
||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,109 @@
|
||||
import { getAnthropic, SONNET_MODEL } from './client'
|
||||
import type { AtomSelection } from './schemas'
|
||||
import type { ComposerInputs } from './inputs'
|
||||
|
||||
// Two voices: second-person ownership ("Du driver…") only when BankID
|
||||
// CompanyRoles has confirmed the active user holds a director-like position
|
||||
// at this company. Otherwise we use neutral third-person ("Coredination AB
|
||||
// är…") so manual-orgnr signups (accountant-on-behalf-of, employees,
|
||||
// family members setting up a parent's company) don't get a narrative
|
||||
// presuming they personally own the company. Same content, different voice.
|
||||
const SHARED_PROMPT_HEADER = `Du skriver en kort, saklig profil av ett företag. Profilen visas för användaren under rubriken "Profil" och används som bakgrund åt en bokföringsassistent. Den är INTE en hälsning och INTE ett chattmeddelande.
|
||||
|
||||
Stil:
|
||||
- Max 80 ord, två till tre meningar.
|
||||
- Saklig och konkret. Inga floskler, inga utropstecken, inga emoji, ingen avslutande fråga ("Stämmer det?").
|
||||
- Skriv ALDRIG i jag-form ("Jag ser att…"). Det är en beskrivning, inte assistenten som talar.
|
||||
- Använd ALDRIG tankstreck (— eller –). Använd kommatecken, punkt eller skriv "till" för intervall ("2,5 till 5 miljoner"). Hård regel.
|
||||
|
||||
Innehåll:
|
||||
1. Beskriv verksamheten med egna ord utifrån SNI-koder och verksamhetsbeskrivning: vad företaget gör, juridisk form och ägarbild om den är känd. Återge inte verksamhetsbeskrivningen ordagrant: den visas redan separat under "Verksamhet".
|
||||
2. Avsluta med en mening om vad assistenten är inställd på att hjälpa till med för den här typen av verksamhet, utifrån de valda specialiteterna.
|
||||
|
||||
Skriv endast själva profiltexten. Ingen rubrik, inga punktlistor.`
|
||||
|
||||
const VOICE_DIRECTOR = `\n\nRöst: Andra person, ägar-/ledningsperspektiv. "Du driver…", "Din verksamhet…". Användaren är verifierad styrelseledamot eller firmatecknare i bolaget.`
|
||||
|
||||
const VOICE_NEUTRAL = `\n\nRöst: Tredje person, neutral. "Coredination AB är…", "Bolaget bedriver…". Användaren kan vara ägare, anställd eller redovisningskonsult: vi vet inte. Skriv ALDRIG "Du driver…", "Din verksamhet…" eller andra formuleringar som antar att användaren själv äger eller leder bolaget. Använd företagsnamnet eller "Bolaget".`
|
||||
|
||||
function systemPromptFor(userIsConfirmedDirector: boolean): string {
|
||||
return SHARED_PROMPT_HEADER + (userIsConfirmedDirector ? VOICE_DIRECTOR : VOICE_NEUTRAL)
|
||||
}
|
||||
|
||||
export async function writeNarrative(
|
||||
inputs: ComposerInputs,
|
||||
selection: AtomSelection,
|
||||
): Promise<string> {
|
||||
const anthropic = getAnthropic()
|
||||
|
||||
const response = await anthropic.messages.create({
|
||||
model: SONNET_MODEL,
|
||||
max_tokens: 400,
|
||||
system: systemPromptFor(inputs.userIsConfirmedDirector),
|
||||
messages: [
|
||||
{
|
||||
role: 'user',
|
||||
content: buildUserPrompt(inputs, selection),
|
||||
},
|
||||
],
|
||||
})
|
||||
|
||||
const text = response.content
|
||||
.filter((b) => b.type === 'text')
|
||||
.map((b) => (b as { type: 'text'; text: string }).text)
|
||||
.join('')
|
||||
.trim()
|
||||
|
||||
return text
|
||||
}
|
||||
|
||||
function buildUserPrompt(inputs: ComposerInputs, selection: AtomSelection): string {
|
||||
const lines: string[] = []
|
||||
lines.push(`Företag: ${inputs.companyName}`)
|
||||
lines.push(`Juridisk form: ${inputs.entityType}`)
|
||||
|
||||
if (inputs.ticSnapshot) {
|
||||
const tic = inputs.ticSnapshot as Record<string, unknown>
|
||||
const sni = (tic.sniCodes as { code: string; name: string }[] | undefined) ?? []
|
||||
if (sni.length > 0) {
|
||||
lines.push(`SNI: ${sni.map((s) => `${s.code} ${s.name}`).join('; ')}`)
|
||||
}
|
||||
if (typeof tic.purpose === 'string' && tic.purpose.trim().length > 0) {
|
||||
// Verksamhetsbeskrivning is the most important signal for the
|
||||
// confirming voice: pass it verbatim so the model can paraphrase.
|
||||
lines.push(`Verksamhetsbeskrivning (Bolagsverket): ${tic.purpose as string}`)
|
||||
}
|
||||
const reg = tic.registration as { fTax?: boolean; vat?: boolean; payroll?: boolean } | undefined
|
||||
if (reg) {
|
||||
const flags = [
|
||||
reg.fTax ? 'F-skatt' : null,
|
||||
reg.vat ? 'momsregistrerad' : null,
|
||||
reg.payroll ? 'arbetsgivare' : null,
|
||||
].filter(Boolean)
|
||||
if (flags.length > 0) lines.push(`Registreringar: ${flags.join(', ')}`)
|
||||
}
|
||||
if (tic.employeeRange) lines.push(`Anställda: ${tic.employeeRange as string}`)
|
||||
if (tic.turnoverRange) lines.push(`Omsättning: ${tic.turnoverRange as string}`)
|
||||
const owners = tic.beneficialOwners as
|
||||
| { name: string; extentDescription?: string | null }[]
|
||||
| undefined
|
||||
if (Array.isArray(owners) && owners.length > 0) {
|
||||
const names = owners.map((o) => o.name).join(', ')
|
||||
lines.push(
|
||||
`Verkliga huvudmän: ${names}${owners.length === 1 ? ' (ensam ägare)' : ''}`,
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
if (inputs.sieSummary && inputs.sieSummary.top_accounts.length > 0) {
|
||||
const top = inputs.sieSummary.top_accounts.slice(0, 5)
|
||||
lines.push(`Topp-konton i SIE: ${top.map((a) => a.account).join(', ')}`)
|
||||
}
|
||||
|
||||
lines.push('')
|
||||
lines.push(`Valda horizontals: ${selection.horizontal_atoms.join(', ') || '(inga)'}`)
|
||||
lines.push(`Valda verticals: ${selection.vertical_atoms.join(', ') || '(inga)'}`)
|
||||
lines.push(`Valda modifiers: ${selection.modifier_atoms.join(', ') || '(inga)'}`)
|
||||
|
||||
return lines.join('\n')
|
||||
}
|
||||
@@ -0,0 +1,45 @@
|
||||
import { getAnthropic, SONNET_MODEL } from './client'
|
||||
|
||||
// Cache pre-warm after composition: fire a max_tokens: 1 request with the
|
||||
// assembled atom bodies so the Block 1 cache prefix lands warm before the
|
||||
// user's first chat turn. Best-effort: if this fails, the loop still works,
|
||||
// just with a cold first turn.
|
||||
//
|
||||
// Bodies come from the DB (agent_atom_registry.body), not disk, so pre-warm
|
||||
// no longer depends on .claude/skills being present at runtime. In dev before
|
||||
// `npm run skills:generate` has seeded bodies, the list is empty and pre-warm
|
||||
// simply no-ops (a cold first turn, which is acceptable for a dev convenience).
|
||||
//
|
||||
// Note: we use max_tokens: 1 (not 0). The Anthropic API requires at least
|
||||
// 1 output token. Pre-warm cost is dominated by input processing, so a
|
||||
// single output token is negligible.
|
||||
//
|
||||
// Plan ref: §6 (cache pre-warming), §10 (caching strategy).
|
||||
|
||||
export async function preWarmAtomCache(opts: {
|
||||
atomBodies: string[]
|
||||
ttl?: '5m' | '1h'
|
||||
}): Promise<void> {
|
||||
const { atomBodies, ttl = '1h' } = opts
|
||||
|
||||
const bodies = atomBodies.filter((b) => b && b.length > 0)
|
||||
if (bodies.length === 0) return
|
||||
|
||||
const anthropic = getAnthropic()
|
||||
try {
|
||||
await anthropic.messages.create({
|
||||
model: SONNET_MODEL,
|
||||
max_tokens: 1,
|
||||
system: [
|
||||
{
|
||||
type: 'text',
|
||||
text: bodies.join('\n\n---\n\n'),
|
||||
cache_control: { type: 'ephemeral', ttl },
|
||||
},
|
||||
],
|
||||
messages: [{ role: 'user', content: 'warmup' }],
|
||||
})
|
||||
} catch {
|
||||
// Fire-and-forget: pre-warm failure must never block the composer.
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,101 @@
|
||||
import { z } from 'zod'
|
||||
|
||||
// Atom selection output. The Opus call returns this via tool_use forcing:
|
||||
// the model is forced to invoke `compose_agent_profile(...)` once, which
|
||||
// gives us Zod-validatable structured output instead of free-text JSON.
|
||||
export const AtomSelectionSchema = z.object({
|
||||
horizontal_atoms: z
|
||||
.array(z.string())
|
||||
.describe('Atom IDs of horizontal regulatory skills to load (e.g. "horizontal/swedish-vat").'),
|
||||
vertical_atoms: z
|
||||
.array(z.string())
|
||||
.describe(
|
||||
'Atom IDs of industry/vertical atoms (e.g. "vertical/konsult-it"). Empty array if no vertical fits.',
|
||||
),
|
||||
modifier_atoms: z
|
||||
.array(z.string())
|
||||
.describe(
|
||||
'Atom IDs of cross-cutting modifier atoms (e.g. "modifier/single-shareholder-ab-fmb").',
|
||||
),
|
||||
is_multi_vertical: z
|
||||
.boolean()
|
||||
.describe('True when the company genuinely spans more than one industry.'),
|
||||
verification_questions: z
|
||||
.array(z.string())
|
||||
.describe(
|
||||
'Short Swedish questions the user must confirm during Phase B verification. Highest-leverage uncertainties only.',
|
||||
),
|
||||
uncertainty_notes: z
|
||||
.array(z.string())
|
||||
.describe('Free-form notes the composer wants to surface to a developer reviewing the selection.'),
|
||||
})
|
||||
|
||||
export type AtomSelection = z.infer<typeof AtomSelectionSchema>
|
||||
|
||||
// JSON-Schema for the tool_use forcing. Anthropic's API requires the tool
|
||||
// schema in plain JSON Schema (not Zod). Kept in sync with AtomSelectionSchema
|
||||
// by convention; the response is re-validated through Zod after parsing.
|
||||
// Typed as the SDK's InputSchema shape (mutable) so it satisfies the
|
||||
// Tool.input_schema parameter.
|
||||
export const ATOM_SELECTION_TOOL_SCHEMA: {
|
||||
type: 'object'
|
||||
properties: Record<string, unknown>
|
||||
required: string[]
|
||||
additionalProperties: boolean
|
||||
} = {
|
||||
type: 'object',
|
||||
properties: {
|
||||
horizontal_atoms: { type: 'array', items: { type: 'string' } },
|
||||
vertical_atoms: { type: 'array', items: { type: 'string' } },
|
||||
modifier_atoms: { type: 'array', items: { type: 'string' } },
|
||||
is_multi_vertical: { type: 'boolean' },
|
||||
verification_questions: { type: 'array', items: { type: 'string' } },
|
||||
uncertainty_notes: { type: 'array', items: { type: 'string' } },
|
||||
},
|
||||
required: [
|
||||
'horizontal_atoms',
|
||||
'vertical_atoms',
|
||||
'modifier_atoms',
|
||||
'is_multi_vertical',
|
||||
'verification_questions',
|
||||
'uncertainty_notes',
|
||||
],
|
||||
additionalProperties: false,
|
||||
}
|
||||
|
||||
// Source signals snapshot. Persisted in agent_profiles.source_signals so the
|
||||
// selection is reconstructable later even if upstream data (TIC, SIE) changes.
|
||||
export const SourceSignalsSchema = z.object({
|
||||
tic: z.record(z.string(), z.unknown()).nullable(),
|
||||
sie_summary: z
|
||||
.object({
|
||||
top_accounts: z.array(z.object({ account: z.string(), abs_amount: z.number() })),
|
||||
top_counterparties: z.array(z.object({ name: z.string(), abs_amount: z.number() })),
|
||||
year_count: z.number(),
|
||||
})
|
||||
.nullable(),
|
||||
banking_summary: z
|
||||
.object({
|
||||
top_counterparties: z.array(z.object({ name: z.string(), abs_amount: z.number() })),
|
||||
monthly_volume: z.number().nullable(),
|
||||
})
|
||||
.nullable(),
|
||||
atom_registry_version: z.number(),
|
||||
})
|
||||
|
||||
export type SourceSignals = z.infer<typeof SourceSignalsSchema>
|
||||
|
||||
// Output of the full composer pipeline.
|
||||
export interface ComposedProfile {
|
||||
companyId: string
|
||||
horizontalAtoms: string[]
|
||||
verticalAtoms: string[]
|
||||
modifierAtoms: string[]
|
||||
isMultiVertical: boolean
|
||||
verificationQuestions: string[]
|
||||
uncertaintyNotes: string[]
|
||||
profileSummary: string
|
||||
sourceSignals: SourceSignals
|
||||
composerModel: string
|
||||
composedAt: string
|
||||
}
|
||||
@@ -0,0 +1,184 @@
|
||||
import type { SupabaseClient } from '@supabase/supabase-js'
|
||||
import { createLogger } from '@/lib/logger'
|
||||
|
||||
const log = createLogger('agent.composer.tic-fetch')
|
||||
|
||||
// Live-fetch the TIC company profile via the existing extension HTTP route
|
||||
// and cache it on `companies.tic_snapshot`. Used by the agent onboarding
|
||||
// stream (Phase A step 1) and the /onboarding/agent server component so the
|
||||
// review card has SNI, verksamhetsbeskrivning, address, and recent financials
|
||||
// without requiring the user to have visited the TIC workspace beforehand.
|
||||
//
|
||||
// Why HTTP self-fetch rather than a direct import: core-build CI forbids
|
||||
// imports from @/extensions/ in lib/agent/*. Going through the extension's
|
||||
// public HTTP surface keeps the boundary intact and works the same in dev
|
||||
// and on Vercel. The TIC handler already accepts cookie-auth, so we just
|
||||
// forward the user's session cookie.
|
||||
//
|
||||
// Stale-cache policy: anything cached within the last 7 days is reused
|
||||
// verbatim. TIC data is slow-changing (sniCodes, registration, address
|
||||
// rarely flip) so this avoids re-hitting TIC on every page load.
|
||||
//
|
||||
// Rate budget: the /profile endpoint fans out to ~13 TIC (Lens) calls and
|
||||
// the account has a ~3000/mo ceiling. So we DON'T eagerly re-fetch every
|
||||
// pre-v2 (v1) snapshot: that would blow the budget across the customer
|
||||
// base. Instead, v1 snapshots upgrade to v2 lazily: only when a caller
|
||||
// that actually consumes the v2 sections passes `upgradeV1: true` (today
|
||||
// just the agent-onboarding paths, a deliberate once-per-company action).
|
||||
|
||||
const STALE_AFTER_MS = 7 * 24 * 60 * 60 * 1000 // 7 days
|
||||
// Default fetch timeout. The agent-onboarding callers override with a longer
|
||||
// budget (10s) since the user is on a wait-screen with visible progress and
|
||||
// the prior 5s default killed every signup-time fetch in May (~530 wasted
|
||||
// upstream Lens calls: the abort fired client-side but the upstream calls
|
||||
// kept running and counted against quota). Other callers (background jobs,
|
||||
// dev tooling) stay on the conservative default.
|
||||
const FETCH_TIMEOUT_MS = 5_000
|
||||
|
||||
export interface TicSnapshotResult {
|
||||
snapshot: Record<string, unknown> | null
|
||||
source: 'cached' | 'fetched' | 'fallback'
|
||||
}
|
||||
|
||||
// A snapshot written before the TIC v2 migration lacks the v2-only
|
||||
// `statuses` section. v2 always includes the key (possibly an empty
|
||||
// array), so its absence is a reliable "this is a v1 snapshot" signal.
|
||||
function isV1Snapshot(snapshot: Record<string, unknown> | null): boolean {
|
||||
return snapshot != null && !('statuses' in snapshot)
|
||||
}
|
||||
|
||||
export async function ensureTicSnapshot(opts: {
|
||||
supabase: SupabaseClient
|
||||
companyId: string
|
||||
cookieHeader: string
|
||||
// Origin to use for the internal self-fetch. The caller derives this from
|
||||
// the incoming request's host header so dev (localhost:3000), preview
|
||||
// (vercel.app), and production all reach their own instance of the TIC
|
||||
// route. Falls back to NEXT_PUBLIC_APP_URL when not supplied: fine for
|
||||
// background jobs but wrong for request-scoped paths because that env var
|
||||
// is the production canonical URL even in dev.
|
||||
origin?: string
|
||||
// When true, a cached snapshot still inside the 7-day window is
|
||||
// re-fetched if it's a pre-v2 (v1) shape. Gated to deliberate, bounded
|
||||
// callers (agent onboarding) so the v1→v2 upgrade doesn't fan out across
|
||||
// every company and exhaust the monthly TIC budget.
|
||||
upgradeV1?: boolean
|
||||
// Override the default 5s fetch timeout. Use when the caller has a UI
|
||||
// affordance for waiting (agent onboarding wait-screen) so legitimate
|
||||
// fetches don't get aborted before the ~13-call Lens fan-out completes:
|
||||
// which was the root cause of the May 2026 quota-burn incident.
|
||||
timeoutMs?: number
|
||||
}): Promise<TicSnapshotResult> {
|
||||
const {
|
||||
supabase,
|
||||
companyId,
|
||||
cookieHeader,
|
||||
origin,
|
||||
upgradeV1 = false,
|
||||
timeoutMs = FETCH_TIMEOUT_MS,
|
||||
} = opts
|
||||
|
||||
const { data: companyRow } = await supabase
|
||||
.from('companies')
|
||||
.select('org_number, tic_snapshot, tic_snapshot_fetched_at')
|
||||
.eq('id', companyId)
|
||||
.single()
|
||||
|
||||
if (!companyRow) return { snapshot: null, source: 'fallback' }
|
||||
|
||||
const cachedSnapshot = companyRow.tic_snapshot as Record<string, unknown> | null
|
||||
const needsV2Upgrade = upgradeV1 && isV1Snapshot(cachedSnapshot)
|
||||
|
||||
// Fresh cache hit: nothing to do. (Unless the caller needs v2 fields and
|
||||
// the cache is still v1, in which case we fall through to a refetch.)
|
||||
if (
|
||||
cachedSnapshot &&
|
||||
!isStale(companyRow.tic_snapshot_fetched_at as string | null) &&
|
||||
!needsV2Upgrade
|
||||
) {
|
||||
return { snapshot: cachedSnapshot, source: 'cached' }
|
||||
}
|
||||
|
||||
// Org number drifts: some onboarding flows persist it on company_settings
|
||||
// only (TicWorkspace reads from there). Prefer companies.org_number but
|
||||
// fall back to company_settings.org_number so existing companies aren't
|
||||
// permanently blocked from TIC enrichment.
|
||||
let orgNumber = (companyRow.org_number as string | null) ?? null
|
||||
if (!orgNumber) {
|
||||
const { data: settingsRow } = await supabase
|
||||
.from('company_settings')
|
||||
.select('org_number')
|
||||
.eq('company_id', companyId)
|
||||
.maybeSingle()
|
||||
orgNumber = (settingsRow?.org_number as string | null) ?? null
|
||||
}
|
||||
if (!orgNumber) {
|
||||
return { snapshot: (companyRow.tic_snapshot as Record<string, unknown> | null) ?? null, source: 'fallback' }
|
||||
}
|
||||
|
||||
const profile = await fetchTicProfile(orgNumber, cookieHeader, origin, timeoutMs)
|
||||
if (!profile) {
|
||||
// Fall through with whatever (possibly stale) snapshot we already have.
|
||||
return {
|
||||
snapshot: (companyRow.tic_snapshot as Record<string, unknown> | null) ?? null,
|
||||
source: 'fallback',
|
||||
}
|
||||
}
|
||||
|
||||
// Persist. Best-effort: if the update fails, we still return the profile
|
||||
// we just fetched so the current request can use it.
|
||||
const { error } = await supabase
|
||||
.from('companies')
|
||||
.update({
|
||||
tic_snapshot: profile,
|
||||
tic_snapshot_fetched_at: new Date().toISOString(),
|
||||
})
|
||||
.eq('id', companyId)
|
||||
if (error) {
|
||||
// Stale data is fine for the current request, but a silent write
|
||||
// failure means the next caller re-fetches TIC unnecessarily and the
|
||||
// monthly TIC budget bleeds. Surface it via the structured logger.
|
||||
log.warn('tic snapshot persist failed', { error: error.message, companyId })
|
||||
}
|
||||
|
||||
return { snapshot: profile, source: 'fetched' }
|
||||
}
|
||||
|
||||
function isStale(fetchedAt: string | null): boolean {
|
||||
if (!fetchedAt) return true
|
||||
const ts = Date.parse(fetchedAt)
|
||||
if (Number.isNaN(ts)) return true
|
||||
return Date.now() - ts > STALE_AFTER_MS
|
||||
}
|
||||
|
||||
async function fetchTicProfile(
|
||||
orgNumber: string,
|
||||
cookieHeader: string,
|
||||
origin: string | undefined,
|
||||
timeoutMs: number,
|
||||
): Promise<Record<string, unknown> | null> {
|
||||
const baseUrl = origin || process.env.NEXT_PUBLIC_APP_URL || 'http://localhost:3000'
|
||||
const url = `${baseUrl}/api/extensions/ext/tic/profile?org_number=${encodeURIComponent(orgNumber)}`
|
||||
|
||||
try {
|
||||
const res = await fetch(url, {
|
||||
headers: cookieHeader ? { cookie: cookieHeader } : undefined,
|
||||
signal: AbortSignal.timeout(timeoutMs),
|
||||
})
|
||||
if (!res.ok) {
|
||||
log.warn('tic profile non-ok', { url, status: res.status })
|
||||
return null
|
||||
}
|
||||
const body = (await res.json()) as { data?: Record<string, unknown> }
|
||||
return body.data ?? null
|
||||
} catch (err) {
|
||||
// Network error, timeout, TIC extension disabled, TIC API misconfigured.
|
||||
// Any of these is a normal fallback: return null so the caller can
|
||||
// degrade gracefully.
|
||||
log.warn('tic profile fetch failed', {
|
||||
url,
|
||||
error: err instanceof Error ? err.message : String(err),
|
||||
})
|
||||
return null
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user