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.
WRITE ACCESS CONTRACT: You are running with auto-approved writes inside a writable workspace. Treat the working directory as fully writable. Do NOT preemptively skip or block tasks on permission, sandbox, or read-only grounds. Attempt every required edit; only report failure AFTER a real OS-level rejection from a specific shell command. Do not infer 'read-only' from absence of activity; absence is not denial. If a single shell command unexpectedly fails, retry with a different invocation before concluding the environment is restricted.
You are an independent reviewer. Critique the plan against the actual repository.
Create a light but high-quality implementation plan for Discord bot presence behavior in /Users/user_c042661f/Documents/Veas.
Goal: make the bot feel more real by not appearing green/active all day, while guaranteeing it is online whenever it is typing.
Context:
Discord transport is in app/services/discord.py and uses a persistent Gateway websocket to receive DMs.
Typing indicators are sent through app.services.discord.send_typing and DiscordPacer in app/services/pacer.py.
The bot currently identifies without explicit presence, so Discord appears to show it online/green continuously while connected.
The bot must continue receiving Discord DMs reliably.
Presence is global to the bot, not per-DM.
Hard requirements:
Bot presence must be online whenever the bot sends or maintains a typing indicator.
Presence must not flap mechanically on every event.
Default no-conversation state should be invisible/offline or otherwise not green.
Inbound message, composing/typing, sending, reaction, and after-send tail should have believable transitions.
Use bounded randomness, but make it deterministic/testable with injectable random/sleep/clock where practical.
Implementation should be centralized, probably a DiscordPresenceManager tied to the Gateway websocket, not hand-rolled inside every send path.
Include tests and rollout/deploy considerations.
Deliverable: a concise implementation plan with recommended state machine, settings, code touch points, tests, risks, and exact sequencing. Do not implement code in this plan run.
{"checks":[],"flags":[{"id":"FLAG-001","concern":"Presence state machine: The plan does not state that typing-critical online upgrades bypass the minimum transition gap, so an implementation that applies DISCORD_PRESENCE_MIN_TRANSITION_GAP_S uniformly could delay the online presence update until after send_typing.","category":"correctness","severity_hint":"likely-significant","evidence":"The plan requires _send_bot_typing_pulse to call presence_manager.typing_started(...) immediately before self._send_typing(channel_id), while the manager state model also has last_transition_at enforcing min_transition_gap_s. The test list checks online-before-typing in a normal path, but does not include the case where the bot just downgraded to invisible inside the min transition gap. This conflicts with the hard requirement that presence be online whenever typing is sent."},{"id":"FLAG-002","concern":"Gateway lifecycle: The plan does not define what typing paths must do when the Gateway sender is detached during reconnect, even though typing is sent over REST and presence updates require the active websocket.","category":"completeness","severity_hint":"likely-significant","evidence":"In the repository, and call REST typing independently of . The plan says to when exits and to force online before low-level typing, but it does not require to wait for a sender, fail closed, or suppress the typing indicator when no Gateway websocket is attached. During a reconnect, direct sends could still emit Discord typing while the manager cannot send opcode 3 first."}],"verified_flag_ids":[],"disputed_flag_ids":[]}
Discord currently keeps a persistent Gateway websocket in app/services/discord.py, identifies without an explicit presence, and therefore appears online/green for the whole connected session. That connection must stay up so DMs remain reliable; the fix should change Gateway presence, not disconnect the bot.
Presence is global to the bot, so the manager should maintain global “holds” rather than per-DM state. Typing paths acquire an online hold before calling Discord typing and keep it through the expected visible typing window plus a short tail. Non-typing activity can request softer, delayed transitions so the bot feels present during conversation without flapping on every message.
The execute phase should write this plan document to docs/discord-presence-pacing-plan.md exactly.
Add a small manager in app/services/discord.py near DiscordGatewayBot, or a dedicated app/services/discord_presence.py if the class makes discord.py too large.
Constructor dependencies should be injectable for deterministic tests: settings, send_json or websocket sender, sleep, now, and random.Random/uniform.
State model:
default: invisible/offline-looking baseline.
online_hold: hard online until a deadline; used for typing and send-critical work.
soft_online: optional believable activity window for inbound/reaction/send tails.
attach_sender(send_json) when the websocket connects.
detach_sender() on reconnect/close.
initial_presence_payload() for Identify.
typing_started(visible_s=None) or hold_online(reason, min_until) before any typing API call.
message_received() for inbound DM soft online window.
message_sent() for after-send tail.
reaction_sent() for reaction tail.
close() to cancel background tasks.
Internally, recompute desired status from active holds and schedule one delayed downgrade to default. Avoid one task per event when a single reschedulable downgrade task works.
Do not emit redundant presence updates when desired status already matches current_status.
In docs/discord-presence-pacing-plan.md, include the state machine table:
Event
Desired behavior
Gateway connect
Identify as invisible; stay connected.
Inbound DM
Maybe go online after bounded jitter for a short window, unless already online.
Bot typing pulse
Force online before send_typing; hold through visible typing plus tail.
Thinking/composing typing loop
Maintain hard online hold across pulses.
Send message
Stay online for randomized after-send tail, then return invisible.
Reaction-only response
Brief online tail around reaction, without long green presence.
Update DiscordGatewayBot.__init__ to accept presence_manager: DiscordPresenceManager | None.
In _run_once, include presence_manager.initial_presence_payload() in Identify when enabled.
After websocket connect, attach a sender that serializes presence update payloads to ws.send(json.dumps(payload)).
Detach the sender when _run_once exits so reconnects cannot write to a stale websocket.
On close, close the manager after cancelling heartbeat.
In app/main.py, create one presence manager when Discord provider is enabled and pass it to both DiscordGatewayBot and DiscordPacer.
In docs/discord-presence-pacing-plan.md, call out that presence manager ownership follows the Gateway connection because presence updates require the active websocket.
Ensure perform_initial_typing_until_stopped, perform_thinking_typing_until_stopped, final answer typing, and incremental typing all inherit the guarantee through _send_bot_typing_pulse.
Update low-level discord.send_text(..., send_typing_indicator=True) so fallback/direct sends also force online before send_typing(channel_id) and call message_sent() after a successful send. Prefer routing through the same manager rather than duplicating logic.
If module-level send_text cannot receive the app-owned manager cleanly, add a module-level setter used during startup and reset during shutdown; keep all presence decisions inside the manager.
In docs/discord-presence-pacing-plan.md, explicitly state the invariant: no code path may call Discord typing without first acquiring an online presence hold.
On accepted partner DM in _handle_message, call presence_manager.message_received() before process_inbound or immediately after validation.
On add_reaction, call reaction_sent() around a successful reaction. Keep the actual reaction sparse policy in DiscordPacer; presence should only represent the transport activity.
On successful send_text, call message_sent() after rest.send_message(...).raise_for_status().
Avoid changing pacing decisions (wait, react, silence, answer) in this phase; presence should observe those outcomes.
In docs/discord-presence-pacing-plan.md, document the global-presence caveat: one DM’s typing can make the bot online for everyone, so holds must be short and bounded.
Step 7: Add deterministic unit tests (tests/test_discord.py, tests/test_pacer.py, tests/test_main_startup_pacing.py, docs/discord-presence-pacing-plan.md)
Scope: Medium
Test initial Identify includes invisible presence while still connecting and receiving events.
Test DiscordPresenceManager does not send duplicate presence updates for repeated inbound events inside the min transition gap.
Test typing guarantee: _send_bot_typing_pulse sends online presence before typing.
Test typing hold prevents immediate downgrade until typing visible duration plus tail expires.
Test after-send tail uses bounded randomness with an injected deterministic random source.
Test direct send_text(send_typing_indicator=True) forces online before low-level typing; send_typing_indicator=False should not create a typing hold but should still apply after-send tail after successful send if presence is enabled.
Test reaction-only path applies a short tail without changing reaction policy.
Update docs/discord-presence-pacing-plan.md with the test matrix and commands.
Add rollout notes to docs/discord-presence-pacing-plan.md:
Deploy with DISCORD_PRESENCE_ENABLED=true in staging first.
Confirm Gateway Identify succeeds and no reconnect loop appears.
Observe logs for presence update failures and websocket reconnect behavior.
Manual smoke: bot appears offline while idle, turns online before visible typing, remains online while typing, and returns offline after the after-send tail.
Keep a fast rollback: set DISCORD_PRESENCE_ENABLED=false, leaving Discord pacing and DM ingestion intact.
Execution Order
Update settings and tests first; this gives clear bounds before behavior changes.
Add DiscordPresenceManager in isolation with injected time/random/sender.
Wire the manager into Gateway Identify and presence update sends.
Wire typing paths next, because “online whenever typing” is the hard invariant.
Add softer inbound/send/reaction transitions after the typing guarantee is proven.
Finish by writing and verifying docs/discord-presence-pacing-plan.md exactly at that path.
Validation Order
Run focused unit tests for config and the presence manager’s state transitions.
Run transport tests that assert websocket Identify and presence update payload ordering.
Run pacer tests that assert online precedes typing.
Run startup wiring tests to prove one manager is shared by Gateway and pacer.
Run the full suite.
Risks
Discord may rate-limit excessive presence updates. Mitigation: suppress duplicates, use min_transition_gap_s, and schedule downgrades instead of toggling per event.
Presence is global, not per-DM. Mitigation: short bounded holds and one centralized state machine.
If a websocket reconnects during a delayed downgrade, a stale task might send to the old socket. Mitigation: sender attach/detach with a generation token.
If low-level direct sends bypass DiscordPacer, typing could appear while invisible. Mitigation: wire send_text/send_typing through the same manager or add tests that fail on this ordering.
If invisible is rejected by Discord for a bot Identify or update, fallback should be a config-only rollback, not disconnecting the Gateway.
Questions
Should the default status be strictly invisible, or is idle acceptable if Discord ever rejects bot invisible updates?
Should scheduled/proactive messages use the same after-send online tail, or should only live DM conversations affect presence?
Should operators see presence transitions in logs, or is test coverage plus Discord behavior enough?
Assumptions
The bot can send invisible in Identify and Gateway Presence Update payloads, based on Discord’s official Gateway docs.
Staying connected to the Gateway while invisible preserves DM receipt reliability.
Presence behavior should only apply when MESSAGING_PROVIDER=discord; other providers remain unchanged.
No database migration is needed because this is runtime state and configuration only.
The existing pacing_events table remains for conversation pacing decisions; presence transitions can be logged but do not need persistence.
Success Criteria
See the structured success_criteria field for reviewer-verifiable gates.
code
Plan metadata:
{
"version": 1,
"timestamp": "2026-05-02T00:58:02Z",
"hash": "sha256:997a404bc593b1fcf3175573eb57c3f8cf87dd4fb179ddae7d49ef3b0d5abc17",
"questions": [
"Should the default status be strictly invisible, or is idle acceptable if Discord ever rejects bot invisible updates?",
"Should scheduled/proactive messages use the same after-send online tail, or should only live DM conversations affect presence?",
"Should operators see presence transitions in logs, or is test coverage plus Discord behavior enough?"
],
"success_criteria": [
{
"criterion": "docs/discord-presence-pacing-plan.md is authored exactly at that path and describes Gateway Identify presence, opcode 3 presence updates, the centralized manager, rollout, and rollback.",
"priority": "must",
"requires": [
"read_files"
]
},
{
"criterion": "Gateway Identify includes an explicit default non-green presence when Discord presence is enabled, while the persistent websocket remains connected for DM ingestion.",
"priority": "must",
"requires": [
"parse_diff",
"run_tests"
]
},
{
"criterion": "Every bot typing path covered by tests acquires or sends an online presence update before calling Discord typing.",
"priority": "must",
"requires": [
"parse_diff",
"run_tests"
]
},
{
"criterion": "Presence transitions are centralized in a manager with injectable clock, sleep, and randomness or equivalent deterministic seams for unit tests.",
"priority": "must",
"requires": [
"parse_diff",
"run_tests"
]
},
{
"criterion": "Repeated inbound/activity events do not produce duplicate or mechanically flapping presence updates inside the configured minimum transition gap.",
"priority": "must",
"requires": [
"run_tests"
]
},
{
"criterion": "Idle/no-conversation state returns to invisible/offline-looking status after bounded tails expire.",
"priority": "must",
"requires": [
"run_tests"
]
},
{
"criterion": "Inbound message, typing/composing, send success, reaction success, and after-send tail behaviors are covered by focused tests.",
"priority": "must",
"requires": [
"run_tests",
"parse_diff"
]
},
{
"criterion": "Targeted Discord/config/pacer/startup tests pass.",
"priority": "must",
"requires": [
"run_tests"
]
},
{
"criterion": "The implementation keeps presence settings bounded and documented with sane defaults.",
"priority": "should",
"requires": [
"read_files",
"parse_diff"
]
},
{
"criterion": "The manager avoids persisting presence state to the database unless a concrete operational need appears.",
"priority": "should",
"requires": [
"parse_diff",
"subjective_judgment"
]
},
{
"criterion": "Manual staging smoke confirms the bot appears offline while idle, online before/during typing, and offline again after the tail.",
"priority": "info",
"requires": [
"verify_physical_device",
"observe_runtime_logs"
]
}
],
"assumptions": [
"The bot can send invisible in Identify and Gateway Presence Update payloads, based on Discord\u2019s official Gateway docs.",
"Staying connected to the Gateway while invisible preserves DM receipt reliability.",
"Presence behavior should only apply when MESSAGING_PROVIDER=discord; other providers remain unchanged.",
"No database migration is needed because this is runtime state and configuration only.",
"The existing pacing_events table remains for conversation pacing decisions; presence transitions can be logged but do not need persistence."
],
"structure_warnings": []
}
code
Plan structure warnings from validator:
[]
Existing flags:
[]
Known accepted debt grouped by subsystem:
{}
Escalated debt subsystems:
[]
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.
code
Your output template is at: /Users/user_c042661f/Documents/Veas/.megaplan/plans/create-a-light-but-high-20260502-0155/critique_output.json
Review the plan with a broad scope. Consider whether the approach is correct, whether it covers
all the places it needs to, whether it would break callers or violate codebase conventions,
and whether its verification strategy is adequate.
Place any concrete concerns in the flags array in the template file using the standard format
(id, concern, category, severity_hint, evidence). Leave checks as an empty array.
Workflow: read the file → investigate → read file again → add findings → write file back.
code
Additional guidelines:
- Robustness level: light. Be pragmatic. Only flag issues that would cause real failures. Ignore style, minor edge cases, and issues the executor will naturally resolve.
- Over-engineering: prefer the simplest approach that fully solves the problem.
- Reuse existing flag IDs when the same concern is still open.
- `verified_flag_ids`: list flag IDs from prior iterations that the revised plan actually resolves (e.g., if the plan was revised to fix FLAG-001, and you confirm the fix is correct, include "FLAG-001"). Only include flags you've verified — don't guess.
- Verify that the plan follows the expected structure when validator warnings or the outline suggest drift.
- Additional flags may use these categories: correctness, security, completeness, performance, maintainability, other.
- Focus on concrete issues, not structural formatting.
app/services/discord.py::send_text
app/services/pacer.py::_send_bot_typing_pulse
DiscordGatewayBot._run_once
detach_sender()
_run_once
typing_started
“You are already running inside the megaplan harness for this step. Do the requested….” Conversation with gpt-5.5, from the Peter O’Mallet DataClaw Conversations dataset. The Chat Archive, 2026. https://thechatarchive.com/c/01m80eqegjqq86waz28p6m9hh6