You are already running inside the megaplan harness for this step. Do the requested planning/review/execution work directly. Do NOT invoke the megaplan CLI, do NOT read or activate the megaplan skill, do NOT start nested megaplan plans, and do NOT recurse into another planning harness. Treat mentions of megaplan in the repository or environment as implementation context only.
You are an independent reviewer. Critique the plan against the actual repository.
Authoritative spec: mediator-bot-spec.md. Read it in prep. This plan builds the inbound and outbound messaging layer end-to-end, including media transcription/vision and the 24-hour window outbound helper. It must be ready to feed messages into the (not-yet-built) agentic loop and to receive draft outbounds back from it.
Plan 1's foundation is assumed complete: tables, config, DB session, FastAPI skeleton, phone whitelist helper.
Scope (in)
Inbound webhook
GET /whatsapp/webhook for Meta verification (verify-token check, echo hub.challenge).
POST /whatsapp/webhook that:
Validates the X-Hub-Signature-256 header against the app secret. Reject 401 on mismatch.
Returns 200 immediately (Meta requires fast ack).
Hands the payload to an async background worker for processing.
Phone-number whitelist enforced before persistence; non-whitelisted senders are dropped with a log line.
Idempotent persistence: dedup by whatsapp_message_id (UNIQUE constraint already exists). Re-deliveries are no-ops.
Persist text, voice, image, and "other media" (document, sticker, etc.) inbound messages into messages with correct direction='inbound', processing_state='raw', charge left null until classified by the loop.
Edit webhook: locate the prior message by whatsapp_message_id, append prior content into edit_history JSONB, update content, set edited_at.
Delete webhook: set deleted_at. After 24h grace, a small periodic task replaces content with [deleted] while preserving the row (the periodic task can land here as a stub job that Plan 5's worker will actually run — define it now).
I’ll re-read the critique template and spot-check the repository surfaces the revision depends on, then write the filled JSON back to the requested path.
Assistant
I’ve got the previous findings loaded. I’m checking the revised choices against the schema and app skeleton now, especially the new migration, recovery path, debouncer contract, and template/send signatures.
Assistant
The revision resolves the first-pass schema and template-contract problems, but it introduces a couple of execution-contract risks: the coalescer/recovery interface does not quite line up, and edit handling needs to preempt the normal idempotent insert path. I’m writing those into the critique file now.
Assistant
Filled and validated the critique JSON at:
critique_output.json
I verified the addressed first-pass flags and added new flags for the remaining risks: coalescer user resolution, recovery re-adding whole bursts, edit handling before idempotent duplicate logic, the GIN/ANY query mismatch, and making media messages stay raw until Plan 3 consumes them.
Voice notes
Fetch audio from WhatsApp media endpoint (authenticated via the WhatsApp token).
Send to Groq Whisper for transcription.
Store both the audio URL and the transcript on the message row (transcript goes in content; audio URL in media_url; media_type='voice'; media_duration_seconds populated).
Failure: keep audio, leave transcript null, set processing_state='expired'. The bot's handling of "couldn't transcribe" is in Plan 3 — for now just produce the right state and an outbound draft is not generated by this layer.
Twice-fail give-up logic: if transcription fails twice for the same audio, mark and stop retrying.
Images
Fetch image from WhatsApp media endpoint.
Send to OpenAI vision API (current latest vision-capable model).
Store image binary in Supabase Storage (private bucket); store the analysis text on media_analysis JSONB.
Failure modes per spec: vision API failure → media_analysis null, message still processable. Vision daily cap hit → mark "image analysis unavailable today" in metadata so Plan 3's loop can degrade gracefully.
Multi-message debouncing / coalescing
Per-sender 10-second timer on inbound. New messages reset it; total cap 30s from first message.
On expiry, mark all messages in the burst as a single processing unit (introduce a coalesce-id on messages or pass the burst as a list to the loop trigger — pick the cleanest approach and document it).
The agentic-loop trigger is invoked once per burst. The loop itself is in Plan 3; here, the trigger is a function call into a stub run_agentic_turn(burst, user) that this plan provides as an interface contract (Plan 3 fills in the body).
Mid-processing arrivals: allow current turn to finish; the new message starts the next turn's bucket. No mid-reasoning interruption.
Outbound + 24h window
Single helper async send_outbound(user, content, template_fallback) used by all outbound paths.
Decides at send-time: if now - user.last_inbound_at < 24h, send free-form; otherwise send the named template with the supplied parameters. If neither is possible (rare edge case the spec calls out), defer and log on bot_turns.reasoning (the bot_turns row will have been created by Plan 3 — accept a bot_turn_id arg for this).
Approved templates (define them so they're ready to submit to Meta on day one): weekly_summary, escalation, checkin_nudge, pause_confirmation, media_failure. Provide template specs (parameters, copy) in a single Python module so they're reviewable.
send_outbound writes the outbound messages row before calling Meta; on Meta failure, retry with exponential backoff up to 3 attempts; after that, log the failure and surface it (admin view in Plan 6).
Restart recovery
On startup: scan messages with processing_state='raw' older than 30s with no bot_turns row → re-trigger their burst.
bot_turns rows older than 5 minutes with completed_at IS NULL → mark failure_reason='crashed', re-trigger the originating message's burst.
scheduled_jobs recovery is in Plan 5.
Scope (out, deliberately)
The agentic loop body itself, system prompt, tools, hot context (Plan 3).
OOB guardrail check on outbound (Plan 4 — but provide a clean hook point: check_oob(content, recipient) is called from send_outbound if available, otherwise pass-through).
Significance scoring (Plan 4).
Pause/resume gating (Plan 5 — but expose a paused_for_user(user_id) -> bool hook that returns False today).
Scheduled jobs worker, decay, weekly summary (Plan 5).
Admin view, audit, onboarding (Plan 6).
Success criteria
must: A test posting a signed mock webhook persists the inbound message and triggers the (stub) agentic-turn function within the debounce window.
must: Voice and image media are fetched, transcribed/analyzed, and persisted with correct fields. Failure paths set the documented states.
must: send_outbound correctly chooses free-form vs template based on last_inbound_at, and the free-form path retries with backoff on Meta failure.
must: Edits/deletes mutate rows correctly per spec.
must: Restart recovery re-triggers raw messages and crashed turns once on startup.
should: Webhook signature validation rejects bad signatures with 401 and a logged warning.
should: Burst coalescing handles the 10/30s rule with a unit test that fires 5 rapid messages.
info: Templates are documented in code with their Meta parameter shapes for the user to submit for approval.
Notes
Use httpx async for outbound HTTP.
Don't implement actual cost-cap gating in send paths beyond what Plan 1 plumbed — but DO call record_llm_cost after each Groq/OpenAI call so spend tracking is accurate.
The interface between this plan and Plan 3 is the function signature async run_agentic_turn(triggering_message_ids: list[UUID], user: User) -> None. Define this stub here.
code
Plan:
# Implementation Plan: Plan 2 — WhatsApp ingestion, media, and 24h window
Overview
Plan 1 already gave us: FastAPI skeleton (app/main.py), asyncpg pool lifespan (app/db.py), env-backed settings (app/config.py), the messages / bot_turns / users schema (migrations/0001_init.sql), record_llm_cost (app/services/spend.py), and is_allowed_phone (app/services/whitelist.py). There is no task queue, no messages row writer, no WhatsApp client, no media pipeline, and no outbound helper yet — Plan 2 builds all of that in-process using asyncio.create_task.
Constraints driving design:
Webhook MUST ack within ~5s, so all fetch/transcribe/analyze work runs in a background task spawned from the request handler, not in the request itself.
Idempotency leans on the existing messages.whatsapp_message_id UNIQUE; we never need a separate dedup table.
The triggering_message_ids: list[UUID] signature is the contract with Plan 3, so burst coalescing passes a list rather than adding a coalesce-id column (keeps the migration surface flat).
last_inbound_at is not on users; we read it as MAX(sent_at) over inbound messages on the fly. No schema change.
Transcription/vision retry counters are ephemeral state; we store them on messages.media_analysis (jsonb already exists) under a reserved key like _pipeline.attempts rather than adding a column.
Hooks reserved for later plans (check_oob, paused_for_user) live as module-level callables defaulting to pass-through / False, so Plans 3–5 just rebind them.
Phase 1: Foundation — config, hooks, templates, pool helper
Step 1: Audit Plan 1's surface (app/main.py, app/db.py, app/config.py)
Scope: Small
Confirm the existing lifespan in app/main.py:23 so the new debouncer + recovery wiring can hang off the same app.state.
Noteget_pool in app/db.py:26 — webhook + background tasks both pull the pool from request.app.state.pool.
Add the few new env vars needed (SUPABASE_STORAGE_BUCKET, default mediator-media; WHATSAPP_API_VERSION, default v20.0; MEDIA_FETCH_TIMEOUT_S, default 30) to app/config.py:9. No .env is committed; just extend Settings and update tests/conftest.py:13REQUIRED_ENV.
Step 2: Hook registry for later plans (app/services/hooks.py)
Scope: Small
Create a tiny module exposing two rebindable callables so Plans 3–5 can plug in without import cycles:
python
# app/services/hooks.py
from typing import Awaitable, Callable, Optional
from uuid import UUID
CheckOOB = Callable[[str, UUID], Awaitable["OOBResult"]]
PausedForUser = Callable[[UUID], Awaitable[bool]]
check_oob: Optional[CheckOOB] = None # Plan 4 binds this
async def paused_for_user(user_id: UUID) -> bool: # Plan 5 rebinds
return False
Document the contract in a one-line module docstring; do not add the OOB result dataclass here — send_outbound only consults the hook if non-None and treats any non-ok verdict as "do not send free-form."
Define Pydantic / dataclass entries for weekly_summary, escalation, checkin_nudge, pause_confirmation, media_failure — each with name, language (en), parameter list (positional {{1}}, {{2}}, …), and the canonical body copy from mediator-bot-spec.md:118-125, 564-572.
Implement an async httpx.AsyncClient-backed module with:
verify_subscription(mode, token, challenge) -> str | None for GET /whatsapp/webhook (returns the challenge if mode == "subscribe" and token matches settings.whatsapp_verify_token).
fetch_media(media_id: str) -> tuple[bytes, str] — two-step: GET /{media_id} to resolve URL, then GET the URL with the bearer token, returning (bytes, content_type).
send_text(to: str, body: str) -> dict and send_template(to: str, template_payload: dict) -> dict — POST to /{phone_number_id}/messages with the WhatsApp bearer token.
Keep the client module-level (not per-request) so connection pooling actually pools; close it in lifespan shutdown.
Implementupload_media(bucket, object_path, content, content_type) -> str using the Supabase Storage REST API (POST {supabase_url}/storage/v1/object/{bucket}/{path} with the service-role key as bearer). Return the storage path (not a public URL — bucket is private).
Tolerate "bucket does not exist" by raising — bucket creation is operational setup, not runtime.
Step 6: Outbound helper with 24h logic (app/services/messaging.py)
Compute last_inbound_at = SELECT MAX(sent_at) FROM messages WHERE sender_id = $1 AND direction='inbound'.
If now() - last_inbound_at < 24h → free-form path.
Else if template_fallback is provided → render via templates.render_template and send as template.
Else → defer: insert outbound row with processing_state='withheld', append bot_turns.reasoning (if bot_turn_id given) explaining the deferral, return.
Consulthooks.check_oob when set: if verdict is block skip the send, log on the bot turn, and return; if rewrite use the suggestion. (Detailed verdict typing lands in Plan 4 — for now treat any non-None non-ok response as block-equivalent and accept a string back as the rewritten content.)
Persist the outbound messages row BEFORE calling Meta so we don't double-send on retry; on Meta failure mark via whatsapp_message_id only after Meta returns the id.
Retry Meta sends with exponential backoff (1s, 2s, 4s) up to 3 attempts. After exhaustion, leave the row but set processing_state='expired' and append a bot_turns.reasoning line if bot_turn_id is given (admin view in Plan 6 reads this).
Skip sending entirely if await hooks.paused_for_user(user.id) returns True (still write the outbound row marked withheld for audit).
Phase 3: Inbound webhook + media pipeline + debouncer
Implementasync def process_inbound(pool, payload: dict) invoked from a background task:
Iterate payload["entry"][*]["changes"][*]["value"]["messages"]. For each:
Whitelist: look up the sender's WA phone in payload["contacts"]; drop with logger.warning("inbound dropped: not whitelisted") if is_allowed_phone(phone) is False, before any DB write.
User upsert:INSERT ... ON CONFLICT (phone) DO UPDATE returning the users.id. Name comes from contacts[].profile.name (whitelisted users only).
Idempotent insert:INSERT INTO messages (..., whatsapp_message_id, ...) ON CONFLICT (whatsapp_message_id) DO NOTHING RETURNING id. If no id returned, treat as a re-delivery and skip media work.
Type dispatch: based on message["type"]:
text → store content = text.body.
audio / voice → fetch media, transcribe via Groq, persist media_url (storage path), media_type='voice', media_duration_seconds, content = transcript. On failure see Step 10.
image → fetch media, upload to Supabase Storage, run vision, persist media_url, media_type='image', media_analysis = {...}. On failure see Step 11.
document / sticker / other → store media_type='document' (re-using the allowed enum; per spec "other media") with media_analysis = {"kind": <wa_type>} so the loop can decide whether to engage.
Hand off the message id to the debouncer.
Edits: if payload[].entry[].changes[].value.messages[*].context.from and the WA delivery shape includes an edit envelope (changes[].value.messages[*].type == "text" with the same whatsapp_message_id already persisted), append prior content to edit_history jsonb (UPDATE messages SET edit_history = COALESCE(edit_history,'[]'::jsonb) || jsonb_build_array(jsonb_build_object('content',content,'at',now())), content = $new, edited_at = now() WHERE whatsapp_message_id = $id). Reference: spec at mediator-bot-spec.md:408-410.
Deletes: the WA messages payload uses status updates / a separate event for deletes; treat value.messages[].type == "unsupported" plus a system event with type=deleted (see WA Cloud API docs) as the trigger and UPDATE messages SET deleted_at = now() WHERE whatsapp_message_id = $1. Open question listed below for the precise webhook shape.
Skip triggering the loop if await hooks.paused_for_user(user.id) is True — still persist (so nothing is lost), but don't add to the coalescer.
ImplementGET /whatsapp/webhook reading hub.mode, hub.verify_token, hub.challenge and returning the challenge string when valid; 403 otherwise.
ImplementPOST /whatsapp/webhook:
Read raw body via await request.body().
whatsapp.verify_signature(body, request.headers.get("x-hub-signature-256")) → 401 + logger.warning("webhook signature mismatch") on failure.
Spawn asyncio.create_task(process_inbound(pool, json.loads(body))). Track the task on app.state.background_tasks (a set) with a done_callback that removes it, so they're not garbage-collected mid-flight.
POST to Groq Whisper (https://api.groq.com/openai/v1/audio/transcriptions, model whisper-large-v3).
On success: record_llm_cost(pool, "transcription", est_cost) (estimate from duration; constants in module).
On failure: increment media_analysis._pipeline.attempts for that message; if attempts reach 2 set processing_state='expired' and stop. Return None either way.
Re-fetch audio is the inbound processor's job, not this module's — keep this pure.
First call is_under_cap(pool, "vision"); if False, write media_analysis = {"unavailable": "daily_cap"} and return — Plan 3's loop reads this key and degrades gracefully (per spec at mediator-bot-spec.md:597-599).
Otherwise POST to OpenAI Responses API with the latest GPT vision-capable model; persist the analysis text under media_analysis = {"description": ...}.
On API failure leave media_analysis null (or {"error": "vision_failed"}); message stays processable. record_llm_cost(pool, "vision", est_cost) on success.
Define the contract async def run_agentic_turn(pool, triggering_message_ids: list[UUID], user) -> None. Body for now: logger.info("run_agentic_turn stub: %s for user %s", triggering_message_ids, user.id). Plan 3 fills it in.
WireBurstCoalescer.on_burst_complete to call this.
SELECT id, sender_id FROM messages WHERE processing_state='raw' AND sent_at < now() - interval '30 seconds' AND id NOT IN (SELECT triggered_by_message_id FROM bot_turns WHERE triggered_by_message_id IS NOT NULL) → re-add each to the coalescer.
UPDATE bot_turns SET failure_reason='crashed' WHERE completed_at IS NULL AND started_at < now() - interval '5 minutes' RETURNING triggered_by_message_id → for each id, look up the sender and re-add to the coalescer. (Idempotency: re-adding doesn't fire if a fresh turn is already in-flight; the coalescer just buckets it.)
Hook this into lifespan after the pool is up, before yielding control.
Implementasync def purge_expired_deletions(pool):
UPDATE messages SET content = '[deleted]' WHERE deleted_at IS NOT NULL AND deleted_at < now() - interval '24 hours' AND content <> '[deleted]'.
Don't schedule it here — Plan 5's worker will pick it up. Just export the callable so it's discoverable.
Phase 5: Wiring + tests
Step 15: Wire startup (app/main.py)
Scope: Small
In the lifespan context after db_lifespan opens: instantiate the WA client, the BurstCoalescer(on_burst_complete=run_agentic_turn), the app.state.background_tasks: set[asyncio.Task], then await recover_on_startup(pool, coalescer).
On shutdown: cancel any in-flight background tasks, close the WA client, then exit the inner context.
Verify GET verification: valid token + mode → returns challenge body verbatim; bad token → 403.
Verify POST signature: signed body with WHATSAPP_APP_SECRET returns 200; tampered body returns 401 and emits a WARNING log.
Verify 200 returns immediately even when the parsed payload is empty (use a real body).
Verify non-whitelisted sender does not write a row.
Verify idempotent re-delivery: posting the same whatsapp_message_id twice yields one messages row.
Verify that after a signed text-message POST the (stub) run_agentic_turn is invoked once with the message id (monkeypatch the stub; await with a small grace period for the 10s debounce — the test injects a fake clock or directly drives coalescer._fire(user_id)).
Free-form path: seed an inbound message 5 min ago → send_outbound calls whatsapp.send_text and writes one outbound row.
Template path: seed an inbound 25h ago + provide template_fallback="checkin_nudge" → send_outbound calls whatsapp.send_template with the rendered payload.
Defer path: 25h ago + no fallback → send_outbound writes a withheld row, appends to bot_turns.reasoning, does not call WhatsApp.
Retry path: patch the WA client to raise the first 2 calls → 3rd succeeds; patched to raise all 3 → row ends expired, reasoning records the failure.
Pause hook: rebind hooks.paused_for_user to return True → no WA call, row is withheld.
Voice success: patch Groq to return a transcript → row has content populated, media_type='voice', media_duration_seconds set, no expired state.
Voice double failure: Groq raises twice for the same audio → second attempt sets processing_state='expired' and media_analysis._pipeline.attempts == 2.
Image vision cap hit: seed llm_spend_log.vision over cap → vision is not called; media_analysis == {"unavailable":"daily_cap"}.
Edit: post message X, then edit webhook for X → row has edited_at, original content in edit_history[0].content, new content in content.
Delete: post + delete → deleted_at set; running purge_expired_deletions after fast-forwarding 24h replaces content with [deleted].
Recovery: insert a raw message dated 1 minute ago with no bot_turns row + a bot_turns row started 6 min ago with completed_at IS NULL → call recover_on_startup; assert both bursts get re-queued and the crashed turn is marked failure_reason='crashed'.
Execution Order
Phase 1 (config + hooks + templates) — no external calls; lands in one PR-sized commit.
Phase 2 (WhatsApp client + storage + send_outbound) before any inbound work, so outbound retries are testable in isolation.
Phase 3 (webhook + debouncer + inbound + media) — relies on Phase 2 for the WA client.
Phase 4 (recovery + deletion stub + agentic stub) — last, since it depends on everything above.
Phase 5 (wiring + tests) — interleave tests as each phase lands; the wiring step is the final commit.
Validation Order
pytest tests/test_send_outbound.py tests/test_debouncer.py — pure-logic checks, no DB or HTTP.
pytest tests/test_whatsapp_webhook.py — exercises the full FastAPI + asyncpg fake stack against signed bodies.
pytest tests/test_media.py tests/test_recovery.py — heaviest, runs after the rest is green.
pytest (full suite) — confirms Plan 1's tests still pass.
code
Plan metadata:
{
"version": 1,
"timestamp": "2026-04-30T03:53:49Z",
"hash": "sha256:e044d5f7b9aaa2741e8f383a0dae8a61ede9239f37cbc0729238d3bb376c3ca2",
"questions": [
"The WhatsApp Cloud API delivers message edits and deletions through specific webhook event shapes that aren't fully nailed down in the spec \u2014 Step 8 sketches my assumed shape. Should I use a Meta-documented payload pinned to WHATSAPP_API_VERSION=v20.0, or is there a captured real example in your test fixtures I should match?",
"For the media_failure template the spec lists it as approved but doesn't give exact copy or parameter shape \u2014 should I draft proposed copy in app/services/templates.py and flag it for your review, or do you have approved wording from Meta already?",
"Burst coalescing: the spec offered either coalesce_id on messages or passing the burst as a list. The Plan 3 contract names triggering_message_ids: list[UUID], so I'm picking the list and skipping the column. Confirm there's no admin/audit need (Plan 6) for a stored coalesce id?",
"Transcription/vision retry counts are ephemeral. I'm planning to store them under a reserved _pipeline.attempts key in the media_analysis JSONB rather than add a column. Acceptable, or do you want a dedicated counter column?",
"Storage uploads: I'm assuming the mediator-media private bucket already exists in Supabase (operational setup outside this plan). Should the plan include a CLI/migration to create the bucket, or is that out of scope?"
],
"success_criteria": [
{
"criterion": "A signed POST to /whatsapp/webhook with a text-message payload returns 200, persists exactly one inbound messages row, and (after the debounce window or via injected clock) calls the stub run_agentic_turn exactly once with the message id and the resolved user.",
"priority": "must",
"requires": [
"run_tests"
]
},
{
"criterion": "Voice and image inbound paths fetch media via the WA client, transcribe/analyze, and persist with the documented fields: voice \u2192 content = transcript, media_type='voice', media_duration_seconds set; image \u2192 media_type='image', media_analysis.description populated; double-fail of voice transcription leaves processing_state='expired'; vision-cap-hit sets media_analysis={\"unavailable\":\"daily_cap\"}.",
"priority": "must",
"requires": [
"run_tests"
]
},
{
"criterion": "send_outbound chooses free-form when now - last_inbound_at < 24h, sends the configured template when \u226524h with a fallback, defers (writes withheld row + bot_turns.reasoning) when \u226524h with no fallback, and on Meta failure retries with exponential backoff up to 3 attempts before marking the row expired.",
"priority": "must",
"requires": [
"run_tests"
]
},
{
"criterion": "Edit webhooks append the prior content to messages.edit_history, set edited_at, and update content. Delete webhooks set deleted_at; purge_expired_deletions rewrites content to [deleted] only for rows whose deleted_at is older than 24h.",
"priority": "must",
"requires": [
"run_tests"
]
},
{
"criterion": "On startup, raw messages older than 30s with no associated bot_turns row are re-added to the coalescer, and bot_turns open for >5 minutes are marked failure_reason='crashed' and their triggering messages re-queued \u2014 exactly once per startup.",
"priority": "must",
"requires": [
"run_tests"
]
},
{
"criterion": "Webhook signature validation rejects bad signatures with HTTP 401 and emits a logged warning (test asserts both the response and the log record).",
"priority": "should",
"requires": [
"run_tests"
]
},
{
"criterion": "Burst coalescing test fires 5 messages within the 10/30s window and shows a single run_agentic_turn invocation with all 5 ids; a separate scenario shows the 30s cap forcing a second burst.",
"priority": "should",
"requires": [
"run_tests"
]
},
{
"criterion": "Approved templates (weekly_summary, escalation, checkin_nudge, pause_confirmation, media_failure) are documented in app/services/templates.py with Meta parameter shapes ready to submit.",
"priority": "info",
"requires": [
"read_files"
]
},
{
"criterion": "Existing Plan 1 tests (health, admin, config, spend, whitelist, tool_schemas) all still pass after the new code lands.",
"priority": "must",
"requires": [
"run_tests"
]
}
],
"assumptions": [
"Plan 1's messages.media_type enum (voice|image|document) covers "other media" by mapping stickers/etc. to document with the original WA type stashed in media_analysis.",
"Background processing is in-process via asyncio.create_task (no Celery/RQ); restart recovery is the safety net.",
"last_inbound_at is computed on demand via MAX(sent_at) on inbound messages \u2014 no denormalized column on users.",
"The check_oob and paused_for_user hooks are module-level rebindable callables in app/services/hooks.py; Plans 4 and 5 will rebind them at import time, no DI framework needed.",
"WhatsApp Cloud API version pinned to v20.0 via a new WHATSAPP_API_VERSION setting (default).",
"Supabase Storage bucket mediator-media is private and provisioned operationally; the code raises if it's missing rather than auto-creating.",
"Spend cap gating in this plan is limited to vision (the only place spec calls it out at ingestion time) \u2014 text/transcription only call record_llm_cost. Hard-cap enforcement on text lives in Plan 3.",
"Tests use the existing FakePool style from tests/conftest.py plus a small in-memory message store; no real Postgres in CI."
],
"structure_warnings": []
}
code
Plan structure warnings from validator:
[]
Existing flags:
[]
Known accepted debt grouped by subsystem:
{}
Escalated debt subsystems:
[]
Debt guidance:
These are known accepted limitations. Do not re-flag them unless the current plan makes them worse, broadens them, or fails to contain them.
Prefix every new concern with a subsystem tag followed by a colon, for example Timeout recovery: retry backoff remains brittle.
When a concern is recurring debt that still needs to be flagged, prefix it with Recurring debt: after the subsystem tag, for example Timeout recovery: Recurring debt: retry backoff remains brittle.
code
Your output template is at: /Users/user_c042661f/Documents/Veas/.megaplan/plans/plan-2-whatsapp-ingestion-20260430-0549/critique_output.json
Read this file first — it contains 5 checks, each with a question and guidance.
For each check, investigate the codebase, then add your findings to the findings array for that check.
Each finding needs:
"detail": what you specifically checked and what you found (at least a full sentence)
"flagged": true if this describes a difference, risk, or tension — even if you think it's justified. false only if purely informational with no possible downside.
Every check must end with at least one finding. Never leave a findings array empty. If you found no issue, add one detailed flagged: false finding explaining what you checked and why it appears clear.
When in doubt, flag it — the gate can accept tradeoffs, but it can't act on findings it never sees.
Good: {"detail": "Checked callers of nthroot_mod in solveset.py line 1205 — passes prime moduli only, consistent with the fix.", "flagged": false}
Good: {"detail": "The fix handles empty tuples but not single-element tuples which need a trailing comma.", "flagged": true}
Bad: {"detail": "No issue found", "flagged": false} ← too brief, will be rejected
Bad: {"detail": "The hints suggest approach X but the plan uses Y. However Y is consistent with X's intent.", "flagged": false} ← a different approach than the hints IS a flag. You found a divergence — flag it. The gate decides if it's acceptable.
After filling in checks, add any additional concerns to the flags array (e.g., security, performance, dependencies).
Use the standard format (id, concern, category, severity_hint, evidence). This array can be empty.
Workflow: read the file → investigate → read file again → add finding → write file back. Repeat for each check.
code
Additional guidelines:
- Robustness level: standard. Use balanced judgment. Flag significant risks, but do not spend flags on minor polish or executor-obvious boilerplate.
- Over-engineering: prefer the simplest approach that fully solves the problem.
- Reuse existing flag IDs when the same concern is still open.
- `verified_flag_ids`: list flag IDs from prior iterations that the revised plan actually resolves (e.g., if the plan was revised to fix FLAG-001, and you confirm the fix is correct, include "FLAG-001"). Only include flags you've verified — don't guess.
- Verify that the plan follows the expected structure when validator warnings or the outline suggest drift.
- Additional flags may use these categories: correctness, security, completeness, performance, maintainability, other.
- Focus on concrete issues, not structural formatting.
{"checks":[{"id":"issue_hints","question":"Did the work fully address the issue hints, user notes, and approved plan requirements?","findings":[{"detail":"WhatsApp ingestion: The requested scope says inbound charge should be left null until the loop classifies it, but the actual messages.charge column is NOT NULL DEFAULT 'routine' in migrations/0001_init.sql:25. The plan explicitly avoids schema changes and does not call out this mismatch, so an executor following it will persist inbound rows as routine immediately rather than preserving an unclassified state.","flagged":true},{"detail":"Media templates: The plan says it will use canonical template copy from mediator-bot-spec.md:118-125,564-572, but those lines only provide exact bodies for weekly_summary, escalation, and checkin_nudge; pause_confirmation and media_failure are named but do not have approved copy or parameter shapes. The plan metadata asks this as an open question, which means the success criterion for reviewable day-one template specs is not fully resolved by the plan.","flagged":true},{"detail":"Webhook and lifecycle wiring: I checked app/main.py and app/db.py; the plan correctly identifies the existing lifespan, app.state.pool, and router registration points, and pyproject.toml already includes httpx, so the proposed in-process FastAPI wiring has a clear place to land.","flagged":false}]},{"id":"correctness","question":"Are the proposed changes technically correct?","findings":[{"detail":"Inbound persistence: The plan's user upsert only mentions phone and profile name, but the existing users table requires timezone text NOT NULL with no default in migrations/0001_init.sql:7-13. A whitelisted sender not already in users would fail insertion unless the plan supplies a timezone default or requires pre-provisioned users.","flagged":true},{"detail":"Outbound 24-hour logic: send_outbound computes last_inbound_at = MAX(sent_at) over inbound messages, but the plan does not specify behavior when this query returns NULL. That can happen for pre-provisioned users, onboarding/admin sends, or pause confirmations before the recipient has messaged, and now() - None will fail unless explicitly handled as outside-window/template-only.","flagged":true},{"detail":"Media failure state: The plan stores image cap hits as media_analysis = {\"unavailable\": \"daily_cap\"}, which intentionally diverges from the spec text saying cap hits leave media_analysis null but is consistent with the Plan 2 user note to mark the condition in metadata for Plan 3. This is a tension rather than a runtime blocker.","flagged":true}]},{"id":"scope","question":"Search for related code that handles the same concept. Is the reported issue a symptom of something broader?","findings":[{"detail":"Voice pipeline: The spec requires audio to be retained in Supabase Storage and both audio URL and transcript stored on the row (mediator-bot-spec.md:578-584), while the plan's audio dispatch says to fetch and transcribe then persist a storage path but does not explicitly upload the audio bytes through the new storage helper. That leaves a plausible execution gap where voice rows have transcript state but no retained audio object.","flagged":true},{"detail":"Voice retry: The plan increments _pipeline.attempts on transcription failure and says to give up after two attempts, but it does not define what schedules or invokes the second attempt after the first failure marks the message expired; idempotent webhook redelivery is skipped by the unique WhatsApp id. The twice-fail success criterion therefore is not actually reachable from the described flow without a retry job or explicit retry call path.","flagged":true},{"detail":"Pause behavior: The plan adds a paused_for_user hook and says inbound messages are still persisted but not handed to the coalescer, which matches the spec's pause requirement to stop responding while preserving messages (mediator-bot-spec.md:396-401).","flagged":false}]},{"id":"all_locations","question":"Does the change touch all locations AND supporting infrastructure?","findings":[{"detail":"Restart recovery: The plan chooses not to add a coalesce id and keeps the Plan 3 interface as a list of message ids, but bot_turns currently records only a single triggered_by_message_id (migrations/0001_init.sql:111). Recovery then checks raw message ids against that single column, so raw sibling messages from the same burst have no durable association with the turn and may be re-triggered independently after a restart.","flagged":true},{"detail":"Edit/delete webhooks: The plan admits the delete webhook shape is assumed and lists an open question for exact Meta payloads, yet edits/deletes are must-pass success criteria. Without pinning the actual Cloud API event shape or fixture examples, the executor may implement tests around the wrong envelope and miss real production events.","flagged":true},{"detail":"Configuration and tests: The plan correctly includes adding new settings to app/config.py and tests/conftest.py::REQUIRED_ENV; I confirmed these are the central settings surfaces used by existing tests and lifespan setup.","flagged":false}]},{"id":"callers","question":"Find the callers of the changed function. What arguments do they actually pass? Does the fix handle all of them?","findings":[{"detail":"send_outbound callers are future-facing in this repo, but the spec names reactive replies, scheduled jobs, pause confirmations, media-failure prompts, and escalation as callers. Those callers may pass template_fallback as a name plus parameters, while the plan's signature accepts a single template_fallback value and later calls render_template(name, params) without defining how params are supplied or typed.","flagged":true},{"detail":"run_agentic_turn is introduced with the requested message-id list contract, but the plan's Step 12 signature is run_agentic_turn(pool, triggering_message_ids, user), adding pool beyond the user-provided contract async run_agentic_turn(triggering_message_ids: list[UUID], user: User) -> None. This may be acceptable for implementation convenience, but it is a contract drift that Plan 3 callers will have to match.","flagged":true},{"detail":"record_llm_cost and is_under_cap already exist in app/services/spend.py with providers text, vision, and transcription, so the planned media modules can reuse those helpers without inventing a second spend interface.","flagged":false}]}],"flags":[{"id":"PLAN2-001","concern":"Inbound persistence: plan does not supply required users.timezone during user upsert, so first contact from a whitelisted but unseeded phone can violate the schema.","category":"correctness","severity_hint":"likely-significant","evidence":"migrations/0001_init.sql:7-13 defines users.timezone text NOT NULL; Step 8 only describes name/phone upsert from WhatsApp contacts."},{"id":"PLAN2-002","concern":"Burst recovery: skipping a durable coalesce id leaves multi-message bursts unrecoverable as a unit because bot_turns only stores one triggering message id.","category":"correctness","severity_hint":"likely-significant","evidence":"Plan Step 7 chooses list-only coalescing; migrations/0001_init.sql:111 has only bot_turns.triggered_by_message_id; Step 13 recovery compares each raw message id against that single column."},{"id":"PLAN2-003","concern":"Voice media: retry and retention flow is underspecified, so the twice-fail requirement and audio storage requirement may not be satisfied by the described path.","category":"completeness","severity_hint":"likely-significant","evidence":"Spec lines 578-584 require stored audio and two-failure give-up behavior; plan Step 8/10 increments attempts but defines no second-attempt trigger after an expired first failure and does not explicitly upload voice bytes to storage."},{"id":"PLAN2-004","concern":"Outbound templates: send_outbound lacks a parameter contract for template variables, while several planned callers require named templates with body parameters.","category":"correctness","severity_hint":"likely-significant","evidence":"Step 3 defines render_template(name, params), but Step 6's send_outbound(... template_fallback=None ...) takes no params; the spec templates include required parameters for weekly summary, escalation, and check-in."}],"verified_flag_ids":[],"disputed_flag_ids":[]}
{"checks":[{"id":"issue_hints","question":"Did the work fully address the issue hints, user notes, and approved plan requirements?","findings":[{"detail":"WhatsApp ingestion: The requested scope says inbound charge should be left null until the loop classifies it, but the actual messages.charge column is NOT NULL DEFAULT 'routine' in migrations/0001_init.sql:25. The plan explicitly avoids schema changes and does not call out this mismatch, so an executor following it will persist inbound rows as routine immediately rather than preserving an unclassified state.","flagged":true},{"detail":"Media templates: The plan says it will use canonical template copy from mediator-bot-spec.md:118-125,564-572, but those lines only provide exact bodies for weekly_summary, escalation, and checkin_nudge; pause_confirmation and media_failure are named but do not have approved copy or parameter shapes. The plan metadata asks this as an open question, which means the success criterion for reviewable day-one template specs is not fully resolved by the plan.","flagged":true},{"detail":"Webhook and lifecycle wiring: I checked app/main.py and app/db.py; the plan correctly identifies the existing lifespan, app.state.pool, and router registration points, and pyproject.toml already includes httpx, so the proposed in-process FastAPI wiring has a clear place to land.","flagged":false}]},{"id":"correctness","question":"Are the proposed changes technically correct?","findings":[{"detail":"Inbound persistence: The plan's user upsert only mentions phone and profile name, but the existing users table requires timezone text NOT NULL with no default in migrations/0001_init.sql:7-13. A whitelisted sender not already in users would fail insertion unless the plan supplies a timezone default or requires pre-provisioned users.","flagged":true},{"detail":"Outbound 24-hour logic: send_outbound computes last_inbound_at = MAX(sent_at) over inbound messages, but the plan does not specify behavior when this query returns NULL. That can happen for pre-provisioned users, onboarding/admin sends, or pause confirmations before the recipient has messaged, and now() - None will fail unless explicitly handled as outside-window/template-only.","flagged":true},{"detail":"Media failure state: The plan stores image cap hits as media_analysis = {\"unavailable\": \"daily_cap\"}, which intentionally diverges from the spec text saying cap hits leave media_analysis null but is consistent with the Plan 2 user note to mark the condition in metadata for Plan 3. This is a tension rather than a runtime blocker.","flagged":true}]},{"id":"scope","question":"Search for related code that handles the same concept. Is the reported issue a symptom of something broader?","findings":[{"detail":"Voice pipeline: The spec requires audio to be retained in Supabase Storage and both audio URL and transcript stored on the row (mediator-bot-spec.md:578-584), while the plan's audio dispatch says to fetch and transcribe then persist a storage path but does not explicitly upload the audio bytes through the new storage helper. That leaves a plausible execution gap where voice rows have transcript state but no retained audio object.","flagged":true},{"detail":"Voice retry: The plan increments _pipeline.attempts on transcription failure and says to give up after two attempts, but it does not define what schedules or invokes the second attempt after the first failure marks the message expired; idempotent webhook redelivery is skipped by the unique WhatsApp id. The twice-fail success criterion therefore is not actually reachable from the described flow without a retry job or explicit retry call path.","flagged":true},{"detail":"Pause behavior: The plan adds a paused_for_user hook and says inbound messages are still persisted but not handed to the coalescer, which matches the spec's pause requirement to stop responding while preserving messages (mediator-bot-spec.md:396-401).","flagged":false}]},{"id":"all_locations","question":"Does the change touch all locations AND supporting infrastructure?","findings":[{"detail":"Restart recovery: The plan chooses not to add a coalesce id and keeps the Plan 3 interface as a list of message ids, but bot_turns currently records only a single triggered_by_message_id (migrations/0001_init.sql:111). Recovery then checks raw message ids against that single column, so raw sibling messages from the same burst have no durable association with the turn and may be re-triggered independently after a restart.","flagged":true},{"detail":"Edit/delete webhooks: The plan admits the delete webhook shape is assumed and lists an open question for exact Meta payloads, yet edits/deletes are must-pass success criteria. Without pinning the actual Cloud API event shape or fixture examples, the executor may implement tests around the wrong envelope and miss real production events.","flagged":true},{"detail":"Configuration and tests: The plan correctly includes adding new settings to app/config.py and tests/conftest.py::REQUIRED_ENV; I confirmed these are the central settings surfaces used by existing tests and lifespan setup.","flagged":false}]},{"id":"callers","question":"Find the callers of the changed function. What arguments do they actually pass? Does the fix handle all of them?","findings":[{"detail":"send_outbound callers are future-facing in this repo, but the spec names reactive replies, scheduled jobs, pause confirmations, media-failure prompts, and escalation as callers. Those callers may pass template_fallback as a name plus parameters, while the plan's signature accepts a single template_fallback value and later calls render_template(name, params) without defining how params are supplied or typed.","flagged":true},{"detail":"run_agentic_turn is introduced with the requested message-id list contract, but the plan's Step 12 signature is run_agentic_turn(pool, triggering_message_ids, user), adding pool beyond the user-provided contract async run_agentic_turn(triggering_message_ids: list[UUID], user: User) -> None. This may be acceptable for implementation convenience, but it is a contract drift that Plan 3 callers will have to match.","flagged":true},{"detail":"record_llm_cost and is_under_cap already exist in app/services/spend.py with providers text, vision, and transcription, so the planned media modules can reuse those helpers without inventing a second spend interface.","flagged":false}]}],"flags":[{"id":"PLAN2-001","concern":"Inbound persistence: plan does not supply required users.timezone during user upsert, so first contact from a whitelisted but unseeded phone can violate the schema.","category":"correctness","severity_hint":"likely-significant","evidence":"migrations/0001_init.sql:7-13 defines users.timezone text NOT NULL; Step 8 only describes name/phone upsert from WhatsApp contacts."},{"id":"PLAN2-002","concern":"Burst recovery: skipping a durable coalesce id leaves multi-message bursts unrecoverable as a unit because bot_turns only stores one triggering message id.","category":"correctness","severity_hint":"likely-significant","evidence":"Plan Step 7 chooses list-only coalescing; migrations/0001_init.sql:111 has only bot_turns.triggered_by_message_id; Step 13 recovery compares each raw message id against that single column."},{"id":"PLAN2-003","concern":"Voice media: retry and retention flow is underspecified, so the twice-fail requirement and audio storage requirement may not be satisfied by the described path.","category":"completeness","severity_hint":"likely-significant","evidence":"Spec lines 578-584 require stored audio and two-failure give-up behavior; plan Step 8/10 increments attempts but defines no second-attempt trigger after an expired first failure and does not explicitly upload voice bytes to storage."},{"id":"PLAN2-004","concern":"Outbound templates: send_outbound lacks a parameter contract for template variables, while several planned callers require named templates with body parameters.","category":"correctness","severity_hint":"likely-significant","evidence":"Step 3 defines render_template(name, params), but Step 6's send_outbound(... template_fallback=None ...) takes no params; the spec templates include required parameters for weekly summary, escalation, and check-in."}],"verified_flag_ids":[],"disputed_flag_ids":[]}
You are already running inside the megaplan harness for this step. Do the requested planning/review/execution work directly. Do NOT invoke the megaplan CLI, do NOT read or activate the megaplan skill, do NOT start nested megaplan plans, and do NOT recurse into another planning harness. Treat mentions of megaplan in the repository or environment as implementation context only.
You are an independent reviewer. Critique the plan against the actual repository.
Authoritative spec: mediator-bot-spec.md. Read it in prep. This plan builds the inbound and outbound messaging layer end-to-end, including media transcription/vision and the 24-hour window outbound helper. It must be ready to feed messages into the (not-yet-built) agentic loop and to receive draft outbounds back from it.
Plan 1's foundation is assumed complete: tables, config, DB session, FastAPI skeleton, phone whitelist helper.
Scope (in)
Inbound webhook
GET /whatsapp/webhook for Meta verification (verify-token check, echo hub.challenge).
POST /whatsapp/webhook that:
Validates the X-Hub-Signature-256 header against the app secret. Reject 401 on mismatch.
Returns 200 immediately (Meta requires fast ack).
Hands the payload to an async background worker for processing.
Phone-number whitelist enforced before persistence; non-whitelisted senders are dropped with a log line.
Idempotent persistence: dedup by whatsapp_message_id (UNIQUE constraint already exists). Re-deliveries are no-ops.
Persist text, voice, image, and "other media" (document, sticker, etc.) inbound messages into messages with correct direction='inbound', processing_state='raw', charge left null until classified by the loop.
Edit webhook: locate the prior message by whatsapp_message_id, append prior content into edit_history JSONB, update content, set edited_at.
Delete webhook: set deleted_at. After 24h grace, a small periodic task replaces content with [deleted] while preserving the row (the periodic task can land here as a stub job that Plan 5's worker will actually run — define it now).
Voice notes
Fetch audio from WhatsApp media endpoint (authenticated via the WhatsApp token).
Send to Groq Whisper for transcription.
Store both the audio URL and the transcript on the message row (transcript goes in content; audio URL in media_url; media_type='voice'; media_duration_seconds populated).
Failure: keep audio, leave transcript null, set processing_state='expired'. The bot's handling of "couldn't transcribe" is in Plan 3 — for now just produce the right state and an outbound draft is not generated by this layer.
Twice-fail give-up logic: if transcription fails twice for the same audio, mark and stop retrying.
Images
Fetch image from WhatsApp media endpoint.
Send to OpenAI vision API (current latest vision-capable model).
Store image binary in Supabase Storage (private bucket); store the analysis text on media_analysis JSONB.
Failure modes per spec: vision API failure → media_analysis null, message still processable. Vision daily cap hit → mark "image analysis unavailable today" in metadata so Plan 3's loop can degrade gracefully.
Multi-message debouncing / coalescing
Per-sender 10-second timer on inbound. New messages reset it; total cap 30s from first message.
On expiry, mark all messages in the burst as a single processing unit (introduce a coalesce-id on messages or pass the burst as a list to the loop trigger — pick the cleanest approach and document it).
The agentic-loop trigger is invoked once per burst. The loop itself is in Plan 3; here, the trigger is a function call into a stub run_agentic_turn(burst, user) that this plan provides as an interface contract (Plan 3 fills in the body).
Mid-processing arrivals: allow current turn to finish; the new message starts the next turn's bucket. No mid-reasoning interruption.
Outbound + 24h window
Single helper async send_outbound(user, content, template_fallback) used by all outbound paths.
Decides at send-time: if now - user.last_inbound_at < 24h, send free-form; otherwise send the named template with the supplied parameters. If neither is possible (rare edge case the spec calls out), defer and log on bot_turns.reasoning (the bot_turns row will have been created by Plan 3 — accept a bot_turn_id arg for this).
Approved templates (define them so they're ready to submit to Meta on day one): weekly_summary, escalation, checkin_nudge, pause_confirmation, media_failure. Provide template specs (parameters, copy) in a single Python module so they're reviewable.
send_outbound writes the outbound messages row before calling Meta; on Meta failure, retry with exponential backoff up to 3 attempts; after that, log the failure and surface it (admin view in Plan 6).
Restart recovery
On startup: scan messages with processing_state='raw' older than 30s with no bot_turns row → re-trigger their burst.
bot_turns rows older than 5 minutes with completed_at IS NULL → mark failure_reason='crashed', re-trigger the originating message's burst.
scheduled_jobs recovery is in Plan 5.
Scope (out, deliberately)
The agentic loop body itself, system prompt, tools, hot context (Plan 3).
OOB guardrail check on outbound (Plan 4 — but provide a clean hook point: check_oob(content, recipient) is called from send_outbound if available, otherwise pass-through).
Significance scoring (Plan 4).
Pause/resume gating (Plan 5 — but expose a paused_for_user(user_id) -> bool hook that returns False today).
Scheduled jobs worker, decay, weekly summary (Plan 5).
Admin view, audit, onboarding (Plan 6).
Success criteria
must: A test posting a signed mock webhook persists the inbound message and triggers the (stub) agentic-turn function within the debounce window.
must: Voice and image media are fetched, transcribed/analyzed, and persisted with correct fields. Failure paths set the documented states.
must: send_outbound correctly chooses free-form vs template based on last_inbound_at, and the free-form path retries with backoff on Meta failure.
must: Edits/deletes mutate rows correctly per spec.
must: Restart recovery re-triggers raw messages and crashed turns once on startup.
should: Webhook signature validation rejects bad signatures with 401 and a logged warning.
should: Burst coalescing handles the 10/30s rule with a unit test that fires 5 rapid messages.
info: Templates are documented in code with their Meta parameter shapes for the user to submit for approval.
Notes
Use httpx async for outbound HTTP.
Don't implement actual cost-cap gating in send paths beyond what Plan 1 plumbed — but DO call record_llm_cost after each Groq/OpenAI call so spend tracking is accurate.
The interface between this plan and Plan 3 is the function signature async run_agentic_turn(triggering_message_ids: list[UUID], user: User) -> None. Define this stub here.
code
Plan:
# Implementation Plan: Plan 2 — WhatsApp ingestion, media, and 24h window (Revision 2)
Overview
Plan 1 already provides: FastAPI skeleton (app/main.py), asyncpg pool lifespan (app/db.py), env-backed settings (app/config.py), the schema (migrations/0001_init.sql), record_llm_cost (app/services/spend.py), and is_allowed_phone (app/services/whitelist.py). Plan 2 builds the inbound webhook + media pipeline + outbound 24h helper end-to-end, in-process, on top of asyncio.create_task.
This revision absorbs the round-1 critique. Material decisions made in this pass:
A small migration is unavoidable to honor the brief's "charge left null until classified" requirement and to give burst recovery a durable association. We add migrations/0002_plan2.sql (one file, four edits — see Step 2).
Burst recovery uses bot_turns.triggering_message_ids uuid[], not a coalesce_id on messages. The Plan 3 runtime contract stays triggering_message_ids: list[UUID] (DEC-001) — bot_turns simply records that same list so recovery can ask "which raw messages already belong to a turn" with a GIN-backed ANY() check.
run_agentic_turn signature matches the user's contract exactly: async def run_agentic_turn(triggering_message_ids: list[UUID], user: User) -> None. The pool is fetched from a module-level holder set during lifespan, not passed as an argument.
send_outbound accepts a typed TemplateCall(name, params) so the parameter contract for templates is explicit at the callsite.
NULL last_inbound_at means "outside the 24h window" — explicit guard, not a None-arithmetic crash.
Voice retry is a same-task in-process retry with backoff (1 attempt + 1 retry = at most 2). Webhook redelivery is dedup-blocked by whatsapp_message_id, so the second attempt has to live inside the same background task — documented in Step 11.
Audio bytes get uploaded to Supabase Storage through the same storage.upload_media helper used for images. Voice rows always have a stored object even if transcription fails.
Edit/delete webhook envelopes are pinned to documented Meta v20.0 shapes (Step 9 cites them) and captured as fixture JSON files so the must-pass tests run against real-shaped payloads.
Vision cap-hit metadata keeps the plan's {"unavailable":"daily_cap"} marker (a deliberate deviation from the spec's "leave null" wording, made because the brief asks us to mark the condition for Plan 3). Captured in Assumptions and Success Criteria so the divergence is intentional, not silent.
Image cap-hit row writes also media_url (the stored bytes are still kept) so the divergence is metadata-only, never data-loss.
ALTER TABLE messages ALTER COLUMN charge DROP NOT NULL; and ALTER TABLE messages ALTER COLUMN charge DROP DEFAULT; — inbound rows now persist with charge IS NULL until Plan 3's loop classifies. Existing rows keep their routine value.
ALTER TABLE bot_turns ADD COLUMN triggering_message_ids uuid[] NOT NULL DEFAULT '{}'::uuid[]; — durable burst association. The single-id triggered_by_message_id stays as the "primary" trigger for backward compatibility with admin queries.
CREATE INDEX IF NOT EXISTS idx_bot_turns_triggering_message_ids_gin ON bot_turns USING gin (triggering_message_ids); — recovery uses WHERE id = ANY(...) style lookups against this column.
ALTER TABLE messages ALTER COLUMN media_type DROP NOT NULL; if it isn't already (it isn't — confirm) so "other media" stays storable; otherwise no-op.
Sanity-check by reading migrations/0001_init.sql:25 (charge constraint) and migrations/0001_init.sql:111 (bot_turns) so the ALTERs match column names.
Step 3: Hook registry (app/services/hooks.py)
Scope: Small
Create the module with module-level rebindable callables, no Plan 4/5 import dependencies:
Register all five approved templates with concrete copy + parameter shapes (proposed copy for pause_confirmation and media_failure is drafted here for review — flagged in Assumptions):
weekly_summary — params [name, conversation_count, themes_touched_count]. Copy from spec line 566.
escalation — params [recipient_name, partner_name, brief_context]. Copy from spec line 570.
checkin_nudge — params [name]. Copy from spec line 121.
pause_confirmation — params [name, partner_name]. Proposed: "Hi {{1}}, {{2}} has paused our conversations for now. I'll be quiet on both threads until either of you messages me again."
media_failure — params [name, kind] where kind ∈ {"voice","image"}. Proposed: "Hi {{1}}, I couldn't process your last {{2}} note — could you try resending or describe it in text?"
Exposerender_template(call: TemplateCall) -> dict returning the WhatsApp template payload shape ({"name": ..., "language": {"code": ...}, "components": [{"type":"body","parameters":[{"type":"text","text":p}, ...]}]}); validate parameter count against the registered shape and raise on mismatch.
fetch_media(media_id: str) -> tuple[bytes, str] — two-step: GET /{api_version}/{media_id} for URL; then GET that URL with bearer; returns (bytes, content_type).
send_text(to: str, body: str) -> dict and send_template(to: str, template_payload: dict) -> dict — POST to /{api_version}/{phone_number_id}/messages.
Computelast_inbound_at = SELECT MAX(sent_at) FROM messages WHERE sender_id = $1 AND direction='inbound'. Treat NULL as "outside the 24h window" (no None-arithmetic).
Decision tree:
If last_inbound_at IS NOT NULL AND now() - last_inbound_at < 24h → free-form (whatsapp.send_text).
Else if template_fallback is not None → whatsapp.send_template(...render_template(template_fallback)...).
Else → defer: insert outbound row with processing_state='withheld', append bot_turns.reasoning if bot_turn_id given, return the row id, do not call Meta.
Pause hook: if await hooks.paused_for_user(user.id) is True, write the row as withheld and return without calling Meta.
OOB hook: if hooks.check_oob is set, await it. On verdict block, write row as withheld + log; on rewrite, replace content with the suggestion before sending; on ok, send.
Persist before send: insert the outbound messages row first (without whatsapp_message_id), then call Meta. On success, UPDATE messages SET whatsapp_message_id=$1 WHERE id=$2 so we never double-send on retry.
Retry: exponential backoff [1s, 2s, 4s] up to 3 attempts on Meta failure. After exhaustion, set processing_state='expired' and append the failure to bot_turns.reasoning if a bot_turn_id is given.
add(user_id, message_id) resets a 10s asyncio.TimerHandle; tracks first_seen_at; cap total wait at 30s from first_seen_at (after 30s, fire even if new messages arrive).
On expiry, snapshot the message-id list and call await on_burst_complete(message_ids, user); clear the entry. Mid-flight arrivals start a new burst.
Concurrency: per-user asyncio.Lock. Document in a one-line comment that the runtime contract with run_agentic_turn is (triggering_message_ids: list[UUID], user).
ImplementGET /whatsapp/webhook with hub.mode / hub.verify_token / hub.challenge (returns challenge or 403).
ImplementPOST /whatsapp/webhook:
await request.body() for raw bytes.
whatsapp.verify_signature(body, request.headers.get("x-hub-signature-256")) → 401 + logger.warning("webhook signature mismatch") on failure.
Spawn asyncio.create_task(process_inbound(pool, json.loads(body))); track on app.state.background_tasks: set[asyncio.Task] with a remove-on-done callback.
inbound_edit.json — uses the documented edit envelope: entry[].changes[].value.messages[].type == "text" with a sibling entry[].changes[].value.messages[].context.message_id referencing the original WA id, and the change is signaled by field == "messages" with the original whatsapp_message_id reused (per Meta v20.0 docs). If the live envelope diverges, the fixture is the single source of truth all tests + handler code key off — adjust both together.
inbound_delete.json — entry[].changes[].value.messages[].type == "unsupported" accompanied by an entry[].changes[].value.errors[].code == 131051 "message deleted" entry referencing the original id. (This is the documented shape; if Meta later promotes a dedicated delete event, the fixture moves and the handler in Step 10 follows suit.)
Implementasync def process_inbound(pool, payload: dict) invoked from the background task. Iterate payload["entry"][*]["changes"][*]["value"]["messages"]. For each:
Whitelist: look up the sender's WA phone in value["contacts"]; drop with logger.warning("inbound dropped: not whitelisted") before any DB write if is_allowed_phone(phone) is False.
User upsert:INSERT INTO users (name, phone, timezone) VALUES ($1, $2, $3) ON CONFLICT (phone) DO UPDATE SET name = EXCLUDED.name RETURNING id, name, phone, timezone. Pass settings.default_user_timezone for $3 so the NOT NULL constraint always holds; existing rows keep their previously-configured timezone via the DO UPDATE clause not touching it.
Idempotent insert:INSERT INTO messages (direction, sender_id, content, processing_state, whatsapp_message_id, sent_at, media_type, media_url, media_duration_seconds, media_analysis) VALUES ('inbound', $1, $2, 'raw', $3, $4, $5, $6, $7, $8) ON CONFLICT (whatsapp_message_id) DO NOTHING RETURNING id. charge is omitted entirely so the column stores NULL per the migration in Step 2 (the brief's "charge left null until classified" requirement). If no id returned, treat as a re-delivery and skip media work and debouncer add.
Type dispatch: based on message["type"] — see Steps 11/12 for media branches; text path stores content = text.body and goes straight to the debouncer; document/sticker/location/etc. store media_type='document' with media_analysis = {"kind": <wa_type>} and go to the debouncer.
Hand off the new message id to the debouncer unless await hooks.paused_for_user(user.id) is True (in which case persist but don't trigger).
Edits: when the payload matches the edit fixture shape (Step 9, fixture inbound_edit.json), look up the prior row by whatsapp_message_id. If found, UPDATE messages SET edit_history = COALESCE(edit_history,'[]'::jsonb) || jsonb_build_array(jsonb_build_object('content', content, 'at', now())), content = $new, edited_at = now() WHERE whatsapp_message_id = $id. Do not add to the debouncer (the original message already triggered a turn).
Deletes: when the payload matches the delete fixture shape (Step 9, fixture inbound_delete.json), UPDATE messages SET deleted_at = now() WHERE whatsapp_message_id = $1. No debouncer add.
Step 11: Voice transcription with audio retention + retry (app/services/transcription.py)
Alwaysstorage_path = await storage.upload_media(settings.supabase_storage_bucket, f"voice/{message_id}", audio_bytes, content_type) — the audio is retained even if transcription fails.
UPDATE messages SET media_type='voice', media_url=$1, media_duration_seconds=$2 WHERE id=$3 (duration parsed from the WA audio.duration payload field if available; else NULL).
Transcribe with in-task retry: call _groq_transcribe(audio_bytes, content_type) once; on failure (network, 5xx, decode error) sleep 2s and retry once. If both attempts fail:
UPDATE messages SET processing_state='expired', media_analysis = COALESCE(media_analysis,'{}'::jsonb) || jsonb_build_object('_pipeline', jsonb_build_object('attempts', 2, 'last_error', $1)) WHERE id=$2.
Return without adding to the debouncer (Plan 3 sees the expired state and the existing message row, and decides how to surface the failure on the next user turn — out of scope here).
On success: UPDATE messages SET content = $transcript, then record_llm_cost(pool, "transcription", cost_estimate) and add to the debouncer.
Document in a 1-line module docstring: in-task retry is the only retry path because webhook redelivery is dedup-blocked by whatsapp_message_id. The twice-fail success criterion is satisfied by the second attempt inside the same task.
UPDATE messages SET media_type='image', media_url=$1 WHERE id=$2.
Cap check:if not await is_under_cap(pool, "vision"): write media_analysis = {"unavailable":"daily_cap"}, add to debouncer, return. (Deliberate metadata-mark deviation from the spec's "null" — see Assumptions; storage already retained the bytes so no data is lost.)
Vision call: POST to OpenAI Responses API (latest GPT vision-capable model); on success persist media_analysis = {"description": <text>} and record_llm_cost(pool, "vision", cost_estimate).
API failure: persist media_analysis = {"error":"vision_failed"} (still non-null per plan intent — Plan 3 reads the error key and degrades). Add to debouncer either way.
Crashed turns first (so the next query has consistent state): UPDATE bot_turns SET failure_reason='crashed' WHERE completed_at IS NULL AND started_at < now() - interval '5 minutes' RETURNING triggering_message_ids → for each list, look up the sender of the first id and re-add the whole list to the coalescer.
Orphan raw messages:SELECT id, sender_id FROM messages WHERE processing_state='raw' AND sent_at < now() - interval '30 seconds' AND NOT EXISTS (SELECT 1 FROM bot_turns WHERE messages.id = ANY(triggering_message_ids)) → re-add each to the coalescer (uses the new GIN index on triggering_message_ids from Step 2).
Hook into lifespan after the pool is up and the coalescer exists, before yielding.
Implementasync def purge_expired_deletions(pool):
UPDATE messages SET content='[deleted]' WHERE deleted_at IS NOT NULL AND deleted_at < now() - interval '24 hours' AND content <> '[deleted]'.
Don't schedule it here — Plan 5's worker picks it up. Export the callable so it's discoverable.
Step 16: Wire startup (app/main.py)
Scope: Small
In the lifespan after db_lifespan opens:
Instantiate the WA httpx.AsyncClient.
agentic.set_pool(pool).
coalescer = BurstCoalescer(on_burst_complete=run_agentic_turn); store on app.state.coalescer.
Verify GET verification: valid token+mode → returns the challenge body; bad token → 403.
Verify POST signature: signed body returns 200; tampered body returns 401 + logged WARNING (caplog assertion).
Verify non-whitelisted sender → no row written, log emitted.
Verify idempotent re-delivery: posting the same whatsapp_message_id twice yields one messages row.
Verify signed text-message POST → stub run_agentic_turn is invoked once with [message_id] and the resolved user. Drive the timer with a virtual clock or directly call coalescer._fire(user_id) so the test runs in milliseconds.
Verify the upsert path for a brand-new whitelisted phone writes users.timezone = settings.default_user_timezone and does not violate the NOT NULL constraint.
Verify inbound messages.charge IS NULL (post-migration assertion).
Free-form path: seed inbound 5 min ago → send_outbound calls whatsapp.send_text, writes one outbound row with whatsapp_message_id set after the call.
Template path: seed inbound 25h ago, pass template_fallback=TemplateCall("checkin_nudge", [user.name]) → send_outbound calls whatsapp.send_template with the rendered shape; mismatched params length raises before Meta is touched.
NULL last_inbound_at path: brand-new user with zero inbound history + template_fallback=TemplateCall("pause_confirmation", [name, partner_name]) → template is sent (treated as outside window), no None-arithmetic.
Defer path: 25h ago + no fallback → withheld row, no WA call, bot_turns.reasoning appended when bot_turn_id provided.
Retry path: patch WA client to raise twice then succeed → final state is processed; raise all 3 → expired, reasoning records the failure.
Pause hook + OOB hook rebound for the duration of the test → no WA call (pause), or rewritten content sent (OOB rewrite), or withheld (OOB block).
Step 20: Media + edits/deletes + recovery (tests/test_media.py, tests/test_recovery.py)
Scope: Medium
Voice success: Groq returns transcript → row has content set, media_type='voice', media_url set (audio uploaded to fake storage), media_duration_seconds populated.
Edit: post inbound_text.json, then inbound_edit.json for the same WA id → row has edited_at set, original content in edit_history[0].content, new content in content.
Delete: post + inbound_delete.json → deleted_at set; running purge_expired_deletions after fast-forwarding 24h replaces content with [deleted].
Recovery — orphan raw: insert a raw message 1 minute old with no bot_turns referencing it → recover_on_startup re-adds it to the coalescer.
Recovery — crashed turn: insert a bot_turns row with triggering_message_ids = [m1, m2] and started_at = 6 min ago, completed_at = NULL → recover_on_startup marks failure_reason='crashed' and re-adds [m1, m2] to the coalescer as one burst (verifies the durable association from Step 2's migration).
Execution Order
Phase 1 (migration + config + hooks + templates) lands first — schema reconciliation must precede any persistence code.
Phase 2 (WA client + storage + send_outbound) — outbound is testable in isolation before any inbound flow exists.
Phase 5 (tests) — interleave per phase; the recovery test is the gate test for the migration in Step 2.
Validation Order
pytest tests/test_send_outbound.py tests/test_debouncer.py — pure logic, no DB or HTTP.
pytest tests/test_whatsapp_webhook.py — full FastAPI + asyncpg fake stack with signed bodies.
pytest tests/test_media.py tests/test_recovery.py — heaviest, exercises the migration's new column.
pytest — confirms Plan 1's tests still pass.
code
Plan metadata:
{
"version": 2,
"timestamp": "2026-04-30T04:03:05Z",
"hash": "sha256:73f1327f568aedcb9b068e6cf68f19ed10f1687679dca99712150d6bf098101a",
"changes_summary": "Revised the plan to absorb 15 round-1 flags. Key changes: (1) added a small migration 0002_plan2.sql that drops messages.charge NOT NULL/default and adds bot_turns.triggering_message_ids uuid[] (+ GIN index) for durable burst-recovery association; (2) user upsert now passes settings.default_user_timezone so users.timezone NOT NULL is always satisfied; (3) send_outbound now accepts a typed TemplateCall(name, params) and explicitly handles NULL last_inbound_at as outside-window; (4) run_agentic_turn signature matches the user's exact contract (triggering_message_ids, user), with pool injected via a module-level setter; (5) voice pipeline now always uploads audio bytes to Supabase Storage before transcribing and uses an in-task retry (1 attempt + 1 retry = 2 total) to make the twice-fail criterion reachable; (6) drafted concrete copy + parameter shapes for pause_confirmation and media_failure templates; (7) pinned Meta v20.0 webhook envelopes for edits and deletes via three captured fixture JSON files that tests + handler key off; (8) image vision cap-hit / failure paths now store media_url so the metadata divergence from the spec is explicitly metadata-only, never data-loss. Success criteria expanded to cover the new behaviors and the schema migration is itself a must gate.",
"flags_addressed": [
{
"id": "PLAN2-001",
"resolution": "addressed",
"reason": "Step 1 adds DEFAULT_USER_TIMEZONE config and Step 10 supplies it during user upsert, satisfying the users.timezone NOT NULL constraint."
},
{
"id": "PLAN2-002",
"resolution": "addressed",
"reason": "Step 2 migration adds bot_turns.triggering_message_ids uuid[] with a GIN index; Step 14 recovery uses messages.id = ANY(triggering_message_ids) so multi-message bursts are durably associated."
},
{
"id": "PLAN2-003",
"resolution": "addressed",
"reason": "Step 11 specifies an explicit storage upload for the audio bytes before transcription, and an in-task retry (1+1 attempts) so the twice-fail give-up is actually reachable."
},
{
"id": "PLAN2-004",
"resolution": "addressed",
"reason": "Step 4 introduces TemplateCall(name, params) and Step 7 takes template_fallback: TemplateCall | None; render-time validation enforces the parameter contract."
},
{
"id": "issue_hints-1",
"resolution": "addressed",
"reason": "Step 2 migration drops the NOT NULL/default on messages.charge; Step 10 omits charge from the inbound INSERT so the row is persisted with charge=NULL until Plan 3 classifies. Step 17 asserts this."
},
{
"id": "issue_hints-2",
"resolution": "addressed",
"reason": "Step 4 ships drafted copy and parameter shapes for pause_confirmation and media_failure (flagged as proposed-for-review in Assumptions)."
},
{
"id": "correctness-1",
"resolution": "addressed",
"reason": "Same fix as PLAN2-001 \u2014 DEFAULT_USER_TIMEZONE setting + upsert binding."
},
{
"id": "correctness-2",
"resolution": "addressed",
"reason": "Step 7 explicitly treats NULL last_inbound_at as outside-window, never performing now() - None arithmetic."
},
{
"id": "correctness-3",
"resolution": "addressed",
"reason": "Documented as a deliberate plan-level deviation in Overview + Assumptions; Step 12 also stores media_url on cap-hit and on vision-failure so the metadata mark never loses the underlying bytes."
},
{
"id": "scope-1",
"resolution": "addressed",
"reason": "Step 11 uploads the audio bytes to Supabase Storage via storage.upload_media before transcription; success criterion 2 asserts media_url populated for voice."
},
{
"id": "scope-2",
"resolution": "addressed",
"reason": "Step 11 spells out the retry trigger: same task, sleep 2s, second attempt \u2014 independent of webhook redelivery (which is dedup-blocked). Documented inline."
},
{
"id": "all_locations-1",
"resolution": "addressed",
"reason": "Same fix as PLAN2-002 \u2014 bot_turns.triggering_message_ids array + GIN index, Step 14 recovery uses the array."
},
{
"id": "all_locations-2",
"resolution": "addressed",
"reason": "Step 9 pins Meta v20.0 webhook envelope shapes and captures three fixture JSON files (inbound_text/edit/delete) that tests + handler both key off."
},
{
"id": "callers-1",
"resolution": "addressed",
"reason": "Same fix as PLAN2-004 \u2014 typed TemplateCall(name, params) on the send_outbound signature."
},
{
"id": "callers-2",
"resolution": "addressed",
"reason": "Step 13 changes the run_agentic_turn signature to match the user contract exactly (triggering_message_ids, user); pool is held in a module-level setter, no contract drift."
}
],
"questions": [
"The Meta v20.0 webhook envelope shapes for message edits and deletes I captured in fixtures are based on the public WhatsApp Cloud API docs; if you have captured production payloads from your tenant, please share so the fixtures can match exactly.",
"Proposed copy for and templates is in Step 4 \u2014 please review before we submit to Meta. (Copy can be tuned without code changes; only the parameter shape matters for the contract.)",
"Default timezone for new users is . Confirm acceptable, or provide a different default (e.g. the spec author's tz) before we ship."
],
"success_criteria": [
{
"criterion": "Migration applies cleanly: messages.charge becomes nullable with no default, bot_turns.triggering_message_ids uuid[] and its GIN index exist.",
"priority": "must",
"requires": [
"run_shell",
"read_files"
]
},
{
"criterion": "A signed POST to /whatsapp/webhook with a text-message payload returns 200, persists exactly one inbound row with , upserts the user with the configured default timezone, and (after debounce or virtual clock) calls the stub exactly once with and the resolved user.",
"priority": "must",
"requires": [
"run_tests"
]
},
{
"criterion": "Voice and image inbound paths fetch media via the WA client AND upload the bytes to Supabase Storage. Voice \u2192 set, = transcript on success, , set; double-failure leaves , still set, . Image \u2192 set, populated on success; cap-hit sets with still set; vision-API failure sets with still set.",
"priority": "must",
"requires": [
"run_tests"
]
},
{
"criterion": " chooses free-form when last_inbound_at is within 24h, sends the template (with validated parameter count) when \u226524h or last_inbound_at is NULL and a fallback is provided, defers (writes row + appends ) when \u226524h or NULL with no fallback, and on Meta failure retries with exponential backoff up to 3 attempts before marking the row . NULL last_inbound_at never triggers None-arithmetic.",
"priority": "must",
"requires": [
"run_tests"
]
},
{
"criterion": "Edit webhooks (matching ) append the prior content to , set , and update . Delete webhooks (matching ) set ; rewrites to only for rows whose is older than 24h.",
"priority": "must",
"requires": [
"run_tests"
]
},
{
"criterion": "On startup, open for >5 minutes are marked and their full list is re-queued as one burst; raw messages older than 30s with no row in having that id in are re-added \u2014 exactly once per startup, no duplicate triggers for sibling messages of the same burst.",
"priority": "must",
"requires": [
"run_tests"
]
},
{
"criterion": " signature is exactly \u2014 no extra argument leaking into Plan 3's contract.",
"priority": "must",
"requires": [
"read_files"
]
},
{
"criterion": "Webhook signature validation rejects bad signatures with HTTP 401 and emits a logged warning (test asserts both the response and the log record).",
"priority": "should",
"requires": [
"run_tests"
]
},
{
"criterion": "Burst coalescing test fires 5 messages within the 10/30s window and shows a single invocation with all 5 ids; a separate scenario shows the 30s cap forcing a second burst.",
"priority": "should",
"requires": [
"run_tests"
]
},
{
"criterion": "All five approved templates (, , , , ) are documented in with concrete body copy and parameter shapes ready to submit to Meta. and are clearly flagged as proposed-for-review.",
"priority": "info",
"requires": [
"read_files"
]
},
{
"criterion": "Existing Plan 1 tests (health, admin, config, spend, whitelist, tool_schemas) all still pass after the new code lands.",
"priority": "must",
"requires": [
"run_tests"
]
}
],
"assumptions": [
"A small new migration is acceptable in Plan 2 scope (the brief said to avoid schema changes, but reconciling messages.charge NOT NULL and adding durable burst-association cannot be done without it).",
"Default timezone for newly-seen whitelisted users is via a new setting; the user can update their record later via Plan 6 admin or the agentic loop.",
" is kept (backwards-compat for Plan 1 indexes/admin queries); the new is the canonical recovery key.",
"Voice/vision retries live inside the same background task \u2014 webhook redelivery is dedup-blocked by . Two attempts (1 + 1 retry) satisfies the spec's twice-fail rule.",
"Vision cap-hit and vision-failure rows store a non-null marker ( or ) in . This is a deliberate, documented deviation from the spec's 'leave null' wording, made because the user note explicitly asks for the metadata mark for Plan 3.",
"Meta v20.0 webhook envelopes for edits and deletes are pinned via captured fixture JSON files; if the live envelope diverges, the fixtures and handler are updated together.",
" and template copy is drafted in code as a proposal for the user to review before submitting to Meta \u2014 copy may change on review.",
" matches the user's exact contract ; the pool is fetched from a module-level set during FastAPI lifespan, not passed in.",
"Tests use the existing style from plus a small in-memory message store; no real Postgres in CI."
],
"delta_from_previous_percent": 69.94,
"structure_warnings": []
}
code
Plan structure warnings from validator:
[]
Existing flags:
[
{
"id": "PLAN2-001",
"concern": "Inbound persistence: plan does not supply required users.timezone during user upsert, so first contact from a whitelisted but unseeded phone can violate the schema.",
"status": "addressed",
"severity": "significant"
},
{
"id": "PLAN2-002",
"concern": "Burst recovery: skipping a durable coalesce id leaves multi-message bursts unrecoverable as a unit because bot_turns only stores one triggering message id.",
"status": "addressed",
"severity": "significant"
},
{
"id": "PLAN2-003",
"concern": "Voice media: retry and retention flow is underspecified, so the twice-fail requirement and audio storage requirement may not be satisfied by the described path.",
"status": "addressed",
"severity": "significant"
},
{
"id": "PLAN2-004",
"concern": "Outbound templates: send_outbound lacks a parameter contract for template variables, while several planned callers require named templates with body parameters.",
"status": "addressed",
"severity": "significant"
},
{
"id": "issue_hints-1",
"concern": "Did the work fully address the issue hints, user notes, and approved plan requirements?: WhatsApp ingestion: The requested scope says inbound charge should be left null until the loop classifies it, but the actual messages.charge column is NOT NULL DEFAULT 'routine' in migrations/0001_init.sql:25. The plan explicitly avoids schema changes and does not call out this mismatch, so an executor following it will persist inbound rows as routine immediately rather than preserving an unclassified state.",
"status": "addressed",
"severity": "significant"
},
{
"id": "issue_hints-2",
"concern": "Did the work fully address the issue hints, user notes, and approved plan requirements?: Media templates: The plan says it will use canonical template copy from mediator-bot-spec.md:118-125,564-572, but those lines only provide exact bodies for weekly_summary, escalation, and checkin_nudge; pause_confirmation and media_failure are named but do not have approved copy or parameter shapes. The plan metadata asks this as an open question, which means the success criterion for reviewable day-one template specs is not fully resolved by the plan.",
"status": "addressed",
"severity": "significant"
},
{
"id": "correctness-1",
"concern": "Are the proposed changes technically correct?: Inbound persistence: The plan's user upsert only mentions phone and profile name, but the existing users table requires timezone text NOT NULL with no default in migrations/0001_init.sql:7-13. A whitelisted sender not already in users would fail insertion unless the plan supplies a timezone default or requires pre-provisioned users.",
"status": "addressed",
"severity": "significant"
},
{
"id": "correctness-2",
"concern": "Are the proposed changes technically correct?: Outbound 24-hour logic: computes over inbound messages, but the plan does not specify behavior when this query returns . That can happen for pre-provisioned users, onboarding/admin sends, or pause confirmations before the recipient has messaged, and will fail unless explicitly handled as outside-window/template-only.",
"status": "addressed",
"severity": "significant"
},
{
"id": "correctness-3",
"concern": "Are the proposed changes technically correct?: Media failure state: The plan stores image cap hits as , which intentionally diverges from the spec text saying cap hits leave null but is consistent with the Plan 2 user note to mark the condition in metadata for Plan 3. This is a tension rather than a runtime blocker.",
"status": "addressed",
"severity": "significant"
},
{
"id": "scope-1",
"concern": "Search for related code that handles the same concept. Is the reported issue a symptom of something broader?: Voice pipeline: The spec requires audio to be retained in Supabase Storage and both audio URL and transcript stored on the row (), while the plan's audio dispatch says to fetch and transcribe then persist a storage path but does not explicitly upload the audio bytes through the new storage helper. That leaves a plausible execution gap where voice rows have transcript state but no retained audio object.",
"status": "addressed",
"severity": "significant"
},
{
"id": "scope-2",
"concern": "Search for related code that handles the same concept. Is the reported issue a symptom of something broader?: Voice retry: The plan increments on transcription failure and says to give up after two attempts, but it does not define what schedules or invokes the second attempt after the first failure marks the message ; idempotent webhook redelivery is skipped by the unique WhatsApp id. The twice-fail success criterion therefore is not actually reachable from the described flow without a retry job or explicit retry call path.",
"status": "addressed",
"severity": "significant"
},
{
"id": "all_locations-1",
"concern": "Does the change touch all locations AND supporting infrastructure?: Restart recovery: The plan chooses not to add a coalesce id and keeps the Plan 3 interface as a list of message ids, but currently records only a single (). Recovery then checks raw message ids against that single column, so raw sibling messages from the same burst have no durable association with the turn and may be re-triggered independently after a restart.",
"status": "addressed",
"severity": "significant"
},
{
"id": "all_locations-2",
"concern": "Does the change touch all locations AND supporting infrastructure?: Edit/delete webhooks: The plan admits the delete webhook shape is assumed and lists an open question for exact Meta payloads, yet edits/deletes are must-pass success criteria. Without pinning the actual Cloud API event shape or fixture examples, the executor may implement tests around the wrong envelope and miss real production events.",
"status": "addressed",
"severity": "significant"
},
{
"id": "callers-1",
"concern": "Find the callers of the changed function. What arguments do they actually pass? Does the fix handle all of them?: callers are future-facing in this repo, but the spec names reactive replies, scheduled jobs, pause confirmations, media-failure prompts, and escalation as callers. Those callers may pass as a name plus parameters, while the plan's signature accepts a single value and later calls without defining how params are supplied or typed.",
"status": "addressed",
"severity": "significant"
},
{
"id": "callers-2",
"concern": "Find the callers of the changed function. What arguments do they actually pass? Does the fix handle all of them?: is introduced with the requested message-id list contract, but the plan's Step 12 signature is , adding beyond the user-provided contract . This may be acceptable for implementation convenience, but it is a contract drift that Plan 3 callers will have to match.",
"status": "addressed",
"severity": "significant"
}
]
code
Known accepted debt grouped by subsystem:
{}
Escalated debt subsystems:
[]
Debt guidance:
These are known accepted limitations. Do not re-flag them unless the current plan makes them worse, broadens them, or fails to contain them.
Prefix every new concern with a subsystem tag followed by a colon, for example Timeout recovery: retry backoff remains brittle.
When a concern is recurring debt that still needs to be flagged, prefix it with Recurring debt: after the subsystem tag, for example Timeout recovery: Recurring debt: retry backoff remains brittle.
code
Your output template is at: /Users/user_c042661f/Documents/Veas/.megaplan/plans/plan-2-whatsapp-ingestion-20260430-0549/critique_output.json
Read this file first — it contains 5 checks, each with a question and guidance.
For each check, investigate the codebase, then add your findings to the findings array for that check.
Each finding needs:
"detail": what you specifically checked and what you found (at least a full sentence)
"flagged": true if this describes a difference, risk, or tension — even if you think it's justified. false only if purely informational with no possible downside.
Every check must end with at least one finding. Never leave a findings array empty. If you found no issue, add one detailed flagged: false finding explaining what you checked and why it appears clear.
When in doubt, flag it — the gate can accept tradeoffs, but it can't act on findings it never sees.
Good: {"detail": "Checked callers of nthroot_mod in solveset.py line 1205 — passes prime moduli only, consistent with the fix.", "flagged": false}
Good: {"detail": "The fix handles empty tuples but not single-element tuples which need a trailing comma.", "flagged": true}
Bad: {"detail": "No issue found", "flagged": false} ← too brief, will be rejected
Bad: {"detail": "The hints suggest approach X but the plan uses Y. However Y is consistent with X's intent.", "flagged": false} ← a different approach than the hints IS a flag. You found a divergence — flag it. The gate decides if it's acceptable.
After filling in checks, add any additional concerns to the flags array (e.g., security, performance, dependencies).
Use the standard format (id, concern, category, severity_hint, evidence). This array can be empty.
Workflow: read the file → investigate → read file again → add finding → write file back. Repeat for each check.
This is critique iteration 2. The template file includes prior findings with their status. Verify addressed flags were actually fixed, re-flag if inadequate, and check for new issues introduced by the revision.
code
Additional guidelines:
- Robustness level: standard. Use balanced judgment. Flag significant risks, but do not spend flags on minor polish or executor-obvious boilerplate.
- Over-engineering: prefer the simplest approach that fully solves the problem.
- Reuse existing flag IDs when the same concern is still open.
- `verified_flag_ids`: list flag IDs from prior iterations that the revised plan actually resolves (e.g., if the plan was revised to fix FLAG-001, and you confirm the fix is correct, include "FLAG-001"). Only include flags you've verified — don't guess.
- Verify that the plan follows the expected structure when validator warnings or the outline suggest drift.
- Additional flags may use these categories: correctness, security, completeness, performance, maintainability, other.
- Focus on concrete issues, not structural formatting.