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 in prep, focusing on: "Onboarding", "Operations", "Feedback Loop", and the admin/audit-related references throughout (especially get_bot_actions and the "why did you tell her that?" use case).
Plans 1–5 are assumed complete. The system is functionally end-to-end. This plan adds the operator-facing surfaces, the onboarding behavior, and the polish that makes the system usable for the two real partners.
Scope (in)
Onboarding (light, conversational)
Welcome message: warm, explanatory; sets expectations (reflection and mediation assistant, not a therapist; will get things wrong; please correct me; how the basics work). Keep copy short and WhatsApp-conversational. Stored as a constant; sent on first inbound from each whitelisted user (via send_outbound; uses free-form within the 24h window which is guaranteed since the user just messaged in).
Natural early seeding: the system prompt already (from Plan 3) instructs gentle one-or-two contextual questions in the first conversations. This plan adds:
A users.onboarding_state enum column (pending | welcomed | seeded | complete) — migration on top of Plan 1's schema. Only used to gate the welcome message and inform the loop's prompt-side hot context (e.g., "user is in early conversations — be upfront about thin context").
Hot context includes onboarding_state so the loop adjusts behavior without needing extra logic.
Acknowledge thin context: nothing to implement beyond the prompt guidance already in Plan 3 + the onboarding_state hint.
Admin view ([REDACTED], read-only)
Single FastAPI router at /admin, [REDACTED] via Basic Auth or session cookie (admin password from env per Plan 1).
Pages (server-rendered, simple HTML — no SPA needed):
Recent turns: list of bot_turns newest first, paginated. Click into a turn to see prompt snapshot, reasoning, model version, triggering message, final outbound, and all tool_calls rows for that turn.
Recent messages: both threads, newest first, with charge level and processing state. Edit history visible.
Scheduled jobs: pending/fired/cancelled with type, scheduled_for, fired_at.
Spend: recent days of llm_spend_log per provider, with cap line drawn.
Escalations: distinguished bot_turns rows where escalate_to_partner was called.
All views are read-only — no admin actions in v1 (the spec explicitly says admin is for debugging without writing SQL). If the user wants a manual escalation toggle later, it can be added.
Audit endpoint (get_bot_actions)
Already implemented as a tool in Plan 3 for the loop. Verify it answers "why did you tell her that?" correctly: given a date_range and target_type, returns the relevant turns with reasoning and the outbound content.
Add a thin admin route that exposes the same query for human inspection.
Feedback loop
log_feedback tool already exists from Plan 3. Verify it's wired:
Conversational feedback recognized in the loop ("that was helpful", "no, that's wrong") and logged via the tool.
Source set to 'conversational'.
WhatsApp reaction webhook integration: register the reaction events in the webhook handler from Plan 2 (this is a small extension; reactions arrive as a different webhook payload type). On reaction: locate the assistant message by ID, write a feedback row with source='reaction', target_type='message', sentiment derived from the emoji (👍/❤️ → positive, 👎 → negative, others → mixed).
Admin view shows recent feedback grouped by sentiment.
Operations polish
Monitoring: document the external uptime + cron-ping setup (README ops section). Add a /health/deep endpoint that checks DB, Anthropic API reachability (lightweight ping, cached for 60s), and returns a JSON summary. Real alerting is external.
Backups: Supabase has automated backups; document the tested-restore procedure. Add a small script that pulls a fresh dump and writes a checksum file — operators run it quarterly.
Staging path: ability to test prompt changes against past message logs without sending output. Implement as a CLI: python -m app.staging replay --prompt-version <name> --since <date> --user <id> that runs the loop in a dry-run mode against historical messages, printing what it WOULD have sent and written. Does not call send_outbound or write to DB.
Daily LLM spend cap enforcement: Plan 1 plumbed the helpers; now wire them into the actual call sites. Each Anthropic / OpenAI / Groq call checks is_under_cap(provider) first and degrades gracefully:
Conversational LLM cap hit → respond once with "I'm running into limits today, will catch up tomorrow" and queue silently.
Vision cap hit → fall back to "I see you sent an image — can you describe it?" (already wired in Plan 2; just verify cap check is in place).
Transcription cap hit → "I can't transcribe right now — can you send it as text?".
Alerts at 80% of cap: when a per-provider per-day spend crosses 80%, log a distinguished WARNING line; surface the warning in the admin view's Spend page. External alerting is out of scope.
Final polish
README updates: deployment runbook, env var checklist (final), admin URL + password, how to read the admin views, how to run the staging CLI, backup procedure.
"Open Decisions Before Build" from the spec: this plan does NOT implement the assistant's name (placeholder remains in the prompt), welcome copy is provided but flagged in README as "edit before launch", and weekly-summary timing per partner is configurable in env. The co-designer-vs-recipient question is explicitly out of scope (it's a non-technical decision for the user).
Scope (out, deliberately)
WhatsApp reactions sentiment refinement beyond the simple emoji map.
Multi-tenant or per-couple isolation (the spec is for one couple).
Anything not explicitly in the spec.
Success criteria
must: New user gets the welcome message on their first inbound and users.onboarding_state advances correctly.
must: Admin view loads behind auth, all listed pages render, turn detail shows prompt, reasoning, and tool_calls.
must: /health/deep returns a JSON summary including DB and Anthropic reachability.
must: Reaction webhook produces a feedback row with the right sentiment derivation.
must: All three provider caps are enforced in the call sites with the documented graceful degradation.
must: Staging CLI runs the loop in dry-run mode against historical messages without writing or sending.
should: Spend page shows per-provider daily usage with cap line and 80% warnings.
should: README runbook is sufficient for the operator (the spec author) to deploy and operate without extra hand-holding.
info: Backup checksum script exists.
Notes
Keep the admin UI dead simple. Bootstrap CSS or Pico.css from a CDN is fine. No JS framework.
Auth: HTTP Basic Auth is acceptable given the small audience (one operator). Document [REDACTED].
This is the final plan — leave the codebase in a launchable state with the README runbook complete.
The repository already has the Plan 1-5 backbone: FastAPI routers in app/routers/, the agentic loop in app/services/agentic.py, WhatsApp ingestion in app/services/inbound.py, schema migrations in migrations/, tool schemas and read/write tools, spend helpers, media handlers, and tests with a FakePool harness. The main gaps for this plan are concrete operator surfaces and final production behavior: app/routers/admin.py is still a placeholder, users has no onboarding_state, /health is shallow, WhatsApp reactions are not parsed, transcription lacks a cap check, text cap failure is not yet graceful, staging replay does not exist, and README ops content is still foundation-level.
Phase 1: Schema And Shared State
Step 1: Add onboarding schema and user model support (migrations/0005_plan6_ops.sql, app/models/user.py, tests/conftest.py)
Scope: Small
Create a forward migration adding users.onboarding_state text NOT NULL DEFAULT 'pending' with a check constraint for pending|welcomed|seeded|complete.
Add targeted indexes only if queries need them; no broad indexing is needed for two users.
Extend upsert_user/fetch_user_by_id only where needed without changing the frozen User dataclass unless runtime code needs the field frequently.
Update FakePool user rows to default onboarding_state='pending' and handle updates/selects used by onboarding and admin tests.
Step 2: Add welcome-message constants and first-inbound gate (app/services/onboarding.py, app/services/inbound.py, app/services/messaging.py if needed)
Scope: Medium
Add a short WELCOME_MESSAGE constant in a dedicated app/services/onboarding.py module.
In process_inbound, after whitelist user upsert and before/after inbound insert, check users.onboarding_state; for pending, call send_outbound(pool, user, WELCOME_MESSAGE) and update state to welcomed.
Keep this independent from the coalescer so the welcome is immediate and the normal agentic turn still processes the user’s message.
Make the state transition idempotent with a conditional update such as WHERE id=$1 AND onboarding_state='pending', so webhook retries cannot send duplicate welcomes.
Add tests for first whitelisted inbound sends once, sets welcomed, and duplicate delivery does not send again.
Step 3: Put onboarding state in hot context (app/services/hot_context.py, tests/test_hot_context.py)
Scope: Small
Extend _user_profile to select onboarding_state with a fallback for test rows.
Render current and partner onboarding states in render_hot_context, using concise text like onboarding_state: welcomed.
Add a focused hot-context test proving the state is visible to the prompt.
Keep HTTP Basic Auth exactly as implemented and add a small server-rendered HTML helper layer in the same router or a small app/services/admin_views.py module.
Add /admin as a dashboard linking to all pages.
Add paginated list/detail routes:
/admin/turns and /admin/turns/{turn_id} for bot turns, prompt snapshot, reasoning, model version, triggering message, final outbound, and tool calls.
/admin/messages for both threads, newest first, charge, processing state, edit history.
Use plain HTML tables with escaped content via html.escape; Pico.css or Bootstrap CDN is acceptable but not required.
Keep routes read-only: all methods are GET, no forms that mutate state.
Add tests for auth still applying to at least one subpage, dashboard links rendering, and representative rows rendering for turns/detail/tool calls and feedback/spend.
Step 5: Expose audit query for humans (app/routers/admin.py, app/services/tools/read_tools.py if needed)
Scope: Medium
Verify get_bot_actions joins enough data to answer “why did you tell her that?”; currently it returns turn IDs, reasoning, final output IDs, and tool calls, but not outbound content.
Extend the read tool query to include final outbound content and triggering message content, or add an admin-specific query with those joins if changing the tool schema would be higher risk.
Add /admin/audit with query params for start, end, target_type, user_in_context, and limit, rendering the same useful fields: reasoning, final outbound content, triggering inbound content, and relevant tool calls.
Keep the existing prompt instruction and log_feedback tool as the primary implementation.
Add or strengthen an agentic test where the model emits log_feedback with source='conversational' after user feedback like “that was helpful” or “no, that’s wrong”.
Avoid adding keyword heuristics in Python unless tests show the prompt/tool loop cannot reliably express the behavior.
Locate the target assistant/outbound message by reaction.message_id matching messages.whatsapp_message_id; only log feedback if that message is an outbound assistant message.
Map 👍 and ❤️ to positive, 👎 to negative, and all other emojis to mixed.
Insert feedback with source='reaction', target_type='message', target_id=<local message id>, and content=<emoji>.
Do not enqueue the coalescer for reactions.
Add tests for positive, negative, mixed, unknown target no-op, and non-whitelisted sender no-op if the payload includes sender identity.
Extend record_llm_cost to detect when a provider/day crosses 80% of the configured cap.
Log a distinguished WARNING exactly once per provider/day after crossing the threshold. The simplest durable implementation is to add columns to llm_spend_log such as warned_80_at timestamptz; if avoiding schema churn is preferred, admin can infer warning state from totals, but “once” logging is harder.
Update the admin Spend page to show recent per-provider totals, caps, percent used, and an 80% warning marker.
Add unit tests for under threshold, crossing threshold, and already-warned behavior.
Step 9: Make all provider caps enforced at call sites (app/services/agentic.py, app/services/transcription.py, app/services/vision.py, app/services/scoring.py, app/services/oob_check.py, tests/test_llm_phase.py, tests/test_media.py)
Scope: Medium
Text: keep the existing pre-call checks in _create_message_with_retry, but update _run_agentic so SpendCapExceeded before any outbound sends one graceful message once: “I’m running into limits today, will catch up tomorrow.” Then mark/leave the triggering messages so they can be recovered or queued without repeated spam.
Vision: verify the existing cap behavior remains in place and add a test that the downstream assistant context leads to the “describe it” fallback if not already covered.
Transcription: add is_under_cap(pool, 'transcription') before _groq_transcribe; on cap hit, update the message content to the documented fallback text or media metadata, enqueue the coalescer so the assistant can respond conversationally, and do not call Groq.
Scoring/OOB: keep existing text cap checks, but ensure their errors degrade in the caller rather than crash user-facing delivery where applicable.
Add tests that Anthropic/OpenAI/Groq clients are not called when the respective cap is exhausted.
Add python -m app.staging replay --prompt-version <name> --since <date> --user <id> using stdlib argparse to avoid new dependencies.
Query historical inbound messages since the date for the selected user, ordered by sent time.
Run the loop in a dry-run mode that prints what it would send and what writes it would attempt, but never calls send_outbound and never writes to the real DB.
The simplest implementation path is to factor the agentic loop so outbound and write tools can be swapped for a dry-run sink. If that is too invasive, create a replay-specific DryRunPool wrapper that rejects mutating SQL and a dry-run tool registry that records intended writes.
Make prompt version selection explicit: either use the current prompt renderer with an override label stored in the prompt snapshot, or load named prompt text if the repo already has prompt versions by the time this is implemented.
Add tests that replay prints candidate outbound text, blocks all DB writes, and does not call WhatsApp.
Phase 6: Documentation And Launch Polish
Step 13: Update runbook and env checklist (README.md, optionally docs/ops.md)
Scope: Medium
Refresh README from “foundation scaffold” to launch runbook.
Document final env vars: admin password, weekly summary timing, spend caps, model names, scheduler settings, media/storage, Sentry/logging, WhatsApp credentials.
Document admin URL, Basic [REDACTED], [REDACTED], and how to read each admin view.
Flag welcome copy as “edit before launch”; keep assistant name placeholder decision out of scope; note co-designer-vs-recipient as non-technical/out of scope.
Execution Order
Land schema/FakePool updates first so tests can model Plan 6 state.
Implement onboarding and hot context before admin, because admin pages will read the same new user state.
Build admin list/detail pages and audit route next, using simple queries and escaping.
Add reaction feedback and strengthen conversational feedback tests.
Wire spend cap edge behavior after existing call sites are understood, because it touches user-visible fallback behavior.
Add deep health, backup script, and staging CLI.
Finish with README/runbook updates and full-suite verification.
Validation Order
Start with focused tests: tests/test_whatsapp_webhook.py, tests/test_hot_context.py, tests/test_admin.py, tests/test_spend.py, tests/test_health.py, tests/test_media.py, and new tests/test_staging.py.
Run the existing agentic and tool tests after any loop/tool changes: tests/test_agentic.py, tests/test_agentic_lifecycle.py, tests/test_tools.py, tests/test_llm_phase.py.
Run the full suite with pytest -q.
Optionally run a local app smoke test with uvicorn app.main:app --reload and inspect /admin, /admin/turns, /admin/spend, and /health/deep with test credentials.
code
Plan metadata:
{
"version": 1,
"timestamp": "2026-04-30T12:27:44Z",
"hash": "sha256:98564fc899e58109f5d14deee505c9dc7615fadd7a9f83081b1c1d17fd92765c",
"questions": [
"For /health/deep, should Anthropic reachability be a real minimal API request, or is an authenticated HTTP endpoint/version check acceptable to avoid token spend?",
"For staging replay, does --prompt-version <name> need to load historical named prompt files, or is it enough in v1 to tag/override SYSTEM_PROMPT_VERSION while using the current prompt renderer?",
"Should the welcome message be exactly authored now by engineering, or will the operator provide final copy before launch?"
],
"success_criteria": [
{
"criterion": "A whitelisted user on first inbound receives exactly one welcome outbound, and users.onboarding_state advances from pending to welcomed without duplicate sends on webhook redelivery.",
"priority": "must",
"requires": [
"run_tests",
"read_files"
]
},
{
"criterion": "Hot context includes the current user onboarding state so the prompt can adjust early-conversation behavior.",
"priority": "must",
"requires": [
"run_tests",
"read_files"
]
},
{
"criterion": "Admin routes are protected by HTTP Basic Auth, and all listed read-only pages render representative data without mutation endpoints.",
"priority": "must",
"requires": [
"run_tests",
"read_files",
"parse_diff"
]
},
{
"criterion": "Turn detail renders prompt snapshot, reasoning, model version, triggering message, final outbound content, and all tool calls for the turn.",
"priority": "must",
"requires": [
"run_tests",
"read_files"
]
},
{
"criterion": "The admin audit route exposes get_bot_actions-equivalent results with reasoning and outbound content sufficient for the 'why did you tell her that?' use case.",
"priority": "must",
"requires": [
"run_tests",
"read_files"
]
},
{
"criterion": "WhatsApp reaction webhook payloads create feedback rows with source='reaction', target_type='message', and emoji-derived positive/negative/mixed sentiment.",
"priority": "must",
"requires": [
"run_tests",
"read_files"
]
},
{
"criterion": "Conversational feedback can be logged through the existing log_feedback tool with source='conversational'.",
"priority": "must",
"requires": [
"run_tests",
"read_files"
]
},
{
"criterion": "/health/deep returns a JSON summary including DB and Anthropic reachability and returns 503 when either required check fails.",
"priority": "must",
"requires": [
"run_tests",
"read_files"
]
},
{
"criterion": "Text, vision, and transcription provider caps are checked before external provider calls, and cap-hit behavior follows the documented graceful degradation paths.",
"priority": "must",
"requires": [
"run_tests",
"read_files",
"observe_runtime_logs"
]
},
{
"criterion": "Staging replay CLI runs with python -m app.staging replay --prompt-version <name> --since <date> --user <id> and proves it does not send WhatsApp messages or write to the database.",
"priority": "must",
"requires": [
"run_tests",
"run_shell",
"read_files"
]
},
{
"criterion": "All existing and new tests pass with pytest -q.",
"priority": "must",
"requires": [
"run_tests"
]
},
{
"criterion": "Spend admin page shows recent per-provider daily usage, configured caps, percent used, and 80% warning state.",
"priority": "should",
"requires": [
"run_tests",
"inspect_runtime_ui",
"subjective_judgment"
]
},
{
"criterion": "README runbook is sufficient for a single operator to deploy, use admin views, run staging replay, rotate admin password, monitor health, and perform backup restore practice.",
"priority": "should",
"requires": [
"read_files",
"subjective_judgment"
]
},
{
"criterion": "Admin HTML remains intentionally simple, escaped, read-only, and does not introduce a SPA or frontend build step.",
"priority": "should",
"requires": [
"read_files",
"parse_diff",
"subjective_judgment"
]
},
{
"criterion": "Backup dump/checksum script exists and documents quarterly operator execution; live restore remains manually verified by the operator.",
"priority": "info",
"requires": [
"run_shell",
"verify_physical_device"
]
}
],
"assumptions": [
"Plans 1-5 are considered functionally complete; existing behavior should be preserved unless directly required by Plan 6.",
"HTTP Basic Auth with username admin and ADMIN_PASSWORD is acceptable for all admin pages.",
"The admin UI can use plain server-rendered HTML with escaped values and no JavaScript framework.",
"Welcome copy can start as a short engineering-authored constant and be flagged in README for final operator editing before launch.",
"Reaction feedback targets only outbound assistant messages whose WhatsApp message ID is already stored locally; unknown reaction targets are ignored and logged at most.",
"For 80% spend warnings, adding a small migration to persist warning state is acceptable if needed to avoid repeated warning logs.",
"Staging replay should prioritize non-writing/non-sending safety over perfectly simulating every production side effect.",
"Existing FakePool tests are the primary cheap validation path; DB-backed tests remain optional when TEST_DATABASE_URL is unset."
],
"structure_warnings": []
}
code
Plan structure warnings from validator:
[]
Existing flags:
[]
Known accepted debt grouped by subsystem:
{
"are-the-proposed-changes-technically-correct": [
{
"id": "DEBT-001",
"concern": "are the proposed changes technically correct?: debouncer callback: revised step 8 defines burstcoalescer.add(user_id, message_id) but says expiry calls on_burst_complete(message_ids, user). i found no existing user model or repository helper in the current codebase, and the plan does not say whether the coalescer stores the user object, fetches it from the pool, or receives it in add, so the callback cannot reliably supply the user argument required by run_agentic_turn as written.",
"occurrence_count": 1,
"plan_ids": [
"plan-2-whatsapp-ingestion-20260430-0549"
]
},
{
"id": "DEBT-002",
"concern": "are the proposed changes technically correct?: edit idempotency: revised step 9 says the edit fixture reuses the original whatsapp message id, while revised step 10's normal message flow does insert ... on conflict (whatsapp_message_id) do nothing and treats no returned id as a redelivery. unless edit detection runs before the generic idempotent insert path, a real edit will be classified as a duplicate and skipped instead of updating edit_history, but the plan does not explicitly require that ordering.",
"occurrence_count": 1,
"plan_ids": [
"plan-2-whatsapp-ingestion-20260430-0549"
]
},
{
"id": "DEBT-011",
"concern": "are the proposed changes technically correct?: checked the revised escalate_to_partner sequence. step 5 constructs the templatecall and awaits send_outbound(...) before the text says it enforces the crisis/explicit-request gate, so an implementation following the plan literally could send an unauthorized escalation before rejecting the tool call.",
"occurrence_count": 1,
"plan_ids": [
"plan-3-agentic-loop-tools-20260430-0648"
]
},
{
"id": "DEBT-012",
"concern": "are the proposed changes technically correct?: checked the revised tool_call_count expectations against the spec. the plan's e2e criterion expects tool_call_count == 3 because only write calls are counted, but the spec says bot_turns records tool count for admin visibility into pathological loops; excluding phase a read calls hides most loop activity.",
"occurrence_count": 1,
"plan_ids": [
"plan-3-agentic-loop-tools-20260430-0648"
]
},
{
"id": "DEBT-025",
"concern": "are the proposed changes technically correct?: query-level decay: observations.significance is nullable in tool_schemas.py and in current tests for failed scoring, and scoring.rescore_observations can leave it null after a failed re-score. the plan's sql function recency_weighted_score(significance, last_reinforced_at, created_at) does not specify null handling or nulls last; in postgres, ordering that nullable expression desc can surface null-scored failed observations before valid scored observations unless the executor adds nulls last or coalesce.",
"occurrence_count": 1,
"plan_ids": [
"plan-5-scheduled-jobs-decay-20260430-1337"
]
},
{
"id": "DEBT-026",
"concern": "are the proposed changes technically correct?: escalation gate metadata: the plan says escalate_to_partner should accept is_crisis=true only when the current trigger charge is actually crisis, but the existing write-tool context only has turncontext(triggering_message_ids, user, partner, phase) and the charge is currently computed locally inside agentic.run_agentic_turn from hot context. the plan does not explicitly add that charge or an explicit-request marker to turncontext or the tool-call validator, so the proposed guard has no reliable data path in the current code shape.",
"occurrence_count": 1,
"plan_ids": [
"plan-5-scheduled-jobs-decay-20260430-1337"
]
}
],
"check-in-scheduling": [
{
"id": "DEBT-022",
"concern": "check-in scheduling: one-pending-check-in invariant remains race-prone without a partial unique index or transactional locking strategy.",
"occurrence_count": 1,
"plan_ids": [
"plan-5-scheduled-jobs-decay-20260430-1337"
]
}
],
"debouncer": [
{
"id": "DEBT-005",
"concern": "debouncer: coalescer cannot satisfy the run_agentic_turn(message_ids, user) callback contract from an add(user_id, message_id) api unless it stores or resolves the user object.",
"occurrence_count": 1,
"plan_ids": [
"plan-2-whatsapp-ingestion-20260430-0549"
]
}
],
"did-the-work-fully-address-the-issue-hints-user-notes-and-approved-plan-requirements": [
{
"id": "DEBT-018",
"concern": "did the work fully address the issue hints, user notes, and approved plan requirements?: checked the search-before-write requirement against the new phase split. because phase b exposes only write/schedule tools, the model cannot recover by calling get_memories, get_observations, or list_themes if it realizes during phase b that it lacks enough read context to safely add versus update; this creates tension with the explicit agentic-search dedup requirement.",
"occurrence_count": 1,
"plan_ids": [
"plan-3-agentic-loop-tools-20260430-0648"
]
},
{
"id": "DEBT-024",
"concern": "did the work fully address the issue hints, user notes, and approved plan requirements?: weekly summary timing: the spec requires the recurring weekly summary to fire at 09:00 local on the user's configured day, and the plan explicitly asks where that configuration should live. the implementation plan chooses global env defaults plus per-job context overrides, but /pause supersedes all pending jobs and /resume restores weekly summaries; without a durable per-user schedule field or an explicit rule to read the last superseded weekly job context, resume/startup seeding can silently lose the user's configured day.",
"occurrence_count": 1,
"plan_ids": [
"plan-5-scheduled-jobs-decay-20260430-1337"
]
}
],
"does-the-change-touch-all-locations-and-supporting-infrastructure": [
{
"id": "DEBT-003",
"concern": "does the change touch all locations and supporting infrastructure?: recovery/coalescer api mismatch: revised step 14 says recovery should re-add a whole triggering_message_ids list as one burst, but revised step 8 only specifies add(user_id, message_id) for one message at a time. calling add repeatedly can reset timers or merge with live inbound state, so the plan needs either an explicit add_burst(user_id, ids)/fire(ids) path or clear semantics for preserving a recovered burst as a single unit.",
"occurrence_count": 1,
"plan_ids": [
"plan-2-whatsapp-ingestion-20260430-0549"
]
},
{
"id": "DEBT-004",
"concern": "does the change touch all locations and supporting infrastructure?: indexing claim: revised step 2 says the new gin index supports recovery's messages.id = any(triggering_message_ids) lookup, but postgres gin indexes on arrays are normally used by array operators such as @>, &&, or <@, not by scalar = any(array) in a correlated subquery. the executor should either use an indexable predicate like triggering_message_ids @> array[messages.id] or drop the claim that this query is gin-backed.",
"occurrence_count": 1,
"plan_ids": [
"plan-2-whatsapp-ingestion-20260430-0549"
]
},
{
"id": "DEBT-014",
"concern": "does the change touch all locations and supporting infrastructure?: checked audit support around prompt_snapshot. the revised step 8 still opens bot_turns with prompt_snapshot before building hot context, while the spec's worked example calls for <full prompt> after hot context is loaded; unless the executor reorders this, the stored prompt snapshot will omit the per-turn hot context actually injected into the llm.",
"occurrence_count": 1,
"plan_ids": [
"plan-3-agentic-loop-tools-20260430-0648"
]
},
{
"id": "DEBT-028",
"concern": "does the change touch all locations and supporting infrastructure?: check-in uniqueness: the success criteria require one pending check-in per user, and the current schedule_checkin implementation performs a separate update scheduled_jobs set status='superseded' followed by insert into scheduled_jobs. the plan later says to add db-level coverage, but the migration step only mentions indexes and does not specify a partial unique index such as one pending check-in per user, so two concurrent schedule calls can still race and leave multiple pending check-ins.",
"occurrence_count": 1,
"plan_ids": [
"plan-5-scheduled-jobs-decay-20260430-1337"
]
}
],
"edit-handling": [
{
"id": "DEBT-007",
"concern": "edit handling: edit events that reuse the original whatsapp message id can be swallowed by the normal idempotent insert path unless edit detection is explicitly performed before duplicate-message handling.",
"occurrence_count": 1,
"plan_ids": [
"plan-2-whatsapp-ingestion-20260430-0549"
]
}
],
"escalation-gate": [
{
"id": "DEBT-023",
"concern": "escalation gate: the plan does not define how the write tool receives authoritative trigger charge or explicit-request evidence.",
"occurrence_count": 1,
"plan_ids": [
"plan-5-scheduled-jobs-decay-20260430-1337"
]
}
],
"escalation-gate-ordering": [
{
"id": "DEBT-016",
"concern": "escalation gate ordering: the revised escalate_to_partner step sends the partner outbound before the plan text says it enforces the crisis/explicit-request gate.",
"occurrence_count": 1,
"plan_ids": [
"plan-3-agentic-loop-tools-20260430-0648"
]
}
],
"find-the-callers-of-the-changed-function-what-arguments-do-they-actually-pass-does-the-fix-handle-all-of-them": [
{
"id": "DEBT-015",
"concern": "find the callers of the changed function. what arguments do they actually pass? does the fix handle all of them?: checked the new hooks.check_oob default against existing tests. tests/test_send_outbound.py has an autouse fixture that sets the hook to none, so preserving an intentional no-hook test path is compatible with the plan's module-level default, but the new plan 3 e2e test must install a counting hook if it wants to assert the pass-through was invoked.",
"occurrence_count": 1,
"plan_ids": [
"plan-3-agentic-loop-tools-20260430-0648"
]
},
{
"id": "DEBT-029",
"concern": "find the callers of the changed function. what arguments do they actually pass? does the fix handle all of them?: the plan proposes replacing hooks.paused_for_user() with a db-backed implementation and notes that changing call sites to pass pool is cleaner. grep shows current direct callers in messaging.send_outbound, inbound.process_inbound, and agentic.run_agentic_turn; tests also monkeypatch a one-argument hook. if the executor chooses the cleaner signature change, all these callers and tests must be updated together, and media handlers still need separate pause coverage as noted in the scope finding.",
"occurrence_count": 1,
"plan_ids": [
"plan-5-scheduled-jobs-decay-20260430-1337"
]
},
{
"id": "DEBT-030",
"concern": "find the callers of the changed function. what arguments do they actually pass? does the fix handle all of them?: the current send_outbound callers are agentic.run_agentic_turn, write_tools.escalate_to_partner, and tests, and the function currently accepts only template_fallback and bot_turn_id keyword arguments. adding an ignore_pause keyword is compatible if defaulted to false, but /pause confirmation send sites must pass it explicitly or the confirmation rows will be withheld immediately after the global pause flag is set.",
"occurrence_count": 1,
"plan_ids": [
"plan-5-scheduled-jobs-decay-20260430-1337"
]
}
],
"media-state": [
{
"id": "DEBT-009",
"concern": "media state: the plan should explicitly keep successfully media-enriched inbound messages in processing_state='raw' until the agentic loop consumes them.",
"occurrence_count": 1,
"plan_ids": [
"plan-2-whatsapp-ingestion-20260430-0549"
]
}
],
"pause-resume": [
{
"id": "DEBT-021",
"concern": "pause/resume: media inbound paths can bypass the pause gate and enqueue voice/image messages after enrichment.",
"occurrence_count": 1,
"plan_ids": [
"plan-5-scheduled-jobs-decay-20260430-1337"
]
}
],
"query-level-decay": [
{
"id": "DEBT-020",
"concern": "query-level decay: nullable observation significance can break default weighted ordering unless null scores are explicitly handled.",
"occurrence_count": 1,
"plan_ids": [
"plan-5-scheduled-jobs-decay-20260430-1337"
]
}
],
"recovery": [
{
"id": "DEBT-006",
"concern": "recovery: re-queueing crashed turns with multiple triggering_message_ids is underspecified because the coalescer only exposes single-message add, not a way to restore a whole burst atomically.",
"occurrence_count": 1,
"plan_ids": [
"plan-2-whatsapp-ingestion-20260430-0549"
]
}
],
"recovery-query": [
{
"id": "DEBT-008",
"concern": "recovery query: the plan's claimed gin-backed lookup uses messages.id = any(triggering_message_ids), which is unlikely to use the array gin index as written.",
"occurrence_count": 1,
"plan_ids": [
"plan-2-whatsapp-ingestion-20260430-0549"
]
}
],
"search-for-related-code-that-handles-the-same-concept-is-the-reported-issue-a-symptom-of-something-broader": [
{
"id": "DEBT-010",
"concern": "search for related code that handles the same concept. is the reported issue a symptom of something broader?: media processing state after success: the success criteria for text and outbound mention processed state, but revised steps 11 and 12 do not explicitly say successful voice or image messages should remain raw for the agentic loop rather than be marked processed by the media layer. this is likely intentional because plan 3 owns loop processing, but it is a contract point worth keeping visible so the executor does not mark media messages processed before the agent sees them.",
"occurrence_count": 1,
"plan_ids": [
"plan-2-whatsapp-ingestion-20260430-0549"
]
},
{
"id": "DEBT-013",
"concern": "search for related code that handles the same concept. is the reported issue a symptom of something broader?: checked the scope of the two-phase split against the five-primitive write tools. the split solves ordering, but it broadens orchestration complexity because phase b must reason over phase a's transcript and the sent outbound without read tools; this is a new design risk specifically for dedup and multi-primitive decisions.",
"occurrence_count": 1,
"plan_ids": [
"plan-3-agentic-loop-tools-20260430-0648"
]
},
{
"id": "DEBT-027",
"concern": "search for related code that handles the same concept. is the reported issue a symptom of something broader?: pause is broader than text/document inbound: process_inbound checks hooks.paused_for_user before coalescing text and document messages, but audio and image messages delegate to handle_voice and handle_image, and both media handlers call coalescer.add(user.id, message_id, user) after enrichment without any pause check. the plan's pause tests mention inbound persistence without enqueueing, but the implementation steps do not call out these media handlers, so paused voice/image messages can still enter the agentic loop if only inbound.py is updated.",
"occurrence_count": 1,
"plan_ids": [
"plan-5-scheduled-jobs-decay-20260430-1337"
]
}
],
"two-phase-dedup-tension": [
{
"id": "DEBT-017",
"concern": "two-phase dedup tension: phase b is write-only, so the agent cannot perform the required search-before-write reads if it enters the write phase without enough context to choose add vs update vs supersede.",
"occurrence_count": 1,
"plan_ids": [
"plan-3-agentic-loop-tools-20260430-0648"
]
}
],
"weekly-summary-scheduling": [
{
"id": "DEBT-019",
"concern": "weekly summary scheduling: per-user configured day can be lost on pause/resume if timing exists only in pending job context or global defaults.",
"occurrence_count": 1,
"plan_ids": [
"plan-5-scheduled-jobs-decay-20260430-1337"
]
}
]
}
code
Escalated debt subsystems:
[
{
"subsystem": "are-the-proposed-changes-technically-correct",
"total_occurrences": 6,
"plan_count": 3,
"entries": [
{
"id": "DEBT-001",
"concern": "are the proposed changes technically correct?: debouncer callback: revised step 8 defines burstcoalescer.add(user_id, message_id) but says expiry calls on_burst_complete(message_ids, user). i found no existing user model or repository helper in the current codebase, and the plan does not say whether the coalescer stores the user object, fetches it from the pool, or receives it in add, so the callback cannot reliably supply the user argument required by run_agentic_turn as written.",
"occurrence_count": 1,
"plan_ids": [
"plan-2-whatsapp-ingestion-20260430-0549"
]
},
{
"id": "DEBT-002",
"concern": "are the proposed changes technically correct?: edit idempotency: revised step 9 says the edit fixture reuses the original whatsapp message id, while revised step 10's normal message flow does insert ... on conflict (whatsapp_message_id) do nothing and treats no returned id as a redelivery. unless edit detection runs before the generic idempotent insert path, a real edit will be classified as a duplicate and skipped instead of updating edit_history, but the plan does not explicitly require that ordering.",
"occurrence_count": 1,
"plan_ids": [
"plan-2-whatsapp-ingestion-20260430-0549"
]
},
{
"id": "DEBT-011",
"concern": "are the proposed changes technically correct?: checked the revised escalate_to_partner sequence. step 5 constructs the templatecall and awaits send_outbound(...) before the text says it enforces the crisis/explicit-request gate, so an implementation following the plan literally could send an unauthorized escalation before rejecting the tool call.",
"occurrence_count": 1,
"plan_ids": [
"plan-3-agentic-loop-tools-20260430-0648"
]
},
{
"id": "DEBT-012",
"concern": "are the proposed changes technically correct?: checked the revised tool_call_count expectations against the spec. the plan's e2e criterion expects tool_call_count == 3 because only write calls are counted, but the spec says bot_turns records tool count for admin visibility into pathological loops; excluding phase a read calls hides most loop activity.",
"occurrence_count": 1,
"plan_ids": [
"plan-3-agentic-loop-tools-20260430-0648"
]
},
{
"id": "DEBT-025",
"concern": "are the proposed changes technically correct?: query-level decay: observations.significance is nullable in tool_schemas.py and in current tests for failed scoring, and scoring.rescore_observations can leave it null after a failed re-score. the plan's sql function recency_weighted_score(significance, last_reinforced_at, created_at) does not specify null handling or nulls last; in postgres, ordering that nullable expression desc can surface null-scored failed observations before valid scored observations unless the executor adds nulls last or coalesce.",
"occurrence_count": 1,
"plan_ids": [
"plan-5-scheduled-jobs-decay-20260430-1337"
]
},
{
"id": "DEBT-026",
"concern": "are the proposed changes technically correct?: escalation gate metadata: the plan says escalate_to_partner should accept is_crisis=true only when the current trigger charge is actually crisis, but the existing write-tool context only has turncontext(triggering_message_ids, user, partner, phase) and the charge is currently computed locally inside agentic.run_agentic_turn from hot context. the plan does not explicitly add that charge or an explicit-request marker to turncontext or the tool-call validator, so the proposed guard has no reliable data path in the current code shape.",
"occurrence_count": 1,
"plan_ids": [
"plan-5-scheduled-jobs-decay-20260430-1337"
]
}
]
},
{
"subsystem": "does-the-change-touch-all-locations-and-supporting-infrastructure",
"total_occurrences": 4,
"plan_count": 3,
"entries": [
{
"id": "DEBT-003",
"concern": "does the change touch all locations and supporting infrastructure?: recovery/coalescer api mismatch: revised step 14 says recovery should re-add a whole triggering_message_ids list as one burst, but revised step 8 only specifies add(user_id, message_id) for one message at a time. calling add repeatedly can reset timers or merge with live inbound state, so the plan needs either an explicit add_burst(user_id, ids)/fire(ids) path or clear semantics for preserving a recovered burst as a single unit.",
"occurrence_count": 1,
"plan_ids": [
"plan-2-whatsapp-ingestion-20260430-0549"
]
},
{
"id": "DEBT-004",
"concern": "does the change touch all locations and supporting infrastructure?: indexing claim: revised step 2 says the new gin index supports recovery's messages.id = any(triggering_message_ids) lookup, but postgres gin indexes on arrays are normally used by array operators such as @>, &&, or <@, not by scalar = any(array) in a correlated subquery. the executor should either use an indexable predicate like triggering_message_ids @> array[messages.id] or drop the claim that this query is gin-backed.",
"occurrence_count": 1,
"plan_ids": [
"plan-2-whatsapp-ingestion-20260430-0549"
]
},
{
"id": "DEBT-014",
"concern": "does the change touch all locations and supporting infrastructure?: checked audit support around prompt_snapshot. the revised step 8 still opens bot_turns with prompt_snapshot before building hot context, while the spec's worked example calls for <full prompt> after hot context is loaded; unless the executor reorders this, the stored prompt snapshot will omit the per-turn hot context actually injected into the llm.",
"occurrence_count": 1,
"plan_ids": [
"plan-3-agentic-loop-tools-20260430-0648"
]
},
{
"id": "DEBT-028",
"concern": "does the change touch all locations and supporting infrastructure?: check-in uniqueness: the success criteria require one pending check-in per user, and the current schedule_checkin implementation performs a separate update scheduled_jobs set status='superseded' followed by insert into scheduled_jobs. the plan later says to add db-level coverage, but the migration step only mentions indexes and does not specify a partial unique index such as one pending check-in per user, so two concurrent schedule calls can still race and leave multiple pending check-ins.",
"occurrence_count": 1,
"plan_ids": [
"plan-5-scheduled-jobs-decay-20260430-1337"
]
}
]
},
{
"subsystem": "find-the-callers-of-the-changed-function-what-arguments-do-they-actually-pass-does-the-fix-handle-all-of-them",
"total_occurrences": 3,
"plan_count": 2,
"entries": [
{
"id": "DEBT-015",
"concern": "find the callers of the changed function. what arguments do they actually pass? does the fix handle all of them?: checked the new hooks.check_oob default against existing tests. tests/test_send_outbound.py has an autouse fixture that sets the hook to none, so preserving an intentional no-hook test path is compatible with the plan's module-level default, but the new plan 3 e2e test must install a counting hook if it wants to assert the pass-through was invoked.",
"occurrence_count": 1,
"plan_ids": [
"plan-3-agentic-loop-tools-20260430-0648"
]
},
{
"id": "DEBT-029",
"concern": "find the callers of the changed function. what arguments do they actually pass? does the fix handle all of them?: the plan proposes replacing hooks.paused_for_user() with a db-backed implementation and notes that changing call sites to pass pool is cleaner. grep shows current direct callers in messaging.send_outbound, inbound.process_inbound, and agentic.run_agentic_turn; tests also monkeypatch a one-argument hook. if the executor chooses the cleaner signature change, all these callers and tests must be updated together, and media handlers still need separate pause coverage as noted in the scope finding.",
"occurrence_count": 1,
"plan_ids": [
"plan-5-scheduled-jobs-decay-20260430-1337"
]
},
{
"id": "DEBT-030",
"concern": "find the callers of the changed function. what arguments do they actually pass? does the fix handle all of them?: the current send_outbound callers are agentic.run_agentic_turn, write_tools.escalate_to_partner, and tests, and the function currently accepts only template_fallback and bot_turn_id keyword arguments. adding an ignore_pause keyword is compatible if defaulted to false, but /pause confirmation send sites must pass it explicitly or the confirmation rows will be withheld immediately after the global pause flag is set.",
"occurrence_count": 1,
"plan_ids": [
"plan-5-scheduled-jobs-decay-20260430-1337"
]
}
]
},
{
"subsystem": "search-for-related-code-that-handles-the-same-concept-is-the-reported-issue-a-symptom-of-something-broader",
"total_occurrences": 3,
"plan_count": 3,
"entries": [
{
"id": "DEBT-010",
"concern": "search for related code that handles the same concept. is the reported issue a symptom of something broader?: media processing state after success: the success criteria for text and outbound mention processed state, but revised steps 11 and 12 do not explicitly say successful voice or image messages should remain raw for the agentic loop rather than be marked processed by the media layer. this is likely intentional because plan 3 owns loop processing, but it is a contract point worth keeping visible so the executor does not mark media messages processed before the agent sees them.",
"occurrence_count": 1,
"plan_ids": [
"plan-2-whatsapp-ingestion-20260430-0549"
]
},
{
"id": "DEBT-013",
"concern": "search for related code that handles the same concept. is the reported issue a symptom of something broader?: checked the scope of the two-phase split against the five-primitive write tools. the split solves ordering, but it broadens orchestration complexity because phase b must reason over phase a's transcript and the sent outbound without read tools; this is a new design risk specifically for dedup and multi-primitive decisions.",
"occurrence_count": 1,
"plan_ids": [
"plan-3-agentic-loop-tools-20260430-0648"
]
},
{
"id": "DEBT-027",
"concern": "search for related code that handles the same concept. is the reported issue a symptom of something broader?: pause is broader than text/document inbound: process_inbound checks hooks.paused_for_user before coalescing text and document messages, but audio and image messages delegate to handle_voice and handle_image, and both media handlers call coalescer.add(user.id, message_id, user) after enrichment without any pause check. the plan's pause tests mention inbound persistence without enqueueing, but the implementation steps do not call out these media handlers, so paused voice/image messages can still enter the agentic loop if only inbound.py is updated.",
"occurrence_count": 1,
"plan_ids": [
"plan-5-scheduled-jobs-decay-20260430-1337"
]
}
]
}
]
code
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`.
Your output template is at: /Users/user_c042661f/Documents/Veas/.megaplan/plans/plan-6-onboarding-admin-view-20260430-1425/critique_output.json
Review the plan with a broad scope. Consider whether the approach is correct, whether it covers
all the places it needs to, whether it would break callers or violate codebase conventions,
and whether its verification strategy is adequate.
Place any concrete concerns in the flags array in the template file using the standard format
(id, concern, category, severity_hint, evidence). Leave checks as an empty array.
Workflow: read the file → investigate → read file again → add findings → write file back.
code
Additional guidelines:
- Robustness level: light. Be pragmatic. Only flag issues that would cause real failures. Ignore style, minor edge cases, and issues the executor will naturally resolve.
- 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":[],"flags":[{"id":"FLAG-001","concern":"Onboarding welcome gate: the planned first-inbound welcome ordering is unsafe. Step 2 allows the welcome send before or after inserting the inbound message, but send_outbound determines WhatsApp free-form eligibility from SELECT MAX(sent_at) FROM messages WHERE sender_id=$1 AND direction='inbound'; if the welcome runs before the inbound row is committed it will be withheld as outside the 24h window. The step also sends before the conditional WHERE onboarding_state='pending' state update, so two concurrent first webhooks can both observe pending and both send. The plan should require an atomic claim of pending state after inbound persistence and before sending, with duplicate/retry behavior defined.","category":"correctness","severity_hint":"likely-significant","evidence":"Plan Phase 1 Step 2 says to send the welcome 'before/after inbound insert' and then update state idempotently. In app/services/messaging.py, send_outbound checks the 24h window by reading the latest inbound message from the database before sending; in app/services/inbound.py, inbound rows are inserted by _insert_message before normal coalescing."},{"id":"FLAG-002","concern":"Spend-cap queuing: the graceful conversational cap-hit behavior is underspecified against the current recovery model. The idea requires one 'limits today' response and silent queueing, but the implementation plan only says to 'mark/leave' triggering messages recoverable. Today _run_agentic marks triggering messages processed before any LLM call, and startup recovery requeues incomplete bot_turns by triggering_message_ids regardless of failure_reason. Without a concrete deferred state, completed cap turn, or scheduled retry path, an implementation can either lose the original inbound burst or repeatedly requeue/send cap notices.","category":"correctness","severity_hint":"likely-significant","evidence":"Plan Phase 4 Step 9 describes the text cap fallback and vague queueing. app/services/agentic.py updates triggering messages to processing_state='processed' before run_phase; app/services/recovery.py re-adds old incomplete bot turns via coalescer.add_burst(...) and does not exclude failure_reason='spend_cap'."},{"id":"FLAG-003","concern":"Staging replay: the proposed simple dry-run path cannot run the existing loop as described. Step 12 suggests a DryRunPool that rejects mutating SQL, but the agentic path performs direct writes before it can produce candidate output: opening a bot_turn, marking inbound messages processed, logging tool calls, and recording spend. A reject-on-write pool will abort before replaying; a permissive pool risks touching production data. The plan needs an explicit dry-run adapter/refactor for these direct lifecycle writes, not just dry-run outbound/tool sinks.","category":"completeness","severity_hint":"likely-significant","evidence":"Plan Phase 5 Step 12 lists DryRunPool as the simplest path. app/services/agentic.py calls _open_turn with INSERT INTO bot_turns, then UPDATE messages SET processing_state='processed', and run_phase records tool calls through the registry/write tool path; spend is recorded in _record_response_cost."}],"verified_flag_ids":[],"disputed_flag_ids":[]}