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 preparing an execution-ready briefing document from the approved plan.
Plan 5 — Scheduled jobs + decay + pause/resume + crisis polish
Authoritative spec: mediator-bot-spec.md. Read in prep, focusing on: "Triggers" (scheduled), "Decay", "Multi-Message Handling" (restart recovery for jobs), "Pause / Resume", "Crisis Handling", "WhatsApp 24-Hour Window" for templates, and the bits of "Operations" related to scheduled jobs.
Plans 1–4 are assumed complete. The system can take messages, run the loop with real OOB and scoring, and produce outbounds. This plan adds the time-based behaviors and the global controls (pause, crisis escalation) that the spec describes.
Scope (in)
Scheduled-job worker
A single async worker (background task in the FastAPI app, or a separate Railway worker process — pick whichever is cleaner; document the choice).
Polls scheduled_jobs for status='pending' AND scheduled_for <= now() using SELECT ... FOR UPDATE SKIP LOCKED so two workers can't fire the same job. Each job has a unique ID for idempotency.
On fire: invoke the appropriate handler, then mark status='fired', set fired_at. On handler error: log and leave the job pending for one retry, then mark status='cancelled' with a reason.
Job types
weekly_summary — per partner. Renders the Meta-approved weekly_summary template ("Hi {{1}}, this week we had {{2}} conversations and touched on {{3}} ongoing things. Want to talk through anything? Just ask."). Sends via send_outbound (which handles 24h window). Also performs the decay housekeeping pass (below). Schedule recurrences on completion (one new job per partner per week, configurable timing per user).
checkin — variable check-in (4–24h, the loop chose the timing). One pending per user max. Inserting a new one supersedes any existing pending check-in for that user (mark old one status='superseded'). On fire: triggers the agentic loop with a trigger_metadata={"kind": "checkin", "context": ...} so the loop can produce a context-aware nudge or, if outside the 24h window, send the template.
Assistant
checkin_nudge
watch_item_due — fires when a watch item's due_at arrives. Surfaces it next time the owner is in conversation, OR creates a checkin job at a near-future time so the bot proactively raises it. Pick one based on whether the owner is currently in the 24h window.
oob_review — when an OOB's review_at hits. Triggers the loop with metadata so the bot asks the owner if it's still off-limits.
Late-job handling on restart
On startup: scan scheduled_jobs with status='pending' AND scheduled_for < now():
Less than 1h late → fire normally.
1–24h late → fire with context.delayed = true so the bot can adjust ("I meant to send this earlier...").
More than 24h late → mark cancelled with reason "too stale".
This is in addition to message-recovery from Plan 2.
Decay housekeeping (runs inside the weekly summary job)
Themes with no last_active_at update for 6+ weeks → dormant.
Themes dormant 4+ months → resolved_by_time.
Observations not reinforced for 3+ months → confidence drops one level (high→medium→low). Not reinforced for 6+ months → stale.
Watch items past due_at with no addressing for 30+ days → expired.
Also run the re-scoring pass for observations flagged needs_rescoring=true from Plan 4.
Query-level decay
Add a recency_weighted_score(significance, last_reinforced_at) SQL function or app-side helper. Formula per spec: significance / (1 + age_days / 60) where age_days = EXTRACT(EPOCH FROM (now() - COALESCE(last_reinforced_at, created_at))) / 86400. ~60-day effective half-life. Pure SQL, no exp() needed.
Update the read tools' default sorts to use it. Older content remains searchable but is deprioritized in default surfacing.
Timezone handling
Owner-bound scheduled jobs use the owner's users.timezone. The recurring weekly_summary fires at 09:00 in the owner's local time on the configured day.
schedule_checkin writes absolute UTC instants — the agentic loop converts "in 8 hours" / "tomorrow morning" to UTC at write time using the owner's timezone (timezone-aware datetime math, not naive arithmetic).
Heartbeat and other non-user-bound jobs use UTC.
Pause / Resume
/pause slash command (literal /pause in inbound text — this is the only slash command per spec): on receipt from either user:
Cancel all pending scheduled jobs for both users (status='superseded').
Set a global paused_at flag (one row in a small system_state table — create the table here).
Send pause confirmation outbound to each partner via the pause_confirmation template (works inside or outside 24h window).
The paused_for_user(user_id) hook from Plan 2 now reads from system_state and returns True when paused.
/resume from either partner:
Clear paused_at.
Do NOT auto-process backlog — just re-enable inbound processing.
Restore weekly summary scheduling (insert next weekly_summary jobs).
Crisis handling polish
The system prompt already (from Plan 3) instructs the loop to drop the mediator role and consider escalate_to_partner. This plan tightens the escalation flow:
Concrete gate per spec:escalate_to_partner may only be called when (a) the triggering message meets the crisis charge definition, OR (b) the user explicitly asks the bot to alert their partner. The tool input requires is_crisis: bool and a named reason. Reject any call that doesn't satisfy one of these triggers — the orchestrator validates before sending. This guard is in addition to the prompt-level instruction.
escalate_to_partner writes a distinguished bot_turns.reasoning entry and triggers an outbound to the OTHER partner using the escalation template — including outside the 24h window.
The {{3}} parameter is filled by the bot with a deliberately vague contextual line per spec ("They're going through a hard moment", etc.).
Logs the escalation with sufficient detail for retro audit (admin view in Plan 6 will surface it).
For acute crisis: the bot also surfaces region/language-appropriate emergency resources directly to the affected partner in the conversational outbound. Tested with a deterministic mock LLM.
Heartbeat upgrade
Plan 1 left a heartbeat stub. Implement it now as a periodic scheduled_jobs row of type heartbeat that fires daily and writes a log line; alerts on its absence are external (admin doc).
Scope (out, deliberately)
Admin UI surfaces for jobs/escalations (Plan 6).
Onboarding welcome flow (Plan 6).
Feedback collection (Plan 6).
Anything related to actual emergency resource curation — the spec is explicit that the LLM uses common sense for region/language; no static resource list to maintain here.
Success criteria
must: Scheduled-job worker fires weekly_summary for both partners on schedule, sends via send_outbound, and performs decay housekeeping in the same run.
must: checkin insertion supersedes prior pending check-ins for that user.
must: Late jobs on restart are categorized correctly (<1h, 1–24h, >24h) and handled per spec.
must: /pause halts both partners symmetrically; both receive pause_confirmation. /resume re-enables.
must: escalate_to_partner produces a templated outbound to the other partner using the escalation template, even outside the 24h window.
should: FOR UPDATE SKIP LOCKED poll is verified by a concurrent-worker test.
should: Recency-weighted sort is applied in default tool reads.
info: rescore_observations is invoked from the housekeeping pass.
Notes
Time travel for testing: use freezegun or pass an injectable now() so decay tests don't rely on real wall clock.
Be careful with the global pause flag — it must be checked in the agentic-loop entry path AND in scheduled-job handlers (a job firing while paused should no-op or the worker should skip pending jobs while paused; pick one approach and document).
The repo already has the core FastAPI lifecycle, WhatsApp inbound persistence, debounced agentic turns, outbound 24-hour template routing, scheduled check-in write tools, OOB checks, observation scoring, and a heartbeat stub. The main gap is turning scheduled_jobs into a real runtime system and wiring global controls around it.
I would implement the scheduler as an in-process FastAPI background task in app/main.py, not a separate Railway process. That is the smallest deployment change, and SELECT ... FOR UPDATE SKIP LOCKED still keeps it safe if Railway later runs multiple replicas. The worker logic should live in a separate service module so it can be unit-tested without app startup.
Phase 1: Database and Configuration Foundation
Step 1: Add Plan 5 migration (migrations/0004_plan5_scheduled_jobs.sql)
Scope: Medium
Add system_state as a singleton keyed table for paused_at, paused_by_user_id, and updated_at.
Extend scheduled_jobs.job_type to include heartbeat.
Add cancellation metadata to scheduled_jobs: cancelled_reason text, attempt_count int default 0, and optionally last_error text.
Add needs_rescoring boolean not null default false to observations, because Plan 5 references it but current code only infers rescoring from prompt version or failed scoring.
Add pure SQL function recency_weighted_score(significance integer, last_reinforced_at timestamptz, created_at timestamptz) implementing significance / (1 + age_days / 60).
Add indexes needed by the worker and housekeeping: pending jobs, needs_rescoring, open watch item due dates, and singleton system_state policy/RLS entries consistent with existing migrations.
Keep per-user weekly timing extensible via job context first, avoiding a users table schema change unless the product owner confirms dedicated per-user fields.
Phase 2: Scheduler Runtime
Step 3: Create scheduled job service (app/services/scheduled_jobs.py)
Scope: Large
Implement ScheduledJobWorker with a polling loop and a one-shot run_due_once(now=...) entry for tests.
Claim pending due jobs inside a transaction using SELECT ... FOR UPDATE SKIP LOCKED, increment attempt_count, then dispatch by job_type.
On success, mark jobs fired, set fired_at, and schedule recurrence where required.
On first handler error, leave the job pending with incremented attempt_count and last_error; on second failure, mark cancelled with a reason.
Check the global pause flag before dispatch. While paused, skip normal user-bound jobs instead of firing them. Let heartbeat continue because it is operational, not user-facing.
Step 4: Replace heartbeat stub (app/main.py)
Scope: Small
Remove the current heartbeat_loop() logger-only task.
Start the scheduled job worker in the FastAPI lifespan after recover_on_startup().
Ensure shutdown cancels and awaits the worker task like existing background tasks.
On startup, seed a pending heartbeat row if none exists.
Fetch the target user and compute the last-week conversation count and touched theme count with simple SQL.
Send through send_outbound() using TemplateCall("weekly_summary", [user.name, count, theme_count]) so 24-hour-window routing stays centralized.
Run housekeeping in the same handler after the send attempt.
Schedule the next weekly summary at 09:00 in the owner’s timezone, using timezone-aware zoneinfo conversion to UTC.
Add a helper to seed/restore weekly summaries for all users, used on startup and /resume.
Step 7: Implement housekeeping and decay (app/services/decay.py)
Scope: Large
Move periodic transitions into a focused module with run_decay_housekeeping(pool, now=...).
Themes with no last_active_at update for 6+ weeks become dormant.
Dormant themes whose dormant transition is 4+ months old become resolved_by_time; if no dormant_at column is added, use updated_at from the dormant transition.
Observations use COALESCE(last_reinforced_at, created_at), not last_active_at: 3+ months drops confidence one level, 6+ months marks stale.
Watch items open and due_at < now() - interval '30 days' become expired.
Call scoring.rescore_observations() for failed/old scores and rows flagged needs_rescoring=true, then clear the flag on success.
checkin: call a new job-trigger entry point in agentic.py with trigger_metadata={"kind":"checkin", "context": ...}. If outside the 24-hour window and no free-form output can be sent, use checkin_nudge template.
watch_item_due: if the owner is inside the WhatsApp window, trigger the agentic job entry point with the watch item context; otherwise insert a near-future checkin and supersede any pending check-in for that user.
oob_review: trigger the agentic job entry point with metadata naming the OOB entry and delayed context if present.
heartbeat: write the log line, mark fired, and schedule the next daily heartbeat row.
Add run_agentic_job(user, trigger_metadata) for scheduler-triggered turns without inbound message IDs.
Allow bot_turns.triggered_by_message_id to remain null and triggering_message_ids to be empty for scheduled triggers.
Extend hot context construction to accept explicit trigger metadata rather than only deriving it from message rows.
Keep normal inbound processing unchanged.
Phase 4: Pause and Resume
Step 10: Implement system pause state (app/services/system_state.py, app/services/hooks.py)
Scope: Medium
Add helpers is_paused(pool), pause(pool, user_id), and resume(pool).
Replace hooks.paused_for_user() stub with a DB-backed implementation. Because the current hook signature lacks a pool, either set a module-level pool during app startup or change call sites to pass pool explicitly; changing call sites is cleaner but broader.
Ensure send_outbound() can send pause confirmations even while paused. Add an internal bypass flag such as ignore_pause=True only for system-control notifications.
Step 11: Handle /pause and /resume in inbound processing (app/services/inbound.py)
Scope: Medium
Detect literal text commands after persisting the inbound message.
/pause: mark all pending scheduled jobs for both users superseded, set system_state.paused_at, and send pause_confirmation to both partners with the template fallback.
/resume: clear paused_at, restore weekly summary jobs for both users, and do not enqueue old raw backlog.
Preserve the existing behavior that inbound messages are still stored while paused.
Add tests for symmetry: either partner can pause or resume, and both partners receive confirmation.
Update default observation ordering to recency_weighted_score(significance, last_reinforced_at, created_at) DESC.
Update hot-context observation ordering the same way.
For themes, use app-side or SQL-compatible weighted ordering based on last_reinforced_at where significance is unavailable, likely by prioritizing health/status plus recency; do not invent theme significance without schema support.
Keep explicit non-default sorts like last_active behavior intact.
Step 13: Tighten schedule and escalation schemas (tool_schemas.py, app/services/tools/write_tools.py)
Scope: Medium
Keep schedule_checkin as the only agent-facing scheduler write tool, but document and enforce timezone-aware datetimes. Reject naive datetimes in schema validation if Pydantic allows it cleanly.
Confirm schedule_checkin already supersedes pending check-ins; add DB-level and unit coverage rather than changing the core behavior.
Tighten escalate_to_partner so is_crisis=true is accepted only when the current trigger charge is actually crisis, not merely because the model supplied the flag.
Keep explicit-user-request escalation allowed when the reason names that trigger.
Ensure the escalation outbound always uses the escalation template fallback and logs a distinguished reasoning line.
Phase 6: Tests and Validation
Step 14: Extend test fakes first (tests/conftest.py)
Scope: Medium
Teach FakePool about system_state, generic scheduled job statuses, attempt_count, cancelled_reason, heartbeat rows, and scheduler claim queries.
Keep fake SQL handling narrow to the actual queries introduced.
Weekly summary sends the correct template and invokes decay housekeeping.
Check-in insertion still supersedes prior pending check-ins.
Late restart recovery categorizes <1h, 1-24h, and >24h correctly.
Handler retry behavior leaves pending once, then cancels after the second failure.
FOR UPDATE SKIP LOCKED behavior is covered with either a real asyncpg/Postgres integration test if available or a fake concurrent-claim unit test plus SQL text assertion.
Deterministic mock LLM for acute crisis surfaces emergency-resource language to the affected partner.
escalate_to_partner rejects is_crisis=true when trigger metadata is not crisis and no explicit request exists.
Escalation still sends template fallback to the other partner outside the 24-hour window.
Execution Order
Land DB/config groundwork first so code has stable fields and settings.
Add scheduler service with no handlers beyond heartbeat, then wire startup/shutdown.
Add recovery classification and retry semantics before user-facing job handlers.
Implement weekly summary plus decay, then check-in/watch/OOB handlers.
Wire pause/resume and scheduler pause checks after system_state exists.
Tighten read sorting and crisis gates last, with tests already in place.
Validation Order
Run targeted unit tests for new modules first: tests/test_decay.py, tests/test_scheduled_jobs.py, tests/test_pause_resume.py.
Run existing tool and messaging tests next: tests/test_tools.py, tests/test_send_outbound.py, tests/test_agentic.py, tests/test_recovery.py.
Run the full suite with pytest.
If a Postgres test harness exists or can be added cheaply, run one integration check for the FOR UPDATE SKIP LOCKED claim query and migration SQL.
code
Plan metadata:
{
"version": 1,
"timestamp": "2026-04-30T11:40:14Z",
"hash": "sha256:1f123607ee05c6979ce91cf24633bbe18f0d29d5c4f7bd9433644a544ffc33b0",
"questions": [
"Where should weekly summary recurrence timing live long term: global env defaults only, new per-user columns, or JSON context on each weekly_summary job? The spec says configurable per user, but the current users table has only timezone.",
"Should /resume send a confirmation outbound, or silently re-enable? The idea only requires restoring scheduling and re-enabling inbound processing.",
"For watch_item_due, should the bot prefer immediate agentic triggering when inside the 24-hour window, or always create a near-future check-in to avoid surprise proactive messaging? I assumed immediate inside-window triggering because it best matches the brief.",
"For theme resolved_by_time, is adding a dormant_at column acceptable? Without it, using updated_at as the dormant timestamp is workable but less explicit."
],
"success_criteria": [
{
"criterion": "A scheduler worker claims pending due jobs with FOR UPDATE SKIP LOCKED, dispatches each supported job type, marks successful jobs fired with fired_at, and applies one retry before cancellation on repeated handler failure.",
"priority": "must",
"requires": [
"read_files",
"parse_diff",
"run_tests"
]
},
{
"criterion": "weekly_summary jobs send the approved weekly_summary template through send_outbound, run decay housekeeping in the same job, and schedule the next weekly job at 09:00 in the owner timezone.",
"priority": "must",
"requires": [
"read_files",
"run_tests",
"parse_diff"
]
},
{
"criterion": "schedule_checkin preserves one pending check-in per user by marking older pending check-ins superseded before inserting the new pending job.",
"priority": "must",
"requires": [
"run_tests",
"read_files"
]
},
{
"criterion": "Startup recovery categorizes late pending scheduled jobs as normal under 1 hour late, delayed from 1 to 24 hours late, and cancelled with reason too stale after 24 hours.",
"priority": "must",
"requires": [
"run_tests",
"read_files"
]
},
{
"criterion": "/pause from either partner sets global pause state, supersedes pending scheduled jobs for both users, prevents queued processing while still persisting inbound messages, and sends pause_confirmation to both partners.",
"priority": "must",
"requires": [
"run_tests",
"read_files",
"parse_diff"
]
},
{
"criterion": "/resume clears global pause state, does not process paused backlog, and restores pending weekly summary jobs.",
"priority": "must",
"requires": [
"run_tests",
"read_files",
"parse_diff"
]
},
{
"criterion": "escalate_to_partner rejects calls unless the triggering context is crisis or the user explicitly asked to alert the partner, logs a distinguished reasoning entry, and sends the other partner through the escalation template even outside the 24-hour window.",
"priority": "must",
"requires": [
"run_tests",
"read_files",
"parse_diff"
]
},
{
"criterion": "Decay housekeeping correctly transitions themes, observations, and watch items against deterministic time-traveled fixtures, and observation/theme decay uses last_reinforced_at or created_at rather than last_active_at where specified.",
"priority": "must",
"requires": [
"run_tests",
"read_files"
]
},
{
"criterion": "Default observation surfacing uses the recency-weighted score formula so older observations remain queryable but are deprioritized.",
"priority": "must",
"requires": [
"run_tests",
"read_files",
"parse_diff"
]
},
{
"criterion": "All existing and newly added tests pass with pytest.",
"priority": "must",
"requires": [
"run_tests"
]
},
{
"criterion": "Concurrent worker behavior is verified with a focused test or integration check that demonstrates the same job is not fired twice.",
"priority": "should",
"requires": [
"run_tests",
"read_files"
]
},
{
"criterion": "The scheduler and decay modules keep business logic separated from FastAPI startup code so handlers can be tested as one-shot functions.",
"priority": "should",
"requires": [
"read_files",
"parse_diff",
"subjective_judgment"
]
},
{
"criterion": "The implementation documents the deployment choice of in-process scheduler versus separate Railway worker in code comments or README-level operational notes.",
"priority": "should",
"requires": [
"read_files",
"parse_diff"
]
},
{
"criterion": "Manual Railway/external alerting for missing heartbeat is documented for humans but not implemented as an in-app alert.",
"priority": "info",
"requires": [
"read_files"
]
}
],
"assumptions": [
"Plans 1-4 are complete enough to rely on existing send_outbound, OOB checking, scoring, write tools, and the agentic loop rather than redesigning them.",
"Use an in-process FastAPI background scheduler for Plan 5; SKIP LOCKED makes it horizontally safe enough if multiple app instances later run it.",
"User-bound scheduled jobs store absolute UTC scheduled_for values; timezone conversion happens when creating recurring weekly jobs or agent-generated check-ins.",
"Pause is global for the two-partner system, not per-user, matching the spec symmetry note.",
"Heartbeat should continue while paused because it is operational telemetry, not user-facing mediation.",
"Pause confirmation must bypass the pause guard in send_outbound; other outbound remains blocked or withheld while paused.",
"No static emergency-resource database will be added; crisis-resource wording is left to the deterministic/mockable LLM path per spec.",
"If weekly summary per-user timing is not clarified, implement global env defaults plus per-job context overrides rather than adding user profile fields immediately."
],
"structure_warnings": []
}
code
Gate summary:
{
"passed": true,
"criteria_check": {
"count": 14,
"items": [
{
"criterion": "A scheduler worker claims pending due jobs with FOR UPDATE SKIP LOCKED, dispatches each supported job type, marks successful jobs fired with fired_at, and applies one retry before cancellation on repeated handler failure.",
"priority": "must",
"requires": [
"read_files",
"parse_diff",
"run_tests"
]
},
{
"criterion": "weekly_summary jobs send the approved weekly_summary template through send_outbound, run decay housekeeping in the same job, and schedule the next weekly job at 09:00 in the owner timezone.",
"priority": "must",
"requires": [
"read_files",
"run_tests",
"parse_diff"
]
},
{
"criterion": "schedule_checkin preserves one pending check-in per user by marking older pending check-ins superseded before inserting the new pending job.",
"priority": "must",
"requires": [
"run_tests",
"read_files"
]
},
{
"criterion": "Startup recovery categorizes late pending scheduled jobs as normal under 1 hour late, delayed from 1 to 24 hours late, and cancelled with reason too stale after 24 hours.",
"priority": "must",
"requires": [
"run_tests",
"read_files"
]
},
{
"criterion": "/pause from either partner sets global pause state, supersedes pending scheduled jobs for both users, prevents queued processing while still persisting inbound messages, and sends pause_confirmation to both partners.",
"priority": "must",
"requires": [
"run_tests",
"read_files",
"parse_diff"
]
},
{
"criterion": "/resume clears global pause state, does not process paused backlog, and restores pending weekly summary jobs.",
"priority": "must",
"requires": [
"run_tests",
"read_files",
"parse_diff"
]
},
{
"criterion": "escalate_to_partner rejects calls unless the triggering context is crisis or the user explicitly asked to alert the partner, logs a distinguished reasoning entry, and sends the other partner through the escalation template even outside the 24-hour window.",
"priority": "must",
"requires": [
"run_tests",
"read_files",
"parse_diff"
]
},
{
"criterion": "Decay housekeeping correctly transitions themes, observations, and watch items against deterministic time-traveled fixtures, and observation/theme decay uses last_reinforced_at or created_at rather than last_active_at where specified.",
"priority": "must",
"requires": [
"run_tests",
"read_files"
]
},
{
"criterion": "Default observation surfacing uses the recency-weighted score formula so older observations remain queryable but are deprioritized.",
"priority": "must",
"requires": [
"run_tests",
"read_files",
"parse_diff"
]
},
{
"criterion": "All existing and newly added tests pass with pytest.",
"priority": "must",
"requires": [
"run_tests"
]
},
{
"criterion": "Concurrent worker behavior is verified with a focused test or integration check that demonstrates the same job is not fired twice.",
"priority": "should",
"requires": [
"run_tests",
"read_files"
]
},
{
"criterion": "The scheduler and decay modules keep business logic separated from FastAPI startup code so handlers can be tested as one-shot functions.",
"priority": "should",
"requires": [
"read_files",
"parse_diff",
"subjective_judgment"
]
},
{
"criterion": "The implementation documents the deployment choice of in-process scheduler versus separate Railway worker in code comments or README-level operational notes.",
"priority": "should",
"requires": [
"read_files",
"parse_diff"
]
},
{
"criterion": "Manual Railway/external alerting for missing heartbeat is documented for humans but not implemented as an in-app alert.",
"priority": "info",
"requires": [
"read_files"
]
}
]
},
"preflight_results": {
"project_dir_exists": true,
"project_dir_writable": true,
"success_criteria_present": true,
"claude_available": true,
"codex_available": true
},
"unresolved_flags": [
{
"id": "FLAG-001",
"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.",
"category": "completeness",
"severity_hint": "likely-significant",
"evidence": "Spec requires weekly summary at 09:00 in the owner's timezone on the user's configured day; current users table has only timezone, and the plan supersedes all pending jobs on /pause then restores weekly summary jobs on /resume without defining a durable source for each user's configured day.",
"raised_in": "critique_v1.json",
"status": "open",
"severity": "significant",
"verified": false
},
{
"id": "FLAG-002",
"concern": "Query-level decay: nullable observation significance can break default weighted ordering unless null scores are explicitly handled.",
"category": "correctness",
"severity_hint": "likely-significant",
"evidence": "tool_schemas.ObservationRow.significance is nullable, failed scoring tests persist significance is None, and the planned recency_weighted_score(...) DESC sort does not mention NULLS LAST or COALESCE.",
"raised_in": "critique_v1.json",
"status": "open",
"severity": "significant",
"verified": false
},
{
"id": "FLAG-003",
"concern": "Pause/resume: media inbound paths can bypass the pause gate and enqueue voice/image messages after enrichment.",
"category": "correctness",
"severity_hint": "likely-significant",
"evidence": "app/services/transcription.py::handle_voice and app/services/vision.py::handle_image both call coalescer.add(user.id, message_id, user) without checking hooks.paused_for_user, while process_inbound only checks pause directly for text/document branches.",
"raised_in": "critique_v1.json",
"status": "open",
"severity": "significant",
"verified": false
},
{
"id": "FLAG-004",
"concern": "Check-in scheduling: one-pending-check-in invariant remains race-prone without a partial unique index or transactional locking strategy.",
"category": "correctness",
"severity_hint": "likely-significant",
"evidence": "Current schedule_checkin uses separate update and insert statements; the plan's migration step says indexes but not a unique partial constraint for (user_id) where job_type='checkin' and status='pending'.",
"raised_in": "critique_v1.json",
"status": "open",
"severity": "significant",
"verified": false
},
{
"id": "FLAG-005",
"concern": "Escalation gate: the plan does not define how the write tool receives authoritative trigger charge or explicit-request evidence.",
"category": "correctness",
"severity_hint": "likely-significant",
"evidence": "TurnContext currently carries triggering_message_ids but not trigger charge or explicit-request metadata; _trigger_charge is local to agentic.py, while write_tools.escalate_to_partner is where the planned validation would run.",
"raised_in": "critique_v1.json",
"status": "open",
"severity": "significant",
"verified": false
},
{
"id": "issue_hints",
"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.",
"category": "completeness",
"severity_hint": "likely-significant",
"evidence": "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.",
"raised_in": "critique_v1.json",
"status": "open",
"severity": "significant",
"verified": false
},
{
"id": "correctness-1",
"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.",
"category": "correctness",
"severity_hint": "likely-significant",
"evidence": "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.",
"raised_in": "critique_v1.json",
"status": "open",
"severity": "significant",
"verified": false
},
{
"id": "correctness-2",
"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.",
"category": "correctness",
"severity_hint": "likely-significant",
"evidence": "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.",
"raised_in": "critique_v1.json",
"status": "open",
"severity": "significant",
"verified": false
},
{
"id": "scope",
"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.",
"category": "completeness",
"severity_hint": "likely-significant",
"evidence": "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.",
"raised_in": "critique_v1.json",
"status": "open",
"severity": "significant",
"verified": false
},
{
"id": "all_locations",
"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.",
"category": "completeness",
"severity_hint": "likely-significant",
"evidence": "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.",
"raised_in": "critique_v1.json",
"status": "open",
"severity": "significant",
"verified": false
},
{
"id": "callers-1",
"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.",
"category": "correctness",
"severity_hint": "likely-significant",
"evidence": "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.",
"raised_in": "critique_v1.json",
"status": "open",
"severity": "significant",
"verified": false
},
{
"id": "callers-2",
"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.",
"category": "correctness",
"severity_hint": "likely-significant",
"evidence": "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.",
"raised_in": "critique_v1.json",
"status": "open",
"severity": "significant",
"verified": false
}
],
"recommendation": "PROCEED",
"rationale": "skip iter to keep moving per user directive",
"signals_assessment": "Forced proceed override applied by the orchestrator.",
"warnings": [],
"settled_decisions": [],
"override_forced": true,
"orchestrator_guidance": "Force-proceed override applied. Proceed to finalize.",
"robustness": "standard",
"signals": {
"iteration": 1,
"idea": "# Plan 5 \u2014 Scheduled jobs + decay + pause/resume + crisis polish\n\nAuthoritative spec: mediator-bot-spec.md. Read in prep, focusing on: "Triggers" (scheduled), "Decay", "Multi-Message Handling" (restart recovery for jobs), "Pause / Resume", "Crisis Handling", "WhatsApp 24-Hour Window" for templates, and the bits of "Operations" related to scheduled jobs.\n\nPlans 1\u20134 are assumed complete. The system can take messages, run the loop with real OOB and scoring, and produce outbounds. This plan adds the time-based behaviors and the global controls (pause, crisis escalation) that the spec describes.\n\n## Scope (in)\n\n### Scheduled-job worker\n- A single async worker (background task in the FastAPI app, or a separate Railway worker process \u2014 pick whichever is cleaner; document the choice).\n- Polls scheduled_jobs for status='pending' AND scheduled_for <= now() using SELECT ... FOR UPDATE SKIP LOCKED so two workers can't fire the same job. Each job has a unique ID for idempotency.\n- On fire: invoke the appropriate handler, then mark status='fired', set fired_at. On handler error: log and leave the job pending for one retry, then mark status='cancelled' with a reason.\n\n### Job types\n- weekly_summary \u2014 per partner. Renders the Meta-approved weekly_summary template ("Hi {{1}}, this week we had {{2}} conversations and touched on {{3}} ongoing things. Want to talk through anything? Just ask."). Sends via send_outbound (which handles 24h window). Also performs the decay housekeeping pass (below). Schedule recurrences on completion (one new job per partner per week, configurable timing per user).\n- checkin \u2014 variable check-in (4\u201324h, the loop chose the timing). One pending per user max. Inserting a new one supersedes any existing pending check-in for that user (mark old one status='superseded'). On fire: triggers the agentic loop with a trigger_metadata={\"kind\": \"checkin\", \"context\": ...} so the loop can produce a context-aware nudge or, if outside the 24h window, send the checkin_nudge template.\n- watch_item_due \u2014 fires when a watch item's due_at arrives. Surfaces it next time the owner is in conversation, OR creates a checkin job at a near-future time so the bot proactively raises it. Pick one based on whether the owner is currently in the 24h window.\n- oob_review \u2014 when an OOB's review_at hits. Triggers the loop with metadata so the bot asks the owner if it's still off-limits.\n\n### Late-job handling on restart\n- On startup: scan scheduled_jobs with status='pending' AND scheduled_for < now():\n - Less than 1h late \u2192 fire normally.\n - 1\u201324h late \u2192 fire with context.delayed = true so the bot can adjust ("I meant to send this earlier...").\n - More than 24h late \u2192 mark cancelled with reason \"too stale\".\n- This is in addition to message-recovery from Plan 2.\n\n### Decay housekeeping (runs inside the weekly summary job)\n- Themes with no last_active_at update for 6+ weeks \u2192 dormant.\n- Themes dormant 4+ months \u2192 resolved_by_time.\n- Observations not reinforced for 3+ months \u2192 confidence drops one level (high\u2192medium\u2192low). Not reinforced for 6+ months \u2192 stale.\n- Watch items past due_at with no addressing for 30+ days \u2192 expired.\n- last_reinforced_at (not last_active_at) drives observation/theme decay; verify the queries reflect that.\n- Also run the re-scoring pass for observations flagged needs_rescoring=true from Plan 4.\n\n### Query-level decay\n- Add a recency_weighted_score(significance, last_reinforced_at) SQL function or app-side helper. Formula per spec: significance / (1 + age_days / 60) where age_days = EXTRACT(EPOCH FROM (now() - COALESCE(last_reinforced_at, created_at))) / 86400. ~60-day effective half-life. Pure SQL, no exp() needed.\n- Update the read tools' default sorts to use it. Older content remains searchable but is deprioritized in default surfacing.\n\n### Timezone handling\n- Owner-bound scheduled jobs use the owner's users.timezone. The recurring weekly_summary fires at 09:00 in the owner's local time on the configured day.\n- schedule_checkin writes absolute UTC instants \u2014 the agentic loop converts "in 8 hours" / "tomorrow morning" to UTC at write time using the owner's timezone (timezone-aware datetime math, not naive arithmetic).\n- Heartbeat and other non-user-bound jobs use UTC.\n\n### Pause / Resume\n- /pause slash command (literal /pause in inbound text \u2014 this is the only slash command per spec): on receipt from either user:\n - Cancel all pending scheduled jobs for both users (status='superseded').\n - Set a global paused_at flag (one row in a small system_state table \u2014 create the table here).\n - Send pause confirmation outbound to each partner via the pause_confirmation template (works inside or outside 24h window).\n - The paused_for_user(user_id) hook from Plan 2 now reads from system_state and returns True when paused.\n- /resume from either partner:\n - Clear paused_at.\n - Do NOT auto-process backlog \u2014 just re-enable inbound processing.\n - Restore weekly summary scheduling (insert next weekly_summary jobs).\n\n### Crisis handling polish\n- The system prompt already (from Plan 3) instructs the loop to drop the mediator role and consider escalate_to_partner. This plan tightens the escalation flow:\n - Concrete gate per spec:escalate_to_partner may only be called when (a) the triggering message meets the crisis charge definition, OR (b) the user explicitly asks the bot to alert their partner. The tool input requires is_crisis: bool and a named reason. Reject any call that doesn't satisfy one of these triggers \u2014 the orchestrator validates before sending. This guard is in addition to the prompt-level instruction.\n - escalate_to_partner writes a distinguished bot_turns.reasoning entry and triggers an outbound to the OTHER partner using the escalation template \u2014 including outside the 24h window.\n - The {{3}} parameter is filled by the bot with a deliberately vague contextual line per spec ("They're going through a hard moment", etc.).\n - Logs the escalation with sufficient detail for retro audit (admin view in Plan 6 will surface it).\n- For acute crisis: the bot also surfaces region/language-appropriate emergency resources directly to the affected partner in the conversational outbound. Tested with a deterministic mock LLM.\n\n### Heartbeat upgrade\n- Plan 1 left a heartbeat stub. Implement it now as a periodic scheduled_jobs row of type heartbeat that fires daily and writes a log line; alerts on its absence are external (admin doc).\n\n## Scope (out, deliberately)\n- Admin UI surfaces for jobs/escalations (Plan 6).\n- Onboarding welcome flow (Plan 6).\n- Feedback collection (Plan 6).\n- Anything related to actual emergency resource curation \u2014 the spec is explicit that the LLM uses common sense for region/language; no static resource list to maintain here.\n\n## Success criteria\n- must: Scheduled-job worker fires weekly_summary for both partners on schedule, sends via send_outbound, and performs decay housekeeping in the same run.\n- must: checkin insertion supersedes prior pending check-ins for that user.\n- must: Late jobs on restart are categorized correctly (<1h, 1\u201324h, >24h) and handled per spec.\n- must: /pause halts both partners symmetrically; both receive pause_confirmation. /resume re-enables.\n- must: escalate_to_partner produces a templated outbound to the other partner using the escalation template, even outside the 24h window.\n- must: Decay transitions (theme dormant/resolved_by_time, observation confidence drop/stale, watch items expired) execute correctly against synthetic time-traveled fixtures.\n- should: FOR UPDATE SKIP LOCKED poll is verified by a concurrent-worker test.\n- should: Recency-weighted sort is applied in default tool reads.\n- info: rescore_observations is invoked from the housekeeping pass.\n\n## Notes\n- Time travel for testing: use freezegun or pass an injectable now() so decay tests don't rely on real wall clock.\n- Be careful with the global pause flag \u2014 it must be checked in the agentic-loop entry path AND in scheduled-job handlers (a job firing while paused should no-op or the worker should skip pending jobs while paused; pick one approach and document).",
"significant_flags": 12,
"unresolved_flags": [
{
"id": "FLAG-001",
"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.",
"category": "completeness",
"severity": "significant",
"status": "open"
},
{
"id": "FLAG-002",
"concern": "Query-level decay: nullable observation significance can break default weighted ordering unless null scores are explicitly handled.",
"category": "correctness",
"severity": "significant",
"status": "open"
},
{
"id": "FLAG-003",
"concern": "Pause/resume: media inbound paths can bypass the pause gate and enqueue voice/image messages after enrichment.",
"category": "correctness",
"severity": "significant",
"status": "open"
},
{
"id": "FLAG-004",
"concern": "Check-in scheduling: one-pending-check-in invariant remains race-prone without a partial unique index or transactional locking strategy.",
"category": "correctness",
"severity": "significant",
"status": "open"
},
{
"id": "FLAG-005",
"concern": "Escalation gate: the plan does not define how the write tool receives authoritative trigger charge or explicit-request evidence.",
"category": "correctness",
"severity": "significant",
"status": "open"
},
{
"id": "issue_hints",
"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.",
"category": "completeness",
"severity": "significant",
"status": "open"
},
{
"id": "correctness-1",
"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.",
"category": "correctness",
"severity": "significant",
"status": "open"
},
{
"id": "correctness-2",
"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.",
"category": "correctness",
"severity": "significant",
"status": "open"
},
{
"id": "scope",
"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.",
"category": "completeness",
"severity": "significant",
"status": "open"
},
{
"id": "all_locations",
"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.",
"category": "completeness",
"severity": "significant",
"status": "open"
},
{
"id": "callers-1",
"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.",
"category": "correctness",
"severity": "significant",
"status": "open"
},
{
"id": "callers-2",
"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.",
"category": "correctness",
"severity": "significant",
"status": "open"
}
],
"resolved_flags": [],
"weighted_score": 19.5,
"weighted_history": [
19.5
],
"plan_delta_from_previous": null,
"recurring_critiques": [],
"scope_creep_flags": [],
"loop_summary": "Iteration 1. Weighted score trajectory: 19.5 -> 19.5. Plan deltas: n/a. Recurring critiques: 0. Resolved flags: 0. Open significant flags: 12.",
"debt_overlaps": [],
"escalated_debt_subsystems": []
},
"flag_resolutions": [],
"resolved_flag_ids": [],
"resolution_summary": ""
}
code
Flag registry:
[
{
"id": "FLAG-001",
"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.",
"evidence": "Spec requires weekly summary at 09:00 in the owner's timezone on the user's configured day; current users table has only timezone, and the plan supersedes all pending jobs on /pause then restores weekly summary jobs on /resume without defining a durable source for each user's configured day.",
"status": "open",
"severity": "significant"
},
{
"id": "FLAG-002",
"concern": "Query-level decay: nullable observation significance can break default weighted ordering unless null scores are explicitly handled.",
"evidence": "tool_schemas.ObservationRow.significance is nullable, failed scoring tests persist significance is None, and the planned recency_weighted_score(...) DESC sort does not mention NULLS LAST or COALESCE.",
"status": "open",
"severity": "significant"
},
{
"id": "FLAG-003",
"concern": "Pause/resume: media inbound paths can bypass the pause gate and enqueue voice/image messages after enrichment.",
"evidence": "app/services/transcription.py::handle_voice and app/services/vision.py::handle_image both call coalescer.add(user.id, message_id, user) without checking hooks.paused_for_user, while process_inbound only checks pause directly for text/document branches.",
"status": "open",
"severity": "significant"
},
{
"id": "FLAG-004",
"concern": "Check-in scheduling: one-pending-check-in invariant remains race-prone without a partial unique index or transactional locking strategy.",
"evidence": "Current schedule_checkin uses separate update and insert statements; the plan's migration step says indexes but not a unique partial constraint for (user_id) where job_type='checkin' and status='pending'.",
"status": "open",
"severity": "significant"
},
{
"id": "FLAG-005",
"concern": "Escalation gate: the plan does not define how the write tool receives authoritative trigger charge or explicit-request evidence.",
"evidence": "TurnContext currently carries triggering_message_ids but not trigger charge or explicit-request metadata; _trigger_charge is local to agentic.py, while write_tools.escalate_to_partner is where the planned validation would run.",
"status": "open",
"severity": "significant"
},
{
"id": "verifiability-0",
"concern": "Criterion 11: requires human verification (subjective_judgment).",
"evidence": "",
"status": "open",
"severity": "minor"
},
{
"id": "issue_hints",
"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.",
"evidence": "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.",
"status": "open",
"severity": "significant"
},
{
"id": "correctness-1",
"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.",
"evidence": "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.",
"status": "open",
"severity": "significant"
},
{
"id": "correctness-2",
"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.",
"evidence": "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.",
"status": "open",
"severity": "significant"
},
{
"id": "scope",
"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.",
"evidence": "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.",
"status": "open",
"severity": "significant"
},
{
"id": "all_locations",
"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.",
"evidence": "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.",
"status": "open",
"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?: 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.",
"evidence": "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.",
"status": "open",
"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?: 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.",
"evidence": "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.",
"status": "open",
"severity": "significant"
}
]
"[DEBT] are-the-proposed-changes-technically-correct: 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. (flagged 1 times across 1 plans)",
"[DEBT] are-the-proposed-changes-technically-correct: 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. (flagged 1 times across 1 plans)",
"[DEBT] are-the-proposed-changes-technically-correct: 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. (flagged 1 times across 1 plans)",
"[DEBT] are-the-proposed-changes-technically-correct: 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. (flagged 1 times across 1 plans)",
"[DEBT] are-the-proposed-changes-technically-correct: 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. (flagged 1 times across 1 plans)",
"[DEBT] are-the-proposed-changes-technically-correct: 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. (flagged 1 times across 1 plans)",
"[DEBT] check-in-scheduling: check-in scheduling: one-pending-check-in invariant remains race-prone without a partial unique index or transactional locking strategy. (flagged 1 times across 1 plans)",
"[DEBT] debouncer: 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. (flagged 1 times across 1 plans)",
"[DEBT] did-the-work-fully-address-the-issue-hints-user-notes-and-approved-plan-requirements: 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. (flagged 1 times across 1 plans)",
"[DEBT] did-the-work-fully-address-the-issue-hints-user-notes-and-approved-plan-requirements: 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. (flagged 1 times across 1 plans)",
"[DEBT] does-the-change-touch-all-locations-and-supporting-infrastructure: 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. (flagged 1 times across 1 plans)",
"[DEBT] does-the-change-touch-all-locations-and-supporting-infrastructure: 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. (flagged 1 times across 1 plans)",
"[DEBT] does-the-change-touch-all-locations-and-supporting-infrastructure: 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. (flagged 1 times across 1 plans)",
"[DEBT] does-the-change-touch-all-locations-and-supporting-infrastructure: 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. (flagged 1 times across 1 plans)",
"[DEBT] edit-handling: 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. (flagged 1 times across 1 plans)",
"[DEBT] escalation-gate: escalation gate: the plan does not define how the write tool receives authoritative trigger charge or explicit-request evidence. (flagged 1 times across 1 plans)",
"[DEBT] escalation-gate-ordering: 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. (flagged 1 times across 1 plans)",
"[DEBT] find-the-callers-of-the-changed-function-what-arguments-do-they-actually-pass-does-the-fix-handle-all-of-them: 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. (flagged 1 times across 1 plans)",
"[DEBT] find-the-callers-of-the-changed-function-what-arguments-do-they-actually-pass-does-the-fix-handle-all-of-them: 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. (flagged 1 times across 1 plans)",
"[DEBT] find-the-callers-of-the-changed-function-what-arguments-do-they-actually-pass-does-the-fix-handle-all-of-them: 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. (flagged 1 times across 1 plans)",
"[DEBT] media-state: media state: the plan should explicitly keep successfully media-enriched inbound messages in processing_state='raw' until the agentic loop consumes them. (flagged 1 times across 1 plans)",
"[DEBT] pause-resume: pause/resume: media inbound paths can bypass the pause gate and enqueue voice/image messages after enrichment. (flagged 1 times across 1 plans)",
"[DEBT] query-level-decay: query-level decay: nullable observation significance can break default weighted ordering unless null scores are explicitly handled. (flagged 1 times across 1 plans)",
"[DEBT] recovery: 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. (flagged 1 times across 1 plans)",
"[DEBT] recovery-query: 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. (flagged 1 times across 1 plans)",
"[DEBT] search-for-related-code-that-handles-the-same-concept-is-the-reported-issue-a-symptom-of-something-broader: 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. (flagged 1 times across 1 plans)",
"[DEBT] search-for-related-code-that-handles-the-same-concept-is-the-reported-issue-a-symptom-of-something-broader: 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. (flagged 1 times across 1 plans)",
"[DEBT] search-for-related-code-that-handles-the-same-concept-is-the-reported-issue-a-symptom-of-something-broader: 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. (flagged 1 times across 1 plans)",
"[DEBT] two-phase-dedup-tension: 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. (flagged 1 times across 1 plans)",
"[DEBT] weekly-summary-scheduling: weekly summary scheduling: per-user configured day can be lost on pause/resume if timing exists only in pending job context or global defaults. (flagged 1 times across 1 plans)"
]
code
Requirements:
- Produce structured JSON only.
- `tasks` must be an ordered array of task objects. Every task object must include:
- `id`: short stable task ID like `T1`
- `description`: concrete work item
- `depends_on`: array of earlier task IDs or `[]`
- `status`: always `"pending"` at finalize time
- `executor_notes`: always `""` at finalize time
- `reviewer_verdict`: always `""` at finalize time
- `watch_items` must be an array of strings covering runtime risks, critique concerns, and assumptions to keep visible during execution.
- `sense_checks` must be an array with one verification question per task. Every sense-check object must include:
- `id`: short stable ID like `SC1`
- `task_id`: the related task ID
- `question`: reviewer verification question
- `verdict`: always `""` at finalize time
- `user_actions` must be an array of human-only setup or operational actions. Use IDs `U1`, `U2`, ... and include `description` plus `phase` (`before_execute` or `after_execute`). Use optional `blocks_task_ids` when an action blocks specific tasks, optional `rationale` when useful, and `requires_human_only_reason` ONLY when the user_action is the sole coverage for a plan step.
Include ONLY actions that require a human outside the executor's repo-editing work: env vars or secrets, infra access such as cloud accounts or VPN, DB migrations the human must trigger, manual UI/UX smoke tests, deploys, and out-of-band approvals.
Anything that touches code in the repo MUST be a task, not a user_action. Reading docs, editing files, running tests, and writing migration SQL are tasks. Negative example: writing the migration SQL is a task, not a user_action.
Positive examples: U1: Set ANTHROPIC_API_KEY in .env (before_execute); U2: Manually smoke test the production deploy in the browser (after_execute).
- meta_commentary must be a single string with execution guidance, gotchas, or judgment calls that help the executor succeed.
- validation must be an object that self-checks plan coverage:
- plan_steps_covered: enumerate EVERY step from the approved plan. For each step, provide a short plan_step_summary (the step's intent in one phrase) and finalize_item_ids (array of task IDs T* or user_action IDs U* that implement or cover it — a single plan step may map to multiple tasks and/or user_actions).
- orphan_tasks: task IDs that do not correspond to any plan step. Normally empty. If non-empty, explain in completeness_notes.
- completeness_notes: free-text explanation of any gaps, deviations, or deliberate omissions.
- coverage_complete: set to true only if every plan step has at least one finalize task or user_action AND you have verified the mapping by reviewing each entry. Set to false if any plan step is missing coverage.
- Example:
json "validation": { "plan_steps_covered": [ {"plan_step_summary": "Add retry logic to API client", "finalize_item_ids": ["T1", "T2"]}, {"plan_step_summary": "Set required production secret", "finalize_item_ids": ["U1"]} ], "orphan_tasks": [], "completeness_notes": "All plan steps mapped to tasks.", "coverage_complete": true }
- Preserve information that strong existing artifacts already capture well: execution ordering, watch-outs, reviewer checkpoints, and practical context.
- The structured output should be self-contained: an executor reading only finalize.json should have everything needed to work.
- Keep the task count proportional to the work. A simple 1-2 file fix should be 2 tasks: (1) apply the fix, (2) run tests. Do NOT create separate "inspect" or "read" tasks for simple changes — the executor can read and fix in one step. Only create more tasks when the work has genuinely independent stages.
- - The FINAL task MUST always be to run tests and verify the changes work. If specific test IDs or commands are mentioned in the original task, include them. Otherwise, the executor should find and run the tests most relevant to the files changed. If any test fails, read the error, fix the code, and re-run until they pass. Do NOT create new test files — run the project's existing test suite. Additionally, the executor should write a short throwaway script that reproduces the specific bug described in the task, run it to confirm the fix works, then delete the script.
{"tasks":[{"id":"T1","description":"Add the Plan 5 database/config foundation: create migrations/0004_plan5_scheduled_jobs.sql with system_state, scheduler metadata fields, heartbeat job support, observations.needs_rescoring, durable weekly-summary schedule fields or equivalent durable per-user source, null-safe recency_weighted_score(...), worker/housekeeping indexes, a partial unique constraint for one pending checkin per user, and matching RLS/policies. Add scheduler settings in app/config.py for enablement, poll interval, batch size, weekly defaults, and heartbeat cadence.","depends_on":[],"status":"pending","executor_notes":"","files_changed":[],"commands_run":[],"auto_attributed_files":null,"evidence_files":[],"reviewer_verdict":"","stance":null,"stop_signal":null},{"id":"T2","description":"Implement scheduler runtime and startup recovery: add app/services/scheduled_jobs.py with a testable ScheduledJobWorker.run_due_once(now=...), transactional SELECT ... FOR UPDATE SKIP LOCKED claiming, dispatch, success marking, one retry then cancellation, pause-aware skipping for user-facing jobs, heartbeat continuation while paused, and seed_heartbeat. Replace the FastAPI heartbeat stub in app/main.py with worker lifecycle wiring. Extend app/services/recovery.py to classify late pending jobs as normal under 1 hour, delayed between 1 and 24 hours, and cancelled with too stale after 24 hours.","depends_on":["T1"],"status":"pending","executor_notes":"","files_changed":[],"commands_run":[],"auto_attributed_files":null,"evidence_files":[],"reviewer_verdict":"","stance":null,"stop_signal":null},{"id":"T3","description":"Implement scheduled job handlers and scheduled agentic entry points: weekly summaries send the approved weekly_summary template through send_outbound, run housekeeping, and schedule the next local-09:00 recurrence from durable per-user timing; checkin, watch_item_due, and oob_review trigger run_agentic_job(user, trigger_metadata) or template fallback as specified; heartbeat writes a log line and schedules the next row. Extend agentic.py and hot_context.py so scheduled triggers can run without inbound message IDs.","depends_on":["T2"],"status":"pending","executor_notes":"","files_changed":[],"commands_run":[],"auto_attributed_files":null,"evidence_files":[],"reviewer_verdict":"","stance":null,"stop_signal":null},{"id":"T4","description":"Add focused decay housekeeping in app/services/decay.py: transition stale themes to dormant, dormant themes to resolved_by_time, observations through confidence drop and stale based on COALESCE(last_reinforced_at, created_at), expire old watch items, invoke observation rescoring for failed/old and needs_rescoring=true rows, and clear the flag only on successful rescore.","depends_on":["T1"],"status":"pending","executor_notes":"","files_changed":[],"commands_run":[],"auto_attributed_files":null,"evidence_files":[],"reviewer_verdict":"","stance":null,"stop_signal":null},{"id":"T5","description":"Implement global pause/resume: add app/services/system_state.py, make paused_for_user DB-backed without breaking all existing callers, add send_outbound(..., ignore_pause=False) and use ignore_pause=True for pause confirmations, detect literal /pause and /resume after inbound persistence, supersede all pending user-facing jobs on pause, clear pause and restore weekly summaries on resume, and ensure text, document, voice, and image inbound paths persist but do not enqueue while paused.","depends_on":["T1","T3"],"status":"pending","executor_notes":"","files_changed":[],"commands_run":[],"auto_attributed_files":null,"evidence_files":[],"reviewer_verdict":"","stance":null,"stop_signal":null},{"id":"T6","description":"Apply read-side query decay: update default observation ordering in read tools and hot context to use the SQL weighted score with explicit null handling (NULLS LAST or COALESCE) so null-scored observations cannot sort ahead of scored rows. Keep explicit alternate sorts unchanged, and avoid inventing theme significance where the schema does not support it.","depends_on":["T1"],"status":"pending","executor_notes":"","files_changed":[],"commands_run":[],"auto_attributed_files":null,"evidence_files":[],"reviewer_verdict":"","stance":null,"stop_signal":null},{"id":"T7","description":"Tighten write-tool contracts: keep schedule_checkin transactional and compatible with the partial unique constraint, reject or normalize naive datetimes so check-ins are stored as absolute UTC instants, and update escalate_to_partner so validation happens before any outbound send using authoritative TurnContext metadata for trigger charge and explicit partner-alert requests. Log a distinguished escalation reasoning entry and always use the escalation template fallback for the other partner when allowed.","depends_on":["T1","T3"],"status":"pending","executor_notes":"","files_changed":[],"commands_run":[],"auto_attributed_files":null,"evidence_files":[],"reviewer_verdict":"","stance":null,"stop_signal":null},{"id":"T8","description":"Update test fakes and focused tests for scheduler, pause/resume, decay, sorting, and crisis behavior: extend FakePool narrowly for new scheduler/system_state fields and queries; add or update tests covering weekly summary plus decay, check-in superseding and race protection, late-job recovery, retry cancellation, SKIP LOCKED/concurrent claim behavior, pause symmetry including media paths, resume without backlog replay, deterministic decay thresholds, weighted ordering with null significance, and escalation gate/template fallback.","depends_on":["T2","T3","T4","T5","T6","T7"],"status":"pending","executor_notes":"","files_changed":[],"commands_run":[],"auto_attributed_files":null,"evidence_files":[],"reviewer_verdict":"","stance":null,"stop_signal":null},{"id":"T9","description":"Document operational choices in repo docs or comments: in-process FastAPI scheduler rationale, horizontal safety via SKIP LOCKED, heartbeat-as-scheduled-job behavior, external/Railway alerting expectations for missing heartbeat, and any weekly-summary timing source chosen for per-user recurrence.","depends_on":["T2","T3"],"status":"pending","executor_notes":"","files_changed":[],"commands_run":[],"auto_attributed_files":null,"evidence_files":[],"reviewer_verdict":"","stance":null,"stop_signal":null},{"id":"T10","description":"Run validation and fix until clean: run targeted tests first (tests/test_decay.py, tests/test_scheduled_jobs.py, tests/test_pause_resume.py, tests/test_tools.py, tests/test_hot_context.py, tests/test_agentic.py, tests/test_recovery.py, tests/test_send_outbound.py where present), then full pytest. Also write a short throwaway script outside the repo or in /tmp that reproduces the highest-risk bug paths from this plan, especially check-in uniqueness and pause media enqueue prevention, run it, confirm the fixes, and delete it before finishing. Do not create additional test files in this final validation task.","depends_on":["T8","T9"],"status":"pending","executor_notes":"","files_changed":[],"commands_run":[],"auto_attributed_files":null,"evidence_files":[],"reviewer_verdict":"","stance":null,"stop_signal":null}],"watch_items":["Durable weekly-summary timing is mandatory: pause/resume must not lose a user's configured day/time. Prefer explicit per-user fields or a clearly durable source over pending-job context alone.","Observation significance is nullable. Weighted ordering must use NULLS LAST or COALESCE, and tests should include failed/unscored observations.","Pause must cover all enqueue paths, including voice and image handlers after media enrichment, not just text/document inbound branches.","The one-pending-check-in invariant is race-prone without a partial unique index or equivalent transactional locking. Add DB enforcement and handle conflicts intentionally.","Escalation validation needs authoritative context. Add trigger charge and explicit-alert-request evidence to TurnContext or another trusted validator input before the write tool runs.","Escalation gate must run before any outbound send. This is an existing debt item from prior plans.","Pause confirmations must bypass pause withholding by passing ignore_pause=True; ordinary outbound should still respect pause.","If paused_for_user signature changes, update all callers and tests together: messaging, inbound, agentic, media paths, and monkeypatch fixtures.","Scheduled worker should leave user-facing jobs pending while paused or otherwise avoid firing user messages; heartbeat should still run.","Late recovery should only annotate/cancel jobs and let the worker perform normal dispatch to preserve retry/idempotency semantics.","Do not mark successfully enriched media messages processed before the agentic loop consumes them; preserve the raw-message contract from prior plans.","Keep scheduler and decay logic in testable service modules, with FastAPI startup limited to lifecycle wiring.","No static emergency-resource database is in scope; crisis-resource language remains LLM/mock driven.","The final validation task should not add more test files. Add planned tests in T8, then use the final task only to run tests and a deleted throwaway reproduction script."],"sense_checks":[{"id":"SC1","task_id":"T1","question":"Does the migration/config layer include every durable field and constraint needed for scheduler retries, heartbeat, pause state, rescoring, per-user weekly timing, null-safe recency scoring, and one pending check-in per user?","executor_note":"","verdict":""},{"id":"SC2","task_id":"T2","question":"Can two workers claim due jobs without double-firing, and does startup recovery classify late jobs exactly as under 1h, 1-24h delayed, and over 24h cancelled with too stale?","executor_note":"","verdict":""},{"id":"SC3","task_id":"T3","question":"Does each job type dispatch to the specified behavior, and do weekly summaries both send the approved template and schedule the next local-09:00 recurrence from durable user timing?","executor_note":"","verdict":""},{"id":"SC4","task_id":"T4","question":"Do decay queries use last_reinforced_at or created_at where required, avoid last_active_at for observation decay, and clear needs_rescoring only after successful rescoring?","executor_note":"","verdict":""},{"id":"SC5","task_id":"T5","question":"While paused, are inbound messages of every supported type persisted but prevented from entering the coalescer/agentic loop, and do both partners receive pause confirmation despite pause being active?","executor_note":"","verdict":""},{"id":"SC6","task_id":"T6","question":"Do default observation reads and hot context sort by recency-weighted score without allowing null significance rows to sort above valid scored rows?","executor_note":"","verdict":""},{"id":"SC7","task_id":"T7","question":"Can escalate_to_partner only send after a trusted crisis trigger or explicit partner-alert request is proven, and is the guard executed before any template outbound?","executor_note":"","verdict":""},{"id":"SC8","task_id":"T8","question":"Do the focused tests exercise all Plan 5 success criteria plus the critique flags: weekly timing persistence, null weighted sort, media pause paths, check-in uniqueness, and escalation metadata?","executor_note":"","verdict":""},{"id":"SC9","task_id":"T9","question":"Is the in-process scheduler choice and external heartbeat alerting expectation documented clearly enough for a future deploy/operator to understand the runtime model?","executor_note":"","verdict":""},{"id":"SC10","task_id":"T10","question":"Do targeted tests, full pytest, and the deleted throwaway reproduction script all pass after fixes, with no lingering generated test artifacts?","executor_note":"","verdict":""}],"user_actions":[{"id":"U1","description":"After code lands, set any new scheduler environment variables in the deployment environment if defaults are not acceptable: worker enabled flag, poll interval, batch size, weekly summary default day/time, and heartbeat cadence.","phase":"after_execute","blocks_task_ids":null,"rationale":"Executor can add config defaults, but production env values require deployment access.","requires_human_only_reason":null},{"id":"U2","description":"Apply the new database migration in the target environment before deploying scheduler-enabled code.","phase":"after_execute","blocks_task_ids":null,"rationale":"Writing migration SQL is executor work; running it against production/staging may require human-controlled DB access.","requires_human_only_reason":null},{"id":"U3","description":"Configure or verify external Railway/monitoring alerting for absence of the daily heartbeat log after deployment.","phase":"after_execute","blocks_task_ids":null,"rationale":"The plan explicitly keeps missing-heartbeat alerting outside the app.","requires_human_only_reason":null},{"id":"U4","description":"Smoke test a deployed pause/resume and scheduled-job flow in the real WhatsApp/Railway environment after migration and deploy.","phase":"after_execute","blocks_task_ids":null,"rationale":"Automated tests cover repo behavior, but real Meta template routing and production worker lifecycle need an operational check.","requires_human_only_reason":null}],"meta_commentary":"Execute this as a staged implementation, but keep the critique flags in front of you. The approved plan is sound only if you close the open correctness gaps: durable weekly-summary timing, null-safe recency ordering, media pause coverage, DB-enforced check-in uniqueness, and trusted escalation metadata. Prefer small service modules with injectable now and one-shot methods so tests do not depend on FastAPI startup or wall-clock time. When in doubt, preserve existing inbound/outbound contracts from Plans 1-4 instead of reshaping them broadly.","validation":{"plan_steps_covered":[{"plan_step_summary":"Step 1: Add Plan 5 migration for scheduler, state, rescoring, recency function, and indexes","finalize_item_ids":["T1"]},{"plan_step_summary":"Step 2: Add scheduler settings","finalize_item_ids":["T1","U1"]},{"plan_step_summary":"Step 3: Create scheduled job service and worker","finalize_item_ids":["T2"]},{"plan_step_summary":"Step 4: Replace heartbeat stub and wire app lifecycle","finalize_item_ids":["T2"]},{"plan_step_summary":"Step 5: Add startup late-job recovery","finalize_item_ids":["T2"]},{"plan_step_summary":"Step 6: Implement weekly summary handler","finalize_item_ids":["T3","T4"]},{"plan_step_summary":"Step 7: Implement housekeeping and decay","finalize_item_ids":["T4"]},{"plan_step_summary":"Step 8: Implement check-in, watch item, OOB review, and heartbeat handlers","finalize_item_ids":["T3"]},{"plan_step_summary":"Step 9: Add job-triggered agentic turns","finalize_item_ids":["T3"]},{"plan_step_summary":"Step 10: Implement system pause state","finalize_item_ids":["T5"]},{"plan_step_summary":"Step 11: Handle /pause and /resume inbound commands","finalize_item_ids":["T5"]},{"plan_step_summary":"Step 12: Apply recency-weighted reads","finalize_item_ids":["T6"]},{"plan_step_summary":"Step 13: Tighten schedule and escalation schemas","finalize_item_ids":["T7"]},{"plan_step_summary":"Step 14: Extend test fakes first","finalize_item_ids":["T8"]},{"plan_step_summary":"Step 15: Add focused scheduler tests","finalize_item_ids":["T8","T10"]},{"plan_step_summary":"Step 16: Add pause/resume tests","finalize_item_ids":["T8","T10"]},{"plan_step_summary":"Step 17: Add decay and sorting tests","finalize_item_ids":["T8","T10"]},{"plan_step_summary":"Step 18: Add crisis polish tests","finalize_item_ids":["T8","T10"]},{"plan_step_summary":"Operational documentation for scheduler deployment choice and heartbeat alerting","finalize_item_ids":["T9","U3"]},{"plan_step_summary":"Production migration, env, deploy, and smoke-test operations","finalize_item_ids":["U1","U2","U4"]}],"orphan_tasks":[],"completeness_notes":"All approved plan steps are mapped. The briefing deliberately strengthens the approved plan where critique found gaps: it requires durable per-user weekly timing, null-safe weighted ordering, media pause coverage, DB-level check-in uniqueness, and trusted escalation metadata. User actions are limited to human-controlled deployment, environment, migration, monitoring, and smoke-test operations.","coverage_complete":true},"baseline_test_failures":null,"baseline_test_command":null,"baseline_test_note":"No baseline tests were run during briefing generation; execution task T10 requires targeted and full pytest validation."}