docs(production): standardiserad produktionsberedskap och gap-analys

Lägger docs/production-readiness.md och siax/production-gaps.json enligt SIAX Master Definition of Done. Underlag: git-, kod- och live-evidens 2026-11-11. Nivån är evidensbaserad, inte ett leveransgodkännande.
This commit is contained in:
2026-11-10 09:15:21 +01:00
parent 0fda8cae48
commit 2bee8eb778
6135 changed files with 4 additions and 1718997 deletions
-102
View File
@@ -1,102 +0,0 @@
/**
* Tests for POST /api/agent/composer.
*/
import { describe, it, expect, vi, beforeEach } from 'vitest'
import { NextResponse } from 'next/server'
import { createQueuedMockSupabase, createMockRequest, parseJsonResponse } from '@/tests/helpers'
const { supabase, enqueue, reset } = createQueuedMockSupabase()
const requireAuthMock = vi.fn()
vi.mock('@/lib/auth/require-auth', () => ({
requireAuth: (...args: unknown[]) => requireAuthMock(...args),
}))
vi.mock('@/lib/company/context', () => ({
getActiveCompanyId: vi.fn().mockResolvedValue('company-1'),
requireCompanyId: vi.fn().mockResolvedValue('company-1'),
}))
const checkRateMock = vi.fn()
vi.mock('@/lib/rate-limits/agent', () => ({
checkAgentRateLimit: (...args: unknown[]) => checkRateMock(...args),
agentRateLimitResponseBody: () => ({ error: 'För många förfrågningar.' }),
}))
vi.mock('@/lib/sandbox/guard', () => ({
guardSandbox: vi.fn().mockResolvedValue(null),
}))
vi.mock('@/lib/entitlements/has-capability', () => ({
requireCapability: vi.fn().mockResolvedValue(null),
}))
vi.mock('@/lib/entitlements/keys', () => ({
CAPABILITY: { ai: 'ai' },
}))
const composeMock = vi.fn()
vi.mock('@/lib/agent/composer', () => ({
composeAgentProfile: (...args: unknown[]) => composeMock(...args),
}))
import { POST } from '../composer/route'
const routeParams = { params: Promise.resolve({}) }
beforeEach(() => {
vi.clearAllMocks()
reset()
requireAuthMock.mockResolvedValue({ user: { id: 'user-1' }, supabase, error: null })
checkRateMock.mockResolvedValue({ ok: true })
})
describe('POST /api/agent/composer', () => {
it('returns 401 when not authenticated', async () => {
requireAuthMock.mockResolvedValue({
user: null,
supabase,
error: NextResponse.json({ error: 'Unauthorized' }, { status: 401 }),
})
const req = createMockRequest('/api/agent/composer', { method: 'POST', body: {} })
const res = await POST(req, routeParams)
expect(res.status).toBe(401)
})
it('returns 429 when rate limited', async () => {
checkRateMock.mockResolvedValue({ ok: false, retryAfterSec: 30 })
const req = createMockRequest('/api/agent/composer', { method: 'POST', body: {} })
const res = await POST(req, routeParams)
expect(res.status).toBe(429)
expect(res.headers.get('Retry-After')).toBe('30')
})
it('refuses a viewer with 403 (composer rewrites the profile)', async () => {
enqueue({ data: { role: 'viewer' } })
const req = createMockRequest('/api/agent/composer', { method: 'POST', body: {} })
const { status, body } = await parseJsonResponse<{ error: { code: string } }>(
await POST(req, routeParams)
)
expect(status).toBe(403)
expect(body.error.code).toBe('WRITE_PERMISSION_REQUIRED')
expect(composeMock).not.toHaveBeenCalled()
})
it('runs the composer for a non-viewer member', async () => {
enqueue({ data: { role: 'owner' } })
composeMock.mockResolvedValue({ company_id: 'company-1', profile_summary: 'Byggd' })
const req = createMockRequest('/api/agent/composer', {
method: 'POST',
body: { dry_run: true },
})
const { status, body } = await parseJsonResponse<{ data: { profile_summary: string } }>(
await POST(req, routeParams)
)
expect(status).toBe(200)
expect(body.data.profile_summary).toBe('Byggd')
expect(composeMock).toHaveBeenCalledWith(expect.anything(), 'company-1', { dryRun: true })
})
})
@@ -1,176 +0,0 @@
/**
* Tests for GET /api/agent/conversations and GET/PATCH /api/agent/conversations/[id].
*
* Uses a filter-capturing Supabase mock so the user-scoping regression is
* locked in: RLS on agent_conversations is company-scoped, so the explicit
* .eq('user_id', …) filter in the list route is the only thing preventing
* team members from seeing each other's conversation titles/previews.
*/
import { describe, it, expect, vi, beforeEach } from 'vitest'
import { NextResponse } from 'next/server'
import { createMockRequest, parseJsonResponse } from '@/tests/helpers'
const requireAuthMock = vi.fn()
vi.mock('@/lib/auth/require-auth', () => ({
requireAuth: (...args: unknown[]) => requireAuthMock(...args),
}))
vi.mock('@/lib/company/context', () => ({
getActiveCompanyId: vi.fn().mockResolvedValue('company-1'),
requireCompanyId: vi.fn().mockResolvedValue('company-1'),
}))
import { GET as listGET } from '../conversations/route'
import { GET as detailGET, PATCH as detailPATCH } from '../conversations/[id]/route'
interface CapturedCall {
method: string
args: unknown[]
}
/** Chainable builder that records every call and resolves queued results per from(). */
function createCapturingSupabase(results: { data?: unknown; error?: unknown }[]) {
const calls: CapturedCall[] = []
let idx = 0
const makeBuilder = () => {
const result = results[idx++] ?? { data: null, error: null }
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const b: any = {}
for (const m of ['select', 'eq', 'is', 'or', 'order', 'limit', 'insert', 'update', 'maybeSingle', 'single']) {
b[m] = (...args: unknown[]) => {
calls.push({ method: m, args })
return b
}
}
b.then = (resolve: (v: unknown) => void) =>
resolve({ data: result.data ?? null, error: result.error ?? null, count: null })
return b
}
const supabase = {
from: (table: string) => {
calls.push({ method: 'from', args: [table] })
return makeBuilder()
},
}
return { supabase, calls }
}
const routeParams = { params: Promise.resolve({}) }
const idParams = { params: Promise.resolve({ id: 'conv-1' }) }
beforeEach(() => {
vi.clearAllMocks()
})
describe('GET /api/agent/conversations', () => {
it('returns 401 when not authenticated', async () => {
requireAuthMock.mockResolvedValue({
user: null,
supabase: {},
error: NextResponse.json({ error: 'Unauthorized' }, { status: 401 }),
})
const res = await listGET(createMockRequest('/api/agent/conversations'), routeParams)
expect(res.status).toBe(401)
})
it('returns 400 for a non-numeric limit', async () => {
const { supabase } = createCapturingSupabase([])
requireAuthMock.mockResolvedValue({ user: { id: 'user-1' }, supabase, error: null })
const req = createMockRequest('/api/agent/conversations', { searchParams: { limit: 'abc' } })
const { status } = await parseJsonResponse(await listGET(req, routeParams))
expect(status).toBe(400)
})
it('filters the list by BOTH company_id and the calling user_id', async () => {
const { supabase, calls } = createCapturingSupabase([
{ data: [{ id: 'conv-1', title: 'Min konversation' }] },
])
requireAuthMock.mockResolvedValue({ user: { id: 'user-1' }, supabase, error: null })
const req = createMockRequest('/api/agent/conversations')
const { status, body } = await parseJsonResponse<{ data: unknown[] }>(
await listGET(req, routeParams)
)
expect(status).toBe(200)
expect(body.data).toHaveLength(1)
const eqCalls = calls.filter((c) => c.method === 'eq').map((c) => c.args)
expect(eqCalls).toContainEqual(['company_id', 'company-1'])
// Privacy regression guard: without this filter, company-scoped RLS lets
// every member read colleagues' titles and last_message_preview.
expect(eqCalls).toContainEqual(['user_id', 'user-1'])
})
})
describe('GET /api/agent/conversations/[id]', () => {
it('returns 404 when the conversation is not owned by the caller', async () => {
// Ownership is part of the fetch (.eq user_id) — a non-owned id resolves null.
const { supabase, calls } = createCapturingSupabase([{ data: null }])
requireAuthMock.mockResolvedValue({ user: { id: 'user-1' }, supabase, error: null })
const { status, body } = await parseJsonResponse<{ error: { code: string } }>(
await detailGET(createMockRequest('/api/agent/conversations/conv-1'), idParams)
)
expect(status).toBe(404)
expect(body.error.code).toBe('CONVERSATION_NOT_FOUND')
const eqCalls = calls.filter((c) => c.method === 'eq').map((c) => c.args)
expect(eqCalls).toContainEqual(['user_id', 'user-1'])
})
it('returns the conversation with its messages for the owner', async () => {
const { supabase } = createCapturingSupabase([
{ data: { id: 'conv-1', company_id: 'company-1', user_id: 'user-1', title: 'T' } },
{ data: { role: 'member' } },
{ data: [{ id: 'm1', role: 'user', content: 'Hej' }] },
])
requireAuthMock.mockResolvedValue({ user: { id: 'user-1' }, supabase, error: null })
const { status, body } = await parseJsonResponse<{
data: { conversation: { id: string }; messages: unknown[] }
}>(await detailGET(createMockRequest('/api/agent/conversations/conv-1'), idParams))
expect(status).toBe(200)
expect(body.data.conversation.id).toBe('conv-1')
expect(body.data.messages).toHaveLength(1)
})
})
describe('PATCH /api/agent/conversations/[id]', () => {
it('returns 400 when the body has nothing to update', async () => {
const { supabase } = createCapturingSupabase([])
requireAuthMock.mockResolvedValue({ user: { id: 'user-1' }, supabase, error: null })
const req = createMockRequest('/api/agent/conversations/conv-1', {
method: 'PATCH',
body: {},
})
const { status, body } = await parseJsonResponse<{ error: { code: string } }>(
await detailPATCH(req, idParams)
)
expect(status).toBe(400)
expect(body.error.code).toBe('NOTHING_TO_UPDATE')
})
it('updates pin state for an owned conversation', async () => {
const { supabase } = createCapturingSupabase([
{ data: { user_id: 'user-1', company_id: 'company-1' } },
{ data: { id: 'conv-1', pinned: true } },
])
requireAuthMock.mockResolvedValue({ user: { id: 'user-1' }, supabase, error: null })
const req = createMockRequest('/api/agent/conversations/conv-1', {
method: 'PATCH',
body: { pinned: true },
})
const { status, body } = await parseJsonResponse<{ data: { pinned: boolean } }>(
await detailPATCH(req, idParams)
)
expect(status).toBe(200)
expect(body.data.pinned).toBe(true)
})
})
-184
View File
@@ -1,184 +0,0 @@
/**
* Tests for POST /api/agent/feedback.
*/
import { describe, it, expect, vi, beforeEach } from 'vitest'
import { NextResponse } from 'next/server'
import { createQueuedMockSupabase, createMockRequest, parseJsonResponse } from '@/tests/helpers'
const { supabase, enqueue, reset } = createQueuedMockSupabase()
const requireAuthMock = vi.fn()
vi.mock('@/lib/auth/require-auth', () => ({
requireAuth: (...args: unknown[]) => requireAuthMock(...args),
}))
vi.mock('@/lib/company/context', () => ({
getActiveCompanyId: vi.fn().mockResolvedValue('company-1'),
requireCompanyId: vi.fn().mockResolvedValue('company-1'),
}))
const requireWriteMock = vi.fn()
vi.mock('@/lib/auth/require-write', () => ({
requireWritePermission: (...args: unknown[]) => requireWriteMock(...args),
}))
vi.mock('@/lib/init', () => ({ ensureInitialized: vi.fn() }))
const emitMock = vi.fn()
vi.mock('@/lib/events/bus', () => ({
eventBus: { emit: (...args: unknown[]) => emitMock(...args) },
}))
import { POST } from '../feedback/route'
const routeParams = { params: Promise.resolve({}) }
const CONVERSATION_ID = '11111111-2222-4333-8444-555555555555'
const body = (over: Record<string, unknown> = {}) => ({
conversation_id: CONVERSATION_ID,
sentiment: 'negative',
...over,
})
beforeEach(() => {
vi.clearAllMocks()
reset()
requireAuthMock.mockResolvedValue({ user: { id: 'user-1' }, supabase, error: null })
requireWriteMock.mockResolvedValue({ ok: true })
})
describe('POST /api/agent/feedback', () => {
it('returns 401 when not authenticated', async () => {
requireAuthMock.mockResolvedValue({
user: null,
supabase,
error: NextResponse.json({ error: 'Unauthorized' }, { status: 401 }),
})
const req = createMockRequest('/api/agent/feedback', { method: 'POST', body: body() })
expect((await POST(req, routeParams)).status).toBe(401)
expect(emitMock).not.toHaveBeenCalled()
})
it('returns 400 for a sentiment outside the two votes the UI can send', async () => {
const req = createMockRequest('/api/agent/feedback', {
method: 'POST',
body: body({ sentiment: 'furious' }),
})
const { status } = await parseJsonResponse(await POST(req, routeParams))
expect(status).toBe(400)
expect(emitMock).not.toHaveBeenCalled()
})
it('returns 400 when the conversation id is not a uuid', async () => {
const req = createMockRequest('/api/agent/feedback', {
method: 'POST',
body: body({ conversation_id: 'not-a-uuid' }),
})
const { status } = await parseJsonResponse(await POST(req, routeParams))
expect(status).toBe(400)
})
it('404s on a conversation belonging to another user', async () => {
// Same hole that /api/agent/invoke had: the id is caller-supplied, so
// without the ownership check a member could file feedback against a
// colleague's thread and the triage backlog would carry a conversation the
// reporter never saw.
enqueue({
data: {
id: CONVERSATION_ID,
user_id: 'someone-else',
company_id: 'company-1',
intent_id: 'general.help',
},
})
const req = createMockRequest('/api/agent/feedback', { method: 'POST', body: body() })
const { status } = await parseJsonResponse(await POST(req, routeParams))
expect(status).toBe(404)
expect(emitMock).not.toHaveBeenCalled()
})
it('404s on a conversation in another company', async () => {
enqueue({
data: {
id: CONVERSATION_ID,
user_id: 'user-1',
company_id: 'company-2',
intent_id: 'general.help',
},
})
const req = createMockRequest('/api/agent/feedback', { method: 'POST', body: body() })
expect((await parseJsonResponse(await POST(req, routeParams))).status).toBe(404)
expect(emitMock).not.toHaveBeenCalled()
})
it('404s when the conversation does not exist', async () => {
enqueue({ data: null })
const req = createMockRequest('/api/agent/feedback', { method: 'POST', body: body() })
expect((await parseJsonResponse(await POST(req, routeParams))).status).toBe(404)
})
it('emits agent.feedback with actorType user on the happy path', async () => {
enqueue({
data: {
id: CONVERSATION_ID,
user_id: 'user-1',
company_id: 'company-1',
intent_id: 'vat.review',
},
})
const req = createMockRequest('/api/agent/feedback', {
method: 'POST',
body: body({ sentiment: 'positive', message_index: 4 }),
})
const { status } = await parseJsonResponse(await POST(req, routeParams))
expect(status).toBe(200)
expect(emitMock).toHaveBeenCalledOnce()
const event = emitMock.mock.calls[0]![0] as {
type: string
payload: Record<string, unknown>
}
// Same event type the MCP tool emits, so chat votes land in the backlog
// the product team already reads instead of a second place.
expect(event.type).toBe('agent.feedback')
expect(event.payload.sentiment).toBe('positive')
expect(event.payload.actorType).toBe('user')
expect(event.payload.actorId).toBe('user-1')
expect(event.payload.companyId).toBe('company-1')
expect(event.payload.sessionId).toBe(CONVERSATION_ID)
// Traceable to an answer: a thumbs-down that cannot be tied to a turn is a
// number, not a report.
expect(event.payload.context).toContain('vat.review')
expect(event.payload.context).toContain('#4')
})
it('never carries user free text into the telemetry log', async () => {
// A comment box here would put whatever the user typed, in an accounting
// product, verbatim into event_log under telemetry retention: client
// names, personnummer, case details. The field is not accepted, and a
// caller that sends one anyway must not have it stored.
enqueue({
data: {
id: CONVERSATION_ID,
user_id: 'user-1',
company_id: 'company-1',
intent_id: 'general.help',
},
})
const req = createMockRequest('/api/agent/feedback', {
method: 'POST',
body: body({ comment: 'Anna Andersson 19850101-1234 fick fel konto' }),
})
await POST(req, routeParams)
const event = emitMock.mock.calls[0]![0] as { payload: { context: string } }
expect(event.payload.context).not.toContain('Anna Andersson')
expect(event.payload.context).not.toContain('19850101')
expect(JSON.stringify(event.payload)).not.toContain('19850101')
})
})
-282
View File
@@ -1,282 +0,0 @@
/**
* Tests for POST /api/agent/invoke, focused on conversation ownership.
*
* RLS on agent_conversations/agent_messages is company-scoped, not user-scoped
* (migration 20260517204000), so the route itself has to prove that a resumed
* conversation_id belongs to the caller. Without that check, a member could
* post a colleague's conversation id and have their history loaded into the
* prompt (and their own turns appended to it).
*/
import { describe, it, expect, vi, beforeEach } from 'vitest'
import { NextResponse } from 'next/server'
import { createQueuedMockSupabase, createMockRequest, parseJsonResponse } from '@/tests/helpers'
const { supabase, enqueue, reset } = createQueuedMockSupabase()
const requireAuthMock = vi.fn()
vi.mock('@/lib/auth/require-auth', () => ({
requireAuth: (...args: unknown[]) => requireAuthMock(...args),
}))
vi.mock('@/lib/company/context', () => ({
getActiveCompanyId: vi.fn().mockResolvedValue('company-1'),
requireCompanyId: vi.fn().mockResolvedValue('company-1'),
}))
const checkRateMock = vi.fn()
vi.mock('@/lib/rate-limits/agent', () => ({
checkAgentRateLimit: (...args: unknown[]) => checkRateMock(...args),
agentRateLimitResponseBody: () => ({ error: 'För många förfrågningar.' }),
}))
vi.mock('@/lib/sandbox/guard', () => ({
guardSandbox: vi.fn().mockResolvedValue(null),
}))
vi.mock('@/lib/entitlements/has-capability', () => ({
requireCapability: vi.fn().mockResolvedValue(null),
}))
vi.mock('@/lib/entitlements/keys', () => ({
CAPABILITY: { ai: 'ai' },
}))
vi.mock('@/lib/init', () => ({
ensureInitialized: vi.fn(),
}))
const getIntentMock = vi.fn()
vi.mock('@/lib/agent/intents/registry', () => ({
getIntent: (...args: unknown[]) => getIntentMock(...args),
}))
// Deployment-level AI availability (distinct from the per-company paywall).
// Default: available, so the ownership tests below exercise the real flow.
const aiStatusMock = vi.fn()
vi.mock('@/lib/ai', () => ({
getAiStatus: () => aiStatusMock(),
}))
const runChatTurnMock = vi.fn()
vi.mock('@/lib/agent/chat/run-turn', () => ({
runChatTurn: (...args: unknown[]) => runChatTurnMock(...args),
friendlyModelError: () => 'Något gick fel hos assistenten.',
}))
import { POST } from '../invoke/route'
const CONVERSATION_ID = '11111111-1111-4111-8111-111111111111'
function body(overrides: Record<string, unknown> = {}) {
return {
intent_id: 'general.help',
user_message: 'Hur gick juli?',
...overrides,
}
}
/**
* Queue the reads the route performs before it resolves the conversation.
*
* Ownership is validated ahead of every side effect and of the company/profile
* reads, so a rejected request costs exactly one membership read plus the
* conversation lookup.
*/
function enqueuePreamble() {
enqueue({ data: { role: 'owner' } }) // company_members
}
/** The company + profile reads that only happen once a request is accepted. */
function enqueueAcceptedTail() {
enqueue({ data: { name: 'Nordvik Bygg AB' } }) // companies
enqueue({ data: { full_name: 'Johan Nordvik' } }) // profiles
}
beforeEach(() => {
vi.clearAllMocks()
reset()
requireAuthMock.mockResolvedValue({ user: { id: 'user-1' }, supabase, error: null })
checkRateMock.mockResolvedValue({ ok: true })
getIntentMock.mockReturnValue({ id: 'general.help', sheetTitle: 'Assistenten' })
runChatTurnMock.mockResolvedValue(undefined)
aiStatusMock.mockReturnValue({ configured: true, assistantAvailable: true, provider: 'bedrock' })
})
describe('POST /api/agent/invoke', () => {
it('returns 401 when not authenticated', async () => {
requireAuthMock.mockResolvedValue({
user: null,
supabase,
error: NextResponse.json({ error: 'Unauthorized' }, { status: 401 }),
})
const res = await POST(createMockRequest('/api/agent/invoke', { method: 'POST', body: body() }))
const { status } = await parseJsonResponse(res)
expect(status).toBe(401)
})
it('returns 400 on an invalid body', async () => {
const res = await POST(createMockRequest('/api/agent/invoke', { method: 'POST', body: { intent_id: '' } }))
const { status } = await parseJsonResponse(res)
expect(status).toBe(400)
})
it('returns 400 for an unknown intent', async () => {
getIntentMock.mockReturnValue(undefined)
const res = await POST(createMockRequest('/api/agent/invoke', { method: 'POST', body: body() }))
const { status } = await parseJsonResponse<{ error: string }>(res)
expect(status).toBe(400)
})
// A self-host without an AI key, or on an OpenAI-compatible endpoint the
// chat loop does not speak yet: say so up front with a distinct code, never
// open a stream that dies on the first model call, never confuse it with
// the paywall.
it('returns 503 ai_unconfigured when the deployment has no assistant backend', async () => {
aiStatusMock.mockReturnValue({ configured: false, assistantAvailable: false, provider: 'bedrock' })
enqueuePreamble()
const res = await POST(createMockRequest('/api/agent/invoke', { method: 'POST', body: body() }))
const { status, body: json } = await parseJsonResponse<{ error: string; code: string }>(res)
expect(status).toBe(503)
expect(json.code).toBe('ai_unconfigured')
expect(runChatTurnMock).not.toHaveBeenCalled()
})
it('returns 403 when the user is not a member of the company', async () => {
enqueue({ data: null }) // company_members: no row
const res = await POST(createMockRequest('/api/agent/invoke', { method: 'POST', body: body() }))
const { status } = await parseJsonResponse(res)
expect(status).toBe(403)
})
it('returns 404 when resuming a conversation owned by another user', async () => {
enqueuePreamble()
enqueue({
data: {
id: CONVERSATION_ID,
user_id: 'user-2', // someone else in the same company
company_id: 'company-1',
intent_id: 'general.help',
},
})
const res = await POST(
createMockRequest('/api/agent/invoke', { method: 'POST', body: body({ conversation_id: CONVERSATION_ID }) }),
)
const { status, body: json } = await parseJsonResponse<{ error: string }>(res)
expect(status).toBe(404)
expect(json.error).toBe('Konversationen hittades inte.')
expect(runChatTurnMock).not.toHaveBeenCalled()
})
it('returns 404 when resuming a conversation from another company', async () => {
enqueuePreamble()
enqueue({
data: {
id: CONVERSATION_ID,
user_id: 'user-1', // same user...
company_id: 'company-2', // ...but a company other than the active one
intent_id: 'general.help',
},
})
const res = await POST(
createMockRequest('/api/agent/invoke', { method: 'POST', body: body({ conversation_id: CONVERSATION_ID }) }),
)
const { status } = await parseJsonResponse(res)
expect(status).toBe(404)
expect(runChatTurnMock).not.toHaveBeenCalled()
})
it('returns 404 when the conversation does not exist', async () => {
enqueuePreamble()
enqueue({ data: null })
const res = await POST(
createMockRequest('/api/agent/invoke', { method: 'POST', body: body({ conversation_id: CONVERSATION_ID }) }),
)
const { status } = await parseJsonResponse(res)
expect(status).toBe(404)
expect(runChatTurnMock).not.toHaveBeenCalled()
})
it('returns 400 when the conversation belongs to a different intent', async () => {
enqueuePreamble()
enqueue({
data: {
id: CONVERSATION_ID,
user_id: 'user-1',
company_id: 'company-1',
intent_id: 'vat.review', // tool loadout differs from general.help
},
})
const res = await POST(
createMockRequest('/api/agent/invoke', { method: 'POST', body: body({ conversation_id: CONVERSATION_ID }) }),
)
const { status } = await parseJsonResponse(res)
expect(status).toBe(400)
expect(runChatTurnMock).not.toHaveBeenCalled()
})
it('runs the turn when the caller owns the conversation', async () => {
enqueuePreamble()
enqueue({
data: {
id: CONVERSATION_ID,
user_id: 'user-1',
company_id: 'company-1',
intent_id: 'general.help',
},
})
enqueueAcceptedTail()
const res = await POST(
createMockRequest('/api/agent/invoke', { method: 'POST', body: body({ conversation_id: CONVERSATION_ID }) }),
)
expect(res.status).toBe(200)
// The route streams NDJSON; draining it is enough to know the turn ran.
await res.text()
expect(runChatTurnMock).toHaveBeenCalledTimes(1)
})
it('hands the first-turn profile summary to the turn instead of re-reading it', async () => {
// On a first turn the route reads agent_profiles to build the intent's
// prompt template. run-turn needs the same value for the system prompt, so
// it is passed through rather than read a second time.
getIntentMock.mockReturnValue({
id: 'general.help',
sheetTitle: 'Assistenten',
capture: vi.fn().mockResolvedValue({ some: 'context' }),
promptTemplate: vi.fn().mockReturnValue('templated first turn'),
})
enqueuePreamble()
enqueue({ data: { id: CONVERSATION_ID } }) // conversation insert
enqueueAcceptedTail()
enqueue({ data: { profile_summary: 'Byggkonsult, K2' } }) // agent_profiles
enqueue({ data: [] }) // agent_memory
const res = await POST(
createMockRequest('/api/agent/invoke', {
method: 'POST',
body: { intent_id: 'general.help' }, // no user_message => first turn
}),
)
await res.text()
expect(runChatTurnMock).toHaveBeenCalledTimes(1)
const args = runChatTurnMock.mock.calls[0]![0] as {
preloadedProfileSummary?: string | null
userMessage: string
userMessageHidden?: boolean
}
expect(args.preloadedProfileSummary).toBe('Byggkonsult, K2')
expect(args.userMessage).toBe('templated first turn')
expect(args.userMessageHidden).toBe(true)
})
})
-150
View File
@@ -1,150 +0,0 @@
/**
* Tests for GET/POST /api/agent/memory and PATCH /api/agent/memory/[id].
*/
import { describe, it, expect, vi, beforeEach } from 'vitest'
import { NextResponse } from 'next/server'
import { createQueuedMockSupabase, createMockRequest, parseJsonResponse } from '@/tests/helpers'
const { supabase, enqueue, reset } = createQueuedMockSupabase()
const requireAuthMock = vi.fn()
vi.mock('@/lib/auth/require-auth', () => ({
requireAuth: (...args: unknown[]) => requireAuthMock(...args),
}))
vi.mock('@/lib/company/context', () => ({
getActiveCompanyId: vi.fn().mockResolvedValue('company-1'),
requireCompanyId: vi.fn().mockResolvedValue('company-1'),
}))
const requireWriteMock = vi.fn()
vi.mock('@/lib/auth/require-write', () => ({
requireWritePermission: (...args: unknown[]) => requireWriteMock(...args),
}))
import { GET, POST } from '../memory/route'
import { PATCH } from '../memory/[id]/route'
const routeParams = { params: Promise.resolve({}) }
const idParams = { params: Promise.resolve({ id: 'mem-1' }) }
beforeEach(() => {
vi.clearAllMocks()
reset()
requireAuthMock.mockResolvedValue({ user: { id: 'user-1' }, supabase, error: null })
requireWriteMock.mockResolvedValue({ ok: true })
})
describe('GET /api/agent/memory', () => {
it('returns 401 when not authenticated', async () => {
requireAuthMock.mockResolvedValue({
user: null,
supabase,
error: NextResponse.json({ error: 'Unauthorized' }, { status: 401 }),
})
const res = await GET(createMockRequest('/api/agent/memory'), routeParams)
expect(res.status).toBe(401)
})
it('returns 400 for an unknown kind filter', async () => {
const req = createMockRequest('/api/agent/memory', { searchParams: { kind: 'gossip' } })
const { status } = await parseJsonResponse(await GET(req, routeParams))
expect(status).toBe(400)
})
it('lists memory entries', async () => {
enqueue({ data: [{ id: 'mem-1', kind: 'fact', content: 'Fakturerar i SEK' }] })
const { status, body } = await parseJsonResponse<{ data: unknown[] }>(
await GET(createMockRequest('/api/agent/memory'), routeParams)
)
expect(status).toBe(200)
expect(body.data).toHaveLength(1)
})
})
describe('POST /api/agent/memory', () => {
it('rejects a viewer in the target company with 403', async () => {
// requireWrite passed for the ACTIVE company, but the body targets a
// company where the caller is only a viewer — the re-check must refuse.
enqueue({ data: { role: 'viewer' } })
const req = createMockRequest('/api/agent/memory', {
method: 'POST',
body: { company_id: '7f3e0b1a-9c4d-4a2b-8f6e-1d2c3b4a5e6f', content: 'Ett minne' },
})
const { status, body } = await parseJsonResponse<{ error: { code: string } }>(
await POST(req, routeParams)
)
expect(status).toBe(403)
expect(body.error.code).toBe('WRITE_PERMISSION_REQUIRED')
})
it('rejects an invalid body with 400', async () => {
const req = createMockRequest('/api/agent/memory', {
method: 'POST',
body: { content: 'x' }, // below min length 2
})
const { status } = await parseJsonResponse(await POST(req, routeParams))
expect(status).toBe(400)
})
it('inserts a memory entry for the active company', async () => {
enqueue({ data: { role: 'admin' } }) // membership re-check
enqueue({ data: { id: 'mem-2', kind: 'fact', content: 'Ett minne' } })
const req = createMockRequest('/api/agent/memory', {
method: 'POST',
body: { content: 'Ett minne' },
})
const { status, body } = await parseJsonResponse<{ data: { id: string } }>(
await POST(req, routeParams)
)
expect(status).toBe(200)
expect(body.data.id).toBe('mem-2')
})
})
describe('PATCH /api/agent/memory/[id]', () => {
it('returns 400 when the body has nothing to update', async () => {
const req = createMockRequest('/api/agent/memory/mem-1', { method: 'PATCH', body: {} })
const { status } = await parseJsonResponse(await PATCH(req, idParams))
expect(status).toBe(400)
})
it('returns 404 when the memory row does not exist', async () => {
enqueue({ data: null })
const req = createMockRequest('/api/agent/memory/mem-1', {
method: 'PATCH',
body: { is_pinned: true },
})
const { status, body } = await parseJsonResponse<{ error: { code: string } }>(
await PATCH(req, idParams)
)
expect(status).toBe(404)
expect(body.error.code).toBe('MEMORY_NOT_FOUND')
})
it('updates a memory entry', async () => {
enqueue({ data: { company_id: 'company-1' } }) // row lookup
enqueue({ data: { role: 'member' } }) // membership re-check
enqueue({ data: { id: 'mem-1', is_pinned: true } }) // update
const req = createMockRequest('/api/agent/memory/mem-1', {
method: 'PATCH',
body: { is_pinned: true },
})
const { status, body } = await parseJsonResponse<{ data: { is_pinned: boolean } }>(
await PATCH(req, idParams)
)
expect(status).toBe(200)
expect(body.data.is_pinned).toBe(true)
})
})
@@ -1,92 +0,0 @@
/**
* Tests for POST /api/agent/onboarding/stream — auth surface only.
*
* The composer pipeline itself is exercised via lib tests; here we lock in
* the guard order: 401, membership 403, and the viewer refusal (the pipeline
* upserts agent_profiles, so viewers must not be able to trigger it).
*/
import { describe, it, expect, vi, beforeEach } from 'vitest'
import { createMockRequest, parseJsonResponse } from '@/tests/helpers'
vi.mock('@/lib/company/context', () => ({
getActiveCompanyId: vi.fn().mockResolvedValue('company-1'),
requireCompanyId: vi.fn().mockResolvedValue('company-1'),
}))
vi.mock('@/lib/rate-limits/agent', () => ({
checkAgentRateLimit: vi.fn().mockResolvedValue({ ok: true }),
agentRateLimitResponseBody: () => ({ error: 'För många förfrågningar.' }),
}))
vi.mock('@/lib/sandbox/guard', () => ({ guardSandbox: vi.fn().mockResolvedValue(null) }))
vi.mock('@/lib/entitlements/has-capability', () => ({
requireCapability: vi.fn().mockResolvedValue(null),
}))
vi.mock('@/lib/entitlements/keys', () => ({ CAPABILITY: { ai: 'ai' } }))
// Pipeline internals — never reached in these tests, stubbed so the module loads.
vi.mock('@/lib/agent/composer/inputs', () => ({
gatherComposerInputs: vi.fn(),
inputsToSourceSignals: vi.fn(),
}))
vi.mock('@/lib/agent/composer/atom-selection', () => ({
selectAtoms: vi.fn(),
filterRedundantQuestions: vi.fn(),
}))
vi.mock('@/lib/agent/composer/narrative', () => ({ writeNarrative: vi.fn() }))
vi.mock('@/lib/agent/composer/fallback', () => ({
fallbackAtomSelection: vi.fn(),
fallbackNarrative: vi.fn(),
}))
vi.mock('@/lib/agent/composer/prewarm', () => ({ preWarmAtomCache: vi.fn() }))
vi.mock('@/lib/agent/composer/client', () => ({ OPUS_MODEL: 'opus-test' }))
vi.mock('@/lib/agent/composer/tic-fetch', () => ({ ensureTicSnapshot: vi.fn() }))
vi.mock('@/lib/supabase/server', () => ({ createClient: vi.fn() }))
import { createClient } from '@/lib/supabase/server'
import { POST } from '../onboarding/stream/route'
const mockCreateClient = vi.mocked(createClient)
function mockAuth(userId: string | null, membership: { role: string } | null) {
mockCreateClient.mockResolvedValue({
auth: {
getUser: vi.fn().mockResolvedValue({ data: { user: userId ? { id: userId } : null } }),
},
from: vi.fn().mockReturnValue({
select: vi.fn().mockReturnThis(),
eq: vi.fn().mockReturnThis(),
maybeSingle: vi.fn().mockResolvedValue({ data: membership, error: null }),
}),
// eslint-disable-next-line @typescript-eslint/no-explicit-any
} as any)
}
beforeEach(() => {
vi.clearAllMocks()
})
describe('POST /api/agent/onboarding/stream', () => {
it('returns 401 when not authenticated', async () => {
mockAuth(null, null)
const req = createMockRequest('/api/agent/onboarding/stream', { method: 'POST', body: {} })
const res = await POST(req)
expect(res.status).toBe(401)
})
it('returns 403 for a non-member', async () => {
mockAuth('user-1', null)
const req = createMockRequest('/api/agent/onboarding/stream', { method: 'POST', body: {} })
const { status } = await parseJsonResponse(await POST(req))
expect(status).toBe(403)
})
it('refuses a viewer with 403 (pipeline upserts agent_profiles)', async () => {
mockAuth('user-1', { role: 'viewer' })
const req = createMockRequest('/api/agent/onboarding/stream', { method: 'POST', body: {} })
const { status, body } = await parseJsonResponse<{ error: string }>(await POST(req))
expect(status).toBe(403)
expect(body.error).toContain('läsbehörighet')
})
})
-149
View File
@@ -1,149 +0,0 @@
/**
* Tests for GET/PATCH /api/agent/profile and POST /api/agent/profile/verify.
*
* Covers the role model: reads allow any member, mutations (PATCH, verify)
* refuse viewers — the same rule verify always had, now enforced on PATCH too.
*/
import { describe, it, expect, vi, beforeEach } from 'vitest'
import { NextResponse } from 'next/server'
import { createQueuedMockSupabase, createMockRequest, parseJsonResponse } from '@/tests/helpers'
const { supabase, enqueue, reset } = createQueuedMockSupabase()
const requireAuthMock = vi.fn()
vi.mock('@/lib/auth/require-auth', () => ({
requireAuth: (...args: unknown[]) => requireAuthMock(...args),
}))
vi.mock('@/lib/company/context', () => ({
getActiveCompanyId: vi.fn().mockResolvedValue('company-1'),
requireCompanyId: vi.fn().mockResolvedValue('company-1'),
}))
import { GET, PATCH } from '../profile/route'
import { POST as VERIFY } from '../profile/verify/route'
const routeParams = { params: Promise.resolve({}) }
beforeEach(() => {
vi.clearAllMocks()
reset()
requireAuthMock.mockResolvedValue({ user: { id: 'user-1' }, supabase, error: null })
})
describe('GET /api/agent/profile', () => {
it('returns 401 when not authenticated', async () => {
requireAuthMock.mockResolvedValue({
user: null,
supabase,
error: NextResponse.json({ error: 'Unauthorized' }, { status: 401 }),
})
const res = await GET(createMockRequest('/api/agent/profile'), routeParams)
expect(res.status).toBe(401)
})
it('returns 403 when the caller is not a member of the target company', async () => {
enqueue({ data: null }) // membership lookup
const { status, body } = await parseJsonResponse<{ error: { code: string } }>(
await GET(createMockRequest('/api/agent/profile'), routeParams)
)
expect(status).toBe(403)
expect(body.error.code).toBe('NOT_COMPANY_MEMBER')
})
it('returns the profile for a member (viewers may read)', async () => {
enqueue({ data: { role: 'viewer' } })
enqueue({ data: { company_id: 'company-1', profile_summary: 'Konsultbolag' } })
const { status, body } = await parseJsonResponse<{ data: { profile_summary: string } }>(
await GET(createMockRequest('/api/agent/profile'), routeParams)
)
expect(status).toBe(200)
expect(body.data.profile_summary).toBe('Konsultbolag')
})
})
describe('PATCH /api/agent/profile', () => {
it('refuses a viewer with 403 (profile mutation)', async () => {
enqueue({ data: { role: 'viewer' } })
const req = createMockRequest('/api/agent/profile', {
method: 'PATCH',
body: { profile_summary: 'Nytt sammandrag' },
})
const { status, body } = await parseJsonResponse<{ error: { code: string } }>(
await PATCH(req, routeParams)
)
expect(status).toBe(403)
expect(body.error.code).toBe('WRITE_PERMISSION_REQUIRED')
})
it('returns 404 when the company has no agent_profile row', async () => {
enqueue({ data: { role: 'admin' } })
enqueue({ data: null }) // current profile lookup
const req = createMockRequest('/api/agent/profile', {
method: 'PATCH',
body: { profile_summary: 'Nytt sammandrag' },
})
const { status, body } = await parseJsonResponse<{ error: { code: string } }>(
await PATCH(req, routeParams)
)
expect(status).toBe(404)
expect(body.error.code).toBe('AGENT_PROFILE_NOT_FOUND')
})
it('returns 400 when the body contains nothing to update', async () => {
enqueue({ data: { role: 'admin' } })
enqueue({ data: { field_overrides: null } })
const req = createMockRequest('/api/agent/profile', { method: 'PATCH', body: {} })
const { status, body } = await parseJsonResponse<{ error: { code: string } }>(
await PATCH(req, routeParams)
)
expect(status).toBe(400)
expect(body.error.code).toBe('NOTHING_TO_UPDATE')
})
it('merges field_overrides and updates the profile', async () => {
enqueue({ data: { role: 'admin' } })
enqueue({ data: { field_overrides: { old: { value: 1, overridden_at: 'x' } } } })
enqueue({ data: { company_id: 'company-1', profile_summary: 'Uppdaterad' } })
const req = createMockRequest('/api/agent/profile', {
method: 'PATCH',
body: { profile_summary: 'Uppdaterad', field_overrides: { vat_period: 'quarterly' } },
})
const { status, body } = await parseJsonResponse<{ data: { profile_summary: string } }>(
await PATCH(req, routeParams)
)
expect(status).toBe(200)
expect(body.data.profile_summary).toBe('Uppdaterad')
})
})
describe('POST /api/agent/profile/verify', () => {
it('refuses a viewer with 403', async () => {
enqueue({ data: { role: 'viewer' } })
const req = createMockRequest('/api/agent/profile/verify', { method: 'POST', body: {} })
const { status, body } = await parseJsonResponse<{ error: { code: string } }>(
await VERIFY(req, routeParams)
)
expect(status).toBe(403)
expect(body.error.code).toBe('WRITE_PERMISSION_REQUIRED')
})
it('stamps verified_at for a non-viewer member', async () => {
enqueue({ data: { role: 'owner' } })
enqueue({ data: { company_id: 'company-1', verified_at: '2026-07-03T00:00:00Z', verified_by_user_id: 'user-1' } })
const req = createMockRequest('/api/agent/profile/verify', { method: 'POST', body: {} })
const { status, body } = await parseJsonResponse<{ data: { verified_by_user_id: string } }>(
await VERIFY(req, routeParams)
)
expect(status).toBe(200)
expect(body.data.verified_by_user_id).toBe('user-1')
})
})