You are already running inside the megaplan harness for this step. Do the requested planning/review/execution work directly. Do NOT invoke the megaplan CLI, do NOT read or activate the megaplan skill, do NOT start nested megaplan plans, and do NOT recurse into another planning harness. Treat mentions of megaplan in the repository or environment as implementation context only.
You are an independent reviewer. Critique the plan against the actual repository.
Bot maintains an epic body and checklist for one epic, with section-level body editing. Minimum to have an editorial conversation.
Full spec is at planning-bot-spec.md in this repo root. Refer to it for complete details on Body Structure and Editing, Body Templates, The Checklist as Guide, and Data Model sections.
Body parser/serializer — markdown ↔ structured sections with ## heading delimiters; enforces heading hierarchy (# for title only, ## for sections, ### for sub-headings)
Turn-end epic outline emitted to system_logs at info level
Default body template (design doc) — Goal, Principles, Context, Key Decisions, Open Questions, Deliverable
{"checks":[{"id":"init","question":"Starting repository review","findings":[{"detail":"I will read the provided critique template first, then inspect the repository files the plan depends on before writing the JSON output back to the requested path.","flagged":false}]}],"flags":[],"verified_flag_ids":[],"disputed_flag_ids":[]}
Assistant
{"checks":[{"id":"progress","question":"Repository context","findings":[{"detail":"I have the five required checks. Next I am reading the spec, existing schema, store protocol/adapters, loop, tool registration, and tests to compare the plan against concrete implementation constraints.","flagged":false}]}],"flags":[],"verified_flag_ids":[],"disputed_flag_ids":[]}
Assistant
Assistant
User
Assistant
I’ll update the critique file for iteration 2 by verifying the addressed flags against the actual code paths and looking for new issues introduced by the revised plan.
Assistant
I found one remaining bootstrap weakness introduced by the revision: the database path is planned, but the envelope and local epic_id plumbing are still typed and serialized as if an epic always existed. I’m writing that plus the verified fixes into the critique file now.
Assistant
User
Assistant
I’ll do the third-pass verification now: confirm the rev 3 fixes against the current loop/envelope/CLI/protocol boundaries, then update the critique JSON with any remaining issues.
Assistant
The rev 3 bootstrap thread now covers the earlier envelope/API gap. I’m marking those fixed and keeping only the remaining explicit spec divergences that still need gate acceptance.
Assistant
Title and goal are derived columns from body parsing (# Title and ## Goal first paragraph)
Sprint 2a is the first sprint that gives Arnold a document to edit. Today (post Sprint 1b) the codebase has:
An epics table (already created in supabase/migrations/202604300001_001_core.sql) with id, title, goal, body, state, *_at columns. Title and goal are stored as plain columns. No body parser yet — the tests/store_contract.py fixture inserts an epic with body='# Title' directly.
A loop (agent_kit/loop.py) that drives a model, registers tools (agent_kit/tool_kit.py), records every tool call and external request, and emits events through on_event. The only registered tools today are send_message, set_activity, defer_to_caller, and image-related tools.
A Store protocol (agent_kit/ports.py) backed by SQLite (agent_kit/store/sqlite.py) for invocation mode and Postgres (agent_kit/store/supabase.py) for resident mode. The Store has no methods for epics, checklist items, or epic events yet — those appear in load_hot_context only by raw SQL inside Supabase.
A system_logs table and a log() helper (agent_kit/logging.py) already wired into the loop.
Sprint 2a's job: introduce the body-as-structured-document abstraction, a 12-item-ish tool surface for editing it, the epic_events audit table that powers transactional revert and time-travel reads, and a default checklist seed. Everything is invocation-mode only (resident mode keeps working but doesn't need new behaviour). All tests run against SQLite by default; the Supabase variant runs only when SUPABASE_TEST_DB_URL is set.
Constraints worth naming up front:
The body parser is the single source of truth for epics.title and epics.goal. There is no other path that updates those columns. (Spec §1311–1320.)
Mutually-exclusive body operations: a single edit_epic.body payload picks one of new_content, sections, append, remove_sections, rename_section, or reorder — server rejects mixed payloads.
Section names are case-sensitive. Pre-section content is _preamble. Code fences with ## inside are not section delimiters.
expected_diff comparison is "byte-exact after normalising line endings to \n and stripping trailing whitespace per line" (spec §494).
Sprint 2a does NOT touch sprints/sprint_items, codebases, code_artifacts, feedback, second_opinions, or images — those land in later sprints. The edit_epic.changes.sprints and state.target paths are deliberately deferred to Sprint 4 and should return a not_yet_supported error if the bot tries them.
CLAUDE.md forbids creating a megaplan/ directory; an existing one is harness state, not a target for edits.
The plan is six phases. Phases 1–3 land the schema, parser, and store surface (no tools yet). Phase 4 lands the tool registrations against that surface. Phase 5 wires the turn-end outline log. Phase 6 covers the integration fixture and acceptance criteria.
Createchecklist_items matching spec §1322 exactly: id TEXT PK, epic_id TEXT NOT NULL REFERENCES epics(id) ON DELETE CASCADE, content TEXT NOT NULL, status TEXT CHECK IN ('open','done','skipped','superseded'), position INTEGER NOT NULL, source TEXT CHECK IN ('bot_inferred','user_requested','carried_over','default_seed','second_opinion'), skip_reason TEXT, superseded_by_item_id TEXT REFERENCES checklist_items(id), created_at TIMESTAMPTZ DEFAULT now(), completed_at TIMESTAMPTZ. Index (epic_id, status, position).
Createepic_events matching spec §1381 exactly: id TEXT PK, epic_id TEXT NOT NULL REFERENCES epics(id) ON DELETE CASCADE, transaction_id TEXT NOT NULL, event_type TEXT CHECK IN ('body_edit','checklist_change','sprints_change','state_change','forced_handoff','created','code_referenced','codebase_added','image_generated','second_opinion_requested','reverted_to','sprint_status_change'), summary TEXT NOT NULL, prior_state JSONB, turn_id TEXT REFERENCES bot_turns(id) ON DELETE SET NULL, occurred_at TIMESTAMPTZ DEFAULT now(). Indexes (epic_id, occurred_at DESC) and (transaction_id).
Mirror the Postgres migration in SQLite syntax (TEXT for everything, no JSONB — prior_state becomes TEXT holding a JSON string, consistent with how prompt_snapshot etc. are handled in 001_core.sql).
Register new JSON-encoded columns in _JSON_COLUMNS for both agent_kit/store/sqlite.py:17 and agent_kit/store/supabase.py:12 so update helpers serialise prior_state correctly.
Step 3: Update test truncate list (tests/test_supabase_store.py:33)
Scope: Small
Addchecklist_items and epic_events to the TRUNCATE TABLE … RESTART IDENTITY CASCADE block so the contract test stays green between Supabase runs.
Phase 2: Body parser/serializer
Step 4: Create the parser module (agent_kit/body.py)
Scope: Medium
Implement a pure module with no Store coupling. Public surface (everything else _private):
parse(body: str) -> ParsedBody where ParsedBody is a dataclass with title: str | None, goal_first_paragraph: str | None, sections: list[Section] (in order), preamble: str (text between title line and the first ##, addressable as section name _preamble for read/write ops).
Section: name: str, content: str (the lines after the ## Heading, NOT including the heading line; trailing newline normalised), subheadings: list[str] (raw ### … lines for outline), line_count: int.
serialize(parsed: ParsedBody) -> str — round-trip identity for any input that passed parse() cleanly.
First non-blank line must be # <title> (single #); otherwise raise BodyParseError("body_missing_required_section: title").
Section delimiters are lines that match ^##\s+(.+?)\s*$ (level-2 only). Level-3+ headings stay inside their parent section.
Code-fence guard: track ``` and ~~~ fences during the line scan; ## inside a fenced block is treated as content, not a delimiter. Indented (4-space) code blocks are rare in this corpus — don't implement that edge case for v1; document the gap in a comment on the fence-tracking helper.
Section names case-sensitive; whitespace stripped from the heading text.
Implement section operations as functions on ParsedBody (in-place returns of new ParsedBody): replace_section(name, content), append_to_section(name, content), add_section(name, content, position='after:Foo'|'before:Foo'|'start'|'end'), remove_section(name), rename_section(from_, to), reorder(new_order: list[str]). Each raises a typed error (SectionNotFound, SectionExists, InvalidPosition) the tool layer maps to JSON error payloads.
Implementvalidate_required(parsed: ParsedBody) that the tool layer calls after applying changes and before writing: must contain # title (non-empty), and a ## Goal section whose first non-blank paragraph is non-empty. Raise BodyValidationError("body_missing_required_section: title"|"goal").
Implementcompute_diff(old: str, new: str) -> str — wraps difflib.unified_diff(old.splitlines(keepends=True), new.splitlines(keepends=True), fromfile='before', tofile='after', n=3) and joins. Implementdiffs_equivalent(a: str, b: str) -> bool that normalises both sides per spec §494 (line-endings → \n, strip trailing whitespace per line, drop trailing blank lines) before equality comparison.
Step 5: Create the default-template + checklist-seed module (agent_kit/templates.py)
ConstantDEFAULT_CHECKLIST_SEED: list[str] — the 18 items from spec §634, all with source='default_seed', status 'open', positions 1–18.
Adaptation logic stays out of Sprint 2a's tool layer. The seed is unconditional; the bot adapts during conversation by calling edit_epic({checklist: {update|remove|add: …}}). (Acceptance criterion: "default checklist seeded with 18 items".)
Step 6: Unit tests (tests/test_body_parser.py)
Scope: Medium
Round-trip identity: for ~6 hand-written fixture bodies (preamble-only, single section, six-section design-doc, body with ### Authentication sub-headings under ## Key Decisions, body with a fenced code block containing ## Step 1, body with _preamble content before first ##), assert serialize(parse(body)) == body.
Section ops: for each of replace, append, add (each position variant), remove, rename, reorder — assert the only changed section is the one targeted (byte-equal compare on every other section's serialised form).
Required-element enforcement: missing # line → BodyValidationError(...title); empty ## Goal first paragraph → …goal; ## Goal present with content but only after another section → still passes (only first paragraph matters).
Code-fence guard: body with ``` \n## Inside\n `` is parsed as a single preamble (no section split).
Diff equivalence:diffs_equivalent should return True when the only difference is \r\n vs \n, trailing spaces, or trailing newline; False when content actually differs.
Phase 3: Store surface for epics, checklist, events
Step 7: Extend the Store protocol (agent_kit/ports.py)
Scope: Medium
Add typed methods to the Protocol (and matching implementations in Steps 8–9):
create_epic(*, title, goal, body, state='shaping') -> JSONDict — single-row INSERT into epics. Server takes title/goal/body that the caller has already constructed and parser-validated; the Store does not parse.
load_epic(epic_id) -> JSONDict | None
update_epic_body(epic_id, *, body, title, goal, last_edited_at) -> JSONDict — single UPDATE; the tool layer calls this only after parse + validate succeed.
Why both update_epic_body AND record_epic_event in the same transaction — see Step 11. The protocol just exposes the primitives; the tool layer composes them inside store.transaction().
Step 8: Implement on SupabaseStore (agent_kit/store/supabase.py)
Scope: Medium
Mirror the protocol additions with concrete SQL, using the same _normalize/_json helpers already in the module. _new_id prefixes: 'epic', 'check', 'evt'.
Use store.transaction() internally for seed_checklist (no — single bulk insert is fine; the tool composes the larger transaction).
Step 9: Implement on SQLiteStore (agent_kit/store/sqlite.py)
Scope: Medium
Mirror the same methods. Note the existing module already JSON-encodes _JSON_COLUMNS; add 'prior_state' there. epic_events.transaction_id stays a TEXT (uuid hex string).
Step 10: Extend tests/store_contract.py
Scope: Small
Add a tail block to run_store_contract that exercises the new surface against the existing epic_1: seed an event, append a checklist item, list events, and assert IDs/orderings. Both Supabase and SQLite contract tests pick this up automatically.
Step 11: Wire the editorial tool module (agent_kit/tools/editorial.py)
Scope: Large
Register each tool via @register_tool with explicit JSON schemas mirroring spec §1701 onward.
create_epic(context, title, goal) —
Construct body via templates.DEFAULT_BODY_TEMPLATE(title, goal).
parse + validate_required; on failure return {"error": "body_missing_required_section", "field": …} (don't raise — the model needs to read the message).
Inside store.transaction(): create_epic, seed_checklist(epic_id, DEFAULT_CHECKLIST_SEED), record_epic_event(event_type='created', transaction_id=uuid4().hex, summary=f'Epic created with default design-doc template', prior_state=None, turn_id=context.turn_id).
Reject mixed body operations: at most one of new_content, sections (with optional position for new sections), append, remove_sections, rename_section, reorder per call. (sections may have multiple section names; that's still one op.)
Body path: load current body, parse, apply the requested op(s), validate, serialise → new_body. Compute diff via body.compute_diff(old, new). If expected_diff is provided and not diffs_equivalent(expected_diff, actual_diff), return {"error": "expected_diff_mismatch", "actual_diff": actual_diff} and do not write.
Checklist path: apply add (with start_position = len(existing_open_items) + 1 if no positions given, or honouring positions and shifting where needed), update, remove. Capture prior full checklist as prior_state for the event.
Inside one store.transaction():update_epic_body (if body changed), add/update/delete_checklist_items (if checklist changed), and one record_epic_event per affected family — body_edit with prior_state={'body': old_body}, checklist_change with prior_state={'items': [...]} — all sharing the same transaction_id = uuid4().hex.
No event_id: look up the most recent transaction via latest_transaction_id, fetch all its events.
With event_id: fetch that event and all events with the same transaction_id (to undo the whole edit_epic call, per spec §1399).
Apply each event's prior_state in reverse: body_edit → update_epic_body(prior body) (re-parse to refresh title/goal); checklist_change → wipe current items + re-insert from snapshot.
Append a single reverted_to event with new transaction_id and prior_state={'reverted_transaction_id': original_txn_id, 'reverted_event_ids': [...]} so revert is itself revertible.
render_epic(context, epic_id, format='markdown') — Sprint 2a only ships 'markdown'; 'html' returns not_yet_supported. For markdown: load body and return as-is (image reference resolution lands in Sprint 6; no-op here, but the parameter exists for forward compat).
get_self_understanding(epic_id) — structured summary of epic (goal, state, open checklist items count, section names, last 3 events). The full 7-section snapshot per spec §1068 lands gradually; v1 returns the 5 fields above (document the gap inline).
get_epic_at_time(epic_id, timestamp) — list events with occurred_at <= timestamp ascending; reconstruct: start with epics row's earliest state (find the created event's prior_state is null, so use the row's body and reverse-apply forward — see Note below), then for each event apply the opposite of prior_state, no — actually: replay forward from creation. Implementation choice: snapshot-style. We don't store post-state per event, only prior_state, so we replay backwards from the current state: take current body/checklist, then for each event with occurred_at > timestamp, overlay its prior_state to undo it. The earliest event whose occurred_at > timestamp wins for each field. Return {body, checklist, reconstructed_at: timestamp}.
get_recent_turns(n=10, epic_id?) — query bot_turns ordered by started_at DESC LIMIT n. Add a list_recent_turns Store method or run raw SQL via a new Store helper. Returns each turn's id, started_at, status, triggered message snippets, and a change_summary aggregated from epic_events.summary for that turn_id.
search_tool_calls(tool_name?, epic_id?, since?, limit=20) — query tool_calls joined to bot_turns for epic_id filter. Add Store method search_tool_calls.
Step 13: Register the new tools in the loop import path (agent_kit/loop.py:16)
Scope: Small
Addimport agent_kit.tools.editorial # noqa: F401 and import agent_kit.tools.editorial_reads # noqa: F401 next to the existing communication/images imports so tools auto-register.
Phase 5: Turn-end epic outline log
Step 14: Emit epic_outline after every turn that touched an epic (agent_kit/loop.py)
Scope: Small
At the end of run_turn, after the final update_turn(status='completed') and before returning the envelope: if context.metadata.get('epic_id') is set AND any tool_call this turn had tool_name in {'create_epic','edit_epic','revert'} (cheap: walk events list which already contains tool_call entries), parse the current body and call log(store, 'info', 'application', 'epic_outline', f"Epic outline: {title}", details=outline.dict, turn_id=turn['id'], epic_id=epic_id).
Why "any tool that touched the epic" — per spec §142 acceptance criterion, the row exists "after any turn that touched an epic." Pure-read turns don't need an outline log. Failure paths (status='failed') skip the log; that's the honest signal.
Phase 6: Integration test + acceptance verification
Step 15: Create the 10-turn fixture conversation (tests/test_editorial_loop.py)
Scope: Medium
UseFakeModel(script=…) (already exists per tests/test_run_turn.py:8) with a 10-turn deterministic script that, in order:
Turn 1: tool_use create_epic(title='Auth flow design', goal='Decide on auth provider and token storage').
Turns 2–9: a mix of edit_epic calls hitting all six default sections (Goal, Principles, Context, Key Decisions, Open Questions, Deliverable) at least once via sections ops, plus a couple of append calls and a checklist.update to mark items done. Include one expected_diff round trip and one expected_diff mismatch turn.
Turn 10: revert (most recent transaction), then send_message.
Assertions — one assertion per acceptance criterion in spec §131–142:
After turn 1: epics row exists with parsed title/goal; checklist_items count == 18; one created event.
After loop completes: every default section present; one section-only edit verified by re-parsing pre-state from epic_events.prior_state and confirming all other sections byte-identical.
Whole-body edit path (one of turns 2–9 uses new_content): a body_edit event captured the prior body; manual call to revert(epic_id, event_id=that_event) followed by load_epic(...) returns the prior body byte-equal.
"revert that" turn: most recent transaction undone; new reverted_to event present.
expected_diff mismatch turn: tool result contains error='expected_diff_mismatch' and DB state unchanged.
expected_diff match turn: writes commit normally.
Direct call to get_epic_at_time(epic_id, timestamp_after_turn_5) returns body + checklist matching what turn 5's post-state would have looked like (compute by replaying ourselves from events).
Direct call to get_recent_turns(5) returns 5 turns, most recent first.
Direct call to search_tool_calls(tool_name='edit_epic', epic_id=…) returns ≥3 rows.
At least one system_logs row per touching turn with event_type='epic_outline', with details.sections containing all six default headings.
Step 16: Run the targeted tests, then the full suite
Run the full suite pytest -x to confirm no regression in Sprint 1a/1b tests (the contract tests in particular).
Optionally run SUPABASE_TEST_DB_URL=… pytest tests/test_supabase_store.py if a local Supabase is available (skipped otherwise — that's the existing behaviour).
Execution Order
Schema first (Phase 1). Migrations are cheapest to land and unblock everything else.
Body parser + templates with their unit tests (Phase 2). Pure code, fast tests, no Store coupling — best ROI on early bugs.
Store extensions (Phase 3) — needed before any tool can write.
Tools (Phase 4) — once the parser and store are solid, this is mostly schema-validation + glue.
Outline log (Phase 5) — depends on tools existing.
Integration fixture (Phase 6) — proves the whole pipeline end-to-end.
Validation Order
pytest tests/test_body_parser.py — fastest feedback on parser edge cases.
pytest tests/store_contract.py-driven tests (tests/test_sqlite_store.py, tests/test_supabase_store.py when DB available) — confirms the new Store surface is consistent across adapters.
pytest tests/test_editorial_loop.py — the 10-turn integration.
pytest -x — full regression.
code
Plan metadata:
{
"version": 1,
"timestamp": "2026-04-30T05:19:39Z",
"hash": "sha256:55da79b2775c5dfce81878da5a6ed5d307144229a858dbb11d6d4e334c7b5a2e",
"questions": [
"Tool surface scope: the brief lists get_history, get_self_understanding, get_epic_at_time, get_recent_turns, search_tool_calls, get_section_names as read tools but the spec also mentions get_body_outline and search_in_body. Spec \u00a7163 explicitly defers those last two to Sprint 2b. Plan defers them \u2014 confirm that's correct and we're not pulling them forward.",
"Locking semantics: an edit_epic mutates epics.body and inserts events while the existing epic_locks row is held by the turn (loop.py acquires it). Are concurrent invocation-mode runs against the same epic in scope for Sprint 2a, or is single-writer-by-construction acceptable (matching Sprint 1b's posture)?",
"get_epic_at_time reconstruction: spec \u00a71678 says "replays epic_events". Since we only store prior_state (not post-state), the natural implementation is to replay backwards from the current state \u2014 undoing every event with occurred_at > T. That gives the exact spec semantics. Confirm this read direction is fine, or do you want a forward-replay path that records post_state on every event?",
"Default checklist seed adaptation: the brief mentions "default checklist seed \u2014 18 items with adaptation logic." Sprint 2a's acceptance criterion only requires the bot to seed all 18. Adaptation (drop #1 if obvious, drop #6 if no codebase, etc.) seems to belong in the bot's prompt/decision-making, not server-side at create time. Should the seed code be unconditional in v1, with adaptation deferred to the system prompt later in this sprint or Sprint 2b?",
"Sprints/state path in edit_epic: Sprint 4 owns state.target gating and the full sprints schema. Plan returns not_yet_supported if the bot calls those paths in Sprint 2a. Acceptable, or should we accept-and-store-only (so the server doesn't reject mid-transaction if the bot speculatively includes them)?"
],
"success_criteria": [
{
"criterion": "Postgres migration 004 and SQLite migration 004 create checklist_items and epic_events with the columns, CHECK constraints, FK ON DELETE behaviour, and indexes specified in spec \u00a71322 and \u00a71381.",
"priority": "must",
"requires": [
"read_files"
]
},
{
"criterion": "Body parser round-trip identity holds: serialize(parse(body)) == body for \u22656 fixture bodies including preamble-only, single section, full design-doc template, sub-headings, fenced code containing '##', and a body with non-empty preamble.",
"priority": "must",
"requires": [
"run_tests"
]
},
{
"criterion": "Body parser rejects writes that would leave '# Title' missing or '## Goal' first paragraph empty, with errors body_missing_required_section: title and \u2026: goal respectively.",
"priority": "must",
"requires": [
"run_tests"
]
},
{
"criterion": "create_epic creates an epics row with parser-derived title and goal, seeds 18 default checklist items with status='open' and source='default_seed', and writes one 'created' epic_event sharing a transaction_id.",
"priority": "must",
"requires": [
"run_tests"
]
},
{
"criterion": "edit_epic body section operations leave every non-targeted section byte-identical (verified by parsing prior_state captured in the body_edit event and comparing every other section's serialised form).",
"priority": "must",
"requires": [
"run_tests"
]
},
{
"criterion": "edit_epic with expected_diff that does not match (after \n + trailing-whitespace normalisation) refuses to commit, returns the actual diff, and leaves epics.body, title, goal, and checklist_items untouched.",
"priority": "must",
"requires": [
"run_tests"
]
},
{
"criterion": "edit_epic with expected_diff that matches commits normally and writes one event per affected family (body_edit, checklist_change) sharing a single transaction_id.",
"priority": "must",
"requires": [
"run_tests"
]
},
{
"criterion": "revert(epic_id) with no event_id undoes the entire most-recent transaction (body and checklist together) and appends a 'reverted_to' event with a new transaction_id; the resulting body is byte-equal to the pre-edit body.",
"priority": "must",
"requires": [
"run_tests"
]
},
{
"criterion": "get_epic_at_time(epic_id, T) returns body and checklist state equal to what was committed at the most recent event with occurred_at <= T (verified against an explicit replay computed inside the test fixture).",
"priority": "must",
"requires": [
"run_tests"
]
},
{
"criterion": "get_recent_turns(5) returns the 5 most-recent bot_turns rows (most-recent first) with summaries; search_tool_calls(tool_name='edit_epic', epic_id=X) returns every edit_epic call against epic X with arguments and timestamps.",
"priority": "must",
"requires": [
"run_tests"
]
},
{
"criterion": "After every turn whose tool_calls include create_epic, edit_epic, or revert, exactly one system_logs row exists with category='application', event_type='epic_outline', turn_id=, and details containing title plus a sections array with name + line_count for every section in the body.",
"priority": "must",
"requires": [
"run_tests"
]
},
{
"criterion": "10-turn FakeModel-driven integration fixture in tests/test_editorial_loop.py runs end-to-end, exercises all six default sections, exercises both expected_diff match and mismatch paths, and exercises revert; final assertions cover every Sprint 2a acceptance criterion in spec \u00a7131\u2013142.",
"priority": "must",
"requires": [
"run_tests"
]
},
{
"criterion": "All pre-existing tests in tests/ continue to pass (no regression in Sprint 1a/1b functionality).",
"priority": "must",
"requires": [
"run_tests"
]
},
{
"criterion": "Body parser and section-op modules stay focused: the public surface is parse, serialize, the section ops, validate_required, compute_diff, diffs_equivalent, outline. No tool-layer or Store imports leak into agent_kit/body.py.",
"priority": "should",
"requires": [
"read_files",
"subjective_judgment"
]
},
{
"criterion": "edit_epic rejects requests mixing two body op flavours (e.g. new_content + sections) with a clear error rather than silently picking one.",
"priority": "should",
"requires": [
"run_tests"
]
},
{
"criterion": "agent_kit/body.py stays under ~400 lines and has no third-party dependencies beyond the standard library (difflib, re).",
"priority": "should",
"requires": [
"read_files"
]
}
],
"assumptions": [
"Sprint 2a is invocation-mode only \u2014 no Discord/resident-mode behavior changes. Resident send_message and friends keep working but no new resident wiring is needed.",
"Sprints, state transitions, codebases, code_artifacts, feedback, second_opinions, and image generation are explicitly out of scope. edit_epic returns 'not_yet_supported' when the bot includes changes.sprints or changes.state.",
"Default body template ships with one variant (design-doc); the create_epic tool's template parameter from spec \u00a7534 is deferred since only one value would be valid. If needed later, it's an additive change.",
"Default checklist seed is unconditional in v1 \u2014 all 18 items inserted on every create_epic. Adaptation logic (drop items based on goal phrasing) is the bot's job via subsequent edit_epic calls and lives in the system prompt, not server-side.",
"expected_diff comparison normalises line endings to \n and strips trailing whitespace per line per spec \u00a7494; trailing blank lines are also dropped before equality.",
"get_epic_at_time uses backwards-replay from the current state (undo every event with occurred_at > T) since prior_state is the only snapshot we record. Tied timestamps order by (occurred_at, id).",
"get_self_understanding ships a 5-field summary (goal, state, open checklist count, section names, last 3 events) \u2014 the full 7-section structure described in spec \u00a71068 lands as later-sprint enrichment.",
"render_epic supports format='markdown' only in v1; format='html' returns 'not_yet_supported'. Image-reference resolution is a no-op until Sprint 6.",
"epic_outline log fires for any turn whose tool_calls touched create_epic, edit_epic, or revert \u2014 pure-read turns don't emit the log, matching the spec wording 'turn that touched an epic'.",
"Single-writer concurrency is acceptable; the existing epic_locks mechanism plus the per-edit_epic store.transaction wrapper is sufficient. No additional locking is added in Sprint 2a.",
"The repo's existing megaplan/ directory is harness state and is left untouched; CLAUDE.md's prohibition applies to creating it, not to its presence."
],
"structure_warnings": []
}
code
Plan structure warnings from validator:
[]
Existing flags:
[]
Known accepted debt grouped by subsystem:
{
"are-the-proposed-changes-technically-correct": [
{
"id": "DEBT-011",
"concern": "are the proposed changes technically correct?: storage reconciliation cannot be correct for crash-before-upload unless the ledger row stores enough replay material. step 16 says supabase_storage reconciliation does blob.exists(ref) and reissues if missing, but step 13's pending storage rows for voice/image ingestion do not store the attachment bytes, a durable local blob, or even explicitly the discord attachment url in request_body; without that, the reissue branch has no input.",
"occurrence_count": 1,
"plan_ids": [
"sprint-1b-discord-resident"
]
}
],
"callable-api": [
{
"id": "DEBT-001",
"concern": "sprint 1a plan descopes attachment-passing despite the spec's callable api marking it as 1a acceptance.",
"occurrence_count": 1,
"plan_ids": [
"sprint-1a-agent-kit-core"
]
},
{
"id": "DEBT-002",
"concern": "spec\u2019s sprint 1a readiness gate lists attachment-passing protocol; plan defers it.",
"occurrence_count": 1,
"plan_ids": [
"sprint-1a-agent-kit-core"
]
},
{
"id": "DEBT-003",
"concern": "cli omits --attach in 1a.",
"occurrence_count": 1,
"plan_ids": [
"sprint-1a-agent-kit-core"
]
},
{
"id": "DEBT-004",
"concern": "python run_turn omits attachments= in 1a.",
"occurrence_count": 1,
"plan_ids": [
"sprint-1a-agent-kit-core"
]
},
{
"id": "DEBT-005",
"concern": "plan removes --attach, attachments=, localblobstore, and attachment tests from 1a.",
"occurrence_count": 1,
"plan_ids": [
"sprint-1a-agent-kit-core"
]
}
],
"did-the-work-fully-address-the-issue-hints-user-notes-and-approved-plan-requirements": [
{
"id": "DEBT-007",
"concern": "did the work fully address the issue hints, user notes, and approved plan requirements?: recovery coverage for ingestion-side storage uploads remains underspecified: the plan records pending storage rows before uploading, but the described request_body for those rows only includes deterministic paths, not the original discord attachment url or another durable byte source. if the process crashes before the upload completes, supabase_storage reconciliation can detect the object is missing but cannot reissue the upload deterministically from the stored row.",
"occurrence_count": 1,
"plan_ids": [
"sprint-1b-discord-resident"
]
}
],
"discord-ingestion-recovery": [
{
"id": "DEBT-006",
"concern": "crash-before-storage-upload + discord attachment url expiry results in orphaned ledger rows for voice audio / user-uploaded images. the inbound messages row remains persisted so no silent data loss; the user can re-send. a future sprint may add ingestion-time bytes-to-tmpfile fallback if the orphaned rate is meaningful in production.",
"occurrence_count": 1,
"plan_ids": [
"sprint-1b-discord-resident"
]
}
],
"does-the-change-touch-all-locations-and-supporting-infrastructure": [
{
"id": "DEBT-009",
"concern": "does the change touch all locations and supporting infrastructure?: supporting infrastructure for storage reissue is still incomplete: the plan adds blob.exists, but not a corresponding way for the reconciler to obtain the original attachment payload from the ledger row. since discord attachment urls can be transient, the missing source field is not just a local adapter detail; it affects the recovery contract across discordtransport, external_requests.request_body, and reconciler.",
"occurrence_count": 1,
"plan_ids": [
"sprint-1b-discord-resident"
]
}
],
"find-the-callers-of-the-changed-function-what-arguments-do-they-actually-pass-does-the-fix-handle-all-of-them": [
{
"id": "DEBT-010",
"concern": "find the callers of the changed function. what arguments do they actually pass? does the fix handle all of them?: checked the planned storage reconciliation caller: reconciler can call blob.exists(ref), but when it needs to reissue a missing upload it has no planned argument source for blob.put(...) because the pending request row does not carry the original attachment bytes or a durable fetchable source. that caller path remains under-specified.",
"occurrence_count": 1,
"plan_ids": [
"sprint-1b-discord-resident"
]
}
],
"search-for-related-code-that-handles-the-same-concept-is-the-reported-issue-a-symptom-of-something-broader": [
{
"id": "DEBT-008",
"concern": "search for related code that handles the same concept. is the reported issue a symptom of something broader?: the remaining storage reissue issue applies to both voice and image attachments, not just one branch: voice storage upload needs source audio bytes to recover, and image storage upload needs source image bytes to recover. the plan should store a retrievable source reference in request_body or deliberately mark crash-before-download/upload as orphaned rather than promising deterministic reissue.",
"occurrence_count": 1,
"plan_ids": [
"sprint-1b-discord-resident"
]
}
]
}
Debt guidance:
- These are known accepted limitations. Do not re-flag them unless the current plan makes them worse, broadens them, or fails to contain them.
- Prefix every new concern with a subsystem tag followed by a colon, for example `Timeout recovery: retry backoff remains brittle`.
- When a concern is recurring debt that still needs to be flagged, prefix it with `Recurring debt:` after the subsystem tag, for example `Timeout recovery: Recurring debt: retry backoff remains brittle`.
Your output template is at: /Users/user_c042661f/Documents/arnold-v2/.megaplan/plans/sprint-2a-editorial-core/critique_output.json
Read this file first — it contains 5 checks, each with a question and guidance.
For each check, investigate the codebase, then add your findings to the findings array for that check.
Each finding needs:
"detail": what you specifically checked and what you found (at least a full sentence)
"flagged": true if this describes a difference, risk, or tension — even if you think it's justified. false only if purely informational with no possible downside.
Every check must end with at least one finding. Never leave a findings array empty. If you found no issue, add one detailed flagged: false finding explaining what you checked and why it appears clear.
When in doubt, flag it — the gate can accept tradeoffs, but it can't act on findings it never sees.
Good: {"detail": "Checked callers of nthroot_mod in solveset.py line 1205 — passes prime moduli only, consistent with the fix.", "flagged": false}
Good: {"detail": "The fix handles empty tuples but not single-element tuples which need a trailing comma.", "flagged": true}
Bad: {"detail": "No issue found", "flagged": false} ← too brief, will be rejected
Bad: {"detail": "The hints suggest approach X but the plan uses Y. However Y is consistent with X's intent.", "flagged": false} ← a different approach than the hints IS a flag. You found a divergence — flag it. The gate decides if it's acceptable.
After filling in checks, add any additional concerns to the flags array (e.g., security, performance, dependencies).
Use the standard format (id, concern, category, severity_hint, evidence). This array can be empty.
Workflow: read the file → investigate → read file again → add finding → write file back. Repeat for each check.
code
Additional guidelines:
- Robustness level: standard. Use balanced judgment. Flag significant risks, but do not spend flags on minor polish or executor-obvious boilerplate.
- Over-engineering: prefer the simplest approach that fully solves the problem.
- Reuse existing flag IDs when the same concern is still open.
- `verified_flag_ids`: list flag IDs from prior iterations that the revised plan actually resolves (e.g., if the plan was revised to fix FLAG-001, and you confirm the fix is correct, include "FLAG-001"). Only include flags you've verified — don't guess.
- Verify that the plan follows the expected structure when validator warnings or the outline suggest drift.
- Additional flags may use these categories: correctness, security, completeness, performance, maintainability, other.
- Focus on concrete issues, not structural formatting.
{"checks":[{"id":"issue_hints","question":"Did the work fully address the issue hints, user notes, and approved plan requirements?","findings":[{"detail":"I compared the plan against the explicit user note not to invoke or activate megaplan. The plan treats the existing .megaplan/ directory as harness state and does not propose running the megaplan CLI or creating nested plans, which is consistent with the instruction.","flagged":false},{"detail":"Checked Sprint 2a acceptance in planning-bot-spec.md lines 132-142 against the current loop entrypoint in agent_kit/loop.py. The plan includes a create_epic tool, but it does not address that run_turn currently requires an existing epic_id, acquires an epic_locks row for it before any model/tool call, and creates inbound messages/turns tied to that id; this leaves the acceptance criterion 'Create an epic via natural language' without a concrete bootstrap path when there is no epic yet.","flagged":true},{"detail":"Checked the spec's additional Sprint 2a title/body sync test at planning-bot-spec.md lines 2606-2607. The plan defines _preamble as text between the title line and the first ##, so section replacement of _preamble cannot replace # Title; that diverges from the spec example edit_epic(body: { sections: { _preamble: { replace: '# New Title\\n' } } }) and leaves title editing via section addressing underspecified.","flagged":true}]},{"id":"correctness","question":"Are the proposed changes technically correct?","findings":[{"detail":"I checked the body parsing rules in planning-bot-spec.md lines 503-514 against Phase 2. The spec separates parsing from write validation: bodies with no ## headings are parseable as _preamble, while writes are rejected if they lack # Title or non-empty ## Goal; the plan instead makes parse() raise when the first non-blank line is not # <title>, which conflicts with its own round-trip fixtures for preamble-only/no-section bodies and would break read tools on malformed legacy content.","flagged":true},{"detail":"I checked get_epic_at_time and revert semantics against the epic_events.prior_state contract in planning-bot-spec.md lines 1030-1032 and 1381-1399. The plan stores only metadata on reverted_to events (reverted_transaction_id and ids), then proposes backward replay from current state; a later reverted_to event actually mutates body/checklist, but its event does not contain the pre-revert state needed to undo that mutation when reconstructing a timestamp just before the revert, so time travel across reverts will be incorrect.","flagged":true},{"detail":"I reviewed the create_epic plan against the Data Model requirement in planning-bot-spec.md lines 1314-1316. The plan says create_epic constructs the body and calls parse/validate, but then passes title and goal columns supplied by the caller into Store.create_epic; to satisfy 'the parser is the only writer of epics.title and epics.goal', the tool should explicitly use the parsed title and parsed Goal first paragraph for the insert, not the raw arguments.","flagged":true}]},{"id":"scope","question":"Search for related code that handles the same concept. Is the reported issue a symptom of something broader?","findings":[{"detail":"I searched the current tool system in agent_kit/tool_kit.py and existing tools in agent_kit/tools/communication.py. The plan follows the existing registry/audit pattern for new tools, but it does not mention marking the new read tools with operation_kind='read'; if omitted, @register_tool defaults to write, which would pollute audit semantics for get_epic, get_history, get_recent_turns, and search_tool_calls.","flagged":true},{"detail":"I checked the spec's tool surface around edit_epic in planning-bot-spec.md lines 1703-1740. The plan deliberately returns not_yet_supported for changes.sprints and changes.state, which is a scoped Sprint 2a tradeoff because sprints/state gating are later sprint work, but it also omits changes.meta handling from the schema discussion even though the spec's change object includes meta?: { title?, goal? }; this should be either intentionally rejected or mapped to body edits so callers do not get silent schema drift.","flagged":true}]},{"id":"all_locations","question":"Does the change touch all locations AND supporting infrastructure?","findings":[{"detail":"I checked current registration points in agent_kit/loop.py; tools are available to the model only because agent_kit.tools.communication and agent_kit.tools.images are imported for side effects. The plan correctly includes importing agent_kit.tools.editorial and agent_kit.tools.editorial_reads there, which covers the main tool registration glue.","flagged":false},{"detail":"I checked tests/test_supabase_store.py and the existing _truncate helper. The plan correctly calls out adding checklist_items and epic_events to the truncate list, which is required because the Supabase contract tests share a real database and currently truncate external_requests, tool_calls, messages, bot_turns, system_logs, epic_locks, images, and epics.","flagged":false},{"detail":"I checked agent_kit/store/supabase.py and agent_kit/store/sqlite.py helper patterns. The plan says to add new store methods, but it does not call out adding allowed-column sets or guarded updates for epics, checklist_items, and epic_events in the Supabase adapter analogous to _MESSAGE_COLUMNS, _TURN_COLUMNS, and _IMAGE_COLUMNS; without that supporting adapter glue, update helpers will either be unavailable or bypass the existing column-safety pattern.","flagged":true}]},{"id":"callers","question":"Find the callers of the changed function. What arguments do they actually pass? Does the fix handle all of them?","findings":[{"detail":"I inspected agent_kit/loop.py and tests/test_run_turn.py; current callers of run_turn always provide an epic_id, and test helpers seed an epics row first. The planned create_epic tool does not fit this caller contract for a brand-new epic: using a non-existent id would fail the current lock/message foreign-key path, while using an existing placeholder epic would make the create tool semantically odd unless the loop/CLI grows an explicit no-epic or inbox mode.","flagged":true},{"detail":"I checked ToolRegistry.invoke and audit_wrap in agent_kit/tool_kit.py. Every planned tool function is invoked inside an audit transaction already, so the plan's additional store.transaction() blocks inside create_epic, edit_epic, and revert rely on nested transaction support; SQLite implements savepoints, and psycopg transaction contexts generally support nesting, but this is important enough that the integration test should cover a tool that writes multiple rows plus its audited tool_calls row atomically.","flagged":false}]}],"flags":[{"id":"FLAG-001","concern":"Editorial bootstrap: create_epic is planned as a normal tool, but the current loop requires an existing epic before the model can call any tool, so natural-language epic creation has no executable path.","category":"completeness","severity_hint":"likely-significant","evidence":"agent_kit/loop.py calls store.acquire_epic_lock(epic_id) and store.create_message(epic_id=epic_id, ...) before the model/tool loop; epic_locks.epic_id and messages reference epics(id), while Sprint 2a acceptance requires creating an epic via natural language."},{"id":"FLAG-002","concern":"Body parser/validation: the plan makes parse() reject missing # Title, conflicting with the spec's parseable _preamble fallback and with read/time-travel tools that need to inspect malformed or legacy bodies.","category":"correctness","severity_hint":"likely-significant","evidence":"Spec lines 503-514 say no ## headings means whole body is _preamble and write rejection happens if missing title/Goal after a body edit; Phase 2 says parse() raises on missing first-line title."},{"id":"FLAG-003","concern":"History replay: reverted_to events do not store enough prior state to support backward get_epic_at_time reconstruction across a revert.","category":"correctness","severity_hint":"likely-significant","evidence":"The plan stores only {'reverted_transaction_id', 'reverted_event_ids'} for reverted_to, but the same revert mutates body/checklist; backward replay from current state needs the state immediately before that revert to reconstruct timestamps before it."},{"id":"FLAG-004","concern":"Section addressing: _preamble as planned excludes the title line, so the spec's title edit via _preamble section replacement cannot work.","category":"correctness","severity_hint":"likely-minor","evidence":"The plan defines preamble as text between the title line and the first ##; the spec's Sprint 2a title/body sync test edits _preamble with '# New Title\\n' and expects epics.title to update."}],"verified_flag_ids":[],"disputed_flag_ids":[]}
{"checks":[{"id":"issue_hints","question":"Did the work fully address the issue hints, user notes, and approved plan requirements?","findings":[{"detail":"I compared the plan against the explicit user note not to invoke or activate megaplan. The plan treats the existing .megaplan/ directory as harness state and does not propose running the megaplan CLI or creating nested plans, which is consistent with the instruction.","flagged":false},{"detail":"Checked Sprint 2a acceptance in planning-bot-spec.md lines 132-142 against the current loop entrypoint in agent_kit/loop.py. The plan includes a create_epic tool, but it does not address that run_turn currently requires an existing epic_id, acquires an epic_locks row for it before any model/tool call, and creates inbound messages/turns tied to that id; this leaves the acceptance criterion 'Create an epic via natural language' without a concrete bootstrap path when there is no epic yet.","flagged":true},{"detail":"Checked the spec's additional Sprint 2a title/body sync test at planning-bot-spec.md lines 2606-2607. The plan defines _preamble as text between the title line and the first ##, so section replacement of _preamble cannot replace # Title; that diverges from the spec example edit_epic(body: { sections: { _preamble: { replace: '# New Title\\n' } } }) and leaves title editing via section addressing underspecified.","flagged":true}]},{"id":"correctness","question":"Are the proposed changes technically correct?","findings":[{"detail":"I checked the body parsing rules in planning-bot-spec.md lines 503-514 against Phase 2. The spec separates parsing from write validation: bodies with no ## headings are parseable as _preamble, while writes are rejected if they lack # Title or non-empty ## Goal; the plan instead makes parse() raise when the first non-blank line is not # <title>, which conflicts with its own round-trip fixtures for preamble-only/no-section bodies and would break read tools on malformed legacy content.","flagged":true},{"detail":"I checked get_epic_at_time and revert semantics against the epic_events.prior_state contract in planning-bot-spec.md lines 1030-1032 and 1381-1399. The plan stores only metadata on reverted_to events (reverted_transaction_id and ids), then proposes backward replay from current state; a later reverted_to event actually mutates body/checklist, but its event does not contain the pre-revert state needed to undo that mutation when reconstructing a timestamp just before the revert, so time travel across reverts will be incorrect.","flagged":true},{"detail":"I reviewed the create_epic plan against the Data Model requirement in planning-bot-spec.md lines 1314-1316. The plan says create_epic constructs the body and calls parse/validate, but then passes title and goal columns supplied by the caller into Store.create_epic; to satisfy 'the parser is the only writer of epics.title and epics.goal', the tool should explicitly use the parsed title and parsed Goal first paragraph for the insert, not the raw arguments.","flagged":true}]},{"id":"scope","question":"Search for related code that handles the same concept. Is the reported issue a symptom of something broader?","findings":[{"detail":"I searched the current tool system in agent_kit/tool_kit.py and existing tools in agent_kit/tools/communication.py. The plan follows the existing registry/audit pattern for new tools, but it does not mention marking the new read tools with operation_kind='read'; if omitted, @register_tool defaults to write, which would pollute audit semantics for get_epic, get_history, get_recent_turns, and search_tool_calls.","flagged":true},{"detail":"I checked the spec's tool surface around edit_epic in planning-bot-spec.md lines 1703-1740. The plan deliberately returns not_yet_supported for changes.sprints and changes.state, which is a scoped Sprint 2a tradeoff because sprints/state gating are later sprint work, but it also omits changes.meta handling from the schema discussion even though the spec's change object includes meta?: { title?, goal? }; this should be either intentionally rejected or mapped to body edits so callers do not get silent schema drift.","flagged":true}]},{"id":"all_locations","question":"Does the change touch all locations AND supporting infrastructure?","findings":[{"detail":"I checked current registration points in agent_kit/loop.py; tools are available to the model only because agent_kit.tools.communication and agent_kit.tools.images are imported for side effects. The plan correctly includes importing agent_kit.tools.editorial and agent_kit.tools.editorial_reads there, which covers the main tool registration glue.","flagged":false},{"detail":"I checked tests/test_supabase_store.py and the existing _truncate helper. The plan correctly calls out adding checklist_items and epic_events to the truncate list, which is required because the Supabase contract tests share a real database and currently truncate external_requests, tool_calls, messages, bot_turns, system_logs, epic_locks, images, and epics.","flagged":false},{"detail":"I checked agent_kit/store/supabase.py and agent_kit/store/sqlite.py helper patterns. The plan says to add new store methods, but it does not call out adding allowed-column sets or guarded updates for epics, checklist_items, and epic_events in the Supabase adapter analogous to _MESSAGE_COLUMNS, _TURN_COLUMNS, and _IMAGE_COLUMNS; without that supporting adapter glue, update helpers will either be unavailable or bypass the existing column-safety pattern.","flagged":true}]},{"id":"callers","question":"Find the callers of the changed function. What arguments do they actually pass? Does the fix handle all of them?","findings":[{"detail":"I inspected agent_kit/loop.py and tests/test_run_turn.py; current callers of run_turn always provide an epic_id, and test helpers seed an epics row first. The planned create_epic tool does not fit this caller contract for a brand-new epic: using a non-existent id would fail the current lock/message foreign-key path, while using an existing placeholder epic would make the create tool semantically odd unless the loop/CLI grows an explicit no-epic or inbox mode.","flagged":true},{"detail":"I checked ToolRegistry.invoke and audit_wrap in agent_kit/tool_kit.py. Every planned tool function is invoked inside an audit transaction already, so the plan's additional store.transaction() blocks inside create_epic, edit_epic, and revert rely on nested transaction support; SQLite implements savepoints, and psycopg transaction contexts generally support nesting, but this is important enough that the integration test should cover a tool that writes multiple rows plus its audited tool_calls row atomically.","flagged":false}]}],"flags":[{"id":"FLAG-001","concern":"Editorial bootstrap: create_epic is planned as a normal tool, but the current loop requires an existing epic before the model can call any tool, so natural-language epic creation has no executable path.","category":"completeness","severity_hint":"likely-significant","evidence":"agent_kit/loop.py calls store.acquire_epic_lock(epic_id) and store.create_message(epic_id=epic_id, ...) before the model/tool loop; epic_locks.epic_id and messages reference epics(id), while Sprint 2a acceptance requires creating an epic via natural language."},{"id":"FLAG-002","concern":"Body parser/validation: the plan makes parse() reject missing # Title, conflicting with the spec's parseable _preamble fallback and with read/time-travel tools that need to inspect malformed or legacy bodies.","category":"correctness","severity_hint":"likely-significant","evidence":"Spec lines 503-514 say no ## headings means whole body is _preamble and write rejection happens if missing title/Goal after a body edit; Phase 2 says parse() raises on missing first-line title."},{"id":"FLAG-003","concern":"History replay: reverted_to events do not store enough prior state to support backward get_epic_at_time reconstruction across a revert.","category":"correctness","severity_hint":"likely-significant","evidence":"The plan stores only {'reverted_transaction_id', 'reverted_event_ids'} for reverted_to, but the same revert mutates body/checklist; backward replay from current state needs the state immediately before that revert to reconstruct timestamps before it."},{"id":"FLAG-004","concern":"Section addressing: _preamble as planned excludes the title line, so the spec's title edit via _preamble section replacement cannot work.","category":"correctness","severity_hint":"likely-minor","evidence":"The plan defines preamble as text between the title line and the first ##; the spec's Sprint 2a title/body sync test edits _preamble with '# New Title\\n' and expects epics.title to update."}],"verified_flag_ids":[],"disputed_flag_ids":[]}
You are already running inside the megaplan harness for this step. Do the requested planning/review/execution work directly. Do NOT invoke the megaplan CLI, do NOT read or activate the megaplan skill, do NOT start nested megaplan plans, and do NOT recurse into another planning harness. Treat mentions of megaplan in the repository or environment as implementation context only.
You are an independent reviewer. Critique the plan against the actual repository.
Bot maintains an epic body and checklist for one epic, with section-level body editing. Minimum to have an editorial conversation.
Full spec is at planning-bot-spec.md in this repo root. Refer to it for complete details on Body Structure and Editing, Body Templates, The Checklist as Guide, and Data Model sections.
Body parser/serializer — markdown ↔ structured sections with ## heading delimiters; enforces heading hierarchy (# for title only, ## for sections, ### for sub-headings)
Turn-end epic outline emitted to system_logs at info level
Default body template (design doc) — Goal, Principles, Context, Key Decisions, Open Questions, Deliverable
Sprint 2a gives Arnold a document to edit. Today the codebase has an epics table (supabase/migrations/202604300001_001_core.sql), a turn loop (agent_kit/loop.py) that requires epic_id to acquire epic_locks before any model call, a Store protocol (agent_kit/ports.py) backed by SQLite + Postgres adapters, and a system_logs sink. The only registered tools are send_message, set_activity, defer_to_caller, view_image, send_image, update_image_metadata.
This sprint adds (1) two new tables (checklist_items, epic_events); (2) a body parser/serializer with section addressing; (3) Store CRUD for epics/checklist/events; (4) ~10 new tools (create_epic, edit_epic, revert, render_epic, plus reads); (5) a no-epic turn-mode so create_epic is callable from a fresh state; (6) a turn-end epic_outline log.
Constraints worth pinning up front (now reflecting critique fixes):
Bootstrap path:run_turn(epic_id=None) is now a first-class mode. Lock acquisition is skipped; the inbound message and the bot_turns row are created with epic_id=NULL (both columns are already nullable per supabase/migrations/202604300001_001_core.sql:22, :50). When create_epic fires, it stamps context.metadata['epic_id'], then UPDATEs the inbound message and the turn to point at the new epic. (FLAG-001, issue_hints-1, callers.)
Parser split:parse(body) is lenient — it accepts any input, including bodies missing # Title, bodies with no ## headings (whole body is _preamble), and legacy/malformed content. Only validate_for_write(parsed) is strict and is called only by write paths. (FLAG-002, correctness-1.)
_preamble includes the # Title line per spec §2606. The preamble is the raw text from the start of the body up to (but not including) the first ## line. Replacing _preamble with '# New Title\n' therefore updates the title; removing the # Title line via a preamble write is rejected by validate_for_write with body_missing_required_section: title. (issue_hints-2.)
Title/goal columns are parser-derived only.create_epic and edit_epic write epics.title and epics.goal exclusively from parsed.title and parsed.goal_first_paragraph. Raw title/goal arguments are template inputs only. (correctness-3.)
reverted_to events store full pre-revert state.prior_state = {'body': pre_revert_body, 'checklist': [...], 'reverted_transaction_id': txn, 'reverted_event_ids': [...]} so backward replay across reverts is correct. (FLAG-003, correctness-2.)
Read tools register with operation_kind='read'. Write tools default operation_kind='write'. (scope-1.)
edit_epic.changes.meta is rejected with meta_not_supported: title/goal are derived columns; bot must edit body.sections._preamble (for title) or body.sections.Goal (for goal). (scope-2.)
Mutually exclusive body ops.new_content, , , , , and are mutually exclusive in a single ; mixing returns .
Six phases. Phases 1–3 land schema, parser, and store surface. Phase 4 lands tools. Phase 5 wires the loop bootstrap and outline log. Phase 6 covers the integration fixture.
Createchecklist_items matching spec §1322 exactly: id TEXT PK, epic_id TEXT NOT NULL REFERENCES epics(id) ON DELETE CASCADE, content TEXT NOT NULL, status TEXT CHECK IN ('open','done','skipped','superseded'), position INTEGER NOT NULL, source TEXT CHECK IN ('bot_inferred','user_requested','carried_over','default_seed','second_opinion'), skip_reason TEXT, superseded_by_item_id TEXT REFERENCES checklist_items(id), created_at TIMESTAMPTZ DEFAULT now(), completed_at TIMESTAMPTZ. Index (epic_id, status, position).
Createepic_events matching spec §1381 exactly: id TEXT PK, epic_id TEXT NOT NULL REFERENCES epics(id) ON DELETE CASCADE, transaction_id TEXT NOT NULL, event_type TEXT CHECK IN ('body_edit','checklist_change','sprints_change','state_change','forced_handoff','created','code_referenced','codebase_added','image_generated','second_opinion_requested','reverted_to','sprint_status_change'), summary TEXT NOT NULL, prior_state JSONB, turn_id TEXT REFERENCES bot_turns(id) ON DELETE SET NULL, occurred_at TIMESTAMPTZ DEFAULT now(). Indexes (epic_id, occurred_at DESC) and (transaction_id).
Mirror the Postgres migration in SQLite (TEXT for everything; prior_state is a TEXT JSON blob, consistent with how prompt_snapshot etc. are handled in 001_core.sql).
Registerprior_state in the JSON-encoding sets at agent_kit/store/sqlite.py:17 and agent_kit/store/supabase.py:12.
parse(body: str) -> ParsedBody — lenient. Never raises. ParsedBody: title: str | None, goal_first_paragraph: str | None, preamble: str (raw text from byte 0 up to but not including the first ## line; INCLUDES the # Title line and any blank/text lines after it), sections: list[Section] in order. Section: name: str, content: str, subheadings: list[str], line_count: int. Title is extracted by scanning the preamble for the first non-blank line matching ^#\s+(.+?)\s*$; if absent or empty, title is None. Goal is extracted by finding a section named exactly Goal, taking everything before the first blank line in its content (whitespace-stripped); if section absent or empty, goal_first_paragraph is None. Bodies with no ## headings parse cleanly to sections=[] and preamble=<entire body>.
serialize(parsed: ParsedBody) -> str — round-trip identity for any output of parse. Emits preamble verbatim, then each ## Name\n<content> in order.
validate_for_write(parsed: ParsedBody) -> None — strict, raises BodyValidationError("body_missing_required_section: title") if parsed.title is None or empty, …goal if parsed.goal_first_paragraph is None or empty. Called by every write path before update_epic_body.
outline(parsed: ParsedBody) -> dict — {title, sections: [{name, line_count, subheadings}], total_lines} for the outline log.
Heading rules (spec §503–514):
Section delimiters match ^##\s+(.+?)\s*$ at top level only. Level-3+ headings stay inside their parent section as content.
Code-fence guard: track ``` and ~~~ fences during the scan; ## inside a fenced block is content, not a delimiter. Indented code blocks aren't tracked (rare in this corpus; document the gap inline).
Section names are case-sensitive; whitespace stripped from heading text.
Section operations (replace_section, , , , , ): pure functions on , return new . Each raises typed errors (, , ) the tool layer maps to JSON error payloads.
DEFAULT_BODY_TEMPLATE(title, goal) -> str — emits the six-section design-doc skeleton (# {title}\n\n## Goal\n\n{goal}\n\n## Principles\n\n## Context\n\n## Key Decisions\n\n## Open Questions\n\n## Deliverable\n).
DEFAULT_CHECKLIST_SEED: list[str] — the 18 items from spec §634, all source='default_seed', status='open', positions 1–18.
No adaptation logic in v1 (settled decision SD-003); the bot adapts via post-create edit_epic calls.
Step 6: Parser unit tests (tests/test_body_parser.py)
Scope: Medium
Round-trip identity for ≥6 fixtures: preamble-only (no ##), single section, six-section design-doc, body with ### Authentication sub-headings, body with a fenced code block containing ## Step 1, body with non-empty preamble before first ##. Assert serialize(parse(b)) == b.
Section ops (each variant): only the targeted section changes; every other section's serialised form is byte-equal.
_preamble covers the title:replace_section(parse(body), '_preamble', '# New Title\n') round-trips through parse to a body whose parsed.title == 'New Title'. Removing the # Title line via replace_section('_preamble', '') round-trips to parsed.title is None, and validate_for_write raises body_missing_required_section: title on the result.
Lenient parse: parsing '', 'just text\n', '## Goal\n\ngoal\n' (no title), '# Title\n' (no Goal section), '# Title\n\n## NotGoal\n\nx\n' (no ## Goal) all return ParsedBody without raising. validate_for_write rejects each with the appropriate body_missing_required_section error.
Code-fence guard: body with ```\n## Inside\n``` parses as a single preamble (no section split).
Diff equivalence:diffs_equivalent returns True when only difference is \r\n vs \n, trailing spaces, or trailing blank lines; False on real content delta.
Phase 3: Store surface for epics, checklist, events
Step 7: Extend Store protocol (agent_kit/ports.py)
Scope: Medium
Add typed methods (Protocol + both adapters):
create_epic(*, title, goal, body, state='shaping') -> JSONDict — single-row INSERT. Caller is the tool layer, which has already parsed and validated.
load_epic(epic_id) -> JSONDict | None
update_epic(epic_id, **changes) -> JSONDict — guarded UPDATE via the existing _update helper, restricted to a new _EPIC_COLUMNS = {'title', 'goal', 'body', 'state', 'last_edited_at', 'last_active_at', 'planned_at'} set. Used by edit_epic and revert for body+title+goal updates.
replace_checklist(epic_id, items) -> list[JSONDict] — used by revert: DELETE all rows for epic_id then bulk INSERT from snapshot. Single transaction by virtue of the wrapping store.transaction().
search_tool_calls_by(*, tool_name=None, epic_id=None, since=None, limit=20) -> list[JSONDict] — tool_calls joined to bot_turns for the epic filter.
update_message(...) already exists; we'll reuse it from the loop bootstrap (Step 14) to retro-stamp epic_id on the inbound message.
update_turn(...) already exists; reused to retro-stamp on the bot_turns row.
Step 8: Implement on SupabaseStore (agent_kit/store/supabase.py)
Scope: Medium
Mirror the protocol additions with concrete SQL using the existing _normalize/_json helpers and _new_id (prefixes: 'epic', 'check', 'evt').
Add module-level constants _EPIC_COLUMNS and _CHECKLIST_COLUMNS next to existing _MESSAGE_COLUMNS/_TURN_COLUMNS/_IMAGE_COLUMNS. Wire update_epic and update_checklist_item through the existing self._update helper for column safety.
Update _TURN_COLUMNS to include 'epic_id' so the loop bootstrap (Step 14) can retro-stamp the turn after create_epic fires.
Update _MESSAGE_COLUMNS to include 'epic_id' for the same reason.
Step 9: Implement on SQLiteStore (agent_kit/store/sqlite.py)
Scope: Medium
Mirror the same methods, the same _EPIC_COLUMNS/_CHECKLIST_COLUMNS constants, and the same epic_id additions to existing message/turn column sets.
Add'prior_state' to _JSON_COLUMNS.
Step 10: Extend the contract test (tests/store_contract.py)
Scope: Small
Add a tail block to run_store_contract that exercises the new surface against epic_1: create a second epic via store.create_epic, seed checklist, append events with transaction_ids, list/filter events, query latest_transaction_id, and verify ordering. Both Supabase and SQLite contract tests pick this up automatically.
Register each tool via @register_tool with explicit JSON schemas and operation_kind='write'.
create_epic(context, title, goal) —
Build body via templates.DEFAULT_BODY_TEMPLATE(title, goal).
parsed = body.parse(rendered); body.validate_for_write(parsed) — on BodyValidationError, return {"error": "body_missing_required_section", "field": …} (don't raise; the model needs to read the message).
Inside store.transaction():
epic = store.create_epic(title=parsed.title, goal=parsed.goal_first_paragraph, body=rendered, state='shaping') — title and goal come only from parsed.*, never from raw args (correctness-3).
store.record_epic_event(epic_id=epic['id'], transaction_id=uuid4().hex, event_type='created', summary='Epic created with default design-doc template', prior_state=None, turn_id=context.turn_id).
Bootstrap retro-stamp (when context.metadata['epic_id'] was None): store.update_message(context.metadata['inbound_message_id'], epic_id=epic['id']) and store.update_turn(context.turn_id, epic_id=epic['id']). Set context.metadata['epic_id'] = epic['id'] for downstream tools in the same turn.
Reject unsupported keys: changes.sprints → {"error": "not_yet_supported", "field": "sprints"}; changes.state → {"error": "not_yet_supported", "field": "state"}; changes.meta → {"error": "meta_not_supported", "hint": "title and goal are derived from body; edit body.sections._preamble for title or body.sections.Goal for goal"} (scope-2).
Reject mixed body ops: at most one of new_content | sections | append | remove_sections | rename_section | reorder per call → {"error": "body_op_conflict"}.
Body path:old = store.load_epic(epic_id)['body']; parsed = body.parse(old); apply the requested op; serialise → . . Compute . If provided and , return and .
Register each tool with operation_kind='read' (scope-1).
get_epic(epic_id, sections=None) — parsed = body.parse(epic['body']). Return {title: parsed.title, goal: parsed.goal_first_paragraph, body_full: epic['body'] if sections is None else None, sections: {name: content, …} when sections is supplied, section_names: [s.name for s in parsed.sections], state}. Lenient parse means malformed bodies still load.
get_section_names(epic_id) — return [s.name for s in body.parse(epic['body']).sections].
get_self_understanding(epic_id) — return {goal, state, open_checklist_count, section_names, recent_events: last 3}. Document inline that the spec §1068 7-section structure (recent decisions, code refs, second opinions, etc.) lights up incrementally as later sprints land their tables.
get_epic_at_time(epic_id, timestamp) — backward replay from current state:
created: this is the earliest possible state; if we're rolling past it, return empty/None body+checklist (caller asked for a time before the epic existed).
reverted_to: undo by restoring prior_state['body'] and prior_state['checklist'] (the captured pre-revert snapshot — Step 11.4 makes this work).
Other event_types (sprints, state, code_referenced, etc., none of which fire in Sprint 2a) fall through with a logged warning.
Tied timestamps order by (occurred_at, id) ASC; when walking descending, reverse that.
get_recent_turns(n=10, epic_id=None) — store.list_recent_turns(...); for each turn, attach aggregated from rows with that (single query joined client-side).
Step 13: Register the tools in the loop import path (agent_kit/loop.py:16)
Scope: Small
Addimport agent_kit.tools.editorial # noqa: F401 and import agent_kit.tools.editorial_reads # noqa: F401 next to existing communication/images imports so tools auto-register.
Phase 5: Loop bootstrap + turn-end outline log
Step 14: No-epic turn mode (agent_kit/loop.py:25 and surrounding)
Scope: Medium
Make epic_id Optional on run_turn and propagate through downstream code paths:
When epic_id is None: skip store.acquire_epic_lock entirely. Skip the lock-contended early return.
Inbound message creation (agent_kit/loop.py:79–85): epic_id=None is already nullable (messages.epic_id is FK with ON DELETE SET NULL, NULL allowed). Capture the resulting inbound_message_id in context.metadata['inbound_message_id'] so create_epic can retro-stamp.
store.create_turn(epic_id=None, …) is allowed (bot_turns.epic_id already nullable). The turn row carries NULL until create_epic retro-stamps it.
load_hot_context is currently load_hot_context(epic_id) and dereferences epic; in no-epic mode, skip the call and pass hot_context = {"epic": None, "recent_messages": [], "recent_tool_calls": []} to the model.
After every tool invocation, if context.metadata.get('epic_id') flipped from None to a real id (set by create_epic's post-commit hook in Step 11.2), the loop's lock-release path must skip — there was no lock to release.
CLI plumbing (arnold/cli.py): allow invoking with no --epic-id (or an explicit --no-epic flag); pass epic_id=None to run_turn. The system prompt for that branch should hint "no active epic — call create_epic(title, goal) first if the user is starting one."
Existing callers (tests/test_run_turn.py) keep passing an epic_id and continue to work unchanged. The no-epic path is purely additive.
At the end of run_turn, after update_turn(status='completed', …) and before envelope return: if context.metadata.get('epic_id') is set AND any tool_call this turn had tool_name in {'create_epic','edit_epic','revert'} (walk events), then parsed = body.parse(store.load_epic(epic_id)['body']), details = body.outline(parsed), and call log(store, 'info', 'application', 'epic_outline', f"Epic outline: {parsed.title or '(untitled)'}", details=details, turn_id=turn['id'], epic_id=epic_id).
Failure paths (status='failed') skip the log. Pure-read turns and turns that never created an epic skip the log.
Phase 6: Integration test + regression verification
UseFakeModel(script=…) (per tests/test_run_turn.py:8) and SQLiteStore with a deterministic 10-turn script:
Turn 1: run_turn(epic_id=None, input='Make me an auth flow design epic') → tool_use create_epic(title='Auth flow design', goal='Decide on auth provider and token storage') → final text.
Turns 2–9: run_turn(epic_id=<the new id>) with edit_epic calls hitting all six default sections at least once via sections ops, plus a _preamble replace that updates the title (asserts epics.title reflects the new value), plus an append, plus a checklist.update marking 3 items done. Include one expected_diff round-trip (matching) and one mismatch turn (asserts DB unchanged).
Turn 10: revert (most recent transaction) followed by send_message.
Assertions — one per spec §131–142 acceptance criterion plus the critique-driven additions:
After Turn 1: epics row exists with title='Auth flow design', goal='Decide on auth provider and token storage'; 18 checklist_items with source='default_seed'; one created event; the inbound message and bot_turn both have epic_id retro-stamped.
After all turns: every default section present; section-only edits leave other sections byte-identical (verified by re-parsing prior_state captured in body_edit events).
Whole-body new_content turn: body_edit event captured prior body; manual revert(epic_id, event_id=that_event) then load_epic returns prior body byte-equal.
"revert that" turn: most-recent transaction undone; new reverted_to event present; prior_state contains body + checklist snapshots (FLAG-003 verification).
expected_diff mismatch turn: tool result has error='expected_diff_mismatch'; epics + checklist unchanged.
expected_diff match turn: writes commit normally.
Title-via-preamble turn: before/after epics.title differs; the same transaction's body_edit event captured the old title in prior_state.
get_epic_at_time(epic_id, T_after_turn_5) returns body + checklist matching a hand-rolled replay computed inside the test.
Step 17: Run the targeted tests, then full regression
Scope: Small
pytest tests/test_body_parser.py -x.
pytest tests/test_sqlite_store.py tests/test_sqlite_store_v1b.py -x to confirm the new contract additions pass.
pytest tests/test_editorial_loop.py -x.
pytest -x for the full suite (no Sprint 1a/1b regression).
Optional:SUPABASE_TEST_DB_URL=… pytest tests/test_supabase_store.py if a local Supabase is available.
Execution Order
Schema first (Phase 1) — migrations unblock everything.
Body parser + templates with their unit tests (Phase 2). Pure code, fastest feedback. Land lenient parse + strict validate split before building anything that depends on it.
Store extensions (Phase 3) — column-safety constants + new methods, exercised through the contract test.
Tools (Phase 4) — depends on parser + store. Write tools first (create_epic, edit_epic, revert, render_epic), then reads.
Loop bootstrap + outline log (Phase 5) — depends on tools. Bootstrap first (FLAG-001) so create_epic is callable; then outline log.
Integration fixture (Phase 6) — proves the whole pipeline + every critique fix end-to-end.
Contract tests (tests/test_sqlite_store.py, tests/test_supabase_store.py when DB available) — confirms new Store surface is consistent across adapters and column-safety holds.
pytest tests/test_editorial_loop.py — the 10-turn integration with bootstrap, time-travel-across-revert, _preamble-title, and meta_not_supported assertions.
pytest -x — full regression.
code
Plan metadata:
{
"version": 2,
"timestamp": "2026-04-30T05:29:21Z",
"hash": "sha256:a4f9c4cd1cf6af5e87ed6539a12c6f6715dab0ac1709e41c7a3f49d3a926ae78",
"changes_summary": "Rev 2 addresses all 12 open critique flags by editing the existing six-phase structure rather than restructuring. Key changes: (1) added a no-epic mode to run_turn (epic_id=None), with create_epic retro-stamping the inbound message and bot_turn (FLAG-001/issue_hints-1/callers); (2) split parser into lenient parse() + strict validate_for_write() so reads/time-travel survive malformed bodies (FLAG-002/correctness-1); (3) redefined _preamble to include the # Title line per spec \u00a72606, making replace_section('_preamble', ...) the canonical title-edit path (issue_hints-2); (4) reverted_to events now snapshot full pre-revert body + checklist in prior_state so backward replay works across reverts (FLAG-003/correctness-2); (5) create_epic writes epics.title/goal exclusively from parsed values, never raw args (correctness-3); (6) read tools register with operation_kind='read' (scope-1); (7) edit_epic.changes.meta is explicitly rejected with meta_not_supported and a hint to use body sections (scope-2); (8) added _EPIC_COLUMNS and _CHECKLIST_COLUMNS to both Store adapters and extended _MESSAGE_COLUMNS/_TURN_COLUMNS to allow the bootstrap epic_id retro-stamp (all_locations). Integration test gained explicit assertions for each critique fix (title-via-preamble, time-travel-across-revert, meta_not_supported, operation_kind values).",
"flags_addressed": [
{
"id": "FLAG-001",
"resolution": "addressed",
"reason": "run_turn now accepts epic_id=None; lock acquisition and load_hot_context are skipped; create_epic retro-stamps the inbound message and bot_turn rows. CLI gets a no-epic invocation path. Integration test exercises the bootstrap turn end-to-end."
},
{
"id": "FLAG-002",
"resolution": "addressed",
"reason": "Parser split: parse() is now explicitly lenient and never raises; validate_for_write() is strict and called only by write paths. Round-trip fixtures and time-travel/read tools exercise the lenient path."
},
{
"id": "FLAG-003",
"resolution": "addressed",
"reason": "revert now captures the full pre-revert body + checklist snapshot in the new reverted_to event's prior_state, so backward replay across a revert restores the immediately-pre-revert state. Integration test asserts get_epic_at_time(T_just_before_revert) matches the captured snapshot."
},
{
"id": "issue_hints-1",
"resolution": "addressed",
"reason": "Same fix as FLAG-001: run_turn(epic_id=None) is a first-class mode and create_epic retro-stamps the message + turn after commit."
},
{
"id": "issue_hints-2",
"resolution": "addressed",
"reason": "_preamble is redefined to include the # Title line and any leading text up to the first ## heading, matching spec \u00a72606. replace_section('_preamble', '# New Title\n') is the canonical title-edit path; rename_section to/from _preamble is rejected. Integration test exercises the title-via-preamble case."
},
{
"id": "correctness-1",
"resolution": "addressed",
"reason": "Same fix as FLAG-002: parse() is lenient, validate_for_write() is strict and only used on writes. Read tools and get_epic_at_time work against legacy/malformed bodies without raising."
},
{
"id": "correctness-2",
"resolution": "addressed",
"reason": "Same fix as FLAG-003: reverted_to event prior_state now contains the full pre-revert state."
},
{
"id": "correctness-3",
"resolution": "addressed",
"reason": "create_epic now passes parsed.title and parsed.goal_first_paragraph (not the raw arguments) to store.create_epic. The body parser is the only writer of epics.title and epics.goal, matching spec \u00a71314\u20131316."
},
{
"id": "scope-1",
"resolution": "addressed",
"reason": "All read tools (get_epic, get_section_names, get_history, get_self_understanding, get_epic_at_time, get_recent_turns, search_tool_calls) register with operation_kind='read'. Integration test asserts correct operation_kind in tool_calls rows."
},
{
"id": "scope-2",
"resolution": "addressed",
"reason": "edit_epic explicitly rejects changes.meta with error='meta_not_supported' and a hint pointing to body.sections._preamble (for title) or body.sections.Goal (for goal). Asserted in the integration test."
},
{
"id": "all_locations",
"resolution": "addressed",
"reason": "Both adapters gain module-level _EPIC_COLUMNS and _CHECKLIST_COLUMNS constants wired through the existing _update helper, mirroring _MESSAGE_COLUMNS/_TURN_COLUMNS/_IMAGE_COLUMNS. _MESSAGE_COLUMNS and _TURN_COLUMNS are extended to include 'epic_id' so the bootstrap retro-stamp uses guarded updates."
},
{
"id": "callers",
"resolution": "addressed",
"reason": "Same fix as FLAG-001: run_turn callers can pass epic_id=None for the bootstrap; existing callers (tests/test_run_turn.py) keep passing an epic_id and remain unchanged. The no-epic path is purely additive."
}
],
"questions": [
"Should the no-epic bootstrap path also handle 'user typed a question that doesn't warrant creating an epic' (e.g., greetings, meta-questions)? Plan currently assumes the bot either calls create_epic or sends a message-only response; a turn that ends with epic_id still NULL is treated as a successful no-op (epic_outline log skipped). Is that acceptable, or should we reject turn completion if epic_id is still NULL after the model loop?",
"spec test #7 (planning-bot-spec.md:2606) references a body_version column that does not exist in the current schema. Plan defers introducing body_version, covering the audit/title-update semantics another way. Confirm body_version is fine to skip in Sprint 2a, or pull it forward as a one-line column add in migration 004?",
"get_epic_at_time across reverts: the plan handles the simple case (body+checklist snapshot in reverted_to.prior_state lets backward replay restore the immediate pre-revert state). Does the spec require correct reconstruction at timestamps that fall a body_edit event and a revert that undoes it (e.g., T was after the edit but before the revert)? Backward replay handles that naturally; flagging in case the desired semantics differ."
],
"success_criteria": [
{
"criterion": "Postgres migration 004 and SQLite migration 004 create checklist_items and epic_events with the columns, CHECK constraints, FK ON DELETE behaviour, and indexes specified in spec \u00a71322 and \u00a71381.",
"priority": "must",
"requires": [
"read_files"
]
},
{
"criterion": "body.parse() is lenient and returns a ParsedBody for empty input, plain-text input, bodies with no '##' headings, bodies missing '# Title', and bodies missing '## Goal' \u2014 without raising. Integration tools (get_epic, get_epic_at_time) work against these inputs.",
"priority": "must",
"requires": [
"run_tests"
]
},
{
"criterion": "body.validate_for_write() raises BodyValidationError('body_missing_required_section: title') when parsed.title is None or empty, and 'body_missing_required_section: goal' when parsed.goal_first_paragraph is None or empty. Write tools surface this as a structured tool result error.",
"priority": "must",
"requires": [
"run_tests"
]
},
{
"criterion": "Body parser round-trip identity holds: serialize(parse(body)) == body for \u22656 fixture bodies including preamble-only (no '##'), single section, full design-doc template, sub-headings, fenced code containing '##', and a body with non-empty preamble before the first section.",
"priority": "must",
"requires": [
"run_tests"
]
},
{
"criterion": "_preamble section addressing covers the '# Title' line per spec \u00a72606: replace_section(parsed, '_preamble', '# New Title\n') round-trips to ParsedBody with title='New Title'; replace_section(parsed, '_preamble', '') round-trips to title=None and validate_for_write rejects it with body_missing_required_section: title.",
"priority": "must",
"requires": [
"run_tests"
]
},
{
"criterion": "create_epic creates an epics row whose title and goal columns equal parse(rendered_template).title and .goal_first_paragraph respectively (not the raw input arguments), seeds 18 default checklist items with status='open' and source='default_seed', and writes one 'created' epic_event sharing a transaction_id.",
"priority": "must",
"requires": [
"run_tests"
]
},
{
"criterion": "run_turn(epic_id=None, input=...) executes without acquiring an epic_locks row, creates an inbound message and bot_turn with epic_id=NULL, and \u2014 when create_epic fires within the turn \u2014 retro-stamps both rows with the new epic_id by the time the turn completes.",
"priority": "must",
"requires": [
"run_tests"
]
},
{
"criterion": "edit_epic body section operations leave every non-targeted section byte-identical (verified by parsing prior_state captured in the body_edit event and comparing every other section's serialised form).",
"priority": "must",
"requires": [
"run_tests"
]
},
{
"criterion": "edit_epic with expected_diff that does not match (after \n + trailing-whitespace + trailing-blank-line normalisation) refuses to commit, returns the actual diff, and leaves epics.body, title, goal, and checklist_items untouched.",
"priority": "must",
"requires": [
"run_tests"
]
},
{
"criterion": "edit_epic with expected_diff that matches commits normally and writes one event per affected family (body_edit, checklist_change) sharing a single transaction_id.",
"priority": "must",
"requires": [
"run_tests"
]
},
{
"criterion": "edit_epic rejects changes.meta with error='meta_not_supported' and a hint string referencing body.sections._preamble or body.sections.Goal; epics row is unchanged.",
"priority": "must",
"requires": [
"run_tests"
]
},
{
"criterion": "revert(epic_id) with no event_id undoes the entire most-recent transaction (body, title, goal, and checklist together) and appends a 'reverted_to' event whose prior_state captures the full pre-revert body and checklist; the resulting body is byte-equal to the pre-edit body.",
"priority": "must",
"requires": [
"run_tests"
]
},
{
"criterion": "get_epic_at_time(epic_id, T) returns body and checklist state equal to what was committed at the most recent event with occurred_at <= T \u2014 including timestamps that fall just before a revert (verifies reverted_to.prior_state captures enough state for backward replay).",
"priority": "must",
"requires": [
"run_tests"
]
},
{
"criterion": "get_recent_turns(5) returns the 5 most-recent bot_turns rows (most-recent first) with summaries; search_tool_calls(tool_name='edit_epic', epic_id=X) returns every edit_epic call against epic X with arguments and timestamps.",
"priority": "must",
"requires": [
"run_tests"
]
},
{
"criterion": "All read tools (get_epic, get_section_names, get_history, get_self_understanding, get_epic_at_time, get_recent_turns, search_tool_calls) record operation_kind='read' in tool_calls; all write tools (create_epic, edit_epic, revert, render_epic) record operation_kind='write'.",
"priority": "must",
"requires": [
"run_tests"
]
},
{
"criterion": "After every turn whose tool_calls include create_epic, edit_epic, or revert, exactly one system_logs row exists with category='application', event_type='epic_outline', turn_id=, and details containing title plus a sections array with name + line_count for every section in the body.",
"priority": "must",
"requires": [
"run_tests"
]
},
{
"criterion": "10-turn FakeModel-driven integration fixture in tests/test_editorial_loop.py runs end-to-end starting from epic_id=None, exercises all six default sections, exercises both expected_diff match and mismatch, exercises title editing via *, and test_run_turn variants).",
"priority": "must",
"requires": [
"run_tests"
]
},
{
"criterion": "Both Store adapters expose _EPIC_COLUMNS and _CHECKLIST_COLUMNS allowed-column sets and route update_epic / update_checklist_item through the existing _update helper, matching the _MESSAGE_COLUMNS / _TURN_COLUMNS / _IMAGE_COLUMNS pattern. _MESSAGE_COLUMNS and _TURN_COLUMNS include 'epic_id' so the bootstrap retro-stamp passes column safety.",
"priority": "must",
"requires": [
"read_files"
]
},
{
"criterion": "Body parser and section-op modules stay focused: the public surface is parse, serialize, validate_for_write, the section ops, compute_diff, diffs_equivalent, outline. No tool-layer or Store imports leak into agent_kit/body.py.",
"priority": "should",
"requires": [
"read_files",
"subjective_judgment"
]
},
{
"criterion": "edit_epic rejects requests mixing two body op flavours (e.g. new_content + sections) with error='body_op_conflict' rather than silently picking one.",
"priority": "should",
"requires": [
"run_tests"
]
},
{
"criterion": "agent_kit/body.py stays under ~450 lines and has no third-party dependencies beyond the standard library (difflib, re).",
"priority": "should",
"requires": [
"read_files"
]
}
],
"assumptions": [
"Sprint 2a stays invocation-mode only; no resident-mode behaviour changes.",
"Sprints, sprint_items, codebases, code_artifacts, feedback, second_opinions, and image generation are out of scope. edit_epic.changes.sprints and changes.state return not_yet_supported.",
"edit_epic.changes.meta is explicitly rejected with meta_not_supported and a hint to edit via body.sections._preamble (for title) or body.sections.Goal (for goal); title and goal are derived columns whose only writer is the body parser.",
"_preamble is the raw text from byte 0 up to (but not including) the first ## line, INCLUDING the # Title line and any blank/leading lines before the first section. replace_section('_preamble', '# New Title\n') is the canonical title-edit path per spec \u00a72606. rename_section from/to '_preamble' is rejected.",
"parse() is lenient and never raises on missing #/## headings, malformed input, or empty bodies. validate_for_write() is the only place that raises body_missing_required_section, and is called only on write paths.",
"Default body template ships with one variant (design-doc); create_epic accepts (title, goal) and constructs the body from the template, then derives epics.title and epics.goal from parse() output \u2014 raw args are template inputs only.",
"Default checklist seed is unconditional (all 18 items); adaptation lives in the bot's prompt/decisions, not server-side at create time.",
"expected_diff equivalence: line endings normalised to \n, per-line trailing whitespace stripped, trailing blank lines dropped, then byte-equal compare.",
"render_epic supports format='markdown' only in v1; format='html' returns not_yet_supported. Image-reference resolution is a Sprint 6 no-op.",
"epic_outline log fires on any turn whose tool_calls include create_epic, edit_epic, or revert; pure-read turns and failed turns skip the log.",
"Single-writer concurrency via existing epic_locks + per-edit_epic store.transaction is sufficient. The new no-epic mode skips lock acquisition entirely (no lock contention possible before an epic exists).",
"run_turn gains an Optional epic_id parameter (None = no-epic mode). Existing callers in tests/test_run_turn.py and resident mode keep passing a concrete epic_id and remain unchanged. Bootstrap retro-stamps the inbound message and bot_turn with the new epic_id once create_epic commits.",
"spec test #7 (planning-bot-spec.md:2606) references body_version, but that column does not exist in the current schema; we cover the title/body sync semantics (title updates atomically with body, audit captures the change) without introducing body_version. Adding the column is deferred unless a later sprint requires it.",
"All read tools register with operation_kind='read'; write tools register with operation_kind='write'. The default ('write') is overridden explicitly so audit semantics are correct.",
"The existing megaplan/ directory is harness state and is left untouched; CLAUDE.md's prohibition applies to creating one, not the existing path."
],
"delta_from_previous_percent": 60.45,
"structure_warnings": []
}
code
Plan structure warnings from validator:
[]
Existing flags:
[
{
"id": "FLAG-001",
"concern": "Editorial bootstrap: create_epic is planned as a normal tool, but the current loop requires an existing epic before the model can call any tool, so natural-language epic creation has no executable path.",
"status": "addressed",
"severity": "significant"
},
{
"id": "FLAG-002",
"concern": "Body parser/validation: the plan makes parse() reject missing # Title, conflicting with the spec's parseable _preamble fallback and with read/time-travel tools that need to inspect malformed or legacy bodies.",
"status": "addressed",
"severity": "significant"
},
{
"id": "FLAG-003",
"concern": "History replay: reverted_to events do not store enough prior state to support backward get_epic_at_time reconstruction across a revert.",
"status": "addressed",
"severity": "significant"
},
{
"id": "FLAG-004",
"concern": "Section addressing: _preamble as planned excludes the title line, so the spec's title edit via _preamble section replacement cannot work.",
"status": "open",
"severity": "minor"
},
{
"id": "verifiability-0",
"concern": "Criterion 13: requires human verification (subjective_judgment).",
"status": "open",
"severity": "minor"
},
{
"id": "issue_hints-1",
"concern": "Did the work fully address the issue hints, user notes, and approved plan requirements?: Checked Sprint 2a acceptance in planning-bot-spec.md lines 132-142 against the current loop entrypoint in agent_kit/loop.py. The plan includes a create_epic tool, but it does not address that run_turn currently requires an existing epic_id, acquires an epic_locks row for it before any model/tool call, and creates inbound messages/turns tied to that id; this leaves the acceptance criterion 'Create an epic via natural language' without a concrete bootstrap path when there is no epic yet.",
"status": "addressed",
"severity": "significant"
},
{
"id": "issue_hints-2",
"concern": "Did the work fully address the issue hints, user notes, and approved plan requirements?: Checked the spec's additional Sprint 2a title/body sync test at planning-bot-spec.md lines 2606-2607. The plan defines _preamble as text between the title line and the first ##, so section replacement of _preamble cannot replace # Title; that diverges from the spec example edit_epic(body: { sections: { _preamble: { replace: '# New Title\\n' } } }) and leaves title editing via section addressing underspecified.",
"status": "addressed",
"severity": "significant"
},
{
"id": "correctness-1",
"concern": "Are the proposed changes technically correct?: I checked the body parsing rules in planning-bot-spec.md lines 503-514 against Phase 2. The spec separates parsing from write validation: bodies with no headings are parseable as , while writes are rejected if they lack or non-empty ; the plan instead makes raise when the first non-blank line is not , which conflicts with its own round-trip fixtures for preamble-only/no-section bodies and would break read tools on malformed legacy content.",
"status": "addressed",
"severity": "significant"
},
{
"id": "correctness-2",
"concern": "Are the proposed changes technically correct?: I checked and semantics against the contract in lines 1030-1032 and 1381-1399. The plan stores only metadata on events ( and ids), then proposes backward replay from current state; a later event actually mutates body/checklist, but its event does not contain the pre-revert state needed to undo that mutation when reconstructing a timestamp just before the revert, so time travel across reverts will be incorrect.",
"status": "addressed",
"severity": "significant"
},
{
"id": "correctness-3",
"concern": "Are the proposed changes technically correct?: I reviewed the plan against the Data Model requirement in lines 1314-1316. The plan says constructs the body and calls parse/validate, but then passes title and goal columns supplied by the caller into ; to satisfy 'the parser is the only writer of epics.title and epics.goal', the tool should explicitly use the parsed title and parsed Goal first paragraph for the insert, not the raw arguments.",
"status": "addressed",
"severity": "significant"
},
{
"id": "scope-1",
"concern": "Search for related code that handles the same concept. Is the reported issue a symptom of something broader?: I searched the current tool system in and existing tools in . The plan follows the existing registry/audit pattern for new tools, but it does not mention marking the new read tools with ; if omitted, defaults to write, which would pollute audit semantics for , , , and .",
"status": "addressed",
"severity": "significant"
},
{
"id": "scope-2",
"concern": "Search for related code that handles the same concept. Is the reported issue a symptom of something broader?: I checked the spec's tool surface around in lines 1703-1740. The plan deliberately returns for and , which is a scoped Sprint 2a tradeoff because sprints/state gating are later sprint work, but it also omits handling from the schema discussion even though the spec's change object includes ; this should be either intentionally rejected or mapped to body edits so callers do not get silent schema drift.",
"status": "addressed",
"severity": "significant"
},
{
"id": "all_locations",
"concern": "Does the change touch all locations AND supporting infrastructure?: I checked and helper patterns. The plan says to add new store methods, but it does not call out adding allowed-column sets or guarded updates for , , and in the Supabase adapter analogous to , , and ; without that supporting adapter glue, update helpers will either be unavailable or bypass the existing column-safety pattern.",
"status": "addressed",
"severity": "significant"
},
{
"id": "callers",
"concern": "Find the callers of the changed function. What arguments do they actually pass? Does the fix handle all of them?: I inspected and ; current callers of always provide an , and test helpers seed an row first. The planned tool does not fit this caller contract for a brand-new epic: using a non-existent id would fail the current lock/message foreign-key path, while using an existing placeholder epic would make the create tool semantically odd unless the loop/CLI grows an explicit no-epic or inbox mode.",
"status": "addressed",
"severity": "significant"
}
]
code
Known accepted debt grouped by subsystem:
{
"are-the-proposed-changes-technically-correct": [
{
"id": "DEBT-011",
"concern": "are the proposed changes technically correct?: storage reconciliation cannot be correct for crash-before-upload unless the ledger row stores enough replay material. step 16 says supabase_storage reconciliation does blob.exists(ref) and reissues if missing, but step 13's pending storage rows for voice/image ingestion do not store the attachment bytes, a durable local blob, or even explicitly the discord attachment url in request_body; without that, the reissue branch has no input.",
"occurrence_count": 1,
"plan_ids": [
"sprint-1b-discord-resident"
]
}
],
"callable-api": [
{
"id": "DEBT-001",
"concern": "sprint 1a plan descopes attachment-passing despite the spec's callable api marking it as 1a acceptance.",
"occurrence_count": 1,
"plan_ids": [
"sprint-1a-agent-kit-core"
]
},
{
"id": "DEBT-002",
"concern": "spec\u2019s sprint 1a readiness gate lists attachment-passing protocol; plan defers it.",
"occurrence_count": 1,
"plan_ids": [
"sprint-1a-agent-kit-core"
]
},
{
"id": "DEBT-003",
"concern": "cli omits --attach in 1a.",
"occurrence_count": 1,
"plan_ids": [
"sprint-1a-agent-kit-core"
]
},
{
"id": "DEBT-004",
"concern": "python run_turn omits attachments= in 1a.",
"occurrence_count": 1,
"plan_ids": [
"sprint-1a-agent-kit-core"
]
},
{
"id": "DEBT-005",
"concern": "plan removes --attach, attachments=, localblobstore, and attachment tests from 1a.",
"occurrence_count": 1,
"plan_ids": [
"sprint-1a-agent-kit-core"
]
}
],
"did-the-work-fully-address-the-issue-hints-user-notes-and-approved-plan-requirements": [
{
"id": "DEBT-007",
"concern": "did the work fully address the issue hints, user notes, and approved plan requirements?: recovery coverage for ingestion-side storage uploads remains underspecified: the plan records pending storage rows before uploading, but the described request_body for those rows only includes deterministic paths, not the original discord attachment url or another durable byte source. if the process crashes before the upload completes, supabase_storage reconciliation can detect the object is missing but cannot reissue the upload deterministically from the stored row.",
"occurrence_count": 1,
"plan_ids": [
"sprint-1b-discord-resident"
]
}
],
"discord-ingestion-recovery": [
{
"id": "DEBT-006",
"concern": "crash-before-storage-upload + discord attachment url expiry results in orphaned ledger rows for voice audio / user-uploaded images. the inbound messages row remains persisted so no silent data loss; the user can re-send. a future sprint may add ingestion-time bytes-to-tmpfile fallback if the orphaned rate is meaningful in production.",
"occurrence_count": 1,
"plan_ids": [
"sprint-1b-discord-resident"
]
}
],
"does-the-change-touch-all-locations-and-supporting-infrastructure": [
{
"id": "DEBT-009",
"concern": "does the change touch all locations and supporting infrastructure?: supporting infrastructure for storage reissue is still incomplete: the plan adds , but not a corresponding way for the reconciler to obtain the original attachment payload from the ledger row. since discord attachment urls can be transient, the missing source field is not just a local adapter detail; it affects the recovery contract across , , and .",
"occurrence_count": 1,
"plan_ids": [
"sprint-1b-discord-resident"
]
}
],
"find-the-callers-of-the-changed-function-what-arguments-do-they-actually-pass-does-the-fix-handle-all-of-them": [
{
"id": "DEBT-010",
"concern": "find the callers of the changed function. what arguments do they actually pass? does the fix handle all of them?: checked the planned storage reconciliation caller: can call , but when it needs to reissue a missing upload it has no planned argument source for because the pending request row does not carry the original attachment bytes or a durable fetchable source. that caller path remains under-specified.",
"occurrence_count": 1,
"plan_ids": [
"sprint-1b-discord-resident"
]
}
],
"search-for-related-code-that-handles-the-same-concept-is-the-reported-issue-a-symptom-of-something-broader": [
{
"id": "DEBT-008",
"concern": "search for related code that handles the same concept. is the reported issue a symptom of something broader?: the remaining storage reissue issue applies to both voice and image attachments, not just one branch: voice storage upload needs source audio bytes to recover, and image storage upload needs source image bytes to recover. the plan should store a retrievable source reference in or deliberately mark crash-before-download/upload as orphaned rather than promising deterministic reissue.",
"occurrence_count": 1,
"plan_ids": [
"sprint-1b-discord-resident"
]
}
]
}
Debt guidance:
- These are known accepted limitations. Do not re-flag them unless the current plan makes them worse, broadens them, or fails to contain them.
- Prefix every new concern with a subsystem tag followed by a colon, for example `Timeout recovery: retry backoff remains brittle`.
- When a concern is recurring debt that still needs to be flagged, prefix it with `Recurring debt:` after the subsystem tag, for example `Timeout recovery: Recurring debt: retry backoff remains brittle`.
Your output template is at: /Users/user_c042661f/Documents/arnold-v2/.megaplan/plans/sprint-2a-editorial-core/critique_output.json
Read this file first — it contains 5 checks, each with a question and guidance.
For each check, investigate the codebase, then add your findings to the findings array for that check.
Each finding needs:
"detail": what you specifically checked and what you found (at least a full sentence)
"flagged": true if this describes a difference, risk, or tension — even if you think it's justified. false only if purely informational with no possible downside.
Every check must end with at least one finding. Never leave a findings array empty. If you found no issue, add one detailed flagged: false finding explaining what you checked and why it appears clear.
When in doubt, flag it — the gate can accept tradeoffs, but it can't act on findings it never sees.
Good: {"detail": "Checked callers of nthroot_mod in solveset.py line 1205 — passes prime moduli only, consistent with the fix.", "flagged": false}
Good: {"detail": "The fix handles empty tuples but not single-element tuples which need a trailing comma.", "flagged": true}
Bad: {"detail": "No issue found", "flagged": false} ← too brief, will be rejected
Bad: {"detail": "The hints suggest approach X but the plan uses Y. However Y is consistent with X's intent.", "flagged": false} ← a different approach than the hints IS a flag. You found a divergence — flag it. The gate decides if it's acceptable.
After filling in checks, add any additional concerns to the flags array (e.g., security, performance, dependencies).
Use the standard format (id, concern, category, severity_hint, evidence). This array can be empty.
Workflow: read the file → investigate → read file again → add finding → write file back. Repeat for each check.
This is critique iteration 2. The template file includes prior findings with their status. Verify addressed flags were actually fixed, re-flag if inadequate, and check for new issues introduced by the revision.
code
Additional guidelines:
- Robustness level: standard. Use balanced judgment. Flag significant risks, but do not spend flags on minor polish or executor-obvious boilerplate.
- Over-engineering: prefer the simplest approach that fully solves the problem.
- Reuse existing flag IDs when the same concern is still open.
- `verified_flag_ids`: list flag IDs from prior iterations that the revised plan actually resolves (e.g., if the plan was revised to fix FLAG-001, and you confirm the fix is correct, include "FLAG-001"). Only include flags you've verified — don't guess.
- Verify that the plan follows the expected structure when validator warnings or the outline suggest drift.
- Additional flags may use these categories: correctness, security, completeness, performance, maintainability, other.
- Focus on concrete issues, not structural formatting.
{"checks":[{"id":"issue_hints","question":"Did the work fully address the issue hints, user notes, and approved plan requirements?","findings":[{"detail":"Verified the revised plan still honors the explicit instruction not to invoke or activate megaplan. It mentions the existing .megaplan/ directory only as harness state and does not propose running the megaplan CLI, reading the megaplan skill, or starting a nested plan.","flagged":false},{"detail":"Checked the revised no-epic bootstrap against agent_kit/loop.py, agent_kit/envelope.py, and agent_kit/envelope.schema.json. The plan adds run_turn(epic_id=None) and retro-stamps the DB rows after create_epic, which addresses the storage side of natural-language epic creation, but it does not say to update the local epic_id used by _envelope() or to allow a nullable/late-bound envelope id; as written, a successful bootstrap turn can still return an invalid envelope with epic_id=None even though the schema requires a non-empty string.","flagged":true},{"detail":"Verified the revised _preamble definition against the spec's title/body sync example at planning-bot-spec.md:2606. The plan now defines _preamble as raw text from byte 0 up to the first ##, explicitly including the # Title line, and adds tests for replace_section('_preamble', '# New Title\\n'), which resolves the prior section-addressing concern.","flagged":false},{"detail":"Checked the body_version mention in planning-bot-spec.md:2606-2611 against the current migrations. The current schema has no body_version column and the revised plan explicitly defers it while covering title/body sync via audit events; this is a spec divergence, even if likely acceptable for Sprint 2a because the main Data Model section does not define the column.","flagged":true}]},{"id":"correctness","question":"Are the proposed changes technically correct?","findings":[{"detail":"Verified the parser revision against the spec's body parsing rules in planning-bot-spec.md:503-514. The plan now cleanly separates lenient parse() from strict validate_for_write(), so malformed or legacy bodies can be read and round-tripped while writes still reject missing title or Goal, resolving the prior parser/validation correctness issue.","flagged":false},{"detail":"Verified the revised revert/time-travel design against the epic_events.prior_state contract. reverted_to now stores full pre-revert body and checklist snapshots, and get_epic_at_time explicitly restores that snapshot when walking backward across a revert, which supplies the missing information from the prior plan.","flagged":false},{"detail":"Checked create_epic title/goal handling against planning-bot-spec.md:1314-1316. The revised plan now passes parsed.title and parsed.goal_first_paragraph to store.create_epic, treating raw title and goal arguments only as template inputs, which satisfies the parser-derived column invariant.","flagged":false},{"detail":"Checked the revised no-epic branch against abort, provider-error, tool-error, defer, and final-response returns in agent_kit/loop.py. Those code paths currently call _abort_turn() or _envelope() with the original local epic_id parameter, so the plan needs an explicit local active_epic_id = context.metadata.get('epic_id') handoff before every envelope return or an envelope schema change; otherwise no-epic turns that create an epic, defer, error, or finish without creating one can serialize invalid or misleading envelopes.","flagged":true}]},{"id":"scope","question":"Search for related code that handles the same concept. Is the reported issue a symptom of something broader?","findings":[{"detail":"Verified the read-tool audit fix against agent_kit/tool_kit.py, where register_tool defaults operation_kind to 'write'. The revised plan now requires all editorial read tools to register with operation_kind='read' and adds an integration assertion for the recorded tool_calls.operation_kind, resolving the prior audit-semantics gap.","flagged":false},{"detail":"Verified changes.meta handling against the spec's edit_epic shape. The revised plan explicitly rejects changes.meta with meta_not_supported and points callers to body section edits for title and goal, so the divergence from the spec is now intentional and test-covered rather than silent.","flagged":false},{"detail":"Checked the revised no-epic support against resident-mode code in agent_kit/resident.py and Discord ingestion in agent_kit/transport/discord.py. The plan scopes no-epic mode to invocation/CLI and leaves resident paths requiring concrete epic ids derived from Discord messages, which contains the change and avoids broadening Sprint 2a into resident epic-selection behavior.","flagged":false}]},{"id":"all_locations","question":"Does the change touch all locations AND supporting infrastructure?","findings":[{"detail":"Verified the tool registration glue. The revised plan still imports agent_kit.tools.editorial and agent_kit.tools.editorial_reads for side effects in agent_kit/loop.py, matching the existing communication and images registration pattern.","flagged":false},{"detail":"Verified the adapter column-safety fix against agent_kit/store/supabase.py. The revised plan now adds _EPIC_COLUMNS and _CHECKLIST_COLUMNS, routes updates through _update, and extends _MESSAGE_COLUMNS and _TURN_COLUMNS with epic_id for bootstrap retro-stamping, which addresses the prior missing-supporting-infrastructure concern for Supabase.","flagged":false},{"detail":"Checked all locations touched by run_turn(epic_id=None): agent_kit/ports.py still types create_turn(epic_id: str), agent_kit/envelope.py types Envelope.epic_id: str, agent_kit/envelope.schema.json requires a non-empty string, and arnold/cli.py currently requires --epic. The revised plan mentions CLI no-epic plumbing but does not explicitly include the protocol/envelope/schema changes needed to keep all call boundaries consistent.","flagged":true}]},{"id":"callers","question":"Find the callers of the changed function. What arguments do they actually pass? Does the fix handle all of them?","findings":[{"detail":"Checked existing Python and CLI callers of run_turn. The revised plan is additive for existing tests and resident callers that still pass concrete epic ids, and it adds a new CLI no-epic path for bootstrap, but it must also update the CLI exception envelope path because arnold/cli.py currently builds an error envelope with epic_id=args.epic; with optional --epic, that can become missing or None unless explicitly handled.","flagged":true},{"detail":"Checked current callers of store.create_turn in tests, resident recovery, and the loop. Existing callers pass concrete ids, while the new no-epic loop path passes None; the database allows NULL for bot_turns.epic_id, but the Store protocol and both adapter signatures are still typed as str, so the plan should explicitly update those signatures to str | None to match the intended caller values.","flagged":true},{"detail":"Rechecked nested transaction use through ToolRegistry.audit_wrap. The revised integration plan exercises a multi-row tool write plus its audited tool_calls row, which is the right place to validate the nested store.transaction() behavior for SQLite savepoints and psycopg transaction contexts.","flagged":false}]}],"flags":[{"id":"FLAG-001","concern":"Editorial bootstrap: Rev 2 adds no-epic DB bootstrapping, but the envelope and local loop plumbing still assume a concrete epic id, so natural-language epic creation can complete with an invalid or stale envelope id.","category":"completeness","severity_hint":"likely-significant","evidence":"Envelope.epic_id and envelope.schema.json require a non-empty string, while loop.py return paths call _envelope(..., epic_id=epic_id) using the original parameter. Rev 2 updates context.metadata['epic_id'] after create_epic but does not explicitly update the local id used for envelope returns or alter the schema for no-epic message-only turns."},{"id":"FLAG-005","concern":"Bootstrap API consistency: the plan changes run_turn to accept epic_id=None but does not explicitly update all public/protocol boundaries that currently require a concrete epic id.","category":"completeness","severity_hint":"likely-significant","evidence":"agent_kit/ports.py has Store.create_turn(epic_id: str), agent_kit/envelope.py has Envelope.epic_id: str, agent_kit/envelope.schema.json requires epic_id as a non-empty string, and arnold/cli.py currently requires --epic and uses args.epic in the error envelope path."},{"id":"FLAG-006","concern":"Body version: the revised plan deliberately skips body_version even though the spec's Sprint 2a title/goal sync adversarial tests mention incrementing it.","category":"completeness","severity_hint":"likely-minor","evidence":"planning-bot-spec.md:2606 and planning-bot-spec.md:2611 say title/goal body edits should increment body_version, while current migrations do not define that column and Rev 2 states it will cover audit/title-update semantics without introducing body_version."}],"verified_flag_ids":["FLAG-002","FLAG-003","FLAG-004"],"disputed_flag_ids":[]}
You are already running inside the megaplan harness for this step. Do the requested planning/review/execution work directly. Do NOT invoke the megaplan CLI, do NOT read or activate the megaplan skill, do NOT start nested megaplan plans, and do NOT recurse into another planning harness. Treat mentions of megaplan in the repository or environment as implementation context only.
You are an independent reviewer. Critique the plan against the actual repository.
Bot maintains an epic body and checklist for one epic, with section-level body editing. Minimum to have an editorial conversation.
Full spec is at planning-bot-spec.md in this repo root. Refer to it for complete details on Body Structure and Editing, Body Templates, The Checklist as Guide, and Data Model sections.
Body parser/serializer — markdown ↔ structured sections with ## heading delimiters; enforces heading hierarchy (# for title only, ## for sections, ### for sub-headings)
Turn-end epic outline emitted to system_logs at info level
Default body template (design doc) — Goal, Principles, Context, Key Decisions, Open Questions, Deliverable
Sprint 2a gives Arnold a document to edit. Today the codebase has an epics table (supabase/migrations/202604300001_001_core.sql), a turn loop (agent_kit/loop.py) that requires epic_id to acquire epic_locks before any model call, a Store protocol (agent_kit/ports.py) backed by SQLite + Postgres adapters, an Envelope dataclass (agent_kit/envelope.py:48) and JSON schema (agent_kit/envelope.schema.json:29) that both require a non-empty epic_id string, a CLI (arnold/cli.py:45) with --epic required, and a system_logs sink. The only registered tools are send_message, set_activity, defer_to_caller, view_image, send_image, update_image_metadata.
This sprint adds (1) two new tables (checklist_items, epic_events); (2) a body parser/serializer with section addressing; (3) Store CRUD for epics/checklist/events; (4) ~10 new tools (create_epic, edit_epic, revert, render_epic, plus reads); (5) a no-epic turn-mode threaded consistently through the loop, Store protocol, Envelope, JSON schema, and CLI; (6) a turn-end epic_outline log.
Constraints worth pinning up front (now reflecting all critique fixes):
Bootstrap path threaded through every boundary.run_turn(epic_id: Optional[str] = None). The DB columns messages.epic_id, bot_turns.epic_id, and system_logs.epic_id are already nullable. Rev 3 also makes the public surface match: Store.create_turn(epic_id: str | None), Envelope.epic_id: str | None, envelope.schema.json allows null, CLI --epic is optional, loop.py uses an active_epic_id local that is updated by create_epic before every envelope/abort return. (FLAG-001, FLAG-005, issue_hints-1, all_locations, correctness, callers-1, callers-2.)
Parser split:parse(body) is lenient — accepts any input, never raises. validate_for_write(parsed) is strict and called only by write paths. (FLAG-002, correctness-1.)
_preamble includes the # Title line per spec §2606. Replace via replace_section('_preamble', '# New Title\n') is the canonical title-edit path. (issue_hints-2 rev1.)
Title/goal columns are parser-derived only. (correctness-3.)
reverted_to events store full pre-revert body, title, goal, and checklist snapshot in prior_state so backward replay across reverts is correct. (FLAG-003, correctness-2.)
Read tools register with operation_kind='read'. (scope-1.)
edit_epic.changes.meta is rejected with meta_not_supported. (scope-2.)
Mutually-exclusive body ops in a single edit_epic.body payload; mixing returns body_op_conflict.
expected_diff equivalence:\n line endings, strip trailing whitespace per line, drop trailing blank lines (spec §494).
Out of scope: sprints, sprint_items, codebases, code_artifacts, feedback, second_opinions, image generation. edit_epic.changes.sprints and changes.state return not_yet_supported.
body_version (spec §2606 example) is intentionally deferred. The main Data Model (spec §1311–1320) does not define a body_version column. The audit trail in already captures every body mutation atomically with title/goal updates, which satisfies the title/body sync acceptance test (#7) without introducing a new column. Adding later is an additive migration. (issue_hints-2 rev2 — accepted tradeoff.)
Six phases. Phases 1–3 land schema, parser, and store surface. Phase 4 lands tools. Phase 5 wires the loop bootstrap (now thread-complete across protocol/envelope/schema/CLI) and outline log. Phase 6 covers the integration fixture.
Createchecklist_items matching spec §1322: id TEXT PK, epic_id TEXT NOT NULL REFERENCES epics(id) ON DELETE CASCADE, content TEXT NOT NULL, status TEXT CHECK IN ('open','done','skipped','superseded'), position INTEGER NOT NULL, source TEXT CHECK IN ('bot_inferred','user_requested','carried_over','default_seed','second_opinion'), skip_reason TEXT, superseded_by_item_id TEXT REFERENCES checklist_items(id), created_at TIMESTAMPTZ DEFAULT now(), completed_at TIMESTAMPTZ. Index (epic_id, status, position).
Createepic_events matching spec §1381: id TEXT PK, epic_id TEXT NOT NULL REFERENCES epics(id) ON DELETE CASCADE, transaction_id TEXT NOT NULL, event_type TEXT CHECK IN ('body_edit','checklist_change','sprints_change','state_change','forced_handoff','created','code_referenced','codebase_added','image_generated','second_opinion_requested','reverted_to','sprint_status_change'), summary TEXT NOT NULL, prior_state JSONB, turn_id TEXT REFERENCES bot_turns(id) ON DELETE SET NULL, occurred_at TIMESTAMPTZ DEFAULT now(). Indexes (epic_id, occurred_at DESC) and (transaction_id).
parse(body: str) -> ParsedBody — lenient. Never raises. ParsedBody: title: str | None, goal_first_paragraph: str | None, preamble: str (raw text from byte 0 up to but not including the first ## line, INCLUDING the # Title line and any leading text), sections: list[Section]. Section: name, content, subheadings, line_count. Title is the first non-blank preamble line matching ^#\s+(.+?)\s*$; if absent or empty → None. Goal is the first paragraph (text before first blank line, whitespace-stripped) of the section named exactly Goal; if absent or empty → None. Bodies with no ## headings: sections=[], preamble=<entire body>.
validate_for_write(parsed: ParsedBody) -> None — strict. Raises BodyValidationError("body_missing_required_section: title") or …goal. Called by every write path.
Heading rules (spec §503–514): ^##\s+(.+?)\s*$ at top level only; ###+ stay inside parents; track ``` and ~~~ fences (indented code-block edge case documented but not handled in v1); section names case-sensitive.
Section operations as pure functions on ParsedBody: replace_section, append_to_section, add_section(position='after:Foo'|'before:Foo'|'start'|'end'), remove_section, rename_section, reorder(new_order). Typed errors: SectionNotFound, SectionExists, InvalidPosition. _preamble is addressable: replace_section('_preamble', '# New Title\n') updates the title (spec §2606); rename_section from/to _preamble rejected.
Diff helpers:compute_diff(old, new) wraps difflib.unified_diff(splitlines(keepends=True), …, n=3); normalises per spec §494 (, strip trailing whitespace per line, drop trailing blank lines).
DEFAULT_BODY_TEMPLATE(title, goal) -> str emits the six-section design-doc skeleton.
DEFAULT_CHECKLIST_SEED: list[str] — 18 items from spec §634, all source='default_seed', status='open', positions 1–18.
No adaptation logic in v1 (settled SD-004); the bot adapts via post-create edit_epic calls.
Step 6: Parser unit tests (tests/test_body_parser.py)
Scope: Medium
Round-trip identity for ≥6 fixtures (preamble-only, single section, six-section template, sub-headings, fenced ## Step 1, non-empty preamble before first ##).
Section ops — only the targeted section changes; every other section's serialised form byte-equal.
_preamble covers the title — replace_section('_preamble', '# New Title\n') round-trips to parsed.title=='New Title'; replacing with '' round-trips to title=None and validate_for_write raises body_missing_required_section: title.
Lenient parse — '', 'just text\n', '## Goal\n\ngoal\n' (no title), '# Title\n' (no Goal), '# Title\n\n## NotGoal\n\nx\n' all return ParsedBody without raising; validate_for_write rejects each.
Code-fence guard — body with ```\n## Inside\n``` parses as a single preamble.
Diff equivalence — true on \r\n vs \n / trailing-space / trailing-blank-line differences only; false on real content delta.
Phase 3: Store surface for epics, checklist, events
Step 7: Extend Store protocol (agent_kit/ports.py)
UpdateStore.create_turn signature in the Protocol and both adapters to epic_id: str | None (callers-2). The DB column already permits NULL.
UpdateStore.create_message, update_message, update_turn, and log_system_event already accept epic_id parameters of type str | None; verify no type narrowing is required and adjust if needed.
Step 8: Implement on SupabaseStore (agent_kit/store/supabase.py)
Scope: Medium
Mirror the protocol additions with concrete SQL using existing _normalize/_json helpers and _new_id (prefixes 'epic', 'check', 'evt').
Add module-level _EPIC_COLUMNS and _CHECKLIST_COLUMNS next to _MESSAGE_COLUMNS/_TURN_COLUMNS/_IMAGE_COLUMNS. Wire update_epic and update_checklist_item through self._update.
Update _TURN_COLUMNS to include 'epic_id'. Update _MESSAGE_COLUMNS to include 'epic_id'.
Confirmcreate_turn parameter type is str | None and the existing INSERT (agent_kit/store/supabase.py:113) already passes it through unchanged (Postgres allows NULL on bot_turns.epic_id).
Step 9: Implement on SQLiteStore (agent_kit/store/sqlite.py)
Scope: Medium
Mirror Step 8: same methods, same _EPIC_COLUMNS/_CHECKLIST_COLUMNS constants, same epic_id additions to _MESSAGE_COLUMNS/_TURN_COLUMNS.
Add'prior_state' to _JSON_COLUMNS. Confirmcreate_turn accepts epic_id: str | None.
Step 10: Extend the contract test (tests/store_contract.py)
Scope: Small
Add a tail block exercising the new surface: create an epic, seed checklist, append events with transaction_ids, list/filter events, query latest_transaction_id, verify ordering.
Add an explicit assertion that create_turn(epic_id=None) succeeds and the row stores NULL.
store.record_epic_event(epic_id=epic['id'], transaction_id=uuid4().hex, event_type='created', summary='Epic created with default design-doc template', prior_state=None, turn_id=context.turn_id).
Bootstrap retro-stamp:store.update_message(context.metadata['inbound_message_id'], epic_id=epic['id']) and store.update_turn(context.turn_id, epic_id=epic['id']). Set context.metadata['epic_id'] = epic['id'].
Reject unsupported keys: changes.sprints / changes.state → not_yet_supported; changes.meta → meta_not_supported with hint to use body.sections._preamble (title) or body.sections.Goal (goal).
Body path: load → parse → apply op → serialise → validate_for_write → compute_diff. If expected_diff provided and not diffs_equivalent(...), return {"error":"expected_diff_mismatch", "actual_diff":...} and do not write.
Checklist path: apply add/update/remove with snapshot capture for the event.
get_self_understanding(epic_id) — {goal, state, open_checklist_count, section_names, recent_events: last 3}. Document inline that the spec §1068 7-section structure lights up incrementally.
get_epic_at_time(epic_id, timestamp) — backward replay from current state: walk events with occurred_at > timestamp in descending order; for each, undo using prior_state (body_edit → restore body; checklist_change → restore items; reverted_to → restore from captured pre-revert snapshot, FLAG-003 fix; created → return empty if rolling past it). Tied timestamps order by (occurred_at, id) ASC. Return {body, checklist, reconstructed_at}.
get_recent_turns(n=10, epic_id=None) — store.list_recent_turns(...); for each turn attach change_summary aggregated from epic_events.summary rows with that turn_id.
search_tool_calls(tool_name=None, epic_id=None, since=None, limit=20) — delegates to store.search_tool_calls_by(...).
Step 13: Register tools in the loop import path (agent_kit/loop.py:16)
Phase 5: Loop bootstrap (threaded across all boundaries) + outline log
This phase explicitly enumerates every boundary that previously required a concrete epic_id and updates each one. The fix is one cohesive thread: Optional[str] from CLI → run_turn → Store.create_turn → Envelope.epic_id → JSON schema.
Step 14: No-epic mode in the loop (agent_kit/loop.py)
Lock acquisition (agent_kit/loop.py:43–65): wrap acquire_epic_lock and the lock-contended early return in if epic_id is not None:. When epic_id is None, skip both — there's no row to lock.
Active-epic local handoff: introduce active_epic_id: str | None = epic_id as a local that travels with the turn. Every _envelope(...) and _abort_turn(...) call site (lines 50, 54, 80, 93, 175, 201, 268, 275, 301, 333, 344, 376) reads active_epic_id instead of the parameter epic_id. After every registry.invoke call, refresh: active_epic_id = context.metadata.get('epic_id', active_epic_id). This guarantees that a turn that succeeds via create_epic returns an envelope with the new id, while a turn that errors before/without creating an epic returns an envelope with epic_id=None. (correctness, FLAG-001, issue_hints-1.)
Inbound message creation (agent_kit/loop.py:79–85): when epic_id is None, the message is created with epic_id=None. Capture context.metadata['inbound_message_id'] = inbound['id'] so create_epic can retro-stamp it (Step 11.2).
Turn creation (agent_kit/loop.py:92–102): call store.create_turn(epic_id=active_epic_id, …). The Protocol/adapters now type this as str | None (Step 7.2).
Hot context (agent_kit/loop.py:89): when epic_id is None, skip load_hot_context and synthesize hot_context = {"epic": None, "recent_messages": [], "recent_tool_calls": []}.
Lock release: existing release path runs only when acquire_epic_lock succeeded; the early-return-on-no-lock branch (Step 14.2) means we never attempt a release for the no-epic path.
Dataclass: change Envelope.epic_id: str → Envelope.epic_id: str | None = None at agent_kit/envelope.py:51. The existing _drop_none in to_dict() (agent_kit/envelope.py:112) already strips None values from the JSON output, so a no-epic envelope serialises without an epic_id key. (FLAG-001, FLAG-005, issue_hints-1, all_locations.)
JSON schema (agent_kit/envelope.schema.json:7,29): remove "epic_id" from the top-level required array and change the epic_id property to {"type": ["string", "null"], "minLength": 0} so both omitted and present-but-null forms validate. Existing tests that assert epic_id is non-empty for normal turns still pass (those turns set the field).
No new fields needed; the envelope schema is already permissive about omitted optional keys via _drop_none.
Step 16: CLI accepts --epic as optional (arnold/cli.py)
At the end of run_turn, after update_turn(status='completed', …) and before envelope return: if active_epic_id is not None AND any tool_call this turn had tool_name in {'create_epic','edit_epic','revert'}, then parsed = body.parse(store.load_epic(active_epic_id)['body']), details = body.outline(parsed), log(store, 'info', 'application', 'epic_outline', f"Epic outline: {parsed.title or '(untitled)'}", details=details, turn_id=turn['id'], epic_id=active_epic_id).
Skip the log on status='failed' and on turns where active_epic_id is still None at the end (the bot replied without creating an epic).
Phase 6: Integration test + regression verification
Turn 1: run_turn(epic_id=None, input='Make me an auth flow design epic') → tool_use create_epic(title='Auth flow design', goal='Decide on auth provider and token storage') → final text. Assert envelope epic_id == new_id (verifies active_epic_id handoff).
Turns 2–9: run_turn(epic_id=<the new id>) with edit_epic calls hitting all six default sections via sections ops, plus a _preamble replace that updates the title, plus an append, plus a checklist.update marking 3 items done. Include one expected_diff match and one mismatch.
Assertions — one per spec §131–142 acceptance criterion plus the critique-driven additions:
Bootstrap envelope: Turn 1 envelope has epic_id == new_id (proves active_epic_id was updated before the envelope was built); the inbound message and bot_turn rows have epic_id retro-stamped.
Bootstrap CLI surface: Run python -m arnold turn --input 'create me an epic about Q1 OKRs' (no --epic) via subprocess; assert exit code 0 and stdout JSON has epic_id == <some non-empty string>. Skip if ARNOLD_FAKE_MODEL_SCRIPT isn't supported in the env (use the existing FakeModel env var path from arnold/cli.py:188).
Bootstrap envelope error path: force a model error in a no-epic turn (FakeModel script that raises); assert the resulting envelope has epic_id is None, outcome == 'errored', and the JSON schema validates. (correctness, callers-1.)
After Turn 1: epics row exists with parsed title/goal; 18 checklist_items with source='default_seed'; one created event.
All six default sections present after the loop; section-only edits leave other sections byte-identical (verified via body_edit.prior_state).
Whole-body new_content turn: body_edit event captured prior body; manual revert(epic_id, event_id=that_event) then load_epic returns prior body byte-equal.
Step 19: JSON schema regression test (tests/test_envelope.py or new)
Scope: Small
Add a test that constructs Envelope(epic_id=None, ...), serialises via to_json(), and validates the result against envelope.schema.json using jsonschema (already in [project.optional-dependencies].test). Assert validation passes both with epic_id omitted (via _drop_none) and with epic_id=null if a future caller emits it explicitly.
Step 20: Run the targeted tests, then full regression
Schema first (Phase 1) — migrations unblock everything.
Body parser + templates with their unit tests (Phase 2). Pure code, fastest feedback. Land lenient parse + strict validate_for_write split before anything depends on it.
Store extensions (Phase 3) — column-safety constants + new methods + create_turn(epic_id: str | None) signature, exercised through the contract test.
Tools (Phase 4) — depends on parser + store. Write tools first, then reads (operation_kind='read').
Loop bootstrap threaded through all boundaries (Phase 5: Steps 14 → 15 → 16 → 17 in order). Internal active_epic_id first; then envelope dataclass + JSON schema; then CLI; then outline log.
Integration fixture (Phase 6) — proves the whole pipeline + every critique fix end-to-end, including the bootstrap-API-consistency thread.
Validation Order
pytest tests/test_body_parser.py — fastest feedback on parser edge cases.
Contract tests (SQLite always, Supabase when DB available) — confirms create_turn(epic_id=None) and the new methods are consistent across adapters.
pytest tests/test_editorial_loop.py — the 10-turn integration with bootstrap envelope assertions, time-travel-across-revert, _preamble-title, meta_not_supported, and operation_kind checks.
pytest -x — full regression, including resident-mode and existing CLI tests.
code
Plan metadata:
{
"version": 3,
"timestamp": "2026-04-30T05:38:50Z",
"hash": "sha256:33bb09fb290f12367fca1eaddad96d341f1e122c4b5e5e8ec360da747c64ca93",
"changes_summary": "Rev 3 closes the bootstrap-API-consistency cluster the gate flagged in rev 2. The fix is one cohesive thread of Optional[str] through every public boundary the no-epic mode touches: (1) Phase 3 Step 7.2 explicitly updates Store.create_turn Protocol + both adapter signatures to epic_id: str | None (callers-2). (2) New Phase 5 Step 14.3 introduces an active_epic_id local in loop.py that every _envelope(...) and _abort_turn(...) call site reads, refreshed after every tool invocation, so envelopes returned from a successful bootstrap turn carry the new id and envelopes returned from errored/aborted no-epic turns carry None (correctness, FLAG-001, issue_hints-1). (3) New Phase 5 Step 15 changes Envelope.epic_id to Optional[str] and relaxes envelope.schema.json to accept null/omitted (FLAG-005, all_locations). (4) New Phase 5 Step 16 makes CLI --epic optional and threads through the exception envelope path (callers-1). (5) New Step 19 adds a JSON schema regression test for the no-epic envelope. (6) Phase 6 integration test gains explicit assertions: Turn-1 envelope has epic_id==new_id, no-epic CLI subprocess succeeds, errored no-epic envelope has epic_id=None and validates against the schema. (7) body_version (issue_hints-2) is promoted from quiet deferral to an explicit accepted-tradeoff in the Overview constraints, citing spec \u00a71311\u20131320 vs \u00a72606. No scope growth \u2014 all changes are tightening the existing bootstrap path; nothing pulled forward from later sprints.",
"flags_addressed": [
{
"id": "FLAG-001",
"resolution": "addressed",
"reason": "Step 14.3 introduces an active_epic_id local that every _envelope() and _abort_turn() call site reads, refreshed after every tool invocation. Step 15 makes Envelope.epic_id Optional[str] so envelopes from no-epic-but-no-create turns serialise validly. Integration test Step 18 asserts the Turn-1 envelope has the new id and the errored-no-epic envelope has epic_id=None."
},
{
"id": "FLAG-005",
"resolution": "addressed",
"reason": "Phase 5 Steps 14\u201316 explicitly enumerate every public boundary that needed updating: Store.create_turn signature (Step 7.2 + 8.4 + 9.2), Envelope dataclass (Step 15.1), envelope JSON schema (Step 15.2), CLI --epic (Step 16). Step 19 adds a schema regression test."
},
{
"id": "issue_hints-1",
"resolution": "addressed",
"reason": "Same fix as FLAG-001 + FLAG-005: active_epic_id handoff in loop.py + Envelope.epic_id: Optional[str] + schema relaxation. Bootstrap turn now returns a valid envelope with the newly-created epic id; failure paths return a valid envelope with epic_id=None."
},
{
"id": "issue_hints-2",
"resolution": "addressed",
"reason": "Promoted body_version deferral from a quiet assumption to an explicit accepted tradeoff in the Overview constraints. Rationale: the main Data Model in spec \u00a71311\u20131320 does not define body_version; only the example test in \u00a72606 references it. The audit trail in epic_events.body_edit already captures every body mutation atomically with title/goal updates, satisfying the title/body sync acceptance test without introducing a new column."
},
{
"id": "all_locations",
"resolution": "addressed",
"reason": "Step 7.2 (Store.create_turn signature), Step 15.1 (Envelope dataclass), Step 15.2 (envelope.schema.json), and Step 16.1\u20133 (arnold/cli.py argparse + run + exception paths) are now enumerated as explicit subitems with file:line references."
},
{
"id": "correctness",
"resolution": "addressed",
"reason": "Step 14.3 introduces active_epic_id as the source of truth for every envelope/abort return path inside loop.py; the local is refreshed after every tool invocation so create_epic's retro-stamp propagates to all downstream returns (final response, defer, error, abort)."
},
{
"id": "callers-1",
"resolution": "addressed",
"reason": "Step 16.1 makes CLI --epic optional (default=None); Step 16.3 passes args.epic (now Optional[str]) into the exception envelope; with Envelope.epic_id: Optional[str] from Step 15.1, the error envelope serialises correctly when --epic is omitted."
},
{
"id": "callers-2",
"resolution": "addressed",
"reason": "Step 7.2 updates Store.create_turn in the Protocol + both adapter signatures to epic_id: str | None. Step 8.4 and 9.2 confirm the existing INSERT statements already pass through unchanged (DB columns are nullable). Step 10 adds a contract-test assertion that create_turn(epic_id=None) succeeds."
},
{
"id": "correctness-1",
"resolution": "addressed",
"reason": "Carried over from rev 2: parser split into lenient parse() + strict validate_for_write(); preserved in rev 3 (Step 4)."
},
{
"id": "correctness-2",
"resolution": "addressed",
"reason": "Carried over from rev 2: reverted_to events store full pre-revert body+title+goal+checklist snapshot; preserved in rev 3 (Step 11.4)."
},
{
"id": "correctness-3",
"resolution": "addressed",
"reason": "Carried over from rev 2: create_epic uses parsed.title and parsed.goal_first_paragraph for column writes; preserved in rev 3 (Step 11.2)."
},
{
"id": "scope-1",
"resolution": "addressed",
"reason": "Carried over from rev 2: read tools register with operation_kind='read'; preserved in rev 3 (Step 12.1)."
},
{
"id": "scope-2",
"resolution": "addressed",
"reason": "Carried over from rev 2: edit_epic.changes.meta returns meta_not_supported with hint to use body sections; preserved in rev 3 (Step 11.3)."
},
{
"id": "callers",
"resolution": "addressed",
"reason": "Carried over from rev 2: existing run_turn callers (test_run_turn, resident mode) keep passing concrete epic_ids; the no-epic path is purely additive. Rev 3 strengthens this with the active_epic_id handoff so callers can rely on a consistent envelope contract."
}
],
"questions": [
"Should the no-epic bootstrap path also handle 'user typed a question that doesn't warrant creating an epic' (greetings, meta-questions)? Plan currently treats a turn that ends with active_epic_id still None and outcome='completed' as a valid no-op (epic_outline log skipped, envelope.epic_id is None). Confirm that's acceptable, or should run_turn reject completion when active_epic_id is None and the bot didn't call defer_to_caller?",
"JSON schema relaxation: Step 15.2 changes envelope.schema.json's epic_id to {type: [string, null]} and removes it from required. Are downstream consumers of the schema (subagent contract, test suites in other projects) tolerant of this loosening, or should we keep epic_id required and instead use a sentinel string like '' for the bootstrap window? The Optional approach is cleaner; flagging the alternative in case existing consumers can't tolerate null."
],
"success_criteria": [
{
"criterion": "Postgres migration 004 and SQLite migration 004 create checklist_items and epic_events with the columns, CHECK constraints, FK ON DELETE behaviour, and indexes specified in spec \u00a71322 and \u00a71381.",
"priority": "must",
"requires": [
"read_files"
]
},
{
"criterion": "body.parse() is lenient and returns a ParsedBody for empty input, plain-text input, bodies with no '##' headings, bodies missing '# Title', and bodies missing '## Goal' \u2014 without raising. Read tools and get_epic_at_time work against these inputs.",
"priority": "must",
"requires": [
"run_tests"
]
},
{
"criterion": "body.validate_for_write() raises BodyValidationError('body_missing_required_section: title') when parsed.title is None or empty, and 'body_missing_required_section: goal' when parsed.goal_first_paragraph is None or empty. Write tools surface this as a structured tool result error.",
"priority": "must",
"requires": [
"run_tests"
]
},
{
"criterion": "Body parser round-trip identity holds: serialize(parse(body)) == body for \u22656 fixture bodies including preamble-only (no '##'), single section, full design-doc template, sub-headings, fenced code containing '##', and a body with non-empty preamble before the first section.",
"priority": "must",
"requires": [
"run_tests"
]
},
{
"criterion": "_preamble section addressing covers the '# Title' line per spec \u00a72606: replace_section(parsed, '_preamble', '# New Title\n') round-trips to ParsedBody with title='New Title'; replace_section(parsed, '_preamble', '') round-trips to title=None and validate_for_write rejects it.",
"priority": "must",
"requires": [
"run_tests"
]
},
{
"criterion": "create_epic creates an epics row whose title and goal columns equal parse(rendered_template).title and .goal_first_paragraph respectively (not the raw arguments), seeds 18 default checklist items with status='open' and source='default_seed', and writes one 'created' epic_event sharing a transaction_id.",
"priority": "must",
"requires": [
"run_tests"
]
},
{
"criterion": "run_turn(epic_id=None, input=...) executes without acquiring an epic_locks row, creates an inbound message and bot_turn with epic_id=NULL, and \u2014 when create_epic fires within the turn \u2014 retro-stamps both rows with the new epic_id by the time the turn completes.",
"priority": "must",
"requires": [
"run_tests"
]
},
{
"criterion": "After a successful no-epic bootstrap turn, the returned Envelope has epic_id == <new_id> (proves active_epic_id is updated before the envelope is built); after a no-epic turn that errors before creating an epic, the Envelope has epic_id is None and validates against envelope.schema.json.",
"priority": "must",
"requires": [
"run_tests"
]
},
{
"criterion": "Store.create_turn Protocol signature and both adapter signatures accept epic_id: str | None; create_turn(epic_id=None) succeeds in the contract test against both SQLiteStore and SupabaseStore.",
"priority": "must",
"requires": [
"run_tests",
"read_files"
]
},
{
"criterion": "Envelope.epic_id is typed Optional[str], envelope.schema.json no longer requires epic_id and accepts {string, null} for the field; an Envelope built with epic_id=None serialises and validates against the schema.",
"priority": "must",
"requires": [
"run_tests",
"read_files"
]
},
{
"criterion": "arnold turn CLI accepts an omitted --epic flag and runs end-to-end without errors; the exception envelope path serialises correctly when --epic is omitted (epic_id=None in the resulting envelope).",
"priority": "must",
"requires": [
"run_tests"
]
},
{
"criterion": "edit_epic body section operations leave every non-targeted section byte-identical (verified by parsing prior_state captured in the body_edit event and comparing every other section's serialised form).",
"priority": "must",
"requires": [
"run_tests"
]
},
{
"criterion": "edit_epic with expected_diff that does not match (after \n + trailing-whitespace + trailing-blank-line normalisation) refuses to commit, returns the actual diff, and leaves epics.body, title, goal, and checklist_items untouched.",
"priority": "must",
"requires": [
"run_tests"
]
},
{
"criterion": "edit_epic with expected_diff that matches commits normally and writes one event per affected family (body_edit, checklist_change) sharing a single transaction_id.",
"priority": "must",
"requires": [
"run_tests"
]
},
{
"criterion": "edit_epic rejects changes.meta with error='meta_not_supported' and a hint string referencing body.sections._preamble or body.sections.Goal; epics row is unchanged.",
"priority": "must",
"requires": [
"run_tests"
]
},
{
"criterion": "revert(epic_id) with no event_id undoes the entire most-recent transaction (body, title, goal, and checklist together) and appends a 'reverted_to' event whose prior_state captures the full pre-revert body, title, goal, and checklist; the resulting body is byte-equal to the pre-edit body.",
"priority": "must",
"requires": [
"run_tests"
]
},
{
"criterion": "get_epic_at_time(epic_id, T) returns body and checklist state equal to what was committed at the most recent event with occurred_at <= T \u2014 including timestamps that fall just before a revert (verifies reverted_to.prior_state captures enough state for backward replay).",
"priority": "must",
"requires": [
"run_tests"
]
},
{
"criterion": "get_recent_turns(5) returns the 5 most-recent bot_turns rows (most-recent first) with summaries; search_tool_calls(tool_name='edit_epic', epic_id=X) returns every edit_epic call against epic X with arguments and timestamps.",
"priority": "must",
"requires": [
"run_tests"
]
},
{
"criterion": "All read tools (get_epic, get_section_names, get_history, get_self_understanding, get_epic_at_time, get_recent_turns, search_tool_calls) record operation_kind='read' in tool_calls; all write tools (create_epic, edit_epic, revert, render_epic) record operation_kind='write'.",
"priority": "must",
"requires": [
"run_tests"
]
},
{
"criterion": "After every turn whose tool_calls include create_epic, edit_epic, or revert, exactly one system_logs row exists with category='application', event_type='epic_outline', turn_id=, and details containing title plus a sections array with name + line_count for every section in the body.",
"priority": "must",
"requires": [
"run_tests"
]
},
{
"criterion": "10-turn FakeModel-driven integration fixture in tests/test_editorial_loop.py runs end-to-end starting from epic_id=None, exercises all six default sections, exercises both expected_diff match and mismatch, exercises title editing via *, test_run_turn, and test_cli variants).",
"priority": "must",
"requires": [
"run_tests"
]
},
{
"criterion": "Both Store adapters expose _EPIC_COLUMNS and _CHECKLIST_COLUMNS allowed-column sets and route update_epic / update_checklist_item through the existing _update helper; _MESSAGE_COLUMNS and _TURN_COLUMNS include 'epic_id' so the bootstrap retro-stamp passes column safety.",
"priority": "must",
"requires": [
"read_files"
]
},
{
"criterion": "Body parser and section-op modules stay focused: the public surface is parse, serialize, validate_for_write, the section ops, compute_diff, diffs_equivalent, outline. No tool-layer or Store imports leak into agent_kit/body.py.",
"priority": "should",
"requires": [
"read_files",
"subjective_judgment"
]
},
{
"criterion": "edit_epic rejects requests mixing two body op flavours (e.g. new_content + sections) with error='body_op_conflict' rather than silently picking one.",
"priority": "should",
"requires": [
"run_tests"
]
},
{
"criterion": "agent_kit/body.py stays under ~450 lines and has no third-party dependencies beyond the standard library (difflib, re).",
"priority": "should",
"requires": [
"read_files"
]
}
],
"assumptions": [
"Sprint 2a stays invocation-mode only; no resident-mode behaviour changes.",
"Sprints, sprint_items, codebases, code_artifacts, feedback, second_opinions, and image generation are out of scope. edit_epic.changes.sprints and changes.state return not_yet_supported.",
"edit_epic.changes.meta is rejected with meta_not_supported and a hint to edit via body.sections._preamble (title) or body.sections.Goal (goal); title/goal are derived columns whose only writer is the body parser.",
"_preamble is the raw text from byte 0 up to (but not including) the first ## line, INCLUDING the # Title line and any leading text. replace_section('_preamble', '# New Title\n') is the canonical title-edit path per spec \u00a72606. rename_section from/to '_preamble' is rejected.",
"parse() is lenient and never raises. validate_for_write() is the only place that raises body_missing_required_section, called only on write paths.",
"Default body template ships with one variant (design-doc); create_epic constructs the body from the template, then derives epics.title and epics.goal from parse() output \u2014 raw args are template inputs only.",
"Default checklist seed is unconditional (18 items); adaptation lives in the bot's prompt, not server-side at create time.",
"expected_diff equivalence: \n line endings, strip trailing whitespace per line, drop trailing blank lines, then byte-equal compare.",
"render_epic supports format='markdown' only in v1; 'html' returns not_yet_supported. Image-reference resolution is a Sprint 6 no-op.",
"epic_outline log fires on any turn whose tool_calls include create_epic, edit_epic, or revert; pure-read turns and failed turns skip the log.",
"Single-writer concurrency via existing epic_locks + per-edit_epic store.transaction is sufficient. The new no-epic mode skips lock acquisition entirely (no lock contention possible before an epic exists).",
"Bootstrap consistency is threaded through every public boundary: run_turn(epic_id: str | None), Store.create_turn(epic_id: str | None), Envelope.epic_id: str | None (with envelope.schema.json relaxed to accept null/omitted), CLI --epic optional. The internal active_epic_id local in loop.py drives every envelope/abort return so a successful bootstrap turn returns the new id and a failed/empty no-epic turn returns None.",
"spec test #7 (planning-bot-spec.md:2606) references a body_version column. The main Data Model section (\u00a71311\u20131320) does not define this column. Sprint 2a covers the title/body sync semantics the test cares about (atomic title update with body, audit captures the change) via epic_events.body_edit; introducing a body_version column is deferred as an explicit accepted tradeoff. Adding it later is an additive migration and a one-line UPDATE inside edit_epic.",
"All read tools register with operation_kind='read'; write tools register with operation_kind='write'.",
"The existing megaplan/ directory is harness state and is left untouched."
],
"delta_from_previous_percent": 41.24,
"structure_warnings": []
}
code
Plan structure warnings from validator:
[]
Existing flags:
[
{
"id": "FLAG-001",
"concern": "Editorial bootstrap: Rev 2 adds no-epic DB bootstrapping, but the envelope and local loop plumbing still assume a concrete epic id, so natural-language epic creation can complete with an invalid or stale envelope id.",
"status": "addressed",
"severity": "significant"
},
{
"id": "verifiability-0",
"concern": "Criterion 19: requires human verification (subjective_judgment).",
"status": "open",
"severity": "minor"
},
{
"id": "issue_hints-1",
"concern": "Did the work fully address the issue hints, user notes, and approved plan requirements?: Checked the revised no-epic bootstrap against agent_kit/loop.py, agent_kit/envelope.py, and agent_kit/envelope.schema.json. The plan adds run_turn(epic_id=None) and retro-stamps the DB rows after create_epic, which addresses the storage side of natural-language epic creation, but it does not say to update the local epic_id used by _envelope() or to allow a nullable/late-bound envelope id; as written, a successful bootstrap turn can still return an invalid envelope with epic_id=None even though the schema requires a non-empty string.",
"status": "addressed",
"severity": "significant"
},
{
"id": "issue_hints-2",
"concern": "Did the work fully address the issue hints, user notes, and approved plan requirements?: Checked the body_version mention in planning-bot-spec.md:2606-2611 against the current migrations. The current schema has no body_version column and the revised plan explicitly defers it while covering title/body sync via audit events; this is a spec divergence, even if likely acceptable for Sprint 2a because the main Data Model section does not define the column.",
"status": "addressed",
"severity": "significant"
},
{
"id": "correctness-1",
"concern": "Are the proposed changes technically correct?: I checked the body parsing rules in planning-bot-spec.md lines 503-514 against Phase 2. The spec separates parsing from write validation: bodies with no ## headings are parseable as _preamble, while writes are rejected if they lack # Title or non-empty ## Goal; the plan instead makes parse() raise when the first non-blank line is not # <title>, which conflicts with its own round-trip fixtures for preamble-only/no-section bodies and would break read tools on malformed legacy content.",
"status": "addressed",
"severity": "significant"
},
{
"id": "correctness-2",
"concern": "Are the proposed changes technically correct?: I checked get_epic_at_time and revert semantics against the epic_events.prior_state contract in planning-bot-spec.md lines 1030-1032 and 1381-1399. The plan stores only metadata on reverted_to events ( and ids), then proposes backward replay from current state; a later event actually mutates body/checklist, but its event does not contain the pre-revert state needed to undo that mutation when reconstructing a timestamp just before the revert, so time travel across reverts will be incorrect.",
"status": "addressed",
"severity": "significant"
},
{
"id": "correctness-3",
"concern": "Are the proposed changes technically correct?: I reviewed the plan against the Data Model requirement in lines 1314-1316. The plan says constructs the body and calls parse/validate, but then passes title and goal columns supplied by the caller into ; to satisfy 'the parser is the only writer of epics.title and epics.goal', the tool should explicitly use the parsed title and parsed Goal first paragraph for the insert, not the raw arguments.",
"status": "addressed",
"severity": "significant"
},
{
"id": "scope-1",
"concern": "Search for related code that handles the same concept. Is the reported issue a symptom of something broader?: I searched the current tool system in and existing tools in . The plan follows the existing registry/audit pattern for new tools, but it does not mention marking the new read tools with ; if omitted, defaults to write, which would pollute audit semantics for , , , and .",
"status": "addressed",
"severity": "significant"
},
{
"id": "scope-2",
"concern": "Search for related code that handles the same concept. Is the reported issue a symptom of something broader?: I checked the spec's tool surface around in lines 1703-1740. The plan deliberately returns for and , which is a scoped Sprint 2a tradeoff because sprints/state gating are later sprint work, but it also omits handling from the schema discussion even though the spec's change object includes ; this should be either intentionally rejected or mapped to body edits so callers do not get silent schema drift.",
"status": "addressed",
"severity": "significant"
},
{
"id": "all_locations",
"concern": "Does the change touch all locations AND supporting infrastructure?: Checked all locations touched by : still types , types , requires a non-empty string, and currently requires . The revised plan mentions CLI no-epic plumbing but does not explicitly include the protocol/envelope/schema changes needed to keep all call boundaries consistent.",
"status": "addressed",
"severity": "significant"
},
{
"id": "callers",
"concern": "Find the callers of the changed function. What arguments do they actually pass? Does the fix handle all of them?: I inspected and ; current callers of always provide an , and test helpers seed an row first. The planned tool does not fit this caller contract for a brand-new epic: using a non-existent id would fail the current lock/message foreign-key path, while using an existing placeholder epic would make the create tool semantically odd unless the loop/CLI grows an explicit no-epic or inbox mode.",
"status": "addressed",
"severity": "significant"
},
{
"id": "FLAG-005",
"concern": "Bootstrap API consistency: the plan changes to accept but does not explicitly update all public/protocol boundaries that currently require a concrete epic id.",
"status": "addressed",
"severity": "significant"
},
{
"id": "FLAG-006",
"concern": "Body version: the revised plan deliberately skips even though the spec's Sprint 2a title/goal sync adversarial tests mention incrementing it.",
"status": "open",
"severity": "minor"
},
{
"id": "correctness",
"concern": "Are the proposed changes technically correct?: Checked the revised no-epic branch against abort, provider-error, tool-error, defer, and final-response returns in . Those code paths currently call or with the original local parameter, so the plan needs an explicit local handoff before every envelope return or an envelope schema change; otherwise no-epic turns that create an epic, defer, error, or finish without creating one can serialize invalid or misleading envelopes.",
"status": "addressed",
"severity": "significant"
},
{
"id": "callers-1",
"concern": "Find the callers of the changed function. What arguments do they actually pass? Does the fix handle all of them?: Checked existing Python and CLI callers of . The revised plan is additive for existing tests and resident callers that still pass concrete epic ids, and it adds a new CLI no-epic path for bootstrap, but it must also update the CLI exception envelope path because currently builds an error envelope with ; with optional , that can become missing or unless explicitly handled.",
"status": "addressed",
"severity": "significant"
},
{
"id": "callers-2",
"concern": "Find the callers of the changed function. What arguments do they actually pass? Does the fix handle all of them?: Checked current callers of in tests, resident recovery, and the loop. Existing callers pass concrete ids, while the new no-epic loop path passes ; the database allows NULL for , but the protocol and both adapter signatures are still typed as , so the plan should explicitly update those signatures to to match the intended caller values.",
"status": "addressed",
"severity": "significant"
}
]
code
Known accepted debt grouped by subsystem:
{
"are-the-proposed-changes-technically-correct": [
{
"id": "DEBT-011",
"concern": "are the proposed changes technically correct?: storage reconciliation cannot be correct for crash-before-upload unless the ledger row stores enough replay material. step 16 says supabase_storage reconciliation does blob.exists(ref) and reissues if missing, but step 13's pending storage rows for voice/image ingestion do not store the attachment bytes, a durable local blob, or even explicitly the discord attachment url in request_body; without that, the reissue branch has no input.",
"occurrence_count": 1,
"plan_ids": [
"sprint-1b-discord-resident"
]
}
],
"callable-api": [
{
"id": "DEBT-001",
"concern": "sprint 1a plan descopes attachment-passing despite the spec's callable api marking it as 1a acceptance.",
"occurrence_count": 1,
"plan_ids": [
"sprint-1a-agent-kit-core"
]
},
{
"id": "DEBT-002",
"concern": "spec\u2019s sprint 1a readiness gate lists attachment-passing protocol; plan defers it.",
"occurrence_count": 1,
"plan_ids": [
"sprint-1a-agent-kit-core"
]
},
{
"id": "DEBT-003",
"concern": "cli omits --attach in 1a.",
"occurrence_count": 1,
"plan_ids": [
"sprint-1a-agent-kit-core"
]
},
{
"id": "DEBT-004",
"concern": "python run_turn omits attachments= in 1a.",
"occurrence_count": 1,
"plan_ids": [
"sprint-1a-agent-kit-core"
]
},
{
"id": "DEBT-005",
"concern": "plan removes --attach, attachments=, localblobstore, and attachment tests from 1a.",
"occurrence_count": 1,
"plan_ids": [
"sprint-1a-agent-kit-core"
]
}
],
"did-the-work-fully-address-the-issue-hints-user-notes-and-approved-plan-requirements": [
{
"id": "DEBT-007",
"concern": "did the work fully address the issue hints, user notes, and approved plan requirements?: recovery coverage for ingestion-side storage uploads remains underspecified: the plan records pending storage rows before uploading, but the described request_body for those rows only includes deterministic paths, not the original discord attachment url or another durable byte source. if the process crashes before the upload completes, supabase_storage reconciliation can detect the object is missing but cannot reissue the upload deterministically from the stored row.",
"occurrence_count": 1,
"plan_ids": [
"sprint-1b-discord-resident"
]
}
],
"discord-ingestion-recovery": [
{
"id": "DEBT-006",
"concern": "crash-before-storage-upload + discord attachment url expiry results in orphaned ledger rows for voice audio / user-uploaded images. the inbound messages row remains persisted so no silent data loss; the user can re-send. a future sprint may add ingestion-time bytes-to-tmpfile fallback if the orphaned rate is meaningful in production.",
"occurrence_count": 1,
"plan_ids": [
"sprint-1b-discord-resident"
]
}
],
"does-the-change-touch-all-locations-and-supporting-infrastructure": [
{
"id": "DEBT-009",
"concern": "does the change touch all locations and supporting infrastructure?: supporting infrastructure for storage reissue is still incomplete: the plan adds , but not a corresponding way for the reconciler to obtain the original attachment payload from the ledger row. since discord attachment urls can be transient, the missing source field is not just a local adapter detail; it affects the recovery contract across , , and .",
"occurrence_count": 1,
"plan_ids": [
"sprint-1b-discord-resident"
]
}
],
"find-the-callers-of-the-changed-function-what-arguments-do-they-actually-pass-does-the-fix-handle-all-of-them": [
{
"id": "DEBT-010",
"concern": "find the callers of the changed function. what arguments do they actually pass? does the fix handle all of them?: checked the planned storage reconciliation caller: can call , but when it needs to reissue a missing upload it has no planned argument source for because the pending request row does not carry the original attachment bytes or a durable fetchable source. that caller path remains under-specified.",
"occurrence_count": 1,
"plan_ids": [
"sprint-1b-discord-resident"
]
}
],
"search-for-related-code-that-handles-the-same-concept-is-the-reported-issue-a-symptom-of-something-broader": [
{
"id": "DEBT-008",
"concern": "search for related code that handles the same concept. is the reported issue a symptom of something broader?: the remaining storage reissue issue applies to both voice and image attachments, not just one branch: voice storage upload needs source audio bytes to recover, and image storage upload needs source image bytes to recover. the plan should store a retrievable source reference in or deliberately mark crash-before-download/upload as orphaned rather than promising deterministic reissue.",
"occurrence_count": 1,
"plan_ids": [
"sprint-1b-discord-resident"
]
}
]
}
Debt guidance:
- These are known accepted limitations. Do not re-flag them unless the current plan makes them worse, broadens them, or fails to contain them.
- Prefix every new concern with a subsystem tag followed by a colon, for example `Timeout recovery: retry backoff remains brittle`.
- When a concern is recurring debt that still needs to be flagged, prefix it with `Recurring debt:` after the subsystem tag, for example `Timeout recovery: Recurring debt: retry backoff remains brittle`.
Your output template is at: /Users/user_c042661f/Documents/arnold-v2/.megaplan/plans/sprint-2a-editorial-core/critique_output.json
Read this file first — it contains 5 checks, each with a question and guidance.
For each check, investigate the codebase, then add your findings to the findings array for that check.
Each finding needs:
"detail": what you specifically checked and what you found (at least a full sentence)
"flagged": true if this describes a difference, risk, or tension — even if you think it's justified. false only if purely informational with no possible downside.
Every check must end with at least one finding. Never leave a findings array empty. If you found no issue, add one detailed flagged: false finding explaining what you checked and why it appears clear.
When in doubt, flag it — the gate can accept tradeoffs, but it can't act on findings it never sees.
Good: {"detail": "Checked callers of nthroot_mod in solveset.py line 1205 — passes prime moduli only, consistent with the fix.", "flagged": false}
Good: {"detail": "The fix handles empty tuples but not single-element tuples which need a trailing comma.", "flagged": true}
Bad: {"detail": "No issue found", "flagged": false} ← too brief, will be rejected
Bad: {"detail": "The hints suggest approach X but the plan uses Y. However Y is consistent with X's intent.", "flagged": false} ← a different approach than the hints IS a flag. You found a divergence — flag it. The gate decides if it's acceptable.
After filling in checks, add any additional concerns to the flags array (e.g., security, performance, dependencies).
Use the standard format (id, concern, category, severity_hint, evidence). This array can be empty.
Workflow: read the file → investigate → read file again → add finding → write file back. Repeat for each check.
This is critique iteration 3. The template file includes prior findings with their status. Verify addressed flags were actually fixed, re-flag if inadequate, and check for new issues introduced by the revision.
code
Additional guidelines:
- Robustness level: standard. Use balanced judgment. Flag significant risks, but do not spend flags on minor polish or executor-obvious boilerplate.
- Over-engineering: prefer the simplest approach that fully solves the problem.
- Reuse existing flag IDs when the same concern is still open.
- `verified_flag_ids`: list flag IDs from prior iterations that the revised plan actually resolves (e.g., if the plan was revised to fix FLAG-001, and you confirm the fix is correct, include "FLAG-001"). Only include flags you've verified — don't guess.
- Verify that the plan follows the expected structure when validator warnings or the outline suggest drift.
- Additional flags may use these categories: correctness, security, completeness, performance, maintainability, other.
- Focus on concrete issues, not structural formatting.
{"checks":[{"id":"issue_hints","question":"Did the work fully address the issue hints, user notes, and approved plan requirements?","findings":[{"detail":"Verified the revised plan still honors the explicit instruction not to invoke or activate megaplan. It treats the existing .megaplan/ directory as harness state only and does not propose running the megaplan CLI, reading the megaplan skill, or starting a nested planning harness.","flagged":false},{"detail":"Verified the no-epic bootstrap repair against the current loop, envelope, schema, protocol, and CLI boundaries. Rev 3 now explicitly changes run_turn to accept epic_id: str | None, introduces an active_epic_id local for all envelope/abort returns, changes Store.create_turn to accept str | None, relaxes Envelope.epic_id and envelope.schema.json, and makes CLI --epic optional, which addresses the prior bootstrap-envelope and public-boundary gaps.","flagged":false},{"detail":"Checked the body_version mention in planning-bot-spec.md:2606-2611 against the rev 3 plan. The plan now makes deferring body_version an explicit accepted tradeoff, but the spec's title/goal sync examples still say body edits increment body_version; this remains a divergence for the gate to accept rather than a resolved implementation requirement.","flagged":true}]},{"id":"correctness","question":"Are the proposed changes technically correct?","findings":[{"detail":"Verified the parser design against the body parsing rules in planning-bot-spec.md:503-514. Rev 3 keeps the lenient parse() plus strict validate_for_write() split, so malformed and no-section bodies can be read and round-tripped while writes still reject missing title or Goal.","flagged":false},{"detail":"Verified the revert/time-travel repair. Rev 3 preserves full pre-revert body, title, goal, and checklist snapshots in reverted_to.prior_state, and get_epic_at_time restores that snapshot when walking backward across a revert, which closes the missing-state bug from the earlier plan.","flagged":false},{"detail":"Checked title/goal column derivation against planning-bot-spec.md:1311-1320. Rev 3 keeps create_epic and edit_epic writing epics.title and epics.goal exclusively from parsed body values, so the parser remains the only writer of those derived columns.","flagged":false},{"detail":"Checked get_epic_at_time behavior against planning-bot-spec.md:1678. The spec says if no events exist before the requested timestamp, the tool returns the epic's initial state; Rev 3 instead says that when backward replay rolls past the created event it returns empty/None body and checklist. That may be reasonable for timestamps before the epic existed, but it is a concrete semantic divergence from the written spec.","flagged":true}]},{"id":"scope","question":"Search for related code that handles the same concept. Is the reported issue a symptom of something broader?","findings":[{"detail":"Verified the read-tool audit scope against agent_kit/tool_kit.py, where register_tool defaults to operation_kind='write'. Rev 3 explicitly registers all editorial read tools with operation_kind='read' and includes operation-kind assertions in the integration test, so the audit semantics are covered.","flagged":false},{"detail":"Verified the changes.meta scope decision against the spec's edit_epic object. Rev 3 intentionally rejects changes.meta with meta_not_supported and a hint to edit body sections for title or goal, which contains the scope and makes the spec divergence explicit and test-covered.","flagged":false},{"detail":"Checked no-epic behavior against resident-mode code in agent_kit/resident.py and Discord ingestion in agent_kit/transport/discord.py. Rev 3 keeps no-epic mode scoped to invocation/CLI and leaves resident flows tied to concrete epic ids, so it does not broaden Sprint 2a into resident epic-selection or Discord routing work.","flagged":false}]},{"id":"all_locations","question":"Does the change touch all locations AND supporting infrastructure?","findings":[{"detail":"Verified the tool registration locations. Rev 3 still adds agent_kit.tools.editorial and agent_kit.tools.editorial_reads imports in agent_kit/loop.py, matching the existing side-effect registration pattern used by communication and images tools.","flagged":false},{"detail":"Verified the Supabase adapter support locations. Rev 3 retains _EPIC_COLUMNS and _CHECKLIST_COLUMNS, routes update_epic and update_checklist_item through _update, and extends _MESSAGE_COLUMNS and _TURN_COLUMNS with epic_id for bootstrap retro-stamping, which covers the prior adapter-glue issue.","flagged":false},{"detail":"Verified the Optional epic id thread across all previously missed public boundaries. Rev 3 enumerates Store.create_turn, Envelope.epic_id, envelope.schema.json, arnold/cli.py argument parsing, the CLI exception envelope path, and a schema regression test for no-epic envelopes, so the earlier boundary mismatch is addressed.","flagged":false}]},{"id":"callers","question":"Find the callers of the changed function. What arguments do they actually pass? Does the fix handle all of them?","findings":[{"detail":"Checked existing callers of run_turn in tests, CLI, and resident mode. Rev 3 is additive for callers that still pass a concrete epic id, and it adds explicit tests for the new no-epic Python and CLI callers, including the successful create path and the errored no-epic envelope path.","flagged":false},{"detail":"Checked callers of Store.create_turn. Rev 3 updates the protocol and both adapter signatures to accept epic_id: str | None, and adds a contract assertion that create_turn(epic_id=None) succeeds, matching the new no-epic loop caller while preserving existing concrete-id callers.","flagged":false},{"detail":"Rechecked nested transaction use through ToolRegistry.audit_wrap. The plan continues to rely on nested store.transaction() blocks inside audited tools, and its integration test explicitly covers a multi-row tool mutation plus the audited tool_calls row, which is enough for this sprint's standard robustness level.","flagged":false}]}],"flags":[{"id":"FLAG-006","concern":"Body version: the revised plan deliberately skips body_version even though the spec's Sprint 2a title/goal sync adversarial tests mention incrementing it.","category":"completeness","severity_hint":"likely-minor","evidence":"planning-bot-spec.md:2606 and planning-bot-spec.md:2611 say title/goal body edits should increment body_version, while current migrations do not define that column and Rev 3 explicitly defers it as an accepted tradeoff."},{"id":"FLAG-007","concern":"History semantics: get_epic_at_time behavior before the created event differs from the spec's stated fallback to the epic's initial state.","category":"correctness","severity_hint":"likely-minor","evidence":"planning-bot-spec.md:1678 says if no events exist before the timestamp, return the epic's initial state. Rev 3 says backward replay that rolls past created returns empty/None body and checklist."}],"verified_flag_ids":["FLAG-001","FLAG-002","FLAG-003","FLAG-004","FLAG-005"],"disputed_flag_ids":[]}
Not yet included in a published release.
sections
append
remove_sections
rename_section
reorder
edit_epic.body
body_op_conflict
expected_diff equivalence:\n line endings, strip trailing whitespace per line, drop trailing blank lines (spec §494).
Out of scope: sprints, sprint_items, codebases, code_artifacts, feedback, second_opinions, image generation. edit_epic.changes.sprints and changes.state return not_yet_supported.
CLAUDE.md forbids creating a megaplan/ directory; the existing one is harness state, not a target.
_preamble is addressable as a section name across these ops: replace_section('_preamble', new_text) overwrites the entire preamble (so replace_section('_preamble', '# New Title\n') updates the title; this is the spec §2606 path). append_to_section('_preamble', …) appends. remove_section('_preamble') clears the preamble to empty string. rename_section from/to _preamble is rejected with InvalidPosition (the preamble is a structural slot, not a renamable section).
Checklist path: apply add (positions auto-assigned to max(existing.position) + 1 if absent; else honour and shift), update (per-item, only _CHECKLIST_COLUMNS-allowed fields), remove (delete by id). Capture pre-op snapshot for the event.
Inside one store.transaction() with transaction_id = uuid4().hex:
Resolve target events: no event_id → fetch events_by_transaction(latest_transaction_id(epic_id)). With event_id → fetch the event, then all events sharing its transaction_id (spec §1399).
Capture pre-revert state for the new event's prior_state: {'body': current_body, 'title': current_title, 'goal': current_goal, 'checklist': [...current full snapshot...], 'reverted_transaction_id': txn, 'reverted_event_ids': [e.id for e in target_events]}. This lets backward replay across this revert reconstruct correctly (FLAG-003, correctness-2).
Apply each target event's prior_state in reverse-occurred order: body_edit → store.update_epic(epic_id, body=…, title=…, goal=…); checklist_change → store.replace_checklist(epic_id, prior_items). (Other event types in the transaction — e.g., a future state_change — are no-ops in Sprint 2a; bot won't trigger them.)
Append a new reverted_to event with the captured pre-revert prior_state and a fresh transaction_id. The event is itself revertible because its prior_state carries the full pre-revert snapshot.
render_epic(context, epic_id, format='markdown') — 'markdown' returns the body as-is (image-reference resolution is a Sprint 6 no-op). 'html' → {"error": "not_yet_supported"}.
change_summary
epic_events
turn_id
WHERE turn_id IN (...)
search_tool_calls(tool_name=None, epic_id=None, since=None, limit=20) — delegates to store.search_tool_calls_by(...).
get_epic_at_time(epic_id, T_just_before_revert) returns body+checklist as it was right before the revert (verifies FLAG-003 fix end-to-end).
One system_logs row per touching turn with event_type='epic_outline', category='application', and details.sections containing all six default headings (after the relevant turns).
tool_calls.operation_kind for get_epic, get_section_names, get_history, etc. is 'read'; for create_epic, edit_epic, revert, render_epic is 'write' (scope-1 verification).
preamble, exercises revert with backward replay across the revert, and asserts every Sprint 2a acceptance criterion in spec \u00a7131\u2013142.",
"priority": "must",
"requires": [
"run_tests"
]
},
{
"criterion": "All pre-existing tests in tests/ continue to pass (no regression in Sprint 1a/1b functionality, including resident-mode test_resident*, test_discord
##
_preamble
# Title
## Goal
parse()
# <title>
get_epic_at_time
revert
epic_events.prior_state
planning-bot-spec.md
reverted_to
reverted_transaction_id
reverted_to
create_epic
planning-bot-spec.md
create_epic
Store.create_epic
agent_kit/tool_kit.py
agent_kit/tools/communication.py
operation_kind='read'
@register_tool
get_epic
get_history
get_recent_turns
search_tool_calls
edit_epic
planning-bot-spec.md
not_yet_supported
changes.sprints
changes.state
changes.meta
meta?: { title?, goal? }
agent_kit/store/supabase.py
agent_kit/store/sqlite.py
epics
checklist_items
epic_events
_MESSAGE_COLUMNS
_TURN_COLUMNS
_IMAGE_COLUMNS
agent_kit/loop.py
tests/test_run_turn.py
run_turn
epic_id
epics
create_epic
blob.exists
discordtransport
external_requests.request_body
reconciler
reconciler
blob.exists(ref)
blob.put(...)
request_body
epic_events.body_edit
body_version
CLAUDE.md forbids creating a megaplan/ directory; the existing one is harness state, not a target.
diffs_equivalent(a, b)
\r\n→\n
No third-party deps beyond stdlib (difflib, re). No imports of Store/ports/tool_kit.
One system_logs row per touching turn with event_type='epic_outline', category='application', details.sections containing all six default headings.
pending
preamble, exercises revert with backward replay across the revert, asserts the bootstrap envelope contract, and covers every Sprint 2a acceptance criterion in spec \u00a7131\u2013142.",
"priority": "must",
"requires": [
"run_tests"
]
},
{
"criterion": "All pre-existing tests in tests/ continue to pass (no regression in Sprint 1a/1b functionality, including resident-mode test_resident*, test_discord