feat(agent): 'Vad din agent vet' page rendering the ledger context (P2) (#935)
* feat(agent): 'Vad din agent vet' page rendering the ledger context (P2) The human-facing surface for the openwiki ledger-context: a read-only page that renders the exact payload the AI agent reads (Accounted://ledger/context + the briefing digest) as a legible profile of how this company books. - Route app/(dashboard)/agent-knowledge (server component) calls the shared buildLedgerContext(supabase, companyId) directly: one payload, two renderers, no new API or data path. - Sections mirror the payload 1:1: coverage/freshness strip, counterparty patterns (monochrome confidence bars + seen/agree evidence), supplier patterns, explicit rules shown as authoritative instructions distinct from observed patterns, account usage, VAT profile, conventions. - Nav entry in the Analys group (icon Brain), ungated so it doubles as an upsell; flip requiredCapability to paywall. - Design per .claude/rules/design.md (PageHeader, Card, Table, Badge, AccountNumber BAS tooltips); sv + en strings (agentKnowledge namespace). VAT/BAS labels stay Swedish in both locales per i18n rules. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * feat(agent): deep entity-resolved analysis + radial graph for the knowledge page Reworks the 'Vad din agent vet' page from tables into a radial-hub graph driven by a new full-history deep analysis, per founder feedback. - fix(rpc): median_booking_lag_days now measures real posting promptness via committed_at, not entry_date (which the bank flow sets to the transaction date, giving a ~0 tautology: 151/152 on prod). migration 20260708120000. - feat(rpc): get_ledger_deep_context (migration 20260708130000): full-history, deterministic, read-side. Merges counterparties by normalize_counterparty_key (e.g. Claude = 14 bookings across 12 name variants, weekly, 9 710 kr, always 5420), mines booked verifikat for SEK spend (coalesce amount_sek), detects recurrence cadence, dominant account + share, plus supplier entities. Storno excluded, corrections kept; 19xx/26xx excluded from the dominant contra. - LedgerGraph: radial SVG (company center, accounts inner ring, payees outer ring), hover/focus reveals variants + spend + cadence + account. Keyboard focusable nodes with per-node accessible names + a screen-reader data table. - Page fetches the deep context alongside the light context; coverage strip gains tracked-payee / recurring / tracked-spend stats. sv + en strings. - 14 pg tests (light + deep) green; both RPCs applied to prod + version-matched. Reviewed by an adversarial multi-lens pass (accounting/SQL, frontend/a11y, prod-fact verification); all four verified findings fixed (SEK currency, storno-lag guard, keyboard a11y, spacing tokens). Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * feat(agent): gentle mount fade-in for the radial map (reduced-motion safe) Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * fix(agent): render the page for a rules-only company (empty-state edge case) isEmpty ignored explicit_rules, so a company with configured mapping rules but no posted transactions hit the 'hasn't learned anything' empty state and lost its rules section. Rules are independent of bookings. (CodeRabbit) Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * feat(agent): show Kompetens (skills) + Fakta (memory) on the knowledge page The 'Vad din agent vet' page now shows the full picture of what the agent knows: alongside the booking map, a compact read-only view of its Kompetens (the Swedish accounting/tax knowledge atoms it ships with, grouped by tier as chips with active/dormant state) and the Fakta it remembers (top learned facts with kind + source), each linking to /settings/assistant for full management. Server-rendered via a new buildAgentCompetence() that mirrors GET /api/agent/skills + /api/agent/memory. Also renders in the no-bookings case so a new company still sees its agent's competence. sv + en strings. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * refactor(agent): restructure knowledge page - hero graph + tabbed detail Declutters the page per feedback: the booking map is the always-visible hero, and the supporting detail (Kompetens · Minne · Regler & profil) moves into tabs so only one view shows at a time instead of a long card stack. Split AgentCompetenceSections into standalone CompetenceCard + FactsCard for the tabs; removed the top stat row on request. sv + en. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * feat(agent): Reconciliation Aurora rewrite of the ledger knowledge graph Full rewrite of LedgerGraph: node area = sqrt(spend), colour = cadence, shape = supplier/counterparty, confidence = depth-of-field; on-mount descriptor-collapse animation with xN badge; cadence pulse veins; deterministic seeded layout; framer-motion only (no new deps); keyboard navigation, reduced-motion and sr-only support. Build-verified; 3-lens adversarial review findings fixed. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * fix(agent): sample-size-honest confidence in the ledger knowledge graph dominant_account_share was raw cnt/total, so a counterparty with a single booking rendered as '100% säkerhet': fake certainty by construction (the data_quality_master Item-C / P3 finding). New migration replaces get_ledger_deep_context with a Laplace-smoothed share (cnt+1)/(total+2) (1/1 -> 0.67, 3/3 -> 0.80) and exposes the raw evidence as dominant_account_count / dominant_account_total. The detail card now shows 'Bokförd hit i k av n fall' under the confidence bar; the existing focus buckets, stroke widths and percent labels inherit the honest value unchanged. pg-real test updated to guard the n=1 case. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> --------- Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
This commit is contained in:
co-authored by
Claude Fable 5
parent
64ea0fef02
commit
4b51af3d80
@@ -0,0 +1,99 @@
|
||||
import type { SupabaseClient } from '@supabase/supabase-js'
|
||||
|
||||
// Server-side read of the agent's competence (the domain-knowledge "atoms" it
|
||||
// ships with) and its top learned facts (memory), for the read-only overview
|
||||
// on the "Vad din agent vet" page. Mirrors GET /api/agent/skills and
|
||||
// GET /api/agent/memory so the two surfaces stay consistent; the full editable
|
||||
// management lives in /settings/assistant.
|
||||
|
||||
export type AtomTier = 'horizontal' | 'vertical' | 'modifier'
|
||||
|
||||
export interface AgentAtom {
|
||||
id: string
|
||||
tier: AtomTier
|
||||
title: string
|
||||
description: string
|
||||
/** horizontal atoms apply to every company; vertical/modifier only when the
|
||||
* composer selected them into this company's profile. */
|
||||
active: boolean
|
||||
}
|
||||
|
||||
export type FactKind = 'fact' | 'preference' | 'pattern' | 'correction'
|
||||
export type FactSource = 'composer' | 'user_taught' | 'agent_learned' | 'derived'
|
||||
|
||||
export interface AgentFact {
|
||||
id: string
|
||||
kind: FactKind
|
||||
content: string
|
||||
source: FactSource
|
||||
is_pinned: boolean
|
||||
}
|
||||
|
||||
export interface AgentCompetence {
|
||||
atoms: AgentAtom[]
|
||||
facts: AgentFact[]
|
||||
/** Total active facts (before the overview cap), so the count is honest. */
|
||||
factsActiveTotal: number
|
||||
}
|
||||
|
||||
const FACTS_LIMIT = 12
|
||||
|
||||
export async function buildAgentCompetence(
|
||||
supabase: SupabaseClient,
|
||||
companyId: string,
|
||||
): Promise<AgentCompetence> {
|
||||
const [atomsRes, profileRes, factsRes, factsCountRes] = await Promise.all([
|
||||
// The atom registry is global product content, not tenant data.
|
||||
supabase
|
||||
.from('agent_atom_registry')
|
||||
.select('id, tier, title, description')
|
||||
.eq('is_active', true)
|
||||
.eq('mcp_exposed', true)
|
||||
.is('parent_atom_id', null)
|
||||
.order('tier', { ascending: true })
|
||||
.order('title', { ascending: true }),
|
||||
supabase
|
||||
.from('agent_profiles')
|
||||
.select('vertical_atoms, modifier_atoms')
|
||||
.eq('company_id', companyId)
|
||||
.maybeSingle(),
|
||||
supabase
|
||||
.from('agent_memory')
|
||||
.select('id, kind, content, source, is_pinned')
|
||||
.eq('company_id', companyId)
|
||||
.eq('is_active', true)
|
||||
.order('is_pinned', { ascending: false })
|
||||
.order('relevance_score', { ascending: false })
|
||||
.order('last_accessed_at', { ascending: false, nullsFirst: false })
|
||||
.order('created_at', { ascending: false })
|
||||
.limit(FACTS_LIMIT),
|
||||
supabase
|
||||
.from('agent_memory')
|
||||
.select('id', { count: 'exact', head: true })
|
||||
.eq('company_id', companyId)
|
||||
.eq('is_active', true),
|
||||
])
|
||||
|
||||
if (atomsRes.error) throw new Error(`agent skills failed: ${atomsRes.error.message}`)
|
||||
if (factsRes.error) throw new Error(`agent memory failed: ${factsRes.error.message}`)
|
||||
|
||||
const verticalActive = new Set((profileRes.data?.vertical_atoms as string[] | null) ?? [])
|
||||
const modifierActive = new Set((profileRes.data?.modifier_atoms as string[] | null) ?? [])
|
||||
|
||||
const atoms: AgentAtom[] = (atomsRes.data ?? []).map((a) => {
|
||||
const tier = a.tier as AtomTier
|
||||
const active =
|
||||
tier === 'horizontal' ? true : tier === 'vertical' ? verticalActive.has(a.id) : modifierActive.has(a.id)
|
||||
return { id: a.id, tier, title: a.title, description: a.description, active }
|
||||
})
|
||||
|
||||
const facts: AgentFact[] = (factsRes.data ?? []).map((f) => ({
|
||||
id: f.id,
|
||||
kind: f.kind as FactKind,
|
||||
content: f.content,
|
||||
source: f.source as FactSource,
|
||||
is_pinned: f.is_pinned,
|
||||
}))
|
||||
|
||||
return { atoms, facts, factsActiveTotal: factsCountRes.count ?? facts.length }
|
||||
}
|
||||
@@ -0,0 +1,70 @@
|
||||
import type { SupabaseClient } from '@supabase/supabase-js'
|
||||
|
||||
// Deep, entity-resolved analysis behind the "Vad din agent vet" page. Merges
|
||||
// counterparties across name variants, mines the booked verifikat for real
|
||||
// spend, and detects recurrence. Backed by the get_ledger_deep_context RPC
|
||||
// (full history, deterministic). See migration 20260708130000.
|
||||
|
||||
export interface DeepEntity {
|
||||
/** Display label (the modal raw variant). */
|
||||
name: string
|
||||
/** Identity key: normalized counterparty key, or supplier id. */
|
||||
key: string
|
||||
/** Up to 8 distinct raw labels that merged into this entity. */
|
||||
variants: string[]
|
||||
/** True count of distinct raw labels merged. */
|
||||
variant_count: number
|
||||
/** Number of bookings. */
|
||||
occurrences: number
|
||||
/** Total paid, gross SEK (abs bank amount / invoice total). */
|
||||
total_amount: number
|
||||
first_seen: string
|
||||
last_seen: string
|
||||
/** Median gap between distinct booking dates, days. null if < 2 dates. */
|
||||
cadence_days: number | null
|
||||
dominant_account_number: string | null
|
||||
/**
|
||||
* Laplace-smoothed consistency (cnt+1)/(total+2), 0..1: sample-size-honest,
|
||||
* so a single booking reads 0.67, never 1.0 (migration 20260710090000).
|
||||
*/
|
||||
dominant_account_share: number | null
|
||||
/** Raw evidence: bookings on the dominant account. */
|
||||
dominant_account_count: number | null
|
||||
/** Raw evidence: all counted contra lines for the entity. */
|
||||
dominant_account_total: number | null
|
||||
dominant_vat?: string | null
|
||||
kind: 'counterparty' | 'supplier'
|
||||
}
|
||||
|
||||
export interface DeepLedgerContext {
|
||||
counterparty_entities: DeepEntity[]
|
||||
supplier_entities: DeepEntity[]
|
||||
}
|
||||
|
||||
interface DeepRow {
|
||||
counterparty_entities: Omit<DeepEntity, 'kind'>[]
|
||||
supplier_entities: Omit<DeepEntity, 'kind'>[]
|
||||
}
|
||||
|
||||
/**
|
||||
* Full-history deep analysis. `fromDate = null` means all history; pass a date
|
||||
* to bound the lookback on large tenants (the cache layer is deferred).
|
||||
*/
|
||||
export async function buildDeepEntities(
|
||||
supabase: SupabaseClient,
|
||||
companyId: string,
|
||||
fromDate: string | null = null,
|
||||
): Promise<DeepLedgerContext> {
|
||||
const { data, error } = await supabase.rpc('get_ledger_deep_context', {
|
||||
p_company_id: companyId,
|
||||
p_from_date: fromDate,
|
||||
})
|
||||
if (error) {
|
||||
throw new Error(`ledger deep context failed: ${error.message}`)
|
||||
}
|
||||
const row = (data ?? { counterparty_entities: [], supplier_entities: [] }) as DeepRow
|
||||
return {
|
||||
counterparty_entities: (row.counterparty_entities ?? []).map((e) => ({ ...e, kind: 'counterparty' as const })),
|
||||
supplier_entities: (row.supplier_entities ?? []).map((e) => ({ ...e, kind: 'supplier' as const })),
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user