can you figure out at a high-level how planning-bot-spec.md should be implemented in to this? It should ideally be usable via a discord bot (as per its deisgn) but also via our current agentic process.
Assistant
Read the spec front matter (sprints 1a–7) and surveyed megaplan/cli.py, _core/workflow.py, handlers/, forms/, cloud/wrappers/. Here's how I'd land Arnold inside this repo at a high level — happy to refine before touching code.
The core insight
Arnold and current-megaplan operate at different abstraction levels:
Arnold = epic-level planning to PM-handoff fidelity. Output: a body + queued sprints. Conversational, long-running, Supabase-backed.
They aren't competitors — Arnold's terminal output (planned epic, queued sprints) is exactly the input megaplan wants. So integration is a stack, not a merge: Arnold sits upstream and hands sprints to megaplan to execute.
Architecture: one engine, two transports
Mirror the pattern already in this repo (handlers/ = logic, cli.py = transport, cloud/wrappers/ = cloud transport). New subpackage megaplan/arnold/:
code
megaplan/arnold/
engine/ # pure-Python: agentic loop, ~30 tools, body parser, gating
loop.py
tools/ # one file per tool (send_message, edit_epic, generate_image, ...)
body.py # markdown ↔ sections parser, expected_diff verification
gating.py # state-advance gates, lockdown scan
checklist.py # 18-item seed + adaptation
store/ # Supabase + asyncpg repos; SQLite fallback for local/CLI
migrations/
repos.py
prompts/ # system prompt, per-checklist-item depth guidance
adapters/
discord/ # discord.py gateway, attachments, status message, voice
cli/ # REPL + one-shot for the agentic workflow
bridge/
to_megaplan.py # export a queued sprint as a megaplan plan dir
The engine never imports an adapter; adapters drive the engine. That's what makes Discord and CLI usage symmetric.
Two ways to use it
Discord (spec's primary surface):megaplan arnold serve boots the Discord gateway adapter — same engine, real Supabase, real users.
Agentic CLI (your "current agentic process" requirement):megaplan arnold chat opens a REPL against the same engine, with SQLite by default (no Supabase needed for solo dev). Same tools, same prompts, same body, same gating — just stdio in/out instead of Discord events. This is what your existing claude-driven workflow would call.
A new top-level CLI command megaplan arnold ... (parallel to bakeoff, loop, cloud) keeps it isolated.
The bridge to existing megaplan
When a sprint flips to queued, Arnold can call bridge/to_megaplan.py to materialise a megaplan plan dir from the sprint body + items. Either:
Manual: a tool dispatch_sprint(sprint_id) writes the plan and shells megaplan init.
Automatic: a "queued" hook that submits via the cloud wrappers (mp-run) so execution can run on Railway alongside Arnold.
That closes the loop: Arnold plans, megaplan executes.
Reuse from what's already here
forms/ registry pattern → body templates (design-doc, decision-doc, conversation-prep).
prompts/ layout → Arnold's system prompt + per-item depth guidance.
_core/io.py atomic writes → local Storage cache for images.
Sequencing recommendation
The spec already nails this — 1a/1b are plumbing + robustness, 2a/2b are the editorial product. Before any code:
Split the spec. It's 162KB single-file; the spec itself flags this. Split into architecture.md / behavior.md / sprints.md / setup.md so engineers (or sub-agents) can work concurrent sprints.
Build the engine + CLI adapter first (sprint 1a–2b), no Discord. Tests and the agentic loop are easier to verify in REPL. The whitelist/voice/status-message work in 1b is Discord-specific — defer until 2b is solid.
Add the Discord adapter (sprint 1b's Discord bits) once the engine is real.
Add the bridge to megaplan execution at sprint 4 (when sprints become first-class objects).
Main risks I'd flag now
DB coupling. Spec hardcodes Supabase. Putting a Repository interface in arnold/store/repos.py with Supabase + SQLite implementations is cheap insurance and unlocks the CLI adapter for free.
Tool sprawl. ~30 tools. One-tool-per-file with a small registry (like forms/) keeps it sane.
Two agentic loops in one repo. Be explicit that megaplan's phase machine is not Arnold's loop — different code paths, different state stores. Resist the temptation to unify prematurely.
Want me to draft a more concrete plan for sprint 1a (file list, schemas, CLI command shape) so you can decide whether to assign it?
User
Think it through please, this should be an approach we should apply to multiple tools
Assistant
Thinking through it as a pattern rather than an Arnold-specific integration. The thesis: Arnold is the second instance of a shape that's going to recur, and the right move is to build it concretely but with the seams already in the right places, not to extract a framework today.
What's actually shared across these tools
Every long-running agentic tool you've described or are likely to build (Arnold, Lota, a video-edit assistant, a codebase-research bot, an extension of megaplan itself) has the same five-axis shape:
Axis
Arnold's choice
Generalizes to
Transport (how messages arrive/leave)
Discord gateway
CLI REPL, HTTP, Slack, GitHub Issues (Lota), programmatic call from another agent
Store (typed state across turns)
Supabase + asyncpg
SQLite, file-backed, in-memory
Model (the brain)
Claude Opus 4.7
OpenAI, Gemini, mixed (second opinions)
Blob (large media)
Supabase Storage
local disk, S3
Artifact (the thing being worked on)
Epic body + checklist + sprints
plan, video timeline, codebase analysis, design doc
The Arnold spec hardcodes column 2. To make this a pattern, columns 1–4 become ports and column 5 is the only thing each tool genuinely owns.
The non-obvious shared core
The piece worth lifting out isn't the loop — loops are easy. It's the artifact-edit grammar. What edit_epic does (whole-write, section-write, append, position-anchored insert, rename, expected_diff for optimistic concurrency, transaction-grouped events for revert, server-side gating on state transitions) is structurally identical to what you'd want for any artifact a long-running agent edits. A video timeline has scenes, a plan has phases, a research doc has findings — all addressable, all need diff-verified writes, all need revert, all need gates.
That grammar + the audit ledger underneath it is the universal substrate. It's also the place where most agentic tools subtly fail — bot rewrites everything from memory, drift accumulates, no audit trail. Getting it right once and reusing it is the real win.
What I'd actually build
Concrete, in this repo, in this order:
Build Arnold with ports already drawn, not a framework. New with subdirs split exactly along the port lines: (loop, tools, gating), (body parser, sections, diff, gates, events), (discord, cli), (supabase, sqlite), (anthropic, openai), . Each port is a small . The engine never imports a concrete adapter.
User
So how weoudl you adjust the plan to accommoodate this?
Assistant
Three concrete adjustments. Headline change: there are now two top-level packages, agent_kit/ (the substrate) and arnold/ (the first instance), and the sprint order flips so the substrate is forced into shape before Discord enters the picture.
File structure delta
code
megaplan/agent_kit/ # NEW — the reusable substrate
ports.py # Transport, Store, Model, Blob (Protocols only)
artifact.py # generic Artifact[T]: section-addressed edits, expected_diff, events, revert
diff.py # unified-diff helpers, normalization
ledger.py # transaction-grouped event store, audit query API
loop.py # transport-agnostic turn runtime (coalescing, status, mid-turn, recovery)
tool_kit.py # tool registry, schema validation, audit-wrapping decorator
families/ # SHARED tool families (see below)
artifact_edit.py
audit.py
selection.py
feedback.py
blobs.py
external.py
adapters/
transport_cli.py # stdio REPL — ships day one
transport_discord.py # discord.py gateway — ships sprint 1b
store_sqlite.py # ships day one
store_supabase.py # ships sprint 1b
model_anthropic.py
model_openai.py
blob_local.py
blob_supabase.py
megaplan/arnold/ # the first INSTANCE — only Arnold-specific things here
artifact_epic.py # EpicBody concrete type, parser, heading rules
tools/ # only tools that aren't in a family (very few)
prompts/ # system prompt + per-checklist-item guidance
gates.py # shaping→sprinting→planned conditions, lockdown scan
templates.py # design-doc (v1), decision-doc/etc. (later)
checklist.py # 18-item seed + adaptation
app.py # WIRING: pick adapters, register families + Arnold tools, run loop
cli.py # `megaplan arnold serve|chat|export-sprint`
bridge.py # queued sprint → megaplan plan dir
# Everything Discord-specific (status message format, voice, attachment caps, dynamic timestamps)
# lives in agent_kit/adapters/transport_discord.py — NOT in arnold/.
User
So each - 'turn' happe sinside a subagent when queried via the CLI? How should the doc be updated to accommodate?
Assistant
Right — and this is the missing piece in the spec. The spec only imagines Arnold running as a resident process (gateway connection, owns its own loop lifecycle, polls for messages, manages mid-turn coalescing). When you invoke it via CLI from inside an agentic process, the lifecycle is fundamentally different — the outer agent owns time, Arnold runs one turn per invocation as a subagent, exits, and reports back.
These aren't just two transports of the same loop. They're two execution modes, and the spec needs to acknowledge both because half its sections (coalescing, recovery, status messages, mid-turn handling) only make sense in one of them.
Loop runtime owns the turn lifecycle: detects when to coalesce messages, when to start a turn, when to recover.
Mid-turn arrivals are real; status messages stream live; external_requests ledger is load-bearing.
Invocation mode (CLI, programmatic call from a Claude Code session, megaplan handler, cron, HTTP one-shot):
Ephemeral. Caller invokes megaplan arnold turn --epic X "<input>", Arnold loads state from the store, runs one turn (defined as: one Anthropic invocation expanded to tool-use completion), persists, exits with a structured result.
No coalescing — caller batched inputs before invoking. No mid-turn — the caller blocks. No live status — progress is structured events on stdout (or silent; final summary suffices).
Recovery is the caller's problem — Arnold's job is "run a turn atomically and report." The ledger still helps but is less load-bearing.
The "turn" itself is the same atom in both modes: one Claude invocation that may chain through many internal tool calls until the model stops. What differs is who owns the lifecycle around it.
How the spec should be updated
A new top-level section, slotted right after Models and before What an Epic Is:
## Execution Modes
Arnold runs in two modes. The artifact, tools, prompts, and gating are identical; the lifecycle around a turn differs.
Concern
Resident (Discord)
Invocation (CLI / subagent)
Process lifetime
long-lived
ephemeral, one turn per process
Turn trigger
inbound message + coalescing window
User
let's do it
Assistant
I'll find the exact anchor points first, then apply targeted edits.
Assistant
Now I have what I need. Making the edits.
Edit 1: Insert the new "Execution Modes" section after Models.
Assistant
Edit 2: Insert Subagent Contract + Callable API after Agentic Loop.
Assistant
Edit 3: Add invocation-mode delta to Multi-Message Handling.
Assistant
Edit 4: Add invocation-mode delta to Status Message.
Assistant
Edit 5: Add invocation-mode delta to Idempotency and Recovery.
All six edits applied. Summary of what landed in planning-bot-spec.md:
New sections:
Execution Modes (after Models) — defines resident vs invocation modes, comparison table, push/pull Transport distinction, and which sections apply to which mode.
Subagent Contract (after Agentic Loop) — full Envelope JSON schema, field semantics, determinism guarantees, resident-mode equivalence.
Section deltas (mode-applicability callouts added at top of each):
Multi-Message Handling — coalescing/mid-turn is resident-only.
Status Message — resident-only; invocation mode emits NDJSON events.
Idempotency and Recovery — recovery routine resident-only; ledger applies to both.
Agentic Loop step 5 — send_message writes to reply buffer in invocation mode.
Sprint resequencing:
Sprint 1a rewritten as "agent_kit core + invocation mode" — CLI + SQLite + envelope first, no Discord, no Supabase. Substrate-first.
Sprint 1b rewritten as "Discord resident mode + robustness" — Discord transport + Supabase store land here as the second impl per port, proving the abstractions hold. Discord plumbing from old 1a (whitelist, DM acceptance) moved here. New acceptance criterion: the SQLite-authored Store port contract tests must pass against Supabase unchanged.
Sprints 2a–7 unchanged on the surface — they automatically benefit from the substrate now sitting underneath.
User
Anyhting else missing in the plan? Or confusing?
Assistant
Re-read the new sections plus the surrounding spec with a critical eye. Real concerns, ranked roughly by how much they'd bite an engineer trying to build from this:
Things I'd fix
1. Concurrency between modes on the same epic — undefined. The spec now allows resident-mode (Discord user) and invocation-mode (CLI / megaplan handler) callers to operate on the same epics.body simultaneously. expected_diff gives optimistic concurrency on a single edit, but there's no policy for: a Discord turn in flight when a CLI turn arrives, or vice versa. Options are reasonable (per-epic write lock; reject invocation if resident turn in_progress; allow interleave and let expected_diff sort it out) but the spec needs to pick one. Today an engineer would guess.
2. The Tools section doesn't flag mode applicability per tool. I added mode callouts to the cross-cutting sections but the actual tool list still describes ~30 tools as if they all work in both modes. Several are resident-only or behave differently:
set_typing — no-op in invocation mode
set_activity — emits an event vs. updates Discord status line
send_image — posts to Discord vs. writes to envelope
send_message — posts to Discord vs. appends to reply buffer
The Tools section should either grow a per-tool "Mode" column or bucket tools by mode applicability. Otherwise the engineer has to hunt across the spec to figure out what each tool does in each mode.
3. Attachments in invocation mode are unspecified. Resident mode supports image and voice attachments on inbound messages. The CLI signature I wrote (--input "<text>") has no equivalent. Same for the Python run_turn and HTTP entry points. Need to pin: probably --attach <path> (repeatable) on CLI, attachments: list[Path|bytes] on Python, multipart form on HTTP. Without this, a caller can't send Arnold an image to look at, which kills a real use case (megaplan handler asking Arnold to review a generated diagram).
4. The defer_to_caller tool I referenced is undefined. I mentioned it in the Subagent Contract section as the mechanism for outcome="blocked_on_caller" but never specified its signature, when Arnold should call it, or how it differs from just phrasing a question in reply. Either define it (one tool spec, ~5 lines) or remove the reference and say blocked_on_caller is set heuristically when reply ends with a question mark and no edits were committed. The latter is simpler and probably right.
The Core Principles section says: That principle was written for resident mode where the user is a human in Discord. In invocation mode the caller IS running commands (programmatic invocations). This needs a one-line qualifier: the principle applies to the resident-mode user-bot relationship, not to programmatic callers.
User
Can the agent view the epic all in one go/ load it all into context easily? Or specific chunks?
Assistant
Quick answer first.
Yes — the entire body is loaded into hot context every turn by default. From the Hot Context section: "Identified epic: title, goal, state, full body with section markers visible, ordered list of section names, full checklist, sprints if any." The bot never has to call get_epic to read the body for the current epic; it's already there. Plus checklist, sprints, last 10 messages, last 10 tool calls, recent observations, recent events, image metadata.
Section addressing exists for writing (clean diffs, no drift in untouched sections, smaller audit events), not for fit. Claude Opus 4.7 has 1M context; even a maxed-out epic body is a few thousand lines = a few tens of thousands of tokens. The cost concern is "every turn re-loads the body and re-pays prompt-cache misses on changed bytes," not "doesn't fit."
get_epic(sections=...) / search_in_body / get_body_outline are for the read-modify-write loop ("show me just this section so I can rewrite it cleanly") and for cross-epic peeking, not for working around context limits.
One thing the spec doesn't address that's worth a thought: in invocation mode, should the caller be able to opt into a lean hot context (skip full body, skip recent tool calls) when they're invoking Arnold for a narrow task? Probably yes, via an envelope param like context: "full" | "lean" | "minimal". Not urgent — flagging.
Now applying the fixes you greenlit. Setting up tasks and going.
Assistant
Reading the Tools section and the Core Principles header to find anchor points.
Assistant
Now I have all anchor points. Applying fixes.
Assistant
Fix #1: cross-mode concurrency. Add a new subsection at the end of Execution Modes.
Assistant
Fix #5: qualify "Natural language only" core principle.
Assistant
Fix #2: tool mode-applicability buckets at top of Tools section.
Assistant
Fix #4: define defer_to_caller properly. Add it to the Communication subsection and update the Subagent Contract reference.
Assistant
Update the Subagent Contract section to point to the now-defined tool.
Assistant
Fix #3: attachments in invocation mode. Add a subsection to Callable API.
Update Sprint 1a's readiness gate to enumerate the new sections.
Assistant
All six fixes applied. Summary of what landed:
Fix #1 — Cross-mode concurrency. New "Cross-mode concurrency on the same epic" subsection at the end of Execution Modes. Per-epic advisory write lock (Postgres advisory / SQLite row); resident turns wait on it, invocation turns block up to 60s then return outcome="errored" with error.code="epic_locked"; lock auto-releases on crash via session scope or recovery scan; composes with expected_diff rather than replacing it.
Fix #2 — Tool mode applicability. New "Mode applicability" callout at the top of the Tools section, bucketing all ~30 tools into four categories: both-modes (most), resident-only (set_typing), mode-divergent (send_message, send_image, set_activity), invocation-only (defer_to_caller). Each mode-divergent tool's individual definition also got an inline "(mode-divergent: ...)" annotation.
Fix #3 — Invocation-mode attachments. New subsection in Callable API specifying --attach <path> for CLI, attachments= for Python, multipart for HTTP. Pre-processing path defined: blobstore upload → images row creation (source='caller_uploaded') for images, Whisper transcription + inline marker for audio, then turn proceeds normally.
Fix #4 — defer_to_caller tool. Properly defined under Tools → Communication. Signature: defer_to_caller(questions: list[str], reason?: string). Sets envelope outcome="blocked_on_caller", populates questions. Invocation-mode only; calling it in resident mode logs at warn and is treated as a no-op. Subagent Contract section's reference cleaned up.
Fix #5 — Natural language only qualifier. Core principle now reads "Natural language only — for human users." with a sentence clarifying that programmatic callers in invocation mode use the structured Callable API by definition.
Fix #6 — Engineering Handoff Readiness header. Two new bullets on the readiness checklist (per-tool mode applicability, both execution modes specified). New "Substrate framing" paragraph explicitly noting the spec describes Arnold but bootstraps agent_kit as a reusable substrate. Sprint 1a's readiness gate expanded to enumerate envelope schema, attachment protocol, concurrency lock, mode applicability, and defer_to_caller.
Spec is now self-consistent across both modes. Want me to do a final read-through for any cross-references that drifted, or are you good?
User
yes plz
Assistant
Found several drifts. Let me check a couple more areas before fixing.
Assistant
Found three drifts to fix. Skipping the rest — they're either trivial wording or already correct on closer inspection.
Assistant
Fix A: turns → bot_turns in Sprint 1a.
Assistant
Fix B: Sprint 1a/1b test mapping in Testing section.
Sprint 1a was using bare turns in two places where the rest of the spec uses bot_turns — now consistent.
Testing section's Sprint 1a/1b coverage tables had Discord-specific tests still under 1a; redistributed to match the new sequencing (1a = invocation/SQLite/envelope; 1b = resident/Discord/Supabase + concurrency lock).
Spec opening one-liner now acknowledges Arnold has two surfaces (Discord primary, invocation via CLI/Python/HTTP) — 12 added words, no bloat.
Spec Readiness Rubric criterion #7 evidence now mentions the mode-applicability bucket so the rubric matches reality.
Checked and left alone:
All other turns references are plain English ("3+ turns without body progress"), function names (recent_turns), or idioms ("turns out") — not table references.
"Natural language only" now-qualified principle reads cleanly against the rest of the spec — other "natural language" phrasings (creating epics, queue reordering, codebase mgmt) are about the resident-mode user, which is correct.
Failure mode #11 "Prompt/log redaction (Sprint 1a/5)" — left at 1a; redaction is a substrate/audit concern that applies in both modes and lives at the engine layer, so 1a is the right home.
Title "Planning Assistant — Discord Bot Spec (Arnold)" — slightly imprecise now but renaming felt overaggressive; the opening paragraph corrects the impression in one sentence.
Spec is internally consistent. Ready to either split into the four files the readiness section recommends, or hand off as-is.
megaplan/arnold/
engine/
artifact/
transport/
store/
model/
blob/
Protocol
Build the artifact layer with one type but a generic shape.Artifact[T] with section-addressed editing, expected-diff verification, transaction events. T=EpicBody for v1. This is the part most likely to be reused — design it as if it'll be reused, even though only Arnold uses it now.
CLI adapter on day one, alongside Discord. Not "after Discord works." The CLI adapter is the agentic-process surface and the test harness. If the engine works in the REPL, Discord is mostly plumbing. If it only works in Discord, the engine is too coupled.
Don't extract until tool #3. When the next agentic tool starts (Lota expansion, a codebase-research bot, etc.), look at what's actually duplicated and pull the substrate out into something like megaplan/agent_kit/. Premature extraction is more expensive than duplication here — Arnold's needs (live status messages, voice transcription, mid-turn coalescing) may turn out to be Discord-specific quirks that don't belong in a shared substrate.
What I'd push back on in the spec
A few things that look fine for Arnold-the-bot but won't generalize, worth flagging now so they don't calcify:
Supabase is not a contract. The spec treats it as one. For solo CLI use and tests you want SQLite; for multi-tool reuse you want a Repository protocol. Cheap insurance, unlocks a lot.
Discord conventions in the engine. Status messages, dynamic timestamps, 25MB attachment cap — these belong in the Discord adapter, not the loop. Spec doesn't always keep them separated.
"Every tool has its own ~30 tools" doesn't scale. Arnold's tool set has clear families: artifact-edit, search, audit, external-call, blob. The next tool will want most of these too. Define tool families so they're shareable, not 30 bespoke functions.
The phase machine inside today's megaplan should not move. It looks like the same shape but isn't — its "artifact" is a plan and its "gates" are phase transitions. Don't try to unify them now. Note the structural similarity, leave the door open, move on.
The bridge to the rest of the ecosystem
Once Arnold sits on this substrate, three connections fall out for free:
Arnold → megaplan executor. A "queued sprint" tool dispatches into the existing phase machine via cloud/wrappers/mp-run. Arnold plans, megaplan executes.
Arnold ↔ Lota. Both are long-running agentic tools with different transports (Discord vs GitHub Issues). If Arnold's engine is transport-agnostic, Lota's logic could plug into it with a different transport adapter and a different artifact type.
Other-agent → Arnold. The CLI adapter doubles as a programmatic API. A claude-code session, a megaplan handler, or a scheduled job can all drive Arnold without going near Discord.
Net: build Arnold concretely, with the ports drawn cleanly, and ship it. Extract a substrate at tool #3 when you actually know what's shared. The biggest single design call to lock in now is the artifact-edit grammar — that's the thing you'll regret not generalizing later.
The discipline this enforces: arnold/ should not import anything from discord.py or Supabase. If it does, the seam is wrong.
Sprint resequencing
Spec sequencing is Discord-first. Multi-tool sequencing is substrate-first, two-impls-per-port early, because the only way to know your ports are real is to have two adapters behind each one.
Spec sprint
Adjusted sprint
What changes
1a — Discord plumbing + Supabase + minimal loop
1a — agent_kit core + CLI + SQLite + Anthropic + audit ledger. Ends with: REPL chat against Claude, every tool call audited to SQLite, all four ports defined, one impl of each. No Arnold yet.
Discord and Supabase deferred. Substrate forced into shape against the cheapest possible adapter (CLI).
1b — voice/images/status/recovery
1b — second adapter per port. Add Discord transport, Supabase store, OpenAI model. Plus the cross-cutting reliability work (coalescing, recovery, idempotency, mid-turn, status message).
Voice + images table move out — they're sprint 6 alongside generation. Foundation in place: any port now has two impls, proving abstractions hold.
2a — Artifact[T] + EpicBody. Build the generic Artifact[T] with section-addressed editing and expected_diff, then implement EpicBody as the first T.
The artifact grammar is now in agent_kit, not arnold. EpicBody is the concrete type; the grammar generalizes.
2b — editorial polish + feedback
2b — tool families + Arnold gates. Pull feedback, audit, selection, search into agent_kit families. Arnold registers them all. Gates and lockdown scan are Arnold-specific (arnold/gates.py).
Most of 2b's "tools" become families anyone can register. Per-checklist-item depth guidance stays Arnold-specific.
3 — multi-epic + message search
3 — same, but multi-artifact selection family lives in agent_kit. Arnold parameterizes it for epics.
Future tools that manage multiple artifacts (multiple plans, multiple videos, multiple research docs) reuse this.
external — request_second_opinion, generate_image, transcribe_voice, fetch_codebase, etc. Pluggable per tool.
Arnold's app.py becomes ~50 lines: pick adapters, register the six families with EpicBody as T, register Arnold's gates + checklist + system prompt, run the loop. The next tool's app.py looks the same with a different artifact type and a different system prompt.
What stays the same
The 18-item checklist, the body templates, the gating conditions, the lockdown scan, the persona — all Arnold-specific, all stay in arnold/.
Tests still per sprint, still automated, still LLM-graded where the spec calls for it.
Bridge to megaplan-as-executor unchanged — Arnold plans, megaplan executes.
The honest risk
Building agent_kit/ with one real consumer (Arnold) is exactly the "premature framework" trap. Mitigation: agent_kit/ ships only what Arnold actually uses, no speculative APIs, no abstract base classes for hypothetical future tools. When tool #2 arrives (Lota expansion, codebase-research bot, video editor), let it bend agent_kit/ to its needs — that's the moment you find out which abstractions were real and which were imagined. The two-impl-per-port rule in sprint 1b is the only speculative work, and it pays for itself by catching Discord-specific assumptions before they calcify.
Want me to draft sprint 1a concretely (file list, port signatures, CLI command shape) so you can see whether the substrate-first sequencing actually works on paper?
caller invokes explicitly
Multi-message coalescing
server-side, 10s window
caller batches; Arnold sees one input
Mid-turn message arrival
real concern (see Mid-Turn Handling)
N/A — caller blocks
Status surface
live-edited Discord message
structured progress events on stdout
Recovery
server-side recovery routine + ledger replay
caller retries; ledger replay on next invocation
Subagent return
send_message posts to Discord
exit with structured result envelope
The Transport port distinguishes push transports (resident — events arrive async, transport drives loop) from pull transports (invocation — caller asks for one turn).
Then per-section deltas (small, surgical):
Multi-Message Handling — add: "Invocation mode: coalescing is the caller's responsibility; Arnold sees a single input per turn."
Status Message — add: "Invocation mode: progress is emitted as structured JSON events on stdout ({event: 'tool_call', name: ..., ts: ...}); caller renders or ignores."
Idempotency and Recovery — add: "Invocation mode: process exit ends the turn. If the caller times out or retries, the ledger lets the next invocation reconcile in-flight external requests by idempotency key; otherwise the caller decides."
Mid-Turn Handling — add: "Invocation mode: N/A. Calls are synchronous from the caller's perspective."
Tools section — add: set_typing / status message tools are no-ops in invocation mode (or emit stdout events).
The caller (Claude Code, megaplan handler, cron) reads this and decides what to do next. This is the contract any caller depends on; it's part of the public API.
## Callable API (new section)
Three equivalent entry points to invocation mode:
megaplan arnold turn --epic <id> [--from-stdin] "<input>" — CLI, returns envelope as JSON on stdout.
POST /v1/turn — HTTP one-shot for non-Python callers (deferred; sprint 7).
All three call the same agent_kit.loop.run_turn(...) underneath. The only difference is how state is loaded (from store) and how the envelope is serialized.
Why this matters beyond Arnold
The mode split is the right shape for every agent-kit consumer. A future video-edit bot, codebase-research bot, or Lota expansion will all want the same two modes — Discord/Slack/webhook for human-driven resident use, CLI/programmatic for agentic-process subagent use. Putting run_turn(...) and the envelope contract in agent_kit/loop.py from day one means every tool built on the substrate gets both modes for free.
It also slots Arnold cleanly into the rest of your ecosystem: Claude Code calls Arnold as a subagent the same way it calls any Agent tool today; megaplan handlers can invoke Arnold mid-pipeline; a scheduled job can drive an Arnold turn nightly. None of that works cleanly if "turn" only means "Discord message arrived."
Want me to draft the actual section text in spec-voice and apply it as edits to planning-bot-spec.md?
5. The "Natural language only" core principle now contradicts invocation mode.
"The user does not run commands; the bot does."
6. Engineering Handoff Readiness checkmarks at the top of the spec are now stale. The list claims "All implementation choices pinned" and "All ~30 tools fully specified." After my edits, the new sections (Subagent Contract, Callable API, Execution Modes) introduce decisions that are mostly pinned, but the per-tool mode applicability (#2 above) is not, and the readiness gates per sprint don't yet cover envelope schema versioning, blocked_on_caller semantics, or attachment passing. Either tighten the new sections to close those, or add a caveat to the readiness header. Right now the checkmarks overstate where things are.
Things worth a one-line note, not a fix
7. Hot context cost in invocation mode. Each invocation rebuilds hot context from the store (no in-memory cache between calls). That's fine, but worth flagging in Hot Context — invocation mode is slightly more expensive per turn than resident mode for the same artifact.
8. The spec is now telling two stories without saying so. It's titled "Planning Assistant — Discord Bot Spec (Arnold)" but now also describes a substrate (agent_kit, ports, the Subagent Contract) intended for reuse across future tools. Worth a short framing paragraph at the very top: "This spec describes Arnold, the first user of a planned agent_kit substrate. The substrate's design is implicit in the Execution Modes / Subagent Contract / Callable API sections; future tools will sit on the same ports." Otherwise an engineer reads it as "build Arnold" without realizing the substrate work matters.
9. Bridge to megaplan-as-executor is in our conversation but not the spec. I've been pitching "Arnold plans, megaplan executes" as the killer integration. The spec ends at planned and says downstream is out of scope for v1. Pick: either flag the bridge as an explicit future direction in Sprint 7, or leave it out entirely and let it emerge organically. Currently it's a load-bearing idea in our conversation that an engineer reading just the spec wouldn't see.
10. Tool families are implicit. I argued tool families are how the substrate generalizes (artifact_edit, audit, selection, feedback, blobs, external) but the spec still lists 30 individual tools. Either name the families in the Tools section's intro, or accept they're an implementation grouping that doesn't surface in the spec. Both are defensible — naming them helps the next tool's engineer.
Things I'd leave alone
Sprint 2a–7 are still good. They didn't need restructuring.
The 18-item checklist, body templates, persona, gating logic — all sound, all mode-agnostic.
The Envelope schema — overspecified slightly but better that than under-specified for a public contract.
Sprint 1a's "no Discord, no Supabase" — I considered softening this and decided not to; the discipline matters.
My recommendation
Fix #1, #2, #3, #4 before any code. They're real ambiguities. #5 and #6 are 5-minute edits and prevent confusion. #7–#10 are nice-to-haves; #8 in particular if you actually want this spec to be read as both an Arnold spec and the substrate's bootstrapping doc.