You are already running inside the megaplan harness for this step. Do the requested…
- User
You are already running inside the megaplan harness for this step. Do the requested planning/review/execution work directly. Do NOT invoke the
megaplanCLI, do NOT read or activate themegaplanskill, 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.WRITE ACCESS CONTRACT: You are running with auto-approved writes inside a writable workspace. Treat the working directory as fully writable. Do NOT preemptively skip or block tasks on permission, sandbox, or read-only grounds. Attempt every required edit; only report failure AFTER a real OS-level rejection from a specific shell command. Do not infer 'read-only' from absence of activity; absence is not denial. If a single shell command unexpectedly fails, retry with a different invocation before concluding the environment is restricted.
You are creating an implementation plan for the following idea.
codeIdea:Plan 5b — Plan-5 recovery: pause/resume + write-tool tightening + tests + docs + validation
Authoritative spec:
mediator-bot-spec.md. Read in prep, focusing on: "Pause / Resume", "Crisis Handling" (escalation gate), "Triggers" (scheduled), "Decay" (only as it relates to test coverage), and the relevant parts of "Multi-Message Handling" (media paths under pause).Background
Plan-5 (
plan-5-scheduled-jobs-decay-20260430-1337) was force-proceeded todoneafter codex pre-emptively skipped 5 of 11 tasks in batch 4 onward. The codex executor hallucinated a read-only sandbox and refused before attempting the work. The root cause has been fixed in megaplan (workers.py→_codex_exec_mode_flagsnow always returns--full-autofor non-execute phases, and execute on macOS already had it). With that fix in place, this plan re-runs the five skipped tasks against the existing repo state.The work that landed in plan-5 (do not redo): migration
0004_plan5_scheduled_jobs.sql,app/services/scheduled_jobs.py,app/services/scheduled_job_handlers.py,app/services/decay.py, and the recency-weighted query/sort updates in read tools and hot context.The five tasks below were skipped and must land here. Descriptions are pulled verbatim from plan-5's
finalize.jsonso wording matches the original briefing.Scope (in)
T1 — Global pause/resume (was plan-5 T5)
Implement global pause/resume: add
app/services/system_state.py, makepaused_for_userDB-backed without breaking all existing callers, addsend_outbound(..., ignore_pause=False)and useignore_pause=Truefor pause confirmations, detect literal/pauseand/resumeafter 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.T2 — Write-tool tightening (was plan-5 T7)
Tighten write-tool contracts: keep
schedule_checkintransactional and compatible with the partial unique constraint, reject or normalize naive datetimes so check-ins are stored as absolute UTC instants, and updateescalate_to_partnerso validation happens before any outbound send using authoritativeTurnContextmetadata for trigger charge and explicit partner-alert requests. Log a distinguished escalation reasoning entry and always use theescalationtemplate fallback for the other partner when allowed.T3 — Tests (was plan-5 T8)
Update test fakes and focused tests for scheduler, pause/resume, decay, sorting, and crisis behavior: extend
FakePoolnarrowly 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.T4 — Operational docs (was plan-5 T9)
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.
T5 — Validation (was plan-5 T10)
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.pywhere present), then fullpytest. Also write a short throwaway script in/tmpthat 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.Scope (out, deliberately)
- Re-running anything plan-5 actually completed (T1–T4, T6, T11). Inspect first; do not duplicate.
- Anything from plan-6 (admin view, onboarding, audit, feedback) — that's a separate plan.
- Anything from plan-7 (evals).
Success criteria
must:app/services/system_state.pyexists;paused_for_user(user_id)reads fromsystem_state;/pauseand/resumeliteral slash commands halt and resume both partners symmetrically; pause confirmations useignore_pause=Trueto send through the pause.must:schedule_checkinis transactional under concurrent calls (no double-insert under the partial unique constraint); naive datetimes are rejected or normalized to UTC.must:escalate_to_partnervalidates the gate (crisis charge OR explicit partner-alert request) BEFORE callingsend_outbound, usingTurnContextmetadata as the source of truth.must:pytestis green fortests/test_pause_resume.py(new),tests/test_scheduled_jobs.py,tests/test_decay.py, and any pre-existing tests that continue to apply.must: Operator docs (README ordocs/scheduler.md) explain the scheduler runtime, SKIP LOCKED safety, heartbeat-as-job, and missing-heartbeat alerting.should: Concurrent-claim behavior is covered by a test that fires twoScheduledJobWorker.run_due_once()calls against the same backlog and asserts no double-firing.info: Throwaway repro script in/tmpwas written, run, and deleted (mention in commit/notes).
Notes
-
This is light robustness — one critique + revise iteration, then finalize → execute. No gate, no review.
-
Codex now runs with
--full-autofor all phases on this machine (megaplan fix landed). If a task still hits a "read-only" hallucination, retry once with--fresh. Do not skip pre-emptively. -
Read plan-5's
plan_v1.mdandfinalize.jsonfor design context; do not reinvent decisions plan-5 already made. -
All five tasks should land in a single execute pass — they're not deeply interlocked, but they share
FakePoolextensions andsystem_stateimport surface, so coordinated edits are easier than serial.codeProject directory: /Users/user_c042661f/Documents/Veas No prior clarification artifact exists. Identify ambiguities, ask clarifying questions, and state your assumptions inside the plan output. Requirements: - If the engineering brief suggests an approach, use it as your starting hypothesis — but before committing, consider if there's a simpler or more fundamental fix. The brief is well-researched input, not a final answer. - If the brief is absent, incomplete, or says "skip", inspect the repository yourself before planning. - Stay focused on the requested idea. If repo exploration surfaces unrelated issues or docs, ignore them and return to the task. - Prefer source code, tests, and directly relevant config files. Avoid `.megaplan/`, prior plan artifacts, and unrelated `docs/` or ops/deployment material unless the task explicitly depends on them. - Stop exploring once you have enough evidence to name the concrete touch points and validation path. Do not keep browsing after you can write the plan. - Produce a concrete implementation plan in markdown. - Define observable success criteria as objects with `criterion` (string) and `priority` (`must`, `should`, or `info`): - `must` — hard gate. The reviewer will block on failure. Use for correctness, functional requirements, and verifiable outcomes (e.g., "all existing tests pass", "API returns 200 for valid input"). Every `must` criterion must have a clear yes/no answer. - `should` — quality target. The reviewer flags but does not block. Use for subjective goals, numeric guidelines, and best-effort improvements (e.g., "file under ~300 lines", "no deeply nested conditionals", "each function has a single responsibility"). - `info` — documented for humans, reviewer skips. Use for criteria that cannot be verified in this pipeline (e.g., "13 manual smoke tests pass", "stakeholder sign-off obtained"). - Each success criterion should include a `requires` field listing the capabilities needed for verification. Valid capability strings: `run_shell`, `read_files`, `run_tests`, `parse_diff`, `read_build_output`, `run_linter` (container), `drive_browser`, `inspect_runtime_ui`, `observe_runtime_logs`, `subjective_judgment`, `verify_physical_device` (human). `must` criteria MUST have non-empty `requires`. Example: `{"criterion": "All tests pass", "priority": "must", "requires": ["run_tests"]}`. - Use the `questions` field for ambiguities that would materially change implementation. - Use the `assumptions` field for defaults you are making so planning can proceed now. - Prefer cheap validation steps early. - Keep the plan proportional to the task. A 1-line fix needs a 2-step plan (apply fix + run tests), not a 5-step investigation. - If user notes answer earlier questions, incorporate them into the draft plan instead of re-asking them. - Fix the problem fully. Do not limit scope just to avoid breaking existing tests — update the tests too if needed. - Prefer the simplest, most direct fix. No fallbacks, type conversions, or defensive wrappers without concrete evidence they are needed. - If the task or issue hints suggest a specific approach, follow it. Only deviate with concrete counter-evidence. Plan template — simple format (adapt to the actual repo and scope):
md# Implementation Plan: [Title] ## Overview Summarize the goal, current repository shape, and the constraints that matter. ## Main Phase ### Step 1: Audit the current behavior (`megaplan/prompts.py`) **Scope:** Small 1. **Inspect** the current implementation and call out the exact insertion points (`megaplan/prompts.py:29`). ### Step 2: Add the first change (`megaplan/evaluation.py`) **Scope:** Medium 1. **Implement** the smallest viable change with exact file references (`megaplan/evaluation.py:1`). 2. **Capture** any tricky behavior with a short example. ```python issues = validate_plan_structure(plan_text) ``` ### Step 3: Wire downstream behavior (`megaplan/handlers.py`, `megaplan/workers.py`) **Scope:** Medium 1. **Update** the runtime flow in the touched files (`megaplan/handlers.py:400`, `megaplan/workers.py:199`). ### Step 4: Prove the change (`tests/test_evaluation.py`, `tests/test_megaplan.py`) **Scope:** Small 1. **Run** the cheapest targeted checks first (`tests/test_evaluation.py:1`). 2. **Finish** with broader verification once the wiring is in place (`tests/test_megaplan.py:1`). ## Execution Order 1. Update prompts and mocks before enforcing stricter validation. 2. Land higher-risk wiring after the validator and tests are ready. ## Validation Order 1. Start with focused unit tests. 2. Run the broader suite after the flow changes are in place.For complex plans, use multiple phases:
md## Phase 1: Foundation — Dependencies, DB, Types ### Step 1: Install dependencies (`package.json`) ... ### Step 2: Create database migration (`supabase/migrations/`) ... ## Phase 2: Core Integration ### Step 3: Port the main component (`src/components/`) ...Template guidance:
- Simple plans: use
## Main Phasewith### Step N:sections underneath. - Complex plans: use multiple
## Phase N:sections, each containing### Step N:steps. Step numbers are global (not per-phase). - The flat
## Step N:format (without phases) also works for backwards compatibility. - Key invariants: one H1 title, one
## Overview, numbered step sections (### Step N:or## Step N:), and at least one ordering section.
- Assistant
{"plan":"I’ll inspect the repo touch points the brief names, plus the authoritative spec and the prior plan artifacts the task explicitly references. I’ll stop once I can name the concrete files, risks, and validation path.","questions":[],"success_criteria":[],"assumptions":[]}
- Assistant
{"plan":"The initial scan found the expected service and test files, but this checkout is not a Git repository at
/Users/user_c042661f/Documents/Veas, so the plan should avoid git-dependent validation. I’m reading the spec sections and current implementations now to pin down exact insertion points.","questions":[],"success_criteria":[],"assumptions":["The workspace may be an extracted project directory without.git; validation should rely on filesystem inspection and tests, not git status."]} - Assistant
{"plan":"I found partial Plan-5 scheduler/pause scaffolding already present:
system_stateexists in the migration and the scheduler reads it directly, buthooks.paused_for_useris still a stub and there is noapp/services/system_state.py. The plan needs to make that the single pause API, then wire inbound commands and outbound bypass around it.","questions":[],"success_criteria":[],"assumptions":["The workspace may be an extracted project directory without.git; validation should rely on filesystem inspection and tests, not git status."]} - Assistant
{"plan":"# Implementation Plan: Plan-5 Recovery Pause/Resume, Write-Tool Tightening, Tests, Docs, Validation\n\n## Overview\nThe repo already contains most Plan-5 scheduler/decay work:
migrations/0004_plan5_scheduled_jobs.sql,app/services/scheduled_jobs.py,app/services/scheduled_job_handlers.py,app/services/decay.py, and weighted hot-context queries. The skipped gaps are real:app/services/system_state.pydoes not exist,app/services/hooks.pystill returnsFalsefor pause, inbound media paths can still enqueue while paused,schedule_checkinis not transactional around the partial unique check-in index, andescalate_to_partnertrusts model arguments/reason text instead of trusted turn metadata.\n\nThe implementation should keep the existing Plan-5 shape and add the smallest missing service layer, call-site wiring, tests, docs, and validation. Existing source tests includetests/test_tools.py,tests/test_hot_context.py,tests/test_agentic.py,tests/test_recovery.py, andtests/test_send_outbound.py;tests/test_scheduled_jobs.py,tests/test_decay.py, andtests/test_pause_resume.pyare not present in the source tree and should be added during the test task, not during final validation.\n\n## Phase 1: Pause/Resume Foundation\n\n### Step 1: Add DB-backed system state (app/services/system_state.py,app/services/hooks.py,app/services/scheduled_jobs.py)\nScope: Medium\n1. Createapp/services/system_state.pywith helpers around the existingsystem_statesingleton row:\n -is_paused(pool) -> bool\n -paused_for_user(pool, user_id) -> boolas a global pause check for compatibility with user-scoped callers.\n -pause(pool, user_id, reason=None, now=None)that setspaused_at,paused_by_user_id,pause_reason, andupdated_at.\n -resume(pool, now=None)that clears pause fields and updatesupdated_at.\n -supersede_user_facing_jobs(pool, now=None)that marks pendingweekly_summary,checkin,watch_item_due,oob_review, anddeferred_turnjobssupersededwhile leavingheartbeatalone.\n2. Updatehooks.paused_for_userso existing callers still work. Prefer a minimal compatibility layer that accepts either(user_id)for monkeypatched tests or(pool, user_id)for DB-backed call sites; avoid a hidden module-level pool unless existing app startup forces it.\n3. Replacescheduled_jobs.is_globally_paused()direct SQL with the newsystem_state.is_paused(pool)helper so pause logic has one source.\n\n### Step 2: Add pause-aware outbound bypass (app/services/messaging.py)\nScope: Small\n1. Addignore_pause: bool = Falsetosend_outbound(...).\n2. Keep ordinary outbound withheld while paused.\n3. Allow pause/resume/system-control confirmations through whenignore_pause=True; still run the existing OOB/template/window behavior unless the code path already bypasses it.\n4. Update tests and monkeypatch fakes that spy onsend_outboundto accept the new keyword.\n\n### Step 3: Handle/pauseand/resumeafter inbound persistence (app/services/inbound.py,app/services/scheduled_job_handlers.py)\nScope: Medium\n1. Detect literal text commands only after_insert_message(...)succeeds, so the command message itself is persisted and duplicates remain idempotent.\n2. On/pause: callsystem_state.pause, supersede all pending user-facing jobs for both partners, fetch both users, and send the spec confirmation to both partners withignore_pause=TrueandTemplateCall(\"pause_confirmation\", [...])if the template exists or after adding it toapp/services/templates.py.\n3. On/resume: clear pause, restore weekly summaries via existing durable per-user schedule fields (seed_weekly_summaries/schedule_next_weekly_summary), send a resume confirmation if current product copy already supports it, and do not enqueue the stored backlog.\n4. Gate enqueue paths for text and document directly ininbound.pyusing DB-backed pause checks.\n5. Gate media paths so voice/image messages still fetch/store/transcribe/analyze as applicable but do not callcoalescer.add(...)while paused. This likely means adding a pause check inhandle_voiceandhandle_image, because those functions enqueue after async media processing.\n6. Ensurerecover_on_startupalso respects pause before replaying old raw messages or crashed turns, so restart does not bypass the pause kill switch.\n\n## Phase 2: Write-Tool Tightening\n\n### Step 4: Makeschedule_checkintransactional and UTC-aware (app/services/tools/write_tools.py,tool_schemas.py,tests/conftest.py)\nScope: Medium\n1. Reject naive datetimes at schema or tool boundary. Prefer Pydantic validation inScheduleCheckinInput; otherwise reject at the top ofschedule_checkinwithToolCallRejected.\n2. Normalize aware datetimes to UTC before storing, preserving absolute instants.\n3. Wrap supersede-plus-insert in one DB transaction usingasync with pool.acquire() as conn, conn.transaction(): ...so concurrent calls cooperate withidx_scheduled_jobs_one_pending_checkin_per_user.\n4. Use a partial-unique-compatible SQL pattern: supersede existing pending check-ins for the user, then insert exactly one pending check-in. If an asyncpg unique-violation race can still happen, retry the supersede/insert once inside the same helper rather than broad fallback behavior.\n5. UpdateFakePool/FakeConnectionnarrowly to supportfetchrow,execute, andtransaction()on acquired connections.\n\n### Step 5: Gate escalation from trusted turn metadata (app/services/turn_context.py,app/services/agentic.py,app/services/tools/write_tools.py)\nScope: Medium\n1. ExtendTurnContextwith trusted fields derived before Phase B, such astrigger_charge,trigger_metadata, andexplicit_partner_alert_requested.\n2. Populate those fields in_run_agentic(...)fromhot_context.trigger_metadataand trigger message rows, not from model tool arguments.\n3. Acceptescalate_to_partneronly ifctx.trigger_charge == \"crisis\"orctx.explicit_partner_alert_requested is True.\n4. Reject before anysend_outbound(...)call, log the rejected tool call, and return a typed tool error through the existingToolCallRejectedpath.\n5. Always send allowed escalations toctx.partnerwithTemplateCall(\"escalation\", [ctx.partner.name, ctx.user.name, args.content]), ignoring model-supplied IDs except for warning/audit.\n6. Append a distinguished reasoning line such asESCALATION_SENT gate=crisis reason=...after send succeeds, keeping the existing admin search behavior intact.\n\n## Phase 3: Tests And Fakes\n\n### Step 6: Extend focused tests (tests/conftest.py,tests/test_pause_resume.py,tests/test_scheduled_jobs.py,tests/test_decay.py, existing tests)\nScope: Large\n1. ExtendFakePoolonly for the new SQL shapes: system-state updates, superseding all user-facing jobs, acquired connection transactions, UTC check-in insert behavior, and pause-aware media enqueue paths.\n2. Addtests/test_pause_resume.pycovering:\n - either partner can/pauseand/resumesymmetrically;\n - both partners get pause confirmation throughignore_pause=True;\n - pending user-facing jobs becomesuperseded, heartbeat remains pending;\n - text/document/voice/image inbound rows persist but do not enqueue while paused;\n - resume restores weekly summaries and does not replay raw backlog.\n3. Addtests/test_scheduled_jobs.pycovering weekly-summary seeding/decay, late-job recovery, retry cancellation, check-in superseding/race protection, and two concurrentScheduledJobWorker.run_due_once()calls against the same backlog with no double firing.\n4. Addtests/test_decay.pyfor deterministic threshold behavior using injectednowand existing fake rows.\n5. Updatetests/test_tools.pyandtests/test_agentic.pyfor:\n - naiveScheduleCheckinInput.whenrejection;\n - aware non-UTC datetimes stored as UTC;\n - escalation rejected when model saysis_crisis=Truebut trusted trigger charge is not crisis and no explicit alert metadata exists;\n - allowed crisis/explicit-alert escalation uses theescalationtemplate fallback.\n6. Update existing send-outbound tests for the pause bypass keyword and ordinary pause withholding.\n7. Keep weighted ordering/null-significance coverage intests/test_hot_context.pyif not already sufficient.\n\n## Phase 4: Operator Docs\n\n### Step 7: Document scheduler operations (README.mdordocs/scheduler.md)\nScope: Small\n1. Add a concise scheduler operations section explaining:\n - the in-process FastAPI scheduler rationale;\n -SELECT ... FOR UPDATE SKIP LOCKEDhorizontal safety;\n - heartbeat as ascheduled_jobsrow rather than a separate timer;\n - expected Railway/external alerting for missing heartbeat logs;\n - weekly-summary recurrence source: durableusers.weekly_summary_day,users.weekly_summary_time, andusers.timezone.\n2. Reference the existing env vars already listed inREADME.mdinstead of adding new config unless implementation discovers one is missing.\n\n## Phase 5: Validation\n\n### Step 8: Run cheap targeted validation first\nScope: Medium\n1. Run source import/compile checks after the core edits.\n2. Run targeted tests in this order, skipping only files that still do not exist after the planned test additions is not acceptable for required files:\nsh\n pytest -q tests/test_decay.py tests/test_scheduled_jobs.py tests/test_pause_resume.py\n pytest -q tests/test_tools.py tests/test_hot_context.py tests/test_agentic.py tests/test_recovery.py tests/test_send_outbound.py\n\n3. Fix failures before broadening.\n\n### Step 9: Run full validation and throwaway repro\nScope: Medium\n1. Run fullpytest -q.\n2. Create a short script under/tmpthat exercises the highest-risk bug paths without adding a repo test file:\n - concurrent or repeated check-in scheduling leaves at most one pending check-in;\n - paused text/document/voice/image messages persist but do not enqueue.\n3. Run the script, confirm it passes, and delete it before finishing.\n4. Record in notes that the/tmprepro was written, run, and removed.\n\n## Execution Order\n1. Addsystem_stateand pause-compatible hooks first, because messaging, inbound, scheduler, media, and recovery depend on it.\n2. Addsend_outbound(ignore_pause=...)before wiring/pause, so confirmations can be sent after the pause flag is set.\n3. Wire inbound text/document first, then voice/image handlers, because media enqueue happens later inside separate service functions.\n4. Tighten write tools afterTurnContextmetadata exists, so escalation validation can use trusted context instead of tool arguments.\n5. UpdateFakePooland tests alongside each feature slice; do not defer fake updates to the end.\n6. Write docs after behavior is stable.\n7. Run targeted tests before full pytest and the throwaway/tmprepro.\n\n## Validation Order\n1.pytest -q tests/test_pause_resume.pyonce pause wiring is in place.\n2.pytest -q tests/test_tools.py tests/test_agentic.pyafter write-tool tightening.\n3.pytest -q tests/test_scheduled_jobs.py tests/test_decay.py tests/test_recovery.pyafter scheduler/fake updates.\n4.pytest -q tests/test_hot_context.py tests/test_send_outbound.pyfor regressions around ordering and outbound pause behavior.\n5.pytest -qfor the complete suite.\n6./tmpthrowaway repro script, then delete it.", "questions": ["What trusted upstream signal should represent an explicit partner-alert request: should execution add a deterministic detector from triggering message text for now, or is another classifier/metadata producer expected to populatetrigger_metadata[\"explicit_partner_alert_requested\"]?", "Should/pauseand/resumematch only exact lowercase command bodies after trimming whitespace, or should they be case-insensitive? The spec says literal slash commands; the plan assumes trimmed exact lowercase."], "success_criteria": [{"criterion": "app/services/system_state.pyexists and all normal pause checks read thesystem_state.global_pauserow rather than a hardcoded hook stub.", "priority": "must", "requires": ["read_files", "parse_diff", "run_tests"]}, {"criterion": "A persisted/pausecommand from either partner sets global pause, supersedes all pending user-facing jobs while preserving heartbeat jobs, and sends both partners a pause confirmation withignore_pause=True.", "priority": "must", "requires": ["run_tests", "parse_diff"]}, {"criterion": "While paused, text, document, voice, and image inbound messages are still persisted/media-processed as applicable but do not enter the coalescer or agentic loop.", "priority": "must", "requires": ["run_tests", "parse_diff"]}, {"criterion": "A persisted/resumecommand from either partner clears global pause, restores weekly summary scheduling from durable user timing fields, and does not replay paused raw backlog.", "priority": "must", "requires": ["run_tests", "parse_diff"]}, {"criterion": "send_outboundpreserves ordinary pause withholding and supports anignore_pause=Falsedefault with explicit bypass for pause confirmations.", "priority": "must", "requires": ["run_tests", "parse_diff"]}, {"criterion": "schedule_checkinrejects or normalizes naive datetimes according to the implemented contract, stores aware times as UTC instants, and leaves at most one pending check-in per user under repeated/concurrent calls.", "priority": "must", "requires": ["run_tests", "parse_diff"]}, {"criterion": "escalate_to_partnervalidates trustedTurnContexttrigger metadata before any outbound send and allows only crisis charge or explicit partner-alert request.", "priority": "must", "requires": ["run_tests", "parse_diff"]}, {"criterion": "Allowed escalations always targetctx.partner, use theescalationtemplate fallback, and append a distinguished escalation reasoning entry.", "priority": "must", "requires": ["run_tests", "parse_diff"]}, {"criterion": "tests/test_pause_resume.py,tests/test_scheduled_jobs.py,tests/test_decay.py, and existing applicable tests pass.", "priority": "must", "requires": ["run_tests"]}, {"criterion": "Fullpytest -qpasses after targeted tests are green.", "priority": "must", "requires": ["run_tests"]}, {"criterion": "Operator docs explain in-process scheduler runtime, SKIP LOCKED safety, heartbeat-as-job behavior, missing-heartbeat alerting expectations, and weekly-summary timing source.", "priority": "must", "requires": ["read_files", "parse_diff"]}, {"criterion": "Concurrent scheduled-job claim behavior is covered by a test that runs twoScheduledJobWorker.run_due_once()calls against the same backlog and observes no double firing.", "priority": "should", "requires": ["run_tests", "read_files"]}, {"criterion": "FakePool extensions remain narrow and query-specific rather than becoming a broad SQL interpreter.", "priority": "should", "requires": ["read_files", "subjective_judgment"]}, {"criterion": "A throwaway/tmprepro script for check-in uniqueness and paused media enqueue prevention was written, run, passed, and deleted.", "priority": "info", "requires": ["run_shell"]}], "assumptions": ["This is a planning/review artifact only; no implementation edits are made in this step.", "The existing Plan-5 migration is authoritative for durable fields and indexes; no new migration is planned unless execution discovers schema is missing a field required by the spec.", "Pause is global and symmetric even thoughpaused_for_userremains user-shaped for compatibility.", "Literal command detection will happen only for newly inserted inbound text rows, preserving duplicate webhook idempotency.", "deferred_turnis user-facing for pause purposes even though it was added later in Plan 6, so it should be superseded or skipped with other user-facing jobs.", "If no explicit-alert metadata producer exists, execution should add a small trusted derivation in the agentic/hot-context path and makeTurnContextthe write-tool source of truth.", "The workspace is not a Git repository at/Users/user_c042661f/Documents/Veas; validation should not depend on git commands."]} - User
You are already running inside the megaplan harness for this step. Do the requested planning/review/execution work directly. Do NOT invoke the
megaplanCLI, do NOT read or activate themegaplanskill, 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.WRITE ACCESS CONTRACT: You are running with auto-approved writes inside a writable workspace. Treat the working directory as fully writable. Do NOT preemptively skip or block tasks on permission, sandbox, or read-only grounds. Attempt every required edit; only report failure AFTER a real OS-level rejection from a specific shell command. Do not infer 'read-only' from absence of activity; absence is not denial. If a single shell command unexpectedly fails, retry with a different invocation before concluding the environment is restricted.
You are revising an implementation plan after critique and gate feedback.
codeProject directory: /Users/user_c042661f/Documents/Veas Idea:Plan 5b — Plan-5 recovery: pause/resume + write-tool tightening + tests + docs + validation
Authoritative spec:
mediator-bot-spec.md. Read in prep, focusing on: "Pause / Resume", "Crisis Handling" (escalation gate), "Triggers" (scheduled), "Decay" (only as it relates to test coverage), and the relevant parts of "Multi-Message Handling" (media paths under pause).Background
Plan-5 (
plan-5-scheduled-jobs-decay-20260430-1337) was force-proceeded todoneafter codex pre-emptively skipped 5 of 11 tasks in batch 4 onward. The codex executor hallucinated a read-only sandbox and refused before attempting the work. The root cause has been fixed in megaplan (workers.py→_codex_exec_mode_flagsnow always returns--full-autofor non-execute phases, and execute on macOS already had it). With that fix in place, this plan re-runs the five skipped tasks against the existing repo state.The work that landed in plan-5 (do not redo): migration
0004_plan5_scheduled_jobs.sql,app/services/scheduled_jobs.py,app/services/scheduled_job_handlers.py,app/services/decay.py, and the recency-weighted query/sort updates in read tools and hot context.The five tasks below were skipped and must land here. Descriptions are pulled verbatim from plan-5's
finalize.jsonso wording matches the original briefing.Scope (in)
T1 — Global pause/resume (was plan-5 T5)
Implement global pause/resume: add
app/services/system_state.py, makepaused_for_userDB-backed without breaking all existing callers, addsend_outbound(..., ignore_pause=False)and useignore_pause=Truefor pause confirmations, detect literal/pauseand/resumeafter 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.T2 — Write-tool tightening (was plan-5 T7)
Tighten write-tool contracts: keep
schedule_checkintransactional and compatible with the partial unique constraint, reject or normalize naive datetimes so check-ins are stored as absolute UTC instants, and updateescalate_to_partnerso validation happens before any outbound send using authoritativeTurnContextmetadata for trigger charge and explicit partner-alert requests. Log a distinguished escalation reasoning entry and always use theescalationtemplate fallback for the other partner when allowed.T3 — Tests (was plan-5 T8)
Update test fakes and focused tests for scheduler, pause/resume, decay, sorting, and crisis behavior: extend
FakePoolnarrowly 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.T4 — Operational docs (was plan-5 T9)
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.
T5 — Validation (was plan-5 T10)
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.pywhere present), then fullpytest. Also write a short throwaway script in/tmpthat 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.Scope (out, deliberately)
- Re-running anything plan-5 actually completed (T1–T4, T6, T11). Inspect first; do not duplicate.
- Anything from plan-6 (admin view, onboarding, audit, feedback) — that's a separate plan.
- Anything from plan-7 (evals).
Success criteria
must:app/services/system_state.pyexists;paused_for_user(user_id)reads fromsystem_state;/pauseand/resumeliteral slash commands halt and resume both partners symmetrically; pause confirmations useignore_pause=Trueto send through the pause.must:schedule_checkinis transactional under concurrent calls (no double-insert under the partial unique constraint); naive datetimes are rejected or normalized to UTC.must:escalate_to_partnervalidates the gate (crisis charge OR explicit partner-alert request) BEFORE callingsend_outbound, usingTurnContextmetadata as the source of truth.must:pytestis green fortests/test_pause_resume.py(new),tests/test_scheduled_jobs.py,tests/test_decay.py, and any pre-existing tests that continue to apply.must: Operator docs (README ordocs/scheduler.md) explain the scheduler runtime, SKIP LOCKED safety, heartbeat-as-job, and missing-heartbeat alerting.should: Concurrent-claim behavior is covered by a test that fires twoScheduledJobWorker.run_due_once()calls against the same backlog and asserts no double-firing.info: Throwaway repro script in/tmpwas written, run, and deleted (mention in commit/notes).
Notes
-
This is light robustness — one critique + revise iteration, then finalize → execute. No gate, no review.
-
Codex now runs with
--full-autofor all phases on this machine (megaplan fix landed). If a task still hits a "read-only" hallucination, retry once with--fresh. Do not skip pre-emptively. -
Read plan-5's
plan_v1.mdandfinalize.jsonfor design context; do not reinvent decisions plan-5 already made. -
All five tasks should land in a single execute pass — they're not deeply interlocked, but they share
FakePoolextensions andsystem_stateimport surface, so coordinated edits are easier than serial.codeCurrent plan (markdown): # Implementation Plan: Plan-5 Recovery Pause/Resume, Write-Tool Tightening, Tests, Docs, Validation
Overview
The repo already contains most Plan-5 scheduler/decay work:
migrations/0004_plan5_scheduled_jobs.sql,app/services/scheduled_jobs.py,app/services/scheduled_job_handlers.py,app/services/decay.py, and weighted hot-context queries. The skipped gaps are real:app/services/system_state.pydoes not exist,app/services/hooks.pystill returnsFalsefor pause, inbound media paths can still enqueue while paused,schedule_checkinis not transactional around the partial unique check-in index, andescalate_to_partnertrusts model arguments/reason text instead of trusted turn metadata.The implementation should keep the existing Plan-5 shape and add the smallest missing service layer, call-site wiring, tests, docs, and validation. Existing source tests include
tests/test_tools.py,tests/test_hot_context.py,tests/test_agentic.py,tests/test_recovery.py, andtests/test_send_outbound.py;tests/test_scheduled_jobs.py,tests/test_decay.py, andtests/test_pause_resume.pyare not present in the source tree and should be added during the test task, not during final validation.Phase 1: Pause/Resume Foundation
Step 1: Add DB-backed system state (
app/services/system_state.py,app/services/hooks.py,app/services/scheduled_jobs.py)Scope: Medium
- Create
app/services/system_state.pywith helpers around the existingsystem_statesingleton row:is_paused(pool) -> boolpaused_for_user(pool, user_id) -> boolas a global pause check for compatibility with user-scoped callers.pause(pool, user_id, reason=None, now=None)that setspaused_at,paused_by_user_id,pause_reason, andupdated_at.resume(pool, now=None)that clears pause fields and updatesupdated_at.supersede_user_facing_jobs(pool, now=None)that marks pendingweekly_summary,checkin,watch_item_due,oob_review, anddeferred_turnjobssupersededwhile leavingheartbeatalone.
- Update
hooks.paused_for_userso existing callers still work. Prefer a minimal compatibility layer that accepts either(user_id)for monkeypatched tests or(pool, user_id)for DB-backed call sites; avoid a hidden module-level pool unless existing app startup forces it. - Replace
scheduled_jobs.is_globally_paused()direct SQL with the newsystem_state.is_paused(pool)helper so pause logic has one source.
Step 2: Add pause-aware outbound bypass (
app/services/messaging.py)Scope: Small
- Add
ignore_pause: bool = Falsetosend_outbound(...). - Keep ordinary outbound withheld while paused.
- Allow pause/resume/system-control confirmations through when
ignore_pause=True; still run the existing OOB/template/window behavior unless the code path already bypasses it. - Update tests and monkeypatch fakes that spy on
send_outboundto accept the new keyword.
Step 3: Handle
/pauseand/resumeafter inbound persistence (app/services/inbound.py,app/services/scheduled_job_handlers.py)Scope: Medium
- Detect literal text commands only after
_insert_message(...)succeeds, so the command message itself is persisted and duplicates remain idempotent. - On
/pause: callsystem_state.pause, supersede all pending user-facing jobs for both partners, fetch both users, and send the spec confirmation to both partners withignore_pause=TrueandTemplateCall("pause_confirmation", [...])if the template exists or after adding it toapp/services/templates.py. - On
/resume: clear pause, restore weekly summaries via existing durable per-user schedule fields (seed_weekly_summaries/schedule_next_weekly_summary), send a resume confirmation if current product copy already supports it, and do not enqueue the stored backlog. - Gate enqueue paths for text and document directly in
inbound.pyusing DB-backed pause checks. - Gate media paths so voice/image messages still fetch/store/transcribe/analyze as applicable but do not call
coalescer.add(...)while paused. This likely means adding a pause check inhandle_voiceandhandle_image, because those functions enqueue after async media processing. - Ensure
recover_on_startupalso respects pause before replaying old raw messages or crashed turns, so restart does not bypass the pause kill switch.
Phase 2: Write-Tool Tightening
Step 4: Make
schedule_checkintransactional and UTC-aware (app/services/tools/write_tools.py,tool_schemas.py,tests/conftest.py)Scope: Medium
- Reject naive datetimes at schema or tool boundary. Prefer Pydantic validation in
ScheduleCheckinInput; otherwise reject at the top ofschedule_checkinwithToolCallRejected. - Normalize aware datetimes to UTC before storing, preserving absolute instants.
- Wrap supersede-plus-insert in one DB transaction using
async with pool.acquire() as conn, conn.transaction(): ...so concurrent calls cooperate withidx_scheduled_jobs_one_pending_checkin_per_user. - Use a partial-unique-compatible SQL pattern: supersede existing pending check-ins for the user, then insert exactly one pending check-in. If an asyncpg unique-violation race can still happen, retry the supersede/insert once inside the same helper rather than broad fallback behavior.
- Update
FakePool/FakeConnectionnarrowly to supportfetchrow,execute, andtransaction()on acquired connections.
Step 5: Gate escalation from trusted turn metadata (
app/services/turn_context.py,app/services/agentic.py,app/services/tools/write_tools.py)Scope: Medium
- Extend
TurnContextwith trusted fields derived before Phase B, such astrigger_charge,trigger_metadata, andexplicit_partner_alert_requested. - Populate those fields in
_run_agentic(...)fromhot_context.trigger_metadataand trigger message rows, not from model tool arguments. - Accept
escalate_to_partneronly ifctx.trigger_charge == "crisis"orctx.explicit_partner_alert_requested is True. - Reject before any
send_outbound(...)call, log the rejected tool call, and return a typed tool error through the existingToolCallRejectedpath. - Always send allowed escalations to
ctx.partnerwithTemplateCall("escalation", [ctx.partner.name, ctx.user.name, args.content]), ignoring model-supplied IDs except for warning/audit. - Append a distinguished reasoning line such as
ESCALATION_SENT gate=crisis reason=...after send succeeds, keeping the existing admin search behavior intact.
Phase 3: Tests And Fakes
Step 6: Extend focused tests (
tests/conftest.py,tests/test_pause_resume.py,tests/test_scheduled_jobs.py,tests/test_decay.py, existing tests)Scope: Large
- Extend
FakePoolonly for the new SQL shapes: system-state updates, superseding all user-facing jobs, acquired connection transactions, UTC check-in insert behavior, and pause-aware media enqueue paths. - Add
tests/test_pause_resume.pycovering:- either partner can
/pauseand/resumesymmetrically; - both partners get pause confirmation through
ignore_pause=True; - pending user-facing jobs become
superseded, heartbeat remains pending; - text/document/voice/image inbound rows persist but do not enqueue while paused;
- resume restores weekly summaries and does not replay raw backlog.
- either partner can
- Add
tests/test_scheduled_jobs.pycovering weekly-summary seeding/decay, late-job recovery, retry cancellation, check-in superseding/race protection, and two concurrentScheduledJobWorker.run_due_once()calls against the same backlog with no double firing. - Add
tests/test_decay.pyfor deterministic threshold behavior using injectednowand existing fake rows. - Update
tests/test_tools.pyandtests/test_agentic.pyfor:- naive
ScheduleCheckinInput.whenrejection; - aware non-UTC datetimes stored as UTC;
- escalation rejected when model says
is_crisis=Truebut trusted trigger charge is not crisis and no explicit alert metadata exists; - allowed crisis/explicit-alert escalation uses the
escalationtemplate fallback.
- naive
- Update existing send-outbound tests for the pause bypass keyword and ordinary pause withholding.
- Keep weighted ordering/null-significance coverage in
tests/test_hot_context.pyif not already sufficient.
Phase 4: Operator Docs
Step 7: Document scheduler operations (
README.mdordocs/scheduler.md)Scope: Small
- Add a concise scheduler operations section explaining:
- the in-process FastAPI scheduler rationale;
SELECT ... FOR UPDATE SKIP LOCKEDhorizontal safety;- heartbeat as a
scheduled_jobsrow rather than a separate timer; - expected Railway/external alerting for missing heartbeat logs;
- weekly-summary recurrence source: durable
users.weekly_summary_day,users.weekly_summary_time, andusers.timezone.
- Reference the existing env vars already listed in
README.mdinstead of adding new config unless implementation discovers one is missing.
Phase 5: Validation
Step 8: Run cheap targeted validation first
Scope: Medium
- Run source import/compile checks after the core edits.
- Run targeted tests in this order, skipping only files that still do not exist after the planned test additions is not acceptable for required files:
sh
pytest -q tests/test_decay.py tests/test_scheduled_jobs.py tests/test_pause_resume.py pytest -q tests/test_tools.py tests/test_hot_context.py tests/test_agentic.py tests/test_recovery.py tests/test_send_outbound.py - Fix failures before broadening.
Step 9: Run full validation and throwaway repro
Scope: Medium
- Run full
pytest -q. - Create a short script under
/tmpthat exercises the highest-risk bug paths without adding a repo test file:- concurrent or repeated check-in scheduling leaves at most one pending check-in;
- paused text/document/voice/image messages persist but do not enqueue.
- Run the script, confirm it passes, and delete it before finishing.
- Record in notes that the
/tmprepro was written, run, and removed.
Execution Order
- Add
system_stateand pause-compatible hooks first, because messaging, inbound, scheduler, media, and recovery depend on it. - Add
send_outbound(ignore_pause=...)before wiring/pause, so confirmations can be sent after the pause flag is set. - Wire inbound text/document first, then voice/image handlers, because media enqueue happens later inside separate service functions.
- Tighten write tools after
TurnContextmetadata exists, so escalation validation can use trusted context instead of tool arguments. - Update
FakePooland tests alongside each feature slice; do not defer fake updates to the end. - Write docs after behavior is stable.
- Run targeted tests before full pytest and the throwaway
/tmprepro.
Validation Order
-
pytest -q tests/test_pause_resume.pyonce pause wiring is in place. -
pytest -q tests/test_tools.py tests/test_agentic.pyafter write-tool tightening. -
pytest -q tests/test_scheduled_jobs.py tests/test_decay.py tests/test_recovery.pyafter scheduler/fake updates. -
pytest -q tests/test_hot_context.py tests/test_send_outbound.pyfor regressions around ordering and outbound pause behavior. -
pytest -qfor the complete suite. -
/tmpthrowaway repro script, then delete it.codeCurrent plan metadata: {
"version": 1, "timestamp": "2026-04-30T13:11:15Z", "hash": "sha256:3671f0762ba26f855b696efa180e3ed9886faad6e1764934c313c83a0f1334fa", "questions": [ "What trusted upstream signal should represent an explicit partner-alert request: should execution add a deterministic detector from triggering message text for now, or is another classifier/metadata producer expected to populate
trigger_metadata[\"explicit_partner_alert_requested\"]?", "Should/pauseand/resumematch only exact lowercase command bodies after trimming whitespace, or should they be case-insensitive? The spec says literal slash commands; the plan assumes trimmed exact lowercase." ], "success_criteria": [ { "criterion": "app/services/system_state.pyexists and all normal pause checks read thesystem_state.global_pauserow rather than a hardcoded hook stub.", "priority": "must", "requires": [ "read_files", "parse_diff", "run_tests" ] }, { "criterion": "A persisted/pausecommand from either partner sets global pause, supersedes all pending user-facing jobs while preserving heartbeat jobs, and sends both partners a pause confirmation withignore_pause=True.", "priority": "must", "requires": [ "run_tests", "parse_diff" ] }, { "criterion": "While paused, text, document, voice, and image inbound messages are still persisted/media-processed as applicable but do not enter the coalescer or agentic loop.", "priority": "must", "requires": [ "run_tests", "parse_diff" ] }, { "criterion": "A persisted/resumecommand from either partner clears global pause, restores weekly summary scheduling from durable user timing fields, and does not replay paused raw backlog.", "priority": "must", "requires": [ "run_tests", "parse_diff" ] }, { "criterion": "send_outboundpreserves ordinary pause withholding and supports anignore_pause=Falsedefault with explicit bypass for pause confirmations.", "priority": "must", "requires": [ "run_tests", "parse_diff" ] }, { "criterion": "schedule_checkinrejects or normalizes naive datetimes according to the implemented contract, stores aware times as UTC instants, and leaves at most one pending check-in per user under repeated/concurrent calls.", "priority": "must", "requires": [ "run_tests", "parse_diff" ] }, { "criterion": "escalate_to_partnervalidates trustedTurnContexttrigger metadata before any outbound send and allows only crisis charge or explicit partner-alert request.", "priority": "must", "requires": [ "run_tests", "parse_diff" ] }, { "criterion": "Allowed escalations always targetctx.partner, use theescalationtemplate fallback, and append a distinguished escalation reasoning entry.", "priority": "must", "requires": [ "run_tests", "parse_diff" ] }, { "criterion": "tests/test_pause_resume.py,tests/test_scheduled_jobs.py,tests/test_decay.py, and existing applicable tests pass.", "priority": "must", "requires": [ "run_tests" ] }, { "criterion": "Fullpytest -qpasses after targeted tests are green.", "priority": "must", "requires": [ "run_tests" ] }, { "criterion": "Operator docs explain in-process scheduler runtime, SKIP LOCKED safety, heartbeat-as-job behavior, missing-heartbeat alerting expectations, and weekly-summary timing source.", "priority": "must", "requires": [ "read_files", "parse_diff" ] }, { "criterion": "Concurrent scheduled-job claim behavior is covered by a test that runs twoScheduledJobWorker.run_due_once()calls against the same backlog and observes no double firing.", "priority": "should", "requires": [ "run_tests", "read_files" ] }, { "criterion": "FakePool extensions remain narrow and query-specific rather than becoming a broad SQL interpreter.", "priority": "should", "requires": [ "read_files", "subjective_judgment" ] }, { "criterion": "A throwaway/tmprepro script for check-in uniqueness and paused media enqueue prevention was written, run, passed, and deleted.", "priority": "info", "requires": [ "run_shell" ] } ], "assumptions": [ "This is a planning/review artifact only; no implementation edits are made in this step.", "The existing Plan-5 migration is authoritative for durable fields and indexes; no new migration is planned unless execution discovers schema is missing a field required by the spec.", "Pause is global and symmetric even thoughpaused_for_userremains user-shaped for compatibility.", "Literal command detection will happen only for newly inserted inbound text rows, preserving duplicate webhook idempotency.", "deferred_turnis user-facing for pause purposes even though it was added later in Plan 6, so it should be superseded or skipped with other user-facing jobs.", "If no explicit-alert metadata producer exists, execution should add a small trusted derivation in the agentic/hot-context path and makeTurnContextthe write-tool source of truth.", "The workspace is not a Git repository at/Users/user_c042661f/Documents/Veas; validation should not depend on git commands." ], "structure_warnings": [] }codeGate summary: {"recommendation": "ITERATE", "rationale": "Light robustness: single revision pass to incorporate critique feedback.", "signals_assessment": "", "warnings": [], "settled_decisions": [] }
codeOpen significant flags: [{ "id": "FLAG-001", "severity": "significant", "status": "open", "concern": "Check-in scheduling: the plan only makes the write-tool
schedule_checkintransactional, but the repo has a second check-in writer inapp/services/scheduled_job_handlers.py(schedule_checkin_job) that performs the same supersede-then-insert pattern outside a transaction. Because both paths write rows covered byidx_scheduled_jobs_one_pending_checkin_per_user, concurrent watch-item due handling and model-triggered check-in scheduling can still raise a unique violation or leave retry/cancellation behavior to the worker instead of preserving the one-pending-check-in contract.", "evidence": "app/services/tools/write_tools.pyhasschedule_checkinat lines 352-379, butapp/services/scheduled_job_handlers.pyalso definesschedule_checkin_jobat lines 280-306 andhandle_watch_item_duecalls it at lines 131-136. The plan's Step 4 file scope isapp/services/tools/write_tools.py,tool_schemas.py, andtests/conftest.py, so this second writer is not explicitly tightened." } ]codeRequirements: - Before addressing individual flags, check: does any flag suggest the plan is targeting the wrong code or the wrong root cause? If so, consider whether the plan needs a new approach rather than adjustments. Explain your reasoning. - Update the plan to address the significant issues. - Keep the plan readable and executable. - Return flags_addressed with the exact flag IDs you addressed. - Include `changes_summary` as a short plain-English summary of what changed in the revision. If there were no concrete flags, say that explicitly (for example: `No critique flags were raised; refined wording and kept the plan aligned for execution.`). - Preserve or improve success criteria quality. Each criterion must have a `priority` of `must`, `should`, or `info`. Promote or demote priorities if critique feedback reveals a criterion was over- or under-weighted. - Verify that the plan remains aligned with the user's original intent, not just internal plan quality. - Remove unjustified scope growth. If critique raised scope creep, narrow the plan back to the original idea unless the broader work is strictly required. - Maintain the structural template: H1 title, ## Overview, phase sections with numbered step sections, ## Execution Order or ## Validation Order. - CRITICAL: Your entire revised plan markdown (all sections) must be output as the `plan` field in the structured output. The prose response must not contain the plan text. - CRITICAL: Return only the structured JSON object for the schema fields `plan`, `changes_summary`, `flags_addressed`, `assumptions`, `success_criteria`, and `questions`. Do not add commentary before or after the JSON object. Plan template — simple format (adapt to the actual repo and scope):md# Implementation Plan: [Title] ## Overview Summarize the goal, current repository shape, and the constraints that matter. ## Main Phase ### Step 1: Audit the current behavior (`megaplan/prompts.py`) **Scope:** Small 1. **Inspect** the current implementation and call out the exact insertion points (`megaplan/prompts.py:29`). ### Step 2: Add the first change (`megaplan/evaluation.py`) **Scope:** Medium 1. **Implement** the smallest viable change with exact file references (`megaplan/evaluation.py:1`). 2. **Capture** any tricky behavior with a short example. ```python issues = validate_plan_structure(plan_text) ``` ### Step 3: Wire downstream behavior (`megaplan/handlers.py`, `megaplan/workers.py`) **Scope:** Medium 1. **Update** the runtime flow in the touched files (`megaplan/handlers.py:400`, `megaplan/workers.py:199`). ### Step 4: Prove the change (`tests/test_evaluation.py`, `tests/test_megaplan.py`) **Scope:** Small 1. **Run** the cheapest targeted checks first (`tests/test_evaluation.py:1`). 2. **Finish** with broader verification once the wiring is in place (`tests/test_megaplan.py:1`). ## Execution Order 1. Update prompts and mocks before enforcing stricter validation. 2. Land higher-risk wiring after the validator and tests are ready. ## Validation Order 1. Start with focused unit tests. 2. Run the broader suite after the flow changes are in place.For complex plans, use multiple phases:
md## Phase 1: Foundation — Dependencies, DB, Types ### Step 1: Install dependencies (`package.json`) ... ### Step 2: Create database migration (`supabase/migrations/`) ... ## Phase 2: Core Integration ### Step 3: Port the main component (`src/components/`) ...Template guidance:
- Simple plans: use
## Main Phasewith### Step N:sections underneath. - Complex plans: use multiple
## Phase N:sections, each containing### Step N:steps. Step numbers are global (not per-phase). - The flat
## Step N:format (without phases) also works for backwards compatibility. - Key invariants: one H1 title, one
## Overview, numbered step sections (### Step N:or## Step N:), and at least one ordering section.
- Assistant
{ "plan": "# Implementation Plan: Plan-5 Recovery Pause/Resume, Write-Tool Tightening, Tests, Docs, Validation\n\n## Overview\nThe repo already contains most Plan-5 scheduler/decay work:
migrations/0004_plan5_scheduled_jobs.sql,app/services/scheduled_jobs.py,app/services/scheduled_job_handlers.py,app/services/decay.py, and weighted hot-context queries. The skipped gaps are real:app/services/system_state.pydoes not exist,app/services/hooks.pystill returnsFalsefor pause, inbound media paths can still enqueue while paused, check-in scheduling has non-transactional supersede-then-insert writers, andescalate_to_partnertrusts model arguments/reason text instead of trusted turn metadata.\n\nCritique check: FLAG-001 does not imply the plan targeted the wrong root cause; it shows the original plan found only one of two writers for the same partial unique check-in invariant. The revised approach is to centralize or share the transactional check-in writer so both the agent write tool and scheduled-job handler path are tightened together.\n\nThe implementation should keep the existing Plan-5 shape and add the smallest missing service layer, call-site wiring, tests, docs, and validation. Existing source tests includetests/test_tools.py,tests/test_hot_context.py,tests/test_agentic.py,tests/test_recovery.py, andtests/test_send_outbound.py;tests/test_scheduled_jobs.py,tests/test_decay.py, andtests/test_pause_resume.pyare not present in the source tree and should be added during the test task, not during final validation.\n\n## Phase 1: Pause/Resume Foundation\n\n### Step 1: Add DB-backed system state (app/services/system_state.py,app/services/hooks.py,app/services/scheduled_jobs.py)\nScope: Medium\n1. Createapp/services/system_state.pywith helpers around the existingsystem_statesingleton row:\n -is_paused(pool) -> bool\n -paused_for_user(pool, user_id) -> boolas a global pause check for compatibility with user-scoped callers.\n -pause(pool, user_id, reason=None, now=None)that setspaused_at,paused_by_user_id,pause_reason, andupdated_at.\n -resume(pool, now=None)that clears pause fields and updatesupdated_at.\n -supersede_user_facing_jobs(pool, now=None)that marks pendingweekly_summary,checkin,watch_item_due,oob_review, anddeferred_turnjobssupersededwhile leavingheartbeatalone.\n2. Updatehooks.paused_for_userso existing callers still work. Prefer a minimal compatibility layer that accepts either(user_id)for monkeypatched tests or(pool, user_id)for DB-backed call sites; avoid a hidden module-level pool unless existing app startup forces it.\n3. Replacescheduled_jobs.is_globally_paused()direct SQL with the newsystem_state.is_paused(pool)helper so pause logic has one source.\n\n### Step 2: Add pause-aware outbound bypass (app/services/messaging.py)\nScope: Small\n1. Addignore_pause: bool = Falsetosend_outbound(...).\n2. Keep ordinary outbound withheld while paused.\n3. Allow pause/resume/system-control confirmations through whenignore_pause=True; still run the existing OOB/template/window behavior unless the code path already bypasses it.\n4. Update tests and monkeypatch fakes that spy onsend_outboundto accept the new keyword.\n\n### Step 3: Handle/pauseand/resumeafter inbound persistence (app/services/inbound.py,app/services/scheduled_job_handlers.py)\nScope: Medium\n1. Detect literal text commands only after_insert_message(...)succeeds, so the command message itself is persisted and duplicates remain idempotent.\n2. On/pause: callsystem_state.pause, supersede all pending user-facing jobs for both partners, fetch both users, and send the spec confirmation to both partners withignore_pause=TrueandTemplateCall(\"pause_confirmation\", [...])if the template exists or after adding it toapp/services/templates.py.\n3. On/resume: clear pause, restore weekly summaries via existing durable per-user schedule fields (seed_weekly_summaries/schedule_next_weekly_summary), send a resume confirmation only if current product copy already supports it, and do not enqueue the stored backlog.\n4. Gate enqueue paths for text and document directly ininbound.pyusing DB-backed pause checks.\n5. Gate media paths so voice/image messages still fetch/store/transcribe/analyze as applicable but do not callcoalescer.add(...)while paused. This likely means adding a pause check inhandle_voiceandhandle_image, because those functions enqueue after async media processing.\n6. Ensurerecover_on_startupalso respects pause before replaying old raw messages or crashed turns, so restart does not bypass the pause kill switch.\n\n## Phase 2: Write-Tool Tightening\n\n### Step 4: Make all check-in scheduling transactional and UTC-aware (app/services/tools/write_tools.py,app/services/scheduled_job_handlers.py, optional shared helper,tool_schemas.py,tests/conftest.py)\nScope: Medium\n1. Identify both check-in writers before editing: agent-facingschedule_checkininapp/services/tools/write_tools.pyand scheduler/internalschedule_checkin_jobinapp/services/scheduled_job_handlers.py, which is called byhandle_watch_item_due.\n2. Introduce one shared implementation for supersede-plus-insert if it keeps the code simpler, for example a private helper inscheduled_job_handlers.pyor a small scheduler-write helper module. Both public call sites must use the same transaction-safe path.\n3. Reject naive datetimes at schema or tool boundary. Prefer Pydantic validation inScheduleCheckinInput; otherwise reject at the top ofschedule_checkinwithToolCallRejected. Apply the same aware-datetime requirement to internalschedule_checkin_jobarguments.\n4. Normalize aware datetimes to UTC before storing, preserving absolute instants.\n5. Wrap supersede-plus-insert in one DB transaction usingasync with pool.acquire() as conn, conn.transaction(): ...so both writers cooperate withidx_scheduled_jobs_one_pending_checkin_per_user.\n6. Use a partial-unique-compatible SQL pattern: supersede existing pending check-ins for the user, then insert exactly one pending check-in. If an asyncpg unique-violation race can still happen, retry the supersede/insert once inside the shared helper rather than adding broad fallback behavior.\n7. Keep return shapes compatible:schedule_checkinstill returnsScheduleCheckinOutput, andschedule_checkin_jobstill returns the row needed by scheduled handlers.\n8. UpdateFakePool/FakeConnectionnarrowly to supportfetchrow,execute, andtransaction()on acquired connections.\n\n### Step 5: Gate escalation from trusted turn metadata (app/services/turn_context.py,app/services/agentic.py,app/services/tools/write_tools.py)\nScope: Medium\n1. ExtendTurnContextwith trusted fields derived before Phase B, such astrigger_charge,trigger_metadata, andexplicit_partner_alert_requested.\n2. Populate those fields in_run_agentic(...)fromhot_context.trigger_metadataand trigger message rows, not from model tool arguments.\n3. Acceptescalate_to_partneronly ifctx.trigger_charge == \"crisis\"orctx.explicit_partner_alert_requested is True.\n4. Reject before anysend_outbound(...)call, log the rejected tool call, and return a typed tool error through the existingToolCallRejectedpath.\n5. Always send allowed escalations toctx.partnerwithTemplateCall(\"escalation\", [ctx.partner.name, ctx.user.name, args.content]), ignoring model-supplied IDs except for warning/audit.\n6. Append a distinguished reasoning line such asESCALATION_SENT gate=crisis reason=...after send succeeds, keeping the existing admin search behavior intact.\n\n## Phase 3: Tests And Fakes\n\n### Step 6: Extend focused tests (tests/conftest.py,tests/test_pause_resume.py,tests/test_scheduled_jobs.py,tests/test_decay.py, existing tests)\nScope: Large\n1. ExtendFakePoolonly for the new SQL shapes: system-state updates, superseding all user-facing jobs, acquired connection transactions, UTC check-in insert behavior, and pause-aware media enqueue paths.\n2. Addtests/test_pause_resume.pycovering:\n - either partner can/pauseand/resumesymmetrically;\n - both partners get pause confirmation throughignore_pause=True;\n - pending user-facing jobs becomesuperseded, heartbeat remains pending;\n - text/document/voice/image inbound rows persist but do not enqueue while paused;\n - resume restores weekly summaries and does not replay raw backlog.\n3. Addtests/test_scheduled_jobs.pycovering weekly-summary seeding/decay, late-job recovery, retry cancellation, check-in superseding/race protection through bothschedule_checkinandschedule_checkin_job, and two concurrentScheduledJobWorker.run_due_once()calls against the same backlog with no double firing.\n4. Addtests/test_decay.pyfor deterministic threshold behavior using injectednowand existing fake rows.\n5. Updatetests/test_tools.pyandtests/test_agentic.pyfor:\n - naiveScheduleCheckinInput.whenrejection;\n - aware non-UTC datetimes stored as UTC;\n - escalation rejected when model saysis_crisis=Truebut trusted trigger charge is not crisis and no explicit alert metadata exists;\n - allowed crisis/explicit-alert escalation uses theescalationtemplate fallback.\n6. Update existing send-outbound tests for the pause bypass keyword and ordinary pause withholding.\n7. Keep weighted ordering/null-significance coverage intests/test_hot_context.pyif not already sufficient.\n\n## Phase 4: Operator Docs\n\n### Step 7: Document scheduler operations (README.mdordocs/scheduler.md)\nScope: Small\n1. Add a concise scheduler operations section explaining:\n - the in-process FastAPI scheduler rationale;\n -SELECT ... FOR UPDATE SKIP LOCKEDhorizontal safety;\n - heartbeat as ascheduled_jobsrow rather than a separate timer;\n - expected Railway/external alerting for missing heartbeat logs;\n - weekly-summary recurrence source: durableusers.weekly_summary_day,users.weekly_summary_time, andusers.timezone.\n2. Reference the existing env vars already listed inREADME.mdinstead of adding new config unless implementation discovers one is missing.\n\n## Phase 5: Validation\n\n### Step 8: Run cheap targeted validation first\nScope: Medium\n1. Run source import/compile checks after the core edits.\n2. Run targeted tests in this order, skipping only files that still do not exist after the planned test additions is not acceptable for required files:\nsh\n pytest -q tests/test_decay.py tests/test_scheduled_jobs.py tests/test_pause_resume.py\n pytest -q tests/test_tools.py tests/test_hot_context.py tests/test_agentic.py tests/test_recovery.py tests/test_send_outbound.py\n\n3. Fix failures before broadening.\n\n### Step 9: Run full validation and throwaway repro\nScope: Medium\n1. Run fullpytest -q.\n2. Create a short script under/tmpthat exercises the highest-risk bug paths without adding a repo test file:\n - concurrent or repeated check-in scheduling through both the agent write tool and scheduled-job helper leaves at most one pending check-in;\n - paused text/document/voice/image messages persist but do not enqueue.\n3. Run the script, confirm it passes, and delete it before finishing.\n4. Record in notes that the/tmprepro was written, run, and removed.\n\n## Execution Order\n1. Addsystem_stateand pause-compatible hooks first, because messaging, inbound, scheduler, media, and recovery depend on it.\n2. Addsend_outbound(ignore_pause=...)before wiring/pause, so confirmations can be sent after the pause flag is set.\n3. Wire inbound text/document first, then voice/image handlers, because media enqueue happens later inside separate service functions.\n4. Tighten check-in scheduling as a shared invariant across both check-in writers before broad scheduler tests, so the partial unique index behavior is fixed once.\n5. Tighten escalation afterTurnContextmetadata exists, so validation can use trusted context instead of tool arguments.\n6. UpdateFakePooland tests alongside each feature slice; do not defer fake updates to the end.\n7. Write docs after behavior is stable.\n8. Run targeted tests before full pytest and the throwaway/tmprepro.\n\n## Validation Order\n1.pytest -q tests/test_pause_resume.pyonce pause wiring is in place.\n2.pytest -q tests/test_tools.py tests/test_agentic.pyafter write-tool tightening.\n3.pytest -q tests/test_scheduled_jobs.py tests/test_decay.py tests/test_recovery.pyafter scheduler/fake updates.\n4.pytest -q tests/test_hot_context.py tests/test_send_outbound.pyfor regressions around ordering and outbound pause behavior.\n5.pytest -qfor the complete suite.\n6./tmpthrowaway repro script, then delete it.", "changes_summary": "Addressed FLAG-001 by expanding the check-in scheduling step from only the agent write tool to both existing writers:schedule_checkinandschedule_checkin_job. The revised plan now calls for one shared transaction-safe UTC-aware scheduling path, tests for both callers, and a/tmprepro that covers mixed check-in writers.", "flags_addressed": [ "FLAG-001" ], "assumptions": [ "This is a planning/review artifact only; no implementation edits are made in this step.", "The existing Plan-5 migration is authoritative for durable fields and indexes; no new migration is planned unless execution discovers schema is missing a field required by the spec.", "Pause is global and symmetric even thoughpaused_for_userremains user-shaped for compatibility.", "Literal command detection will happen only for newly inserted inbound text rows, preserving duplicate webhook idempotency.", "deferred_turnis user-facing for pause purposes even though it was added later in Plan 6, so it should be superseded or skipped with other user-facing jobs.", "If no explicit-alert metadata producer exists, execution should add a small trusted derivation in the agentic/hot-context path and makeTurnContextthe write-tool source of truth.", "Bothschedule_checkinandschedule_checkin_jobare covered by the same one-pending-check-in invariant and should use a shared or equivalent transaction-safe implementation.", "The workspace is not a Git repository at/Users/user_c042661f/Documents/Veas; validation should not depend on git commands." ], "success_criteria": [ { "criterion": "app/services/system_state.pyexists and all normal pause checks read thesystem_state.global_pauserow rather than a hardcoded hook stub.", "priority": "must", "requires": [ "read_files", "parse_diff", "run_tests" ] }, { "criterion": "A persisted/pausecommand from either partner sets global pause, supersedes all pending user-facing jobs while preserving heartbeat jobs, and sends both partners a pause confirmation withignore_pause=True.", "priority": "must", "requires": [ "run_tests", "parse_diff" ] }, { "criterion": "While paused, text, document, voice, and image inbound messages are still persisted/media-processed as applicable but do not enter the coalescer or agentic loop.", "priority": "must", "requires": [ "run_tests", "parse_diff" ] }, { "criterion": "A persisted/resumecommand from either partner clears global pause, restores weekly summary scheduling from durable user timing fields, and does not replay paused raw backlog.", "priority": "must", "requires": [ "run_tests", "parse_diff" ] }, { "criterion": "send_outboundpreserves ordinary pause withholding and supports anignore_pause=Falsedefault with explicit bypass for pause confirmations.", "priority": "must", "requires": [ "run_tests", "parse_diff" ] }, { "criterion": "Both check-in writers,schedule_checkinandschedule_checkin_job, use a transaction-safe UTC-aware path compatible with the partial unique index, reject or normalize naive datetimes according to the implemented contract, and leave at most one pending check-in per user under repeated/concurrent calls.", "priority": "must", "requires": [ "run_tests", "parse_diff" ] }, { "criterion": "escalate_to_partnervalidates trustedTurnContexttrigger metadata before any outbound send and allows only crisis charge or explicit partner-alert request.", "priority": "must", "requires": [ "run_tests", "parse_diff" ] }, { "criterion": "Allowed escalations always targetctx.partner, use theescalationtemplate fallback, and append a distinguished escalation reasoning entry.", "priority": "must", "requires": [ "run_tests", "parse_diff" ] }, { "criterion": "tests/test_pause_resume.py,tests/test_scheduled_jobs.py,tests/test_decay.py, and existing applicable tests pass.", "priority": "must", "requires": [ "run_tests" ] }, { "criterion": "Fullpytest -qpasses after targeted tests are green.", "priority": "must", "requires": [ "run_tests" ] }, { "criterion": "Operator docs explain in-process scheduler runtime, SKIP LOCKED safety, heartbeat-as-job behavior, missing-heartbeat alerting expectations, and weekly-summary timing source.", "priority": "must", "requires": [ "read_files", "parse_diff" ] }, { "criterion": "Concurrent scheduled-job claim behavior is covered by a test that runs twoScheduledJobWorker.run_due_once()calls against the same backlog and observes no double firing.", "priority": "should", "requires": [ "run_tests", "read_files" ] }, { "criterion": "FakePool extensions remain narrow and query-specific rather than becoming a broad SQL interpreter.", "priority": "should", "requires": [ "read_files", "subjective_judgment" ] }, { "criterion": "A throwaway/tmprepro script for mixed check-in writer uniqueness and paused media enqueue prevention was written, run, passed, and deleted.", "priority": "info", "requires": [ "run_shell" ] } ], "questions": [ "What trusted upstream signal should represent an explicit partner-alert request: should execution add a deterministic detector from triggering message text for now, or is another classifier/metadata producer expected to populatetrigger_metadata[\"explicit_partner_alert_requested\"]?", "Should/pauseand/resumematch only exact lowercase command bodies after trimming whitespace, or should they be case-insensitive? The spec says literal slash commands; the plan assumes trimmed exact lowercase." ] }