Manifest parity · team-rocket-sop-manifest.json

Alloy platform · Team Rocket Grant

Team Rocket Bot — Standard Operating Structure

End-to-end flow: user input → entitlement → context → agentic loop → final output. Production runtime is Python in serverpilot-discord-bot/; the TypeScript stack in packages/bot/ mirrors the same pipeline. Team Rocket Grant (Discord persona Grunt).

Product identity: Team Rocket Grant is the Discord product name. Grunt is the engineering/runtime nickname. Production code lives in serverpilot-discord-bot/. Primary handler: cogs/chatops.py.

1. Identity Layer (Always On)

Before any message is processed, Grunt carries a fixed Team Rocket persona:

SurfacePath
Live system promptdata/persona.md
Master templatetemplates/team-rocket-master-prompt.md
Hardcoded fallbackcogs/chatops.py_PERSONA_DEFAULT

Operating rule: Grunt is a Team Rocket operative — theatrical, in-character, not a corporate assistant. Admin work still happens via tools, but voice stays in character. Persona is injected during Phase 7 — Context build as the base system layer.

2. Input Surfaces (How a Run Starts)

A run starts when Discord delivers a signal the bot is configured to accept.

flowchart TD
    U[User signal] --> D[Discord Gateway]
    D --> B[bot.py → ChatOps]
    B --> G{Listen gate}
    G -->|no match| X[Ignore]
    G -->|match| P[Pipeline]

Guild chat (on_message)

The bot responds only when at least one trigger matches:

TriggerCondition
@mentionBot user is mentioned
ReplyUser replies to a bot message
Name-dropBOT_NAME in text (default: Grunt)
Watched userAuthor ID in WATCHED_USER_IDS

Also accepted: text + image attachments, or reply-chain images.

Other entry points

EntryBehavior
/ask slashSame pipeline as guild chat; no listen gate
DMs (no guild)Consulting discovery handler — not main harness path

Dropped signals

  • Bot messages
  • Empty prompts with no images (except watched-user rules)
  • Non-members when entitlements apply
  • Messages that fail the listen gate

3. End-to-End Pipeline (Happy Path)

sequenceDiagram
    participant User
    participant Discord
    participant Listen
    participant Entitle
    participant Respond
    participant Context
    participant Harness
    participant Agentic
    participant LLM
    participant Tools
    participant Output

    User->>Discord: message / attachment / /ask
    Discord->>Listen: on_message
    Listen->>Entitle: tier + quota
    Entitle->>Respond: _respond_inner
    Respond->>Respond: image fast path? (optional)
    Respond->>Context: build_context + pick_tools
    Respond->>Harness: session + trace route
    Respond->>Agentic: _run_agentic
    loop until done
        Agentic->>LLM: chat + tool schemas
        LLM-->>Agentic: text and/or tool_calls
        Agentic->>Tools: _dispatch
        Tools-->>Agentic: results
    end
    Agentic->>Output: plain-text reply + trace embeds

4. Phase Map

#PhaseWhat happensStop condition
0Gateway ingestdiscord.py delivers message to ChatOps.on_messageBot author → stop
1Listen gateCheck mention / reply / name-drop / watchedNo trigger → ignore
2Entitlement gateResolve tier from roles; check daily/monthly quotaQuota exceeded → quota embed
3Prompt extractionStrip mentions; merge reply-chain image URLsEmpty + no images → stop
4Session key(guild_id, channel_id, user_id); thread reply may bind existing harness session (I2)
5Image fast pathRegex detects explicit generate/edit → OpenAI image APIHandled → image embed, skip LLM
6Tool selectionKeyword router picks tools; tier / plan-mode / owner filtersWatched → zero tools
7Context buildAssemble system prompt layers (see §5)
8Harness bindTrace route; grunt-work + mirror threads; run_started to control planeSkipped for watched users
9Agentic loopMulti-turn LLM ↔ tool cycleFinal text or max turns
10OutputPlain-text reply + progressive trace embeds
11PersistenceSession history, harness JSON, usage metering, CP events

5. Permission Branching

flowchart LR
    M[Message] --> W{Watched?}
    W -->|yes| WC[OpenAI chat-only
no tools, no harness] W -->|no| E[Entitlement gate] E --> T{Tier} T --> O[Owner: all tools, bypass quota] T --> A[Admin: 2/day] T --> B[Booster: 10/day] T --> D[Default: 1/week] O & A & B & D --> F[filter_tools_for_tier] F --> DIS[_dispatch gates]
TierQuotaTools
OwnerBypassAll groups + host control + harness full mode
Admin2/dayMessaging, discord_admin, …
Booster10/dayKnowledge, media, utility
Default1/weekKnowledge, media only
  • Harness full mode (orchestrator, host tools, /harness) → owner-only, regardless of tier
  • Watched users (I3) → forced chat-only: OpenAI, no tools, no harness, no trace threads

6. Context Assembly (What the LLM Sees)

build_context() in cogs/_context.py stacks layers in order:

  1. Persona — Team Rocket Grunt system prompt (persona.md)
  2. Provider awareness — which model/provider is active
  3. Library blocks — topical recall from configured library channels (I4)
  4. Long-term memory — facts from bot-remember / memory file
  5. Session history — prior turns (compacted if near context limit)
  6. Current user message — text + optional vision image blocks

Tool schemas are attached only when use_tools is on and the user is not on the watched path.

7. Agentic Loop (Core Reasoning Engine)

When use_agentic_loop + tools are enabled:

┌─────────────────────────────────────────┐
│  1. LLM call (system + history + tools) │
│  2. Parse response: text + tool_calls?  │
│  3. If tool_calls:                      │
│     a. Optional confirmation gate       │
│     b. _dispatch each tool              │
│     c. Append results to message history│
│     d. Stream progress to trace embeds  │
│  4. Repeat until no tool_calls or cap   │
│  5. Return final_text                   │
└─────────────────────────────────────────┘

Dispatch enforcement stack (bottom → top)

LayerCheck
1Entitlement tier filter
2Owner gate (host / MCP / destructive ops)
3tool_config.json (enabled, locked params, needsApproval)
4Harness lane policy (specialist allowlists)
5Confirmation gate (_ConfirmView)
6Execute (Discord admin · host · project · MCP · web · images)
7Audit log + control-plane step event

LLM routing (LLMRouter)

NeedDefault provider
ChatDeepSeek
Vision (images in message)OpenAI (auto-reroute)
Image generate/edit (fast path or tool)OpenAI

Sub-agent branch (owner harness)

When orchestrator is active:

flowchart LR
    COORD[Coordinator _run_agentic]
    ORCH[SubAgentOrchestrator.plan_lanes]
    L1[network-engineer lane]
    L2[security-expert lane]
    SYN[synthesize]
    COORD --> ORCH
    ORCH --> L1
    ORCH --> L2
    L1 --> SYN
    L2 --> SYN
    SYN --> COORD

Each lane: read-only tools, ~1400 char output cap, optional forum trace thread via trace_lanes.py.

8. Trace & Observability (Parallel to the Answer)

For non-watched agentic runs, _resolve_trace_route (I1 — sole thread factory) creates:

ArtifactPurpose
Grunt-work threadForum post with full reasoning + tool progress
Mirror threadCondensed copy on the invocation message
Inline fallbackIf forum routing disabled

_TraceSession streams embeds: plantool_start / tool_donelane_spawn / lane_donesynthesisfinal.

Side channel (non-blocking): HarnessManager POSTs run events to control plane at 127.0.0.1:8787 for Agent Studio / dashboard. Failure does not block the Discord reply.

9. Output Surfaces (What the User Receives)

Output typeWhenWhere
Plain-text replyAlways (primary answer)Invocation channel — reply to user
Trace embedsAgentic run with trace routeGrunt-work forum + mirror thread
Image embedFast path or image toolsInvocation channel
Quota embedEntitlement blockInvocation channel
Confirmation promptDestructive / approval-gated toolsInvocation channel (approve/deny buttons)

Final answer rule: Grunt's in-character text is posted separately from trace machinery — users see the personality; operators see the work log.

10. Alternate Paths (Branch Summary)

Branch summary — all optional routes from user input to Discord output:

flowchart TD
    IN[User input] --> L{Listen?}
    L -->|no| DROP[Ignore]
    L -->|yes| W{Watched?}
    W -->|yes| OAI[OpenAI single-turn chat]
    W -->|no| Q{Quota OK?}
    Q -->|no| QE[Quota embed]
    Q -->|yes| IMG{Image fast path?}
    IMG -->|yes| IE[OpenAI image API → embed]
    IMG -->|no| AG{Agentic + tools?}
    AG -->|yes| LOOP[Agentic loop]
    AG -->|no| CHAT[Single-turn chat]
    OAI & LOOP & CHAT & IE --> OUT[Discord output]

11. Persistence After Output

StoreWhatPath
Session historyLast N turns per (guild, channel, user)In-memory SessionStore
Harness sessionsThread bindings, run IDs, lane statedata/harness/sessions.json
Usage meteringTier quota countersEntitlements store
Host auditShell/file commandsdata/host_audit.json
Tool configPer-tool enable/lock/approvaldata/tool_config.json
PersonaLive Grunt voicedata/persona.md

Thread continuity (I2): Replying inside a bound harness thread continues the same session without resetting context.

12. One-Page Operator Checklist

Normal @mention in guild chat

  1. User addresses Grunt (mention, reply, or name-drop)
  2. Bot checks tier/quota
  3. Bot picks tools by intent + tier
  4. Bot loads Team Rocket persona + library + memory + history
  5. Bot opens trace threads (if agentic)
  6. LLM thinks in character, calls tools as needed
  7. User gets Grunt's plain-text reply
  8. Operators see full trace in grunt-work forum
  9. Session + harness state saved for next turn

Chat-only (no admin)

User asks a casual question → keyword router sends minimal/no tools → single or short agentic loop → text reply only.

Admin action

User asks to create channel / assign role / etc. → full tool schemas → confirmation if destructive → tool executes → Grunt complains in character, reports result.

13. Key Files (Source of Truth)

RolePath
Entry + listen gateserverpilot-discord-bot/cogs/chatops.py
Entitlementsserverpilot-discord-bot/cogs/_entitlements.py
Context / personaserverpilot-discord-bot/cogs/_context.py
LLM routingserverpilot-discord-bot/cogs/_llm_router.py
Harnessserverpilot-discord-bot/cogs/_harness/manager.py
Team Rocket promptserverpilot-discord-bot/templates/team-rocket-master-prompt.md
Dev walkthroughbrain/01-Developer-Guide/02 — Message Flow Walkthrough.md
Signal pipeline specdocs/investor/TrainerLabs-Signal-Pipeline.md