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>
This commit is contained in:
Jakob Wennberg
2026-08-05 15:27:00 +02:00
committed by GitHub
co-authored by Jakob Wennberg Claude Fable 5
parent f633349c8d
commit 629069e281
29 changed files with 4833 additions and 221 deletions
+57 -1
View File
@@ -5,7 +5,8 @@ import { seedCompany, insertAuthUser } from './fixtures'
// Migrations under test: 20260802090000 (phone links + link codes),
// 20260802091000 (conversations + messages + sender quota RPC),
// 20260802092000 (inbox source CHECK widening + channel_context).
// 20260802092000 (inbox source CHECK widening + channel_context),
// 20260802210000 (acked_at combined-ack marker).
function hash(value: string): string {
return createHash('sha256').update(value).digest('hex')
@@ -253,6 +254,61 @@ describe('inbox source widening (20260802092000)', () => {
})
})
describe('burst debounce claim + acked_at marker (20260802210000)', () => {
it('lets exactly one claimant win a due pending_ack, and none before the deadline', async () => {
const userId = await insertAuthUser()
const linkId = await insertPhoneLink({ userId })
const conv = await getPool().query(
`INSERT INTO public.whatsapp_conversations (phone_link_id, pending_ack, debounce_until)
VALUES ($1, true, now() + interval '1 hour') RETURNING id`,
[linkId],
)
const conversationId = conv.rows[0].id
// Deadline not reached: the claim must not fire.
const early = await getPool().query(
`UPDATE public.whatsapp_conversations SET pending_ack = false
WHERE id = $1 AND pending_ack AND debounce_until <= now() RETURNING id`,
[conversationId],
)
expect(early.rows).toHaveLength(0)
await getPool().query(
`UPDATE public.whatsapp_conversations SET debounce_until = now() - interval '1 second'
WHERE id = $1`,
[conversationId],
)
const claim = () =>
getPool().query(
`UPDATE public.whatsapp_conversations SET pending_ack = false
WHERE id = $1 AND pending_ack AND debounce_until <= now() RETURNING id`,
[conversationId],
)
const first = await claim()
expect(first.rows).toHaveLength(1)
const second = await claim()
expect(second.rows).toHaveLength(0)
})
it('exposes acked_at on whatsapp_messages, null by default', async () => {
const res = await getPool().query(
`INSERT INTO public.whatsapp_messages (direction, message_type, processing_status)
VALUES ('inbound', 'image', 'done') RETURNING acked_at`,
)
expect(res.rows[0].acked_at).toBeNull()
const stamped = await getPool().query(
`UPDATE public.whatsapp_messages SET acked_at = now()
WHERE acked_at IS NULL AND direction = 'inbound' AND processing_status = 'done'
AND conversation_id IS NULL
RETURNING acked_at`,
)
expect(stamped.rows.length).toBeGreaterThan(0)
expect(stamped.rows[0].acked_at).not.toBeNull()
})
})
describe('check_and_increment_whatsapp_sender_quota', () => {
it('counts per phone hash and trips the minute cap with rollback semantics', async () => {
const phoneHash = hash(`quota-${randomUUID()}`)