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:
@@ -1,94 +0,0 @@
|
||||
import { NextResponse } from 'next/server'
|
||||
import { z } from 'zod'
|
||||
import { withRouteContext } from '@/lib/api/with-route-context'
|
||||
import { validateBody } from '@/lib/api/validate'
|
||||
|
||||
// PATCH /api/agent/memory/[id]
|
||||
//
|
||||
// Mutate a single memory entry. Powers the list/edit/pin/dismiss affordances
|
||||
// on /settings/agent-memory (plan §11).
|
||||
//
|
||||
// content: edit the durable text (kind never changes; that would
|
||||
// muddle the audit lineage). Append-only is preserved by
|
||||
// superseded_by chains when an upstream caller wants it; the
|
||||
// transparency UI is allowed to overwrite in place because
|
||||
// the row's `updated_at` already documents the edit.
|
||||
// is_pinned: boost into the top-N prompt block regardless of score.
|
||||
// is_active: false = dismiss (removes from ranking pool); true = restore.
|
||||
//
|
||||
// RLS scopes to user_company_ids(); we ALSO re-verify membership for the
|
||||
// row's company_id as defense in depth before mutating.
|
||||
|
||||
const PatchSchema = z
|
||||
.object({
|
||||
content: z.string().min(2).max(2000).optional(),
|
||||
is_pinned: z.boolean().optional(),
|
||||
is_active: z.boolean().optional(),
|
||||
})
|
||||
.refine(
|
||||
(v) => v.content !== undefined || v.is_pinned !== undefined || v.is_active !== undefined,
|
||||
{ message: 'Nothing to update' },
|
||||
)
|
||||
|
||||
const notFound = () =>
|
||||
NextResponse.json(
|
||||
{
|
||||
error: {
|
||||
code: 'MEMORY_NOT_FOUND',
|
||||
message: 'Minnet hittades inte.',
|
||||
message_en: 'Memory not found.',
|
||||
},
|
||||
},
|
||||
{ status: 404 },
|
||||
)
|
||||
|
||||
export const PATCH = withRouteContext(
|
||||
'agent.memory.update',
|
||||
async (request, ctx, { params }: { params: Promise<{ id: string }> }) => {
|
||||
const { id } = await params
|
||||
const { supabase, user, log } = ctx
|
||||
|
||||
const validation = await validateBody(request, PatchSchema, {
|
||||
log,
|
||||
operation: 'agent.memory.update',
|
||||
})
|
||||
if (!validation.success) return validation.response
|
||||
const body = validation.data
|
||||
|
||||
const update: Record<string, unknown> = {}
|
||||
if (body.content !== undefined) update.content = body.content
|
||||
if (body.is_pinned !== undefined) update.is_pinned = body.is_pinned
|
||||
if (body.is_active !== undefined) update.is_active = body.is_active
|
||||
|
||||
// Look up the row's company_id and re-check membership before mutating.
|
||||
const { data: existing } = await supabase
|
||||
.from('agent_memory')
|
||||
.select('company_id')
|
||||
.eq('id', id)
|
||||
.maybeSingle()
|
||||
if (!existing) return notFound()
|
||||
|
||||
const { data: membership } = await supabase
|
||||
.from('company_members')
|
||||
.select('role')
|
||||
.eq('company_id', existing.company_id)
|
||||
.eq('user_id', user.id)
|
||||
.maybeSingle()
|
||||
if (!membership) return notFound()
|
||||
|
||||
const { data, error } = await supabase
|
||||
.from('agent_memory')
|
||||
.update(update)
|
||||
.eq('id', id)
|
||||
.eq('company_id', existing.company_id)
|
||||
.select(
|
||||
'id, kind, content, source, source_ref, relevance_score, is_pinned, is_active, last_accessed_at, created_at, updated_at',
|
||||
)
|
||||
.maybeSingle()
|
||||
if (error) throw error
|
||||
if (!data) return notFound()
|
||||
|
||||
return NextResponse.json({ data })
|
||||
},
|
||||
{ requireWrite: true },
|
||||
)
|
||||
@@ -1,300 +0,0 @@
|
||||
import { describe, it, expect, vi, beforeEach } from 'vitest'
|
||||
import {
|
||||
createMockRequest,
|
||||
createMockRouteParams,
|
||||
parseJsonResponse,
|
||||
createQueuedMockSupabase,
|
||||
} from '@/tests/helpers'
|
||||
|
||||
const { supabase: mockSupabase, enqueue, reset } = createQueuedMockSupabase()
|
||||
vi.mock('@/lib/supabase/server', () => ({
|
||||
createClient: () => Promise.resolve(mockSupabase),
|
||||
}))
|
||||
|
||||
const getActiveCompanyIdMock = vi.fn()
|
||||
vi.mock('@/lib/company/context', () => ({
|
||||
getActiveCompanyId: (...args: unknown[]) => getActiveCompanyIdMock(...args),
|
||||
}))
|
||||
|
||||
const requireWritePermissionMock = vi.fn()
|
||||
vi.mock('@/lib/auth/require-write', () => ({
|
||||
requireWritePermission: (...args: unknown[]) => requireWritePermissionMock(...args),
|
||||
}))
|
||||
|
||||
import { GET, POST } from '../route'
|
||||
import { PATCH } from '../[id]/route'
|
||||
|
||||
const mockUser = { id: 'user-1', email: '[email protected]' }
|
||||
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks()
|
||||
reset()
|
||||
mockSupabase.auth.getUser.mockResolvedValue({ data: { user: mockUser } })
|
||||
getActiveCompanyIdMock.mockResolvedValue('company-1')
|
||||
requireWritePermissionMock.mockResolvedValue({ ok: true })
|
||||
})
|
||||
|
||||
describe('GET /api/agent/memory', () => {
|
||||
it('returns 401 when not authenticated', async () => {
|
||||
mockSupabase.auth.getUser.mockResolvedValue({ data: { user: null } })
|
||||
const response = await GET(createMockRequest('/api/agent/memory'), createMockRouteParams({}))
|
||||
const { status, body } = await parseJsonResponse<{ error: string }>(response)
|
||||
expect(status).toBe(401)
|
||||
expect(body.error).toBe('Unauthorized')
|
||||
})
|
||||
|
||||
it('returns 400 when no active company', async () => {
|
||||
getActiveCompanyIdMock.mockResolvedValue(null)
|
||||
const response = await GET(createMockRequest('/api/agent/memory'), createMockRouteParams({}))
|
||||
const { status } = await parseJsonResponse(response)
|
||||
expect(status).toBe(400)
|
||||
})
|
||||
|
||||
it('returns rows for the active company', async () => {
|
||||
const rows = [
|
||||
{
|
||||
id: 'mem-1',
|
||||
kind: 'fact',
|
||||
content: 'Räkenskapsår jan-dec',
|
||||
source: 'composer',
|
||||
source_ref: null,
|
||||
relevance_score: 0.5,
|
||||
is_pinned: false,
|
||||
is_active: true,
|
||||
last_accessed_at: null,
|
||||
created_at: '2026-05-10T09:00:00Z',
|
||||
updated_at: '2026-05-10T09:00:00Z',
|
||||
},
|
||||
]
|
||||
enqueue({ data: rows })
|
||||
const response = await GET(createMockRequest('/api/agent/memory'), createMockRouteParams({}))
|
||||
const { status, body } = await parseJsonResponse<{ data: typeof rows }>(response)
|
||||
expect(status).toBe(200)
|
||||
expect(body.data).toHaveLength(1)
|
||||
expect(body.data[0].id).toBe('mem-1')
|
||||
})
|
||||
|
||||
it('does not require write permission for read', async () => {
|
||||
enqueue({ data: [] })
|
||||
await GET(createMockRequest('/api/agent/memory'), createMockRouteParams({}))
|
||||
expect(requireWritePermissionMock).not.toHaveBeenCalled()
|
||||
})
|
||||
})
|
||||
|
||||
describe('POST /api/agent/memory', () => {
|
||||
it('returns 401 when not authenticated', async () => {
|
||||
mockSupabase.auth.getUser.mockResolvedValue({ data: { user: null } })
|
||||
const response = await POST(
|
||||
createMockRequest('/api/agent/memory', {
|
||||
method: 'POST',
|
||||
body: { content: 'hello world' },
|
||||
}),
|
||||
createMockRouteParams({}),
|
||||
)
|
||||
expect(response.status).toBe(401)
|
||||
})
|
||||
|
||||
it('blocks viewers via requireWritePermission', async () => {
|
||||
const { NextResponse } = await import('next/server')
|
||||
requireWritePermissionMock.mockResolvedValue({
|
||||
ok: false,
|
||||
response: NextResponse.json({ error: 'forbidden' }, { status: 403 }),
|
||||
})
|
||||
const response = await POST(
|
||||
createMockRequest('/api/agent/memory', {
|
||||
method: 'POST',
|
||||
body: { content: 'hello world' },
|
||||
}),
|
||||
createMockRouteParams({}),
|
||||
)
|
||||
expect(response.status).toBe(403)
|
||||
})
|
||||
|
||||
it('rejects too-short content', async () => {
|
||||
const response = await POST(
|
||||
createMockRequest('/api/agent/memory', {
|
||||
method: 'POST',
|
||||
body: { content: 'x' },
|
||||
}),
|
||||
createMockRouteParams({}),
|
||||
)
|
||||
expect(response.status).toBe(400)
|
||||
})
|
||||
|
||||
it('inserts and returns the row on happy path', async () => {
|
||||
const inserted = {
|
||||
id: 'mem-2',
|
||||
kind: 'fact',
|
||||
content: 'En sak att komma ihåg',
|
||||
source: 'user_taught',
|
||||
source_ref: null,
|
||||
relevance_score: 1,
|
||||
is_pinned: false,
|
||||
is_active: true,
|
||||
last_accessed_at: null,
|
||||
created_at: '2026-05-18T10:00:00Z',
|
||||
updated_at: '2026-05-18T10:00:00Z',
|
||||
}
|
||||
// Defense-in-depth: body company_id membership re-check happens after
|
||||
// requireWritePermission. POST flow now is: (1) company_members lookup,
|
||||
// (2) insert.
|
||||
enqueue({ data: { role: 'member' } })
|
||||
enqueue({ data: inserted })
|
||||
const response = await POST(
|
||||
createMockRequest('/api/agent/memory', {
|
||||
method: 'POST',
|
||||
body: { content: 'En sak att komma ihåg' },
|
||||
}),
|
||||
createMockRouteParams({}),
|
||||
)
|
||||
const { status, body } = await parseJsonResponse<{ data: typeof inserted }>(response)
|
||||
expect(status).toBe(200)
|
||||
expect(body.data.id).toBe('mem-2')
|
||||
})
|
||||
|
||||
it('rejects when user is a viewer in the target company', async () => {
|
||||
enqueue({ data: { role: 'viewer' } })
|
||||
const response = await POST(
|
||||
createMockRequest('/api/agent/memory', {
|
||||
method: 'POST',
|
||||
body: { content: 'En sak att komma ihåg' },
|
||||
}),
|
||||
createMockRouteParams({}),
|
||||
)
|
||||
expect(response.status).toBe(403)
|
||||
})
|
||||
})
|
||||
|
||||
describe('PATCH /api/agent/memory/[id]', () => {
|
||||
it('returns 401 when not authenticated', async () => {
|
||||
mockSupabase.auth.getUser.mockResolvedValue({ data: { user: null } })
|
||||
const response = await PATCH(
|
||||
createMockRequest('/api/agent/memory/mem-1', {
|
||||
method: 'PATCH',
|
||||
body: { is_pinned: true },
|
||||
}),
|
||||
createMockRouteParams({ id: 'mem-1' }),
|
||||
)
|
||||
expect(response.status).toBe(401)
|
||||
})
|
||||
|
||||
it('blocks viewers via requireWritePermission', async () => {
|
||||
const { NextResponse } = await import('next/server')
|
||||
requireWritePermissionMock.mockResolvedValue({
|
||||
ok: false,
|
||||
response: NextResponse.json({ error: 'forbidden' }, { status: 403 }),
|
||||
})
|
||||
const response = await PATCH(
|
||||
createMockRequest('/api/agent/memory/mem-1', {
|
||||
method: 'PATCH',
|
||||
body: { is_pinned: true },
|
||||
}),
|
||||
createMockRouteParams({ id: 'mem-1' }),
|
||||
)
|
||||
expect(response.status).toBe(403)
|
||||
})
|
||||
|
||||
it('rejects empty patch body', async () => {
|
||||
const response = await PATCH(
|
||||
createMockRequest('/api/agent/memory/mem-1', { method: 'PATCH', body: {} }),
|
||||
createMockRouteParams({ id: 'mem-1' }),
|
||||
)
|
||||
expect(response.status).toBe(400)
|
||||
})
|
||||
|
||||
it('returns 404 when row not found / not visible via RLS', async () => {
|
||||
// Row lookup returns null → defense-in-depth 404 before update.
|
||||
enqueue({ data: null })
|
||||
const response = await PATCH(
|
||||
createMockRequest('/api/agent/memory/mem-x', {
|
||||
method: 'PATCH',
|
||||
body: { is_pinned: true },
|
||||
}),
|
||||
createMockRouteParams({ id: 'mem-x' }),
|
||||
)
|
||||
expect(response.status).toBe(404)
|
||||
})
|
||||
|
||||
it('returns 404 when user has no membership in row company', async () => {
|
||||
enqueue({ data: { company_id: 'company-2' } })
|
||||
enqueue({ data: null }) // company_members lookup
|
||||
const response = await PATCH(
|
||||
createMockRequest('/api/agent/memory/mem-1', {
|
||||
method: 'PATCH',
|
||||
body: { is_pinned: true },
|
||||
}),
|
||||
createMockRouteParams({ id: 'mem-1' }),
|
||||
)
|
||||
expect(response.status).toBe(404)
|
||||
})
|
||||
|
||||
it('pins a row', async () => {
|
||||
const updated = {
|
||||
id: 'mem-1',
|
||||
kind: 'fact',
|
||||
content: 'X',
|
||||
source: 'composer',
|
||||
source_ref: null,
|
||||
relevance_score: 0.5,
|
||||
is_pinned: true,
|
||||
is_active: true,
|
||||
last_accessed_at: null,
|
||||
created_at: '2026-05-10T09:00:00Z',
|
||||
updated_at: '2026-05-18T10:00:00Z',
|
||||
}
|
||||
// PATCH flow: (1) row lookup, (2) membership lookup, (3) update.
|
||||
enqueue({ data: { company_id: 'company-1' } })
|
||||
enqueue({ data: { role: 'member' } })
|
||||
enqueue({ data: updated })
|
||||
const response = await PATCH(
|
||||
createMockRequest('/api/agent/memory/mem-1', {
|
||||
method: 'PATCH',
|
||||
body: { is_pinned: true },
|
||||
}),
|
||||
createMockRouteParams({ id: 'mem-1' }),
|
||||
)
|
||||
const { status, body } = await parseJsonResponse<{ data: typeof updated }>(response)
|
||||
expect(status).toBe(200)
|
||||
expect(body.data.is_pinned).toBe(true)
|
||||
})
|
||||
|
||||
it('dismisses a row by setting is_active=false', async () => {
|
||||
const updated = {
|
||||
id: 'mem-1',
|
||||
kind: 'fact',
|
||||
content: 'X',
|
||||
source: 'composer',
|
||||
source_ref: null,
|
||||
relevance_score: 0.5,
|
||||
is_pinned: false,
|
||||
is_active: false,
|
||||
last_accessed_at: null,
|
||||
created_at: '2026-05-10T09:00:00Z',
|
||||
updated_at: '2026-05-18T10:00:00Z',
|
||||
}
|
||||
enqueue({ data: { company_id: 'company-1' } })
|
||||
enqueue({ data: { role: 'member' } })
|
||||
enqueue({ data: updated })
|
||||
const response = await PATCH(
|
||||
createMockRequest('/api/agent/memory/mem-1', {
|
||||
method: 'PATCH',
|
||||
body: { is_active: false },
|
||||
}),
|
||||
createMockRouteParams({ id: 'mem-1' }),
|
||||
)
|
||||
const { status, body } = await parseJsonResponse<{ data: typeof updated }>(response)
|
||||
expect(status).toBe(200)
|
||||
expect(body.data.is_active).toBe(false)
|
||||
})
|
||||
|
||||
it('rejects content shorter than 2 chars', async () => {
|
||||
const response = await PATCH(
|
||||
createMockRequest('/api/agent/memory/mem-1', {
|
||||
method: 'PATCH',
|
||||
body: { content: 'x' },
|
||||
}),
|
||||
createMockRouteParams({ id: 'mem-1' }),
|
||||
)
|
||||
expect(response.status).toBe(400)
|
||||
})
|
||||
})
|
||||
@@ -1,135 +0,0 @@
|
||||
import { NextResponse } from 'next/server'
|
||||
import { z } from 'zod'
|
||||
import { withRouteContext } from '@/lib/api/with-route-context'
|
||||
import { validateBody, validateQuery } from '@/lib/api/validate'
|
||||
|
||||
// GET /api/agent/memory
|
||||
//
|
||||
// Lists memory entries for the active company, ordered by pin > relevance >
|
||||
// recency. Powers /settings/agent-memory (transparency UI per plan §11).
|
||||
//
|
||||
// Query params:
|
||||
// include_dismissed: 'true' includes is_active=false rows (audit view).
|
||||
// kind: filter by kind.
|
||||
// limit: 1..200, default 200 (matches the storage cap).
|
||||
//
|
||||
// POST /api/agent/memory
|
||||
//
|
||||
// Inserts a memory entry for the company. Used by Phase B's free-text seed
|
||||
// memory field ("Lägg till om ditt företag (valfritt)") to capture
|
||||
// foundational facts as `kind=fact`, `source=user_taught` with an elevated
|
||||
// relevance score so they land in the top-30 prompt block.
|
||||
//
|
||||
// Also usable from /settings/agent-memory ("Lägg till minne" affordance) and
|
||||
// post-Phase 4 explicit "Kom ihåg det här" surfaces.
|
||||
|
||||
const KIND = ['fact', 'preference', 'pattern', 'correction'] as const
|
||||
const SOURCE = ['composer', 'user_taught', 'agent_learned', 'derived'] as const
|
||||
|
||||
const MEMORY_COLUMNS =
|
||||
'id, kind, content, source, source_ref, relevance_score, is_pinned, is_active, last_accessed_at, created_at, updated_at'
|
||||
|
||||
const ListQuerySchema = z.object({
|
||||
include_dismissed: z.enum(['true', 'false']).optional(),
|
||||
kind: z.enum(KIND).optional(),
|
||||
limit: z.coerce.number().int().min(1).max(200).default(200),
|
||||
})
|
||||
|
||||
const BodySchema = z.object({
|
||||
company_id: z.string().uuid().optional(),
|
||||
content: z.string().min(2).max(2000),
|
||||
kind: z.enum(KIND).default('fact'),
|
||||
source: z.enum(SOURCE).default('user_taught'),
|
||||
source_ref: z.string().max(200).optional(),
|
||||
// Default 1.0 keeps user-taught entries above composer-derived (0.5) by
|
||||
// default; conversation-time captures can land anywhere in [0, 1].
|
||||
relevance_score: z.number().min(0).max(1).default(1.0),
|
||||
})
|
||||
|
||||
export const GET = withRouteContext('agent.memory.list', async (request, ctx) => {
|
||||
const { supabase, companyId, log } = ctx
|
||||
|
||||
const validated = validateQuery(request, ListQuerySchema, {
|
||||
log,
|
||||
operation: 'agent.memory.list',
|
||||
})
|
||||
if (!validated.success) return validated.response
|
||||
const { include_dismissed, kind, limit } = validated.data
|
||||
|
||||
let query = supabase
|
||||
.from('agent_memory')
|
||||
.select(MEMORY_COLUMNS)
|
||||
.eq('company_id', companyId)
|
||||
|
||||
if (include_dismissed !== 'true') query = query.eq('is_active', true)
|
||||
if (kind) query = query.eq('kind', kind)
|
||||
|
||||
query = query
|
||||
.order('is_active', { ascending: false })
|
||||
.order('is_pinned', { ascending: false })
|
||||
.order('relevance_score', { ascending: false })
|
||||
.order('last_accessed_at', { ascending: false, nullsFirst: false })
|
||||
.order('created_at', { ascending: false })
|
||||
.limit(limit)
|
||||
|
||||
const { data, error } = await query
|
||||
if (error) throw error
|
||||
return NextResponse.json({ data: data ?? [] })
|
||||
})
|
||||
|
||||
export const POST = withRouteContext(
|
||||
'agent.memory.create',
|
||||
async (request, ctx) => {
|
||||
const { supabase, companyId: activeCompanyId, user, log } = ctx
|
||||
|
||||
const validation = await validateBody(request, BodySchema, {
|
||||
log,
|
||||
operation: 'agent.memory.create',
|
||||
})
|
||||
if (!validation.success) return validation.response
|
||||
const body = validation.data
|
||||
|
||||
const companyId = body.company_id ?? activeCompanyId
|
||||
|
||||
// requireWrite (wrapper option) checks the *active* company's role; if
|
||||
// the caller passes a different company_id in the body, re-check
|
||||
// membership + non-viewer role for THAT company specifically.
|
||||
const { data: bodyMembership } = await supabase
|
||||
.from('company_members')
|
||||
.select('role')
|
||||
.eq('company_id', companyId)
|
||||
.eq('user_id', user.id)
|
||||
.maybeSingle()
|
||||
if (!bodyMembership || bodyMembership.role === 'viewer') {
|
||||
return NextResponse.json(
|
||||
{
|
||||
error: {
|
||||
code: 'WRITE_PERMISSION_REQUIRED',
|
||||
message: 'Du har endast läsbehörighet i detta företag.',
|
||||
message_en: 'You only have read access in this company.',
|
||||
},
|
||||
},
|
||||
{ status: 403 },
|
||||
)
|
||||
}
|
||||
|
||||
const { data, error } = await supabase
|
||||
.from('agent_memory')
|
||||
.insert({
|
||||
company_id: companyId,
|
||||
kind: body.kind,
|
||||
content: body.content,
|
||||
source: body.source,
|
||||
source_ref: body.source_ref ?? null,
|
||||
relevance_score: body.relevance_score,
|
||||
is_active: true,
|
||||
created_by_user_id: user.id,
|
||||
})
|
||||
.select(MEMORY_COLUMNS)
|
||||
.single()
|
||||
if (error) throw error
|
||||
|
||||
return NextResponse.json({ data })
|
||||
},
|
||||
{ requireWrite: true },
|
||||
)
|
||||
Reference in New Issue
Block a user