Files
accounted/extensions/general/whatsapp-inbox/lib/item-context.ts
T
629069e281 feat(whatsapp-inbox): conversation layer with clarifying questions (#1340)
PR4 of the WhatsApp intake track: turns the per-message PR3 pipeline into a
conversation. Media replies are burst-debounced into ONE combined ack (M4
single / M5 numbered list) sent by the single winner of the atomic
pending_ack claim; losers stay silent. Multi-company senders get the company
question (reply buttons <=3, list 4-10, numbered text >10) with an 8h
sliding pin ('byt' clears it); their receipts park as staged message rows
until the answer and then run through the normal intake path.

Clarifying questions are evaluated per receipt after extraction, max one per
receipt, priority unreadable > representation > partial, keyed on the
Phase-0 classification (legibility/documentKind/merchantCategory) with
heuristic fallbacks (compressed-chat-photo signal, extended meal regex).
Budgets: <=2 content questions per burst, <=6 per sender per Stockholm day;
over budget acks only and flags the item moved_to_app. Questions expire
after 48h (sweep, silent hand-off) and are asked exactly once.

Free-text answers route through the ONE new LLM call
(lib/interpret-answer.ts): Sonnet via Bedrock, max_tokens 600, no thinking,
forced tool call validated by Zod with hard caps, gated by
checkAgentRateLimit, reply framed as untrusted data. Any failure degrades to
storing the raw text as a note; exact 'nej' short-circuits without the LLM.
Answers land in invoice_inbox_items.channel_context
(representation/user_note/quality) with ChannelQuestionAsked/Answered
processing-history events. Late answers match by quoted wamid or the most
recent open question within 7 days.

New per-minute sweep cron (registry-gated physical route, 503
EXTENSION_DISABLED when off) re-claims stuck rows (max 3 attempts), rescues
crashed burst acks, expires questions and pins. One new migration
(20260802210000) adds whatsapp_messages.acked_at, the relational burst-
membership marker, with pg-real coverage for the single-winner claim.

Verified: full vitest suite (12270), pg-real against a migrated
supabase/postgres 15 (977), lint 0 errors, tsc at the 405 baseline,
check:guards green, crontabs regenerated. Mutation-checked the debounce
claim and the daily budget gate.

Co-authored-by: Jakob Wennberg <jakob.wennberg@gmail.com>
Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
2026-08-05 15:27:00 +02:00

80 lines
2.7 KiB
TypeScript

/**
* channel_context helpers for invoice_inbox_items rows created by the chat
* channel, plus the processing_history audit events for the question
* lifecycle (asked/answered/expired: together with representation.raw_answer
* these form the Skatteverket documentation trail).
*
* channel_context is deliberately separate from extracted_data:
* retry-extraction overwrites extracted_data wholesale, and verified human
* answers must never share a container with untrusted OCR output.
*/
import type { SupabaseClient } from '@supabase/supabase-js'
import { appendProcessingHistory } from '@/lib/processing-history/append'
import { createLogger } from '@/lib/logger'
import type { InboxChannelContext } from '@/types'
const log = createLogger('whatsapp-inbox/item-context')
export async function loadItemContext(
supabase: SupabaseClient,
inboxItemId: string,
): Promise<InboxChannelContext> {
const { data } = await supabase
.from('invoice_inbox_items')
.select('channel_context')
.eq('id', inboxItemId)
.maybeSingle()
const context = (data as { channel_context: InboxChannelContext | null } | null)
?.channel_context
return context ?? { channel: 'whatsapp' }
}
export async function updateItemContext(
supabase: SupabaseClient,
inboxItemId: string,
mutate: (context: InboxChannelContext) => InboxChannelContext,
): Promise<void> {
const current = await loadItemContext(supabase, inboxItemId)
await supabase
.from('invoice_inbox_items')
.update({ channel_context: mutate(current) as unknown as Record<string, unknown> })
.eq('id', inboxItemId)
}
export async function appendQuestionHistory(
supabase: SupabaseClient,
args: {
inboxItemId: string
eventType: 'ChannelQuestionAsked' | 'ChannelQuestionAnswered' | 'ChannelQuestionExpired'
questionType: string
correlationId?: string | null
},
): Promise<void> {
try {
const { data } = await supabase
.from('invoice_inbox_items')
.select('company_id, correlation_id')
.eq('id', args.inboxItemId)
.maybeSingle()
const item = data as { company_id: string; correlation_id: string | null } | null
if (!item) return
await appendProcessingHistory({
companyId: item.company_id,
correlationId: args.correlationId ?? item.correlation_id ?? args.inboxItemId,
aggregateType: 'System',
aggregateId: args.inboxItemId,
eventType: args.eventType,
payload: {
channel: 'whatsapp',
inbox_item_id: args.inboxItemId,
question_type: args.questionType,
},
actor: { type: 'system', id: 'whatsapp-inbound' },
occurredAt: new Date(),
})
} catch (err) {
log.error('question history append failed', err, { inboxItemId: args.inboxItemId })
}
}