# Prompt System — Design Notes & Decisions Notes from the initial build of the prompt system (March 2026). ## Architecture Decisions ### Source → Compile → Include pipeline We have a two-stage pipeline for platform documentation: 1. **Sources** (`docs/developer-guide/` at project root) — raw platform docs, maintained directly in the repo 2. **Compiled** (`compiled/`) — distilled fragments optimized for agent consumption 3. **Template** (`index.ts`) — assembles everything into the final prompt Compiled fragments are generated in a human-in-the-loop LLM session and committed to git. The compilation step lets us optimize for the agent audience without cluttering the source docs. ### Compilation is manual and sequential The `compiled/README.md` has detailed instructions for the LLM doing compilation. Key rules: - Work through one source file at a time, sequentially - Present each draft for review before moving on - Preserve specifics when condensing — examples, edge cases, and enumerated constraints are the highest-value content. "Ensure data integrity, including checking for duplicate keys and null foreign references" should NOT become "ensure data integrity" - Manual sources (design notes, media CDN) are already prompt-ready and may go in nearly as-is ### Prompt section ordering Based on Anthropic's long-context research and analysis of Claude Code / Codex / Cursor prompts: 1. **Identity** (top — primacy effect, anchors persona) 2. **Reference docs** (bulk — platform docs, SDK, MSFM, project context) 3. **Behavioral instructions** (bottom — recency effect, 30% improvement per Anthropic) The model attends most strongly to the beginning and end (U-shaped curve). Large reference docs go in the middle where they're available for lookup. Actionable instructions go at the end where the model follows them most precisely. ### XML tags for structure All reference doc blocks are wrapped in descriptive XML tags (``, ``, etc.) per Anthropic's guidance. Claude is specifically tuned to attend to XML structure. Each compiled fragment gets its own inner tag (``, ``, ``, etc.) for clear delineation. ### Template system The prompt builder uses a simple `{{filename}}` include syntax resolved by a single regex. Dynamic parts (project context, phase flag, LSP conditional) use standard JS template literals. No handlebars library, no condition blocks — just string interpolation + file includes. All static/compiled files are loaded with `requireFile` which throws on missing files. Only project-level context (CLAUDE.md, mindstudio.json, file listing) uses soft loading since those depend on the working directory. ## Research-Informed Decisions ### Prompt engineering for coding agents From extensive research into Claude Code, Codex, Cursor, Aider, and academic papers: - **Negative instructions perform worse than positive ones.** "Don't add comments" activates "adding comments." We rewrote all negatives as positive directives. - **Tool-specific guidance belongs in tool descriptions, not the system prompt.** Avoids duplication and keeps the prompt focused on principles. - **The "AI Purple Problem"** — LLMs converge on generic aesthetics (Inter font, purple gradients, three-boxes-with-icons layout). The design fragment explicitly calls these out as anti-patterns and pushes for distinctiveness. - **Examples in prompts are high-value but expensive.** We keep code examples in the compiled fragments (the agent copies patterns directly) but removed style/formatting examples from the base instructions. ### LSP tool simplification Research showed agents rarely use position-dependent LSP tools (definition, references, hover, symbols) — they require knowing the file and line first, which means the agent already read the file. We slimmed down to just `lspDiagnostics` (with code actions for suggested fixes) and `restartProcess`. ### Design quality prompting From research into v0, Lovable, Bolt, and Anthropic's `` cookbook: - LLMs converge on the statistical median of training data — explicitly override generic defaults - Specific avoidance lists work: ban generic fonts, purple gradients, predictable layouts - Committed color palettes beat timid even distribution - Typography is the single fastest way to give an interface identity - The design fragment references iOS, Stripe, Notion, Linear as quality benchmarks and Dribbble/Behance/Mobbin as visual standards ## SDK Usage The canonical import pattern for app methods is `import { mindstudio } from '@mindstudio-ai/agent'` with `mindstudio.generateText(...)`, `mindstudio.runTask(...)`, etc. The `mindstudio` singleton handles auth automatically. `new MindStudioAgent({ apiKey })` is only for external usage outside an app. The SDK ships `llms.txt` at the package root with full signatures for all 170+ actions. The compiled fragment references this path (`dist/methods/node_modules/@mindstudio-ai/agent/llms.txt`) so the agent knows where to look up specific action details. ## Behavioral Instruction Architecture (March 21, 2026) ### Splitting behavioral instructions by concern The original `instructions.md` was a catch-all for workflow, principles, communication, verification details, log paths, and coding conventions. It was overloaded — too many concerns in one file, which likely diluted the signal on individual rules. We split into three behavioral files in the recency zone (bottom of the prompt): - **`intake.md`** — intake mode behavior (already existed) - **`authoring.md`** — spec authoring behavior (already existed) - **`coding.md`** — code authoring behavior (new) - **`instructions.md`** — workflow, general principles, communication style (trimmed) The parallel between `authoring.md` (how to write specs) and `coding.md` (how to write code) is intentional. Two distinct disciplines, two files. ### XML tags vs. bare markdown for behavioral sections The behavioral instruction files at the bottom of the prompt are wrapped in XML tags (``, ``, ``) — except for `instructions.md`, which is left as bare markdown at the very end. The reasoning: XML tags create a subtle framing of "here's a reference block to consult," while bare text at the terminal position reads more like direct commands. Leaving `instructions.md` unwrapped may give it additional weight on top of the recency effect. This is a hypothesis worth testing, not a proven fact. The LSP guidance (`lsp.md`) is nested inside `` since it's only relevant during code work. ### Verification calibration: the 80/20 problem The agent was going overboard on post-build verification — screenshotting every page, running browser tests on every flow, being extremely thorough when "mostly working" would be sufficient. The issue was that `instructions.md` listed every verification tool with guidance on when to use each one, which the agent interpreted as "use all of these after every build." The fix was moving verification guidance to `coding.md` with an explicit 80/20 framing: spot-check the main happy paths, and if those work, trust that the edges are probably fine. The user can surface issues in chat. `runAutomatedBrowserTest` is reserved for interactive flows that can't be verified from a screenshot, or when the user reports something broken. This reframes the default posture from "verify everything" to "verify the critical path." ### Mandatory SDK tool usage for model IDs The agent was guessing model IDs when writing code that calls AI models via the MindStudio SDK. Model IDs change frequently across providers (OpenAI, Anthropic, Google, etc.) and plausible-looking IDs are often wrong. The fix was three-layered: 1. **`coding.md`** — hard rule in the behavioral instructions (recency zone): always use `askMindStudioSdk` before writing any SDK code, with expanded guidance on preferring the SDK over custom API connectors 2. **`askMindStudioSdk.ts` tool description** — strengthened to frame model ID lookup as mandatory, not optional 3. **`sdk-actions.md`** — existing mentions kept as reinforcement (middle zone, lower attention, but contextually relevant when the model is looking at SDK reference) The redundancy across three locations is intentional. The model might skip the behavioral instruction, or might not consult the reference docs, but the tool description is right there at decision time when it's choosing whether to call the tool or guess. ### Negative vs. positive instruction framing — a more nuanced take Our initial research said "negative instructions perform worse than positive ones" and we rewrote all negatives as positives. After further discussion, the picture is more nuanced. There are two distinct mechanisms: **Case 1: Tendencies the model already has.** Overengineering, gold-plating, verbose output, adding unnecessary abstractions. The model is already inclined to do these things. Naming them in a negative instruction ("don't overengineer") activates the exact concept you're trying to suppress, but the concept was already active anyway. The real issue here is that negative framing is weaker than positive framing — "keep solutions minimal" gives the model something to aim for, while "don't overengineer" only says what to avoid. **For ingrained tendencies, prefer positive framing** because the activation cost is zero (already activated) and the positive frame gives better behavioral guidance. **Case 2: Specific things the model wasn't considering.** "Don't use regex backtracking," "don't use xyz-framework." If the model wasn't going to reach for this concept, mentioning it introduces it into the context window and primes the model to consider it. This is the classic "don't think about elephants" problem. **For things the model wouldn't do unprompted, don't mention them at all.** **The exception to Case 2: common defaults the model gravitates toward.** Purple gradients, Inter font, three-box-with-icons layouts, `useEffect` for data fetching. These are statistical medians from training data that the model will produce unprompted. Naming them as anti-patterns is worth the activation cost because they were going to happen anyway. This is why the design fragment's avoidance list works. **Where we landed on overengineering in `coding.md`:** We use a hybrid approach — lead with the positive directive ("match the scope of changes to what was asked, solve the current problem with the minimum code required") then follow with specific negative examples that draw bright lines ("a bug fix is just a bug fix, not an opportunity to refactor the surrounding code"). The negatives here aren't introducing new concepts; they're pushing back against things the model was already going to do. ### Efficiency: avoiding redundant exploration Coding agents waste significant context and tool calls re-reading files they've already seen or re-researching things a subagent already looked up. We added a principle to `instructions.md`: "Work with what you already know." This applies broadly (spec work, intake, coding) so it lives in the general principles rather than `coding.md`. The framing is positive ("prefer acting on information you have") rather than negative ("don't re-read files"). This was inspired by similar guidance in Claude Code's own system prompt, which is explicit about not duplicating work that subagents have done and not re-reading files unnecessarily. ## Sub-Agent Architecture (March 2026) ### The team model Remy delegates to specialized sub-agents rather than trying to do everything itself. A dedicated `static/team.md` file in the main prompt establishes the mental model: "you have specialists, use them liberally." This was consolidated from scattered guidance that was previously in `coding.md`, `authoring.md`, `sdk-actions.md`, and tool descriptions. The key insight: tool descriptions should say "what I do" while `team.md` says "when and why to reach for me." The model needs to already be thinking about delegation before it reads tool descriptions — otherwise it just writes code without considering whether a specialist should handle it. The intro framing ("you have a lot on your plate") gives the model permission to not be good at everything. This is more effective than saying "you're bad at design" — it reframes delegation as smart workload management rather than admitting weakness. ### Sub-agent roster | Agent | Role | Tools | Context | |---|---|---|---| | `productVision` | Roadmap ownership & product strategy | writeRoadmapItem, updateRoadmapItem, deleteRoadmapItem | Spec files + current roadmap | | `sdkConsultant` | MindStudio SDK architecture | None (shells out to `mindstudio ask` CLI) | None (external agent) | | `codeSanityCheck` | Pre-build review | readFile, grep, glob, searchGoogle, fetchUrl, askMindStudioSdk, bash (readonly) | Spec files | | `browserAutomation` | Interactive UI testing | browserCommand, screenshotFullPage, setupBrowser | None (interacts with live preview) | ### Shared infrastructure - `subagents/common/context.ts` — shared `loadSpecContext()` and `loadRoadmapContext()` loaders. Used by designExpert, productVision, and codeSanityCheck. - `subagents/runner.ts` — shared `runSubAgent()` loop with retry logic (uses `streamChatWithRetry`). ### Product vision: third-person prompt experiment The product vision agent uses third-person construction ("The role of the assistant is to act as...") instead of second-person ("You are..."). This is a deliberate workaround for RLHF training that makes models defer to user-stated scope. The third-person framing creates a role-play context where the model is more willing to go beyond what was asked. Combined with three layers of separation from the user (sees spec files not chat, gets brief task from Remy, operates in RP mode), this produces dramatically more ambitious roadmap ideas. ### Code sanity check: "checked-out staff eng" energy The sanity check agent is deliberately low-energy. Its prompt says "lgtm" is a complete response and to let most things slide. This prevents it from becoming a bottleneck or scope-creeper. The only things it flags: outdated packages (via web search), missed SDK managed actions, schema decisions that paint into corners, and file organization that's gotten unwieldy. Tech debt is explicitly called out as normal and sometimes useful in fast-moving products. ### Design expert: runtime-sampled data The design expert's prompt is dynamically assembled per invocation. It samples 15 random fonts + 5 pairings from the Fontshare catalog and 5 random pre-analyzed design inspiration screenshots from Godly. This prevents the model from developing favorites and ensures it considers different options each time. ## Network Resilience (March 2026) Added retry with backoff, streaming stall timeout, friendly error messages, and external tool timeout. See `api.ts` (streamChatWithRetry), `errors.ts` (friendlyError), `headless.ts` (tool timeout), `statusWatcher.ts` (dynamic status labels). ## Roadmap Spec Type (March 2026) New `type: roadmap` for MSFM files in `src/roadmap/`. Each item has frontmatter (name, status, description, effort, requires) and freeform MSFM body. The product vision sub-agent owns this directory. Frontend derives the tree from `requires` fields. ## Other Changes (March 2026) - **Automated message sentinel** — `@@automated::{tag}@@` prefix on user messages, stripped before sending to LLM. Frontend uses for custom rendering. - **Project naming** — `setProjectName` tool for setting display name after intake. - **Dynamic status labels** — `statusWatcher.ts` periodically calls a lightweight endpoint to generate descriptive labels during agent work. - **Asset bundling** — `tsup.config.ts` copies .md/.json/.sh files from src/ to dist/ on build. ## What's Not Done - **Streaming tool output** — writeSpec and editSpec are tagged as streaming candidates but execute with full input for now. Deferred until the platform API supports streaming tool input fields. - **Auto-diagnostics after edit** — could auto-run lspDiagnostics after editFile/writeFile and append errors to the tool result. Depends on sidecar latency. ### Removed: compile/recompile tools We removed the compile and recompile tools. Instead of a separate "compile" step, the flow is: intake conversation → write spec → pause for user review → build everything in one turn using the spec as the master plan. The agent writes methods, tables, interfaces, and manifest updates directly, guided by the spec. No separate compiler agent needed.