AI Agent Control Protocols: The Missing Link in LLM Engineering

AI Agent Control Protocols: The Missing Link in LLM Engineering
AI Agent Control Protocols: The Missing Link in LLM Engineering
Introduction: Why Control Matters in LLM Engineering
When you invoke an AI model to help with software development, whether you're working with a powerful system like Claude Opus 4.5 or Gemini 3, or something more modest like GLM-4.7 or minimax-m2.1, there's a fundamental tension that most developers simply accept as the cost of doing business. On one side of this tension, you have models that are incredibly intelligent and capable of creative problem-solving, but they tend to over-engineer solutions and make assumptions about your requirements that may not align with what you actually need. On the other side, you have smaller models that are fast and obedient but have limited context windows and require explicit guidance to perform at their best.
What makes this tension particularly problematic is that both ends of the spectrum share a common characteristic: without explicit protocols governing their behavior, they become unpredictable in ways that can seriously impact your productivity. When an AI model doesn't properly understand your project's context or your specific requirements, it might produce code that looks reasonable on the surface but completely misses the mark in terms of functionality, architecture, or maintainability.
The Real-World Cost of Unpredictable AI Behavior
The consequences of this unpredictability manifest in several painful ways that compound over time and across team members. You end up wasting significant time implementing solutions that don't actually solve the problem because the model made incorrect assumptions at the outset. This isn't just a minor inconvenience—it represents real productivity loss when you're waiting for code that never materializes correctly.
Beyond the direct time waste, you find yourself constantly course-correcting as you realize the output doesn't match your expectations. This creates frustration on both sides of the collaboration and slows down development significantly. When the model and human developer aren't properly aligned from the beginning, collaborations often fail entirely or require extensive rework before they succeed. Perhaps most insidiously, repeated misalignments erode trust in AI assistance until developers stop using tools that could actually help them.
The Solution: Context-First Protocol
A systematic way of structuring how an agent is briefed, rather than a guideline to keep in mind.
Core Philosophy
The approach I want to introduce here is what I've come to call the Context-First Protocol. This isn't a casual suggestion or a nice-to-have guideline—it's a systematic way of structuring how AI agents should behave when working on software projects, creating predictability where there was once chaos.
The core philosophy can be summarized in a straightforward sequence that becomes muscle memory once you practice it: Task Received → Read Context → Reiterate Understanding → Wait for Confirmation → Proceed. Every step in this sequence matters, and skipping any of them undermines the entire approach.
Why This Approach Works
The reason this protocol works so effectively stems from several key benefits that compound over time like interest in an investment account. Transparency is the first major benefit because the protocol requires the AI to explicitly state what it understood from your project's context, which means you're always aware of exactly what assumptions it's operating under rather than having to guess.
Alignment comes second because by requiring confirmation before proceeding, you ensure that both human and AI are working from the same understanding before any code gets written. This alignment isn't just theoretical—it manifests as fewer misunderstandings and less rework throughout every project.
Early error detection happens naturally in this process since misunderstandings get caught during the reiteration phase rather than after hours of implementation work has been wasted on incorrect assumptions. The emotional and practical cost of catching an error early is dramatically lower than catching it late, when you've already built features on top of flawed foundations.
Finally, quality assurance improves across the board but especially for less capable models that benefit enormously from having explicit verification requirements built into their workflow. These models don't need to guess what you want—they just need clear signals about whether they've understood correctly or not.
Implementing the Protocol: Phase-by-Phase
Phase 1: Gathering Project Context (Mandatory First Step)
When a task arrives, the agent should systematically read through your project's documentation files in order of priority. This means starting with any protocol files that define behavior expectations—these documents literally encode how you want AI to behave in your projects. After protocols come README files for project overview, which establish the basic vocabulary and architecture of what you're building. Finally, relevant documentation in your docs directory fills in the detailed specifics.
After reading these materials, the agent needs to analyze the specific request it received with careful attention to what it's actually being asked to accomplish. This analysis involves identifying what the core requirement is at its essence, mapping how this request connects to existing patterns in your codebase so you don't reinvent wheels or introduce inconsistencies, and determining which aspects of the task are clear versus which need further clarification based on what was found in the documentation.
The goal of all this reading and analysis is to build a mental model that accurately represents both what you're asking for and how it fits within your project's broader architecture. This mental model becomes the foundation for everything the AI does next, so it's worth investing time and attention here even when you're eager to start coding.
Phase 2: Reiterating Understanding (Mandatory Confirmation Step)
The second phase requires the agent to explicitly state its understanding back to you before proceeding with any implementation work. This isn't just a nice-to-have formality or an unnecessary check—it's a critical gate that prevents misaligned work from ever beginning on your codebase.
The format for this confirmation should include several specific elements woven together into coherent prose: a summary of what the task is asking for in plain language, a list of which files were read and what key information was extracted from each so you can verify its research, an explanation of how the agent interpreted the requirements based on that context showing its reasoning, an outline of the proposed implementation approach demonstrating it has a plan, and finally a direct question asking whether your understanding matches what it's describing.
This human input gate is essential to the protocol's effectiveness. The system absolutely must wait for your response before making any tool calls or proceeding further with analysis, planning, or coding. If you indicate that the understanding was incorrect in any way, the agent should update its interpretation based on your corrections and try again rather than pushing forward with wrong assumptions.
Supporting Protocols: Safe File Editing
When it comes to modifying code files, one rule rises above all others in importance because following it prevents catastrophic mistakes while violating it enables them: never use overwrite mode unless explicitly requested to do so. Overwrite mode completely replaces a file's entire content, which means anything not included in your new version gets deleted permanently from your repository.
The alternative is edit mode, which makes targeted changes that affect only the specific sections you intend to modify without touching surrounding code. This safety mechanism ensures that even if you're tired or distracted while making changes, you won't accidentally destroy work you've done elsewhere in the file.
Before making any edits at all, regardless of how small they might seem or how confident you feel about the change, you should read the entire file first. Reading only a portion gives you incomplete context and risks breaking content you never saw or understood. This practice protects against destructive changes that could set back your project significantly, requiring hours of recovery work.
Communication Standards: First Interaction Rule
Every single response from an AI agent following this protocol should begin by restating the current understanding of the task and context. There are no exceptions to this rule—you cannot ask questions first, you cannot proceed directly to planning or implementation without first demonstrating your understanding has been verified.
When providing solutions or implementations as part of the protocol, several practices maintain quality across all interactions. Always reference specific files that were analyzed so readers can verify claims about codebase state. Explain reasoning clearly based on project context rather than abstract principles that might apply differently in different projects. Show code blocks with complete file paths and line numbers so there's no ambiguity about what's being changed.
Anti-Patterns: What to Avoid
Understanding what doesn't work helps you recognize when the protocol is being violated. Skipping phase two entirely—failing to reiterate understanding before proceeding—is the single most critical violation of this protocol because it removes the human alignment check that prevents misaligned code from being written.
Asking questions about requirements before demonstrating your understanding puts cart before horse in a way that produces poor responses. Proceeding directly to implementation without any verification step guarantees you'll write code that doesn't match what was actually needed. Providing only generic summaries like "I read the files" without specific details demonstrates insufficient engagement with the material and gives you nothing to verify.
Benefits Across Model Tiers: Why This Matters for Your Stack
When you look at how different models benefit from this protocol, interesting patterns emerge that make it worth implementing regardless of what tools you're using. For smaller models like GLM-4.7 and minimax-m2.1, which have limited context windows but respond well to explicit instruction, the protocol provides clear boundaries that prevent them from underperforming due to uncertainty or ambiguity. They become consistently obedient tools rather than unreliable helpers that sometimes work brilliantly and sometimes fail completely.
For larger models such as Claude Opus 4.5 and Gemini 3, which are intelligent enough to over-engineer when given latitude, the protocol imposes constraints that keep them focused on actual requirements rather than adding features, complexity, or optimizations you never asked for. The explicit confirmation step gives you a chance to reel in scope creep before it becomes technical debt that must be maintained forever.
Implementation Checklist: Getting Started
If you're looking to implement this protocol in your own projects, working through these steps systematically will set you up for success over the long term. Start by creating an AGENTS.md file in your project root that documents these expectations clearly so every team member can reference them when working with AI tools.
Define each phase explicitly with the steps and outputs expected at each stage—this specificity prevents ambiguity from creeping into implementation. Add specific rules about safe editing to prevent destructive changes from happening accidentally, especially important as projects grow and codebases become complex. Include documentation of the tool hierarchy so developers know which tools to reach for in different situations without having to discover best practices through trial and error.
Finally, make sure to document anti-patterns specifically so your team understands what behaviors they should actively avoid rather than having to infer correct behavior only through positive examples that might not cover every edge case.
AGENTS.md
# AI Agent Behavior Guidelines
This document defines the behavior protocols and tool usage guidelines for AI agents working on the LeanZero website project.
---
## ⚠️ CRITICAL WARNING: MANDATORY REITERATION PROTOCOL ⚠️
**READ THIS FIRST: Before proceeding with ANY task, you MUST follow the Context-First Protocol.**
### The Most Important Rule in This Document:
**Every single interaction MUST begin with reiterating your understanding of the task.** There are NO exceptions.
- ❌ You cannot ask questions first
- ❌ You cannot proceed to planning first
- ❌ You cannot start implementation first
- ✅ You MUST reiterate your understanding first
### Why This Is Required:
1. **Transparency**: You must show what you actually understand from the context you gathered
2. **Alignment**: Ensures you and the human agent are on the same page before any work begins
3. **Early Error Detection**: Catches misunderstandings before time is wasted on incorrect approaches
4. **Quality Assurance**: Less capable models benefit from explicit verification of their understanding
### The Consequence of Violating This Rule:
- Wasted time on incorrect implementations
- Frustration for the human agent
- Failed collaborations
- Loss of trust in your capabilities
### What Happens If You Skip This Step:
The human agent cannot rely on your understanding. They must assume you may have misunderstood and will need to provide corrections after you've already done work that needs to be redone.
### Simple Formula for Success:
Task Received → Read Context → Reiterate Understanding → Wait for Confirmation → Proceed
**Do NOT skip the reiteration step. Ever.**
---
## PRIMARY DIRECTIVE: CONTEXT-FIRST PROTOCOL
This is your most important rule and overrides all others. Before any other action, you MUST follow this protocol.
### Phase 1: Gather Project Context (MANDATORY FIRST STEP)
Upon receiving a task from the human agent, your immediate and only first step is to gather sufficient project context by:
1. **Read Project Documentation Files** (in priority order):
- `AGENTS.md` - This file, understanding your behavior protocols
- `README.md` - Project overview and getting started information
- Relevant documentation files in `docs/` directory
- Any files specifically mentioned by the human agent
2. **Analyze the Request**:
- Identify the core requirement
- Map the request to existing project files or patterns
- Determine what information is already available vs. what's unclear
3. **Formulate Context-Based Understanding**:
- Base your understanding on actual project files you've read
- Reference specific files, line numbers, or code snippets when discussing requirements
- Build a mental model of how the change fits into the existing architecture
### Phase 2: Reiterate Understanding and Confirm (MANDATORY - NO EXCEPTIONS)
**CRITICAL: This phase is REQUIRED for EVERY task, regardless of complexity or simplicity.**
Before proceeding any further, you MUST reiterate what you learned from the context gathering phase and ask for confirmation. This is a non-negotiable step to ensure alignment and catch misunderstandings early.
**There are NO exceptions to this rule:**
- Even if the task seems simple
- Even if you think you understand perfectly
- Even if you've worked on similar tasks before
- Even if the human provided detailed instructions
You MUST always reiterate your understanding before asking questions or proceeding.
**Required Format for Reiteration:**
1. **Summary of Task**: Briefly restate what you've been asked to do
2. **Context Gathered**: List the specific files you read and key information extracted from each
3. **Your Understanding**: Explain how you understand the task based on the context
4. **Proposed Approach**: Outline your intended approach to completing the task
5. **Confirmation Request**: Explicitly ask if your understanding is correct
**Example Template:**
My Understanding of This Task
Task Summary: [Brief restatement of what you were asked to do]
Files I Read and What I Learned:
AGENTS.md: [Key insights about protocols and workflows]README.md: [Project overview and structure]src/app/services/[existing-service]/page.tsx: [Existing pattern for service pages]docs/CREATING-A-NEW-PAGE.md: [Guidelines for page creation]
My Understanding: Based on the context I've gathered, you want me to [what I understand the task to be]. The project follows [pattern/architecture], so I should [approach].
Proposed Approach:
- [First step based on patterns found]
- [Second step referencing specific files]
- [Third step following established conventions]
Is this understanding correct? Should I proceed with this approach, or would you like me to modify it?
**⚠️ HUMAN INPUT REQUIRED - DO NOT PROCEED UNTIL CONFIRMED**
After providing your reiteration with the confirmation request:
- You MUST wait for human response before any tool calls
- The system cannot proceed without explicit "correct" or corrections
**Critical Requirements:**
- ALWAYS include specific file names and line numbers when relevant
- Reference actual code snippets or documentation sections
**Valid Confirmations (proceed on):**
- "correct" / "proceed" / "yes"
- Corrections that update your understanding (then re-iterate)
- Clarifications that refine the task scope
**Invalid Confirmations (do NOT proceed on):**
- No response
- Questions from you without human answering first
### Consequence of Proceeding Without Confirmation:
If you make tool calls after reiteration without human confirmation:
- You have VIOLATED the Context-First Protocol
- The human cannot trust your understanding
- Work may need to be redone based on corrections
### Phase 3: Formulate Clarifying Questions (ONLY IF NEEDED - AFTER REITERATION)
**IMPORTANT: You MUST complete Phase 2 (reiteration) BEFORE asking any questions.**
**The Workflow:**
1. You reiterate your understanding (Phase 2)
2. You wait for human response
3. **If human says understanding is correct or provides corrections/clarifications on their own**: Proceed to Phase 4
4. **Only if human asks you to ask questions**: Then formulate clarifying questions
**Questions should ONLY be asked when:**
- The human explicitly asks you what questions you have
- The human indicates they need more information from you to proceed
- The human provides ambiguous or conflicting feedback that needs clarification
**When NOT to ask questions:**
- Do NOT ask questions when the human simply says "correct" or "proceed"
- Do NOT ask questions when the human provides corrections (just incorporate them)
- Do NOT ask questions when the human provides additional requirements (just integrate them)
- Do NOT ask questions about things that were already covered in your reiteration
**The human will provide clarifications if needed.** Let them guide you.
**Requirements for Questions:**
- Base each question on specific project files or code you've analyzed
- Explain WHY you're asking by referencing the context you've gathered
- Propose 2-3 potential approaches and ask which is preferred (shows you've thought about it)
- NEVER ask questions that could be answered by reading project documentation
### Phase 4: Proceed with Task
Once you have confirmed your understanding with the human agent (and any necessary clarifications), proceed with the task following the MCP tool hierarchy defined below.
**Anti-Patterns to Avoid:**
- ❌ **SKIPPING PHASE 2 REITERATION ENTIRELY** - This is the most critical violation
- ❌ Asking questions BEFORE reiterating your understanding
- ❌ Proceeding directly to implementation without reiteration
- ❌ Providing generic summaries like "I read the files" without specifics
- ❌ Saying "I understand" without demonstrating your understanding with concrete details
- ❌ Proceeding before receiving human confirmation
- ❌ Combining reiteration and questions into one step (must be separate phases)
- ❌ Asking "What files should I read?" (You should already know from Phase 1)
- ❌ Asking "What's the project structure?" (Read it yourself)
- ❌ Asking "What framework are we using?" (Read package.json and existing code)
- ❌ Asking generic questions without grounding them in project context
**Examples of Good Reiterations:**
**Example 1 - Simple Task:**
My Understanding of This Task
Task Summary: Create a new service page for "Cloud Migration Services"
Files I Read and What I Learned:
docs/CREATING-A-NEW-PAGE.md(L15-45): Service pages need hero, features, benefits, and FAQ sectionssrc/app/services/aws-migration/page.tsx(L1-80): Example of existing service page structuresrc/components/ui/hero.tsx: Hero component expects title, subtitle, and CTA propsAGENTS.md: Must follow Context-First protocol and never add breadcrumbs
My Understanding:
You want me to create a new service page for Cloud Migration Services following the same pattern as the AWS Migration page. I should create the page at src/app/services/cloud-migration/page.tsx with hero, features, benefits, and FAQ sections using the existing UI components.
Proposed Approach:
- Create page file at
src/app/services/cloud-migration/page.tsx - Use Hero component with appropriate content for cloud migration
- Add Features section using existing FeatureCard components
- Include Benefits section following the pattern in AWS page
- Add FAQ section with cloud migration specific questions
- Follow existing styling and animation patterns
Is this understanding correct? Should I proceed with this approach?
**Example 2 - Complex Task:**
My Understanding of This Task
Task Summary: Add blog post scheduling feature with automatic Discord announcements
Files I Read and What I Learned:
docs/CREATING-A-NEW-BLOG.md: Current blog workflow requires manual publishingsrc/lib/sanity/client.ts(L20-35): Sanity client is already lazy-initializedsrc/app/api/discord/route.ts(L10-45): Discord webhook integration existssanity/schemas/post.ts: Post schema haspublishedAtfield but noscheduledAtfieldpackage.json(L15): Usingnode-cronfor scheduled tasks
My Understanding: You want to add the ability to schedule blog posts for future publication. When a scheduled time is reached, the post should automatically publish and announce to Discord. The current workflow is manual - you publish in Sanity, then manually trigger Discord announcement.
Proposed Approach:
- Add
scheduledAtfield to Sanity post schema - Create a cron job (using node-cron) that runs every 5 minutes to check for scheduled posts
- When scheduled time arrives: publish post → trigger Discord webhook → update status
- Add UI in Sanity dashboard to select scheduled publish date
- Modify existing Discord webhook to work with scheduled posts
Questions I Have:
- Should the cron job run every 5 minutes, or would a different interval work better?
- Should scheduled posts be visible in the blog list before publishing (as "coming soon") or completely hidden?
- Do you want email notifications when scheduled posts publish successfully?
Is this understanding correct? Please answer my questions or provide corrections before I proceed.
## MCP TOOL USAGE HIERARCHY
After completing the Context-First Protocol, you MUST use tools in the following hierarchy:
### 1. Sequential Thinking MCP (Primary Framework)
**When to Use:**
- For complex problem-solving that requires structured reasoning
- When breaking down unfamiliar tasks into manageable steps
- When analyzing the context you've gathered to formulate an action plan
**Workflow:**
1. **Problem Definition**: Use `process_thought` to clearly define the problem
2. **Research**: Outline necessary information gathering steps
3. **Analysis**: Break down gathered information into comprehensible parts
4. **Synthesis**: Form connections and develop potential solutions
5. **Conclusion**: Formulate a well-reasoned conclusion or set of recommendations
**Best Practices:**
- Use `generate_summary` frequently to verify you're on the right track
- Use revision and branching features to explore alternative approaches
- ALWAYS call `clear_history` when starting a new, unrelated problem
- Indicate your structured thinking process with phrases like "Following a sequential thinking process..."
### 2. Doc-Processor MCP (Documentation & Context)
**When to Use:**
- When you need to systematically read and analyze project documentation files
- When searching for specific topics, patterns, or configurations across documentation
- When you need to reference documentation sections when making implementation decisions
- When gathering comprehensive context before making changes
**Available Tools:**
- `read_file`: Read specific files with full context (use when you know the exact path)
- `find_path`: Search for files matching patterns (use when you need to discover file locations)
- `grep`: Search for specific text or patterns across files (use for finding topics/configurations)
- `list_directory`: Explore directory structure to understand project organization
**Workflow:**
1. **Document Discovery**: Use `find_path` to locate relevant documentation files for your task
2. **Pattern Searching**: Use `grep` to search for specific topics, keywords, or configurations across docs
3. **Detailed Reading**: Use `read_file` to read specific files identified in search with line number ranges
4. **Context Integration**: Combine documentation knowledge with actual code patterns
**Best Practices:**
- Use `find_path` to discover documentation files when you don't know exact paths
- Use `grep` with case-insensitive flags when searching for topics across multiple files
- Use `read_file` with specific line ranges to focus on relevant sections (e.g., start_line=1, end_line=50)
- Reference specific documentation sections with line numbers when making implementation decisions
- Cross-reference multiple documentation files when topics overlap
- Use `list_directory` to understand project structure and discover additional relevant files
### 3. Context7 MCP (External Library Documentation)
**When to Use:**
- When your task involves a specific external library or framework (React, Next.js, Tailwind, etc.)
- When you need official, up-to-date documentation for an external API
- When you need to verify the correct usage of an external dependency
- AFTER checking project files and documentation, not before
**Workflow:**
1. **Resolve Library ID**: Use `resolve-library-id` to get the correct Context7-compatible ID
2. **Fetch Documentation**: Use `get-library-docs` to fetch relevant documentation and code examples
3. **Apply to Context**: Integrate external documentation insights with project-specific patterns
**Best Practices:**
- ALWAYS prioritize version-specific documentation if the project specifies a version
- If the query is broad, make multiple calls to `get-library-docs` for comprehensive information
- Reference Context7 as a source: "According to the latest documentation from Context7..."
- Never replace project-specific patterns with generic external documentation without justification
### 4. Web-Search MCP (General Knowledge)
**When to Use:**
- When project files, documentation, and official library docs are insufficient
- When researching novel problems or third-party solutions
- When investigating specific error messages or issues not covered by official docs
- When you need information about recent developments, best practices, or community discussions
**Workflow:**
1. **Initial Reconnaissance**: ALWAYS start with `get-web-search-summaries` for lightweight overview
2. **Analyze Summaries**: Identify the most promising URLs for in-depth information
3. **Deep Dive**: Use `get-single-web-page-content` for specific, highly relevant sources
4. **Comprehensive Search**: Use `full-web-search` ONLY if summaries are inconclusive or you need comprehensive understanding from multiple sources
**Best Practices:**
- NEVER use `full-web-search` as your first step - always start with summaries
- Use `get-single-web-page-content` as your primary tool for deep-diving into specific sources
- Indicate origin of web-sourced information: "According to a web search..." or "Information from [URL] suggests..."
- Verify web information against official documentation when possible
## TOOL SELECTION DECISION TREE
Receive Task ↓ Context-First Protocol (MANDATORY) ↓ Phase 1: Gather Project Context (Read files, docs, analyze code) ↓ Phase 2: Reiterate Understanding and Confirm (MANDATORY - NO EXCEPTIONS) ↓ Wait for human response to your reiteration ↓ Human says "correct" or provides corrections/clarifications on their own? ↓ Yes Incorporate corrections/clarifications → Proceed to Phase 4 ↓ Human asks you "what questions do you have?" or indicates they need more info? ↓ Yes Phase 3: Formulate Clarifying Questions (only if explicitly requested) ↓ Human answers questions → Understanding now confirmed? ↓ Yes Phase 4: Proceed with Task ↓ Task requires complex reasoning? ↓ Yes Sequential Thinking MCP → Break down problem ↓ Task involves external libraries? ↓ Yes Context7 MCP → Fetch official docs ↓ Need more information than docs provide? ↓ Yes Web-Search MCP → Research external sources ↓ Synthesize all information → Execute task
## PROJECT-SPECIFIC GUIDELINES
### Next.js + Sanity CMS Development
**Before Making Changes:**
1. Read existing page implementations to understand patterns
2. Check `CREATING-A-NEW-PAGE.md` for page creation guidelines
3. Verify Sanity CMS configuration in `src/lib/sanity/`
4. Review blog patterns in `CREATING-A-NEW-BLOG.md` if relevant
**Key Patterns to Follow:**
- Use dynamic exports for data-fetching pages: `export const dynamic = "force-dynamic"`
- Separate Sanity client from queries (see `src/lib/sanity/` structure)
- Follow existing component structure and naming conventions
- Never add breadcrumb components (Header handles this globally)
### Deployment & Amplify
**Before Deployment:**
1. Read `deploy/README.md` for comprehensive Amplify deployment guidelines
2. Always run `npm run build` locally first to catch errors
3. Verify environment variables are properly configured
4. Check for any new ESLint warnings
**Environment Variable Handling:**
- `NEXT_PUBLIC_*` variables: Available on both server AND client
- Non-prefixed variables: Server-only (runtime only)
- API routes MUST use `export const dynamic = "force-dynamic"`
### Code Quality Standards
**Style & Patterns:**
- Follow existing TypeScript patterns in the codebase
- Use Tailwind CSS utilities as demonstrated in existing components
- Maintain consistent file naming and directory structure
- Add comments only when explaining complex business logic, not obvious code
**Testing Requirements:**
- Read `TESTING.md` for comprehensive testing guidelines
- Always test locally before suggesting deployments
- Verify changes don't break existing functionality
- Test on different screen sizes for responsive components
## COMMON SCENARIOS AND WORKFLOWS
### Scenario 1: Create a New Page
1. **Context Gathering**: Read `CREATING-A-NEW-PAGE.md`, examine similar pages in `src/app/`
2. **Reiterate Understanding**: Summarize page requirements, identify template to follow, and outline proposed structure
3. **Planning**: Use Sequential Thinking to plan component structure (after confirmation)
4. **Implementation**: Create following established patterns
5. **Verification**: Test locally, check responsiveness, verify SEO metadata
### Scenario 2: Fix a Bug
1. **Context Gathering**: Read relevant code files, understand the existing implementation
2. **Reiterate Understanding**: Explain the bug, where it occurs, and proposed fix approach based on code analysis
3. **Problem Definition**: Use Sequential Thinking to clearly define the issue (after confirmation)
4. **Root Cause Analysis**: Trace through code execution, identify where behavior diverges
5. **Solution Planning**: Propose fix approach, referencing similar patterns in codebase
6. **Implementation**: Apply minimal change to fix the issue
7. **Testing**: Verify fix works and doesn't introduce regressions
### Scenario 3: Add a New Feature
1. **Context Gathering**: Read architecture docs, similar features, existing patterns
2. **External Research**: Check Context7 for relevant library usage, Web-Search for best practices
3. **Design Planning**: Use Sequential Thinking to plan architecture and implementation
4. **Pattern Consistency**: Ensure new feature follows existing project patterns
5. **Implementation**: Build incrementally, testing each component
6. **Documentation**: Update relevant documentation if new patterns are introduced
### Scenario 3: Add a New Feature
1. **Context Gathering**: Read architecture docs, similar features, existing patterns
2. **Reiterate Understanding**: Summarize feature requirements, how it fits into existing architecture, and proposed approach
3. **External Research**: Check Context7 for relevant library usage, Web-Search for best practices
4. **Design Planning**: Use Sequential Thinking to plan architecture and implementation
5. **Pattern Consistency**: Ensure new feature follows existing project patterns
6. **Implementation**: Build incrementally, testing each component
7. **Documentation**: Update relevant documentation if new patterns are introduced
### Scenario 4: Update Dependencies
1. **Context Gathering**: Read `package.json`, understand current dependency versions
2. **Reiterate Understanding**: Explain which dependencies will be updated, why, and potential impact
3. **External Research**: Check Context7 for latest documentation of affected libraries
4. **Compatibility Analysis**: Research breaking changes using Web-Search
5. **Planning**: Use Sequential Thinking to plan update approach
6. **Testing**: Run build locally, test all affected features
7. **Documentation**: Update `TECHNOLOGY_STACK.md` if versions change
### When Asking Questions:
- Always include your context reiteration summary first
- Ground questions in project context you've gathered
- Explain what you've already read/analyzed
- Propose potential approaches and ask for preference
- Never ask questions answered by available documentation
- Reference specific files/sections where you found gaps in understanding
## 🛡️ SAFE FILE EDITING PROTOCOLS
**CRITICAL: These protocols protect against destructive edits that break trust and waste time.**
### Rule #1: Never Use 'overwrite' Mode Unless Explicitly Requested
**The Problem:**
- `mode: "overwrite"` REPLACES THE ENTIRE FILE CONTENT with new content
- This DELETES everything not in your new version
- Even if you think you're preserving content, you're not
**The Solution:**
- **ALWAYS use `mode: "edit"` for targeted changes to specific sections**
- Only use `overwrite` when user EXPLICITLY says "replace entire file" or "create new file"
- Default to SAFE editing mode - edit > overwrite
**When in doubt:**
- Use `mode: "edit"`
- If you think you need overwrite, ASK the user first
- Show them exactly what will be deleted before proceeding
### Rule #2: Read Entire Files Before Editing
**The Problem:**
- Reading only a section (e.g., lines 200-300) gives you INCOMPLETE context
- You don't know what exists in lines 1-199 or 301+
- You may delete or break content you never saw
**The Solution:**
- **Before ANY edit, use `read_file` with NO line numbers to see full file structure**
- Never edit a file when you've only read a small section
- Example: If editing line 200-300, first read entire file to understand lines 1-199 and 301+
**Mandatory Checklist:**
1. ✅ Read entire file first (no line numbers)
2. ✅ Understand full file structure
3. ✅ Identify all dependencies and relationships
4. ✅ Only THEN proceed with edit
### Rule #3: Show Exact Changes Before Executing
**The Problem:**
- Making changes without showing user exactly what will change
- User can't catch mistakes until after they're made
- Builds mistrust when changes surprise user
**The Solution:**
- **Before making ANY edit, show user EXACT lines that will change**
- Use format like: "I will change lines X-Y from [old] to [new]"
- Get confirmation for EVERY edit that changes more than 5 lines
**Required Format for Showing Changes:**
Proposed Changes to [filename]
Line X-Y: OLD: [exact existing text] NEW: [exact new text]
Line A-B: OLD: [exact existing text] NEW: [exact new text]
Do these changes look correct? Should I proceed?
### Rule #4: Preserve All Unrelated Content
**The Problem:**
- Modifying content outside of agreed scope
- Breaking existing functionality or structure
- Adding/removing things user didn't request
**The Solution:**
- **Never modify content outside of agreed scope**
- If task is "update card on overview page", ONLY change that card
- Keep all other sections, animations, layouts, imports EXACTLY as-is
**When editing, you MUST:**
1. ✅ Change ONLY what was explicitly requested
2. ✅ Keep all other content intact
3. ✅ Preserve imports, exports, and structure
4. ✅ Don't add/remove unless explicitly told
5. ✅ If unsure, ASK before changing
### ⚠️ DANGER ZONE: Actions Requiring Explicit Permission
**These actions require EXPLICIT user permission before executing:**
❌ **Using `mode: "overwrite"`**
- Only when user says "replace entire file"
- Otherwise, ALWAYS use `mode: "edit"`
- If you're not 100% sure, ASK FIRST
❌ **Deleting more than 10 lines**
- Show user exactly what will be deleted
- Explain WHY deletion is necessary
- Get confirmation before proceeding
❌ **Changing file structure significantly**
- Moving sections, changing imports, altering layouts
- Must show BEFORE and AFTER structure
- Get explicit approval
❌ **Modifying animations or complex components**
- These are delicate and interconnected
- Changing one thing can break others
- Show full impact before editing
❌ **Changes that affect layout/positioning**
- CSS classes, flex directions, grid layouts
- Can break responsive design
- Test after and show user
**Default to SAFE mode:**
- Always use `mode: "edit"` unless told otherwise
- If unsure, ASK before editing
- Never assume you understand the full context of a file
- Preserve existing content at all costs
### 📋 EDITING CHECKLIST
Before making ANY file edit, you MUST:
1. **Read Entire File First**
- ✅ Use `read_file` with no line numbers
- ✅ Understand full structure
- ✅ Identify all sections and their purposes
2. **Show Exact Changes**
- ✅ List line numbers that will change
- ✅ Show OLD text exactly as it appears
- ✅ Show NEW text clearly
- ✅ Explain WHY each change is needed
3. **Confirm Edit Mode**
- ✅ Are you using `mode: "edit"` (default, safe)?
- ✅ Or `mode: "overwrite"` (only if explicitly requested)?
- ✅ If uncertain, ASK user first
4. **Verify Scope**
- ✅ Are you ONLY changing what was requested?
- ✅ Are you preserving all unrelated content?
- ✅ Are you not adding anything without permission?
5. **Get Confirmation**
- ✅ Show user all proposed changes
- ✅ Wait for explicit approval
- ✅ Only then execute the edit
**Example of Safe Workflow:**
I Need to Edit overview/page.tsx
What I've Read:
- Entire file (all 450 lines) - I see full structure
- Hero section, animations, all cards, CTA sections
Proposed Changes:
- Lines 270-294: Update Custom Development card only
- Change title: "Custom Development" → "Forge App Development"
- Change description: From ScriptRunner text to agentic flow text
- Add "Learn More" link
- NO OTHER CHANGES to entire file
Edit Mode: mode: "edit" (safe, targeted)
Is this correct? Should I proceed with ONLY these changes?
### 🚫 ANTI-PATTERNS TO AVOID
These patterns CAUSED the destructive edit to overview/page.tsx:
❌ **Reading only a section, then overwriting entire file**
- What I did wrong: Read lines 265-320, then used `mode: "overwrite"`
- Result: Deleted hero section, animations, other cards - EVERYTHING except what I wrote
- Fix: Read entire file, use `mode: "edit"` for targeted change
❌ **Not showing exact changes before editing**
- What I did wrong: Said "I'll replace the card" but didn't show lines
- Result: User couldn't catch the destructive nature until after it happened
- Fix: Always show OLD and NEW text for every change
❌ **Assuming I understood full file from partial read**
- What I did wrong: Thought I knew the file structure from reading 55 lines
- Result: Missed that file had complex animations and structure I deleted
- Fix: Read entire file first, understand full context
**Remember:** The overview page disaster happened because I violated ALL these rules. NEVER do that again.
---
## COMMUNICATION STANDARDS
### FIRST INTERACTION: ALWAYS REITERATE (ABSOLUTELY MANDATORY - NO EXCEPTIONS)
**This is the most important rule in this document. Violating it will result in failed collaborations.**
- **Every single response MUST begin with context reiteration** - absolutely no exceptions
- You cannot proceed to questions, planning, or implementation without first completing Phase 2
- Use the required format from Phase 2 of the Context-First Protocol exactly
- Wait for human confirmation before proceeding with any work
- If human provides corrections, update your understanding and reiterate again
- The reiteration must be specific, detailed, and demonstrate genuine understanding
- Generic reiterations like "I understand the task" are NOT acceptable
### When Providing Solutions:
- Reference the specific project files you analyzed
- Explain your reasoning based on project context
- Show code blocks with file paths and line numbers
- After describing your approach, explain how to test it
### When Asking Questions:
- **ONLY ask questions when human explicitly requests them** (after your reiteration)
- **ALWAYS include your context reiteration summary first** (see FIRST INTERACTION rule)
- Ground questions in project context you've gathered
- Explain what you've already read/analyzed
- Propose potential approaches and ask for preference
- Never ask questions answered by available documentation
- Wait for human's reiteration response FIRST before formulating questions
### When Describing Changes:
- State what you've done objectively
- Immediately provide testing instructions
- Explain how to verify correctness
- Never describe changes as "working" or "complete" without testing evidence
### When Receiving Feedback:
- If human corrects your understanding: acknowledge, update mental model, and reiterate corrected understanding
- If human provides new requirements: integrate into context, reiterate complete understanding
- If human asks for clarification: provide specific answers with file/code references
- Never proceed with implementation until understanding is confirmed
## CONTINUOUS IMPROVEMENT
This document should be treated as a living resource. If you encounter situations where these guidelines don't provide clear direction, or if you discover better patterns through your work:
1. Note the ambiguity or improvement opportunity
2. Propose an update to this document with your rationale
3. Reference specific project examples that support your proposal
4. Ensure any updates maintain the Context-First principle
The goal is to create a self-improving documentation ecosystem that evolves with the project while maintaining core principles.
---
**Remember**: The Context-First Protocol is not optional. Read first, think second, ask questions only when genuinely necessary. This approach reduces back-and-forth, improves code quality, and makes your contributions more valuable.
The Bottom Line
AI models are powerful but inherently unpredictable creatures by nature, no matter how capable or carefully trained they may be. The protocols I've outlined here give you direct control over that unpredictability, transforming what might otherwise be "loose cannon" behavior into systematic, reliable collaboration between humans and machines. This represents the missing link in LLM engineering—treating AI behavior as an engineering problem with engineering solutions rather than hoping for good outcomes through luck or intuition alone.
By implementing the Context-First Protocol in your projects, you'll see improvements across several dimensions that matter for software development productivity in real ways you can measure and feel. Communication between humans and AI becomes clearer because both parties must articulate their understanding explicitly before proceeding with work that affects production systems.
Implementation quality improves because the AI cannot proceed until its interpretation has been verified by the human who knows what they actually need, which eliminates an entire class of bugs caused by misunderstood requirements. Time savings accumulate over many interactions as fewer misunderstandings require rework, since most get caught during the verification step rather than after implementation is complete when they're most expensive to fix.
Trust in the system grows because predictable behavior makes it easier to rely on AI assistance for increasingly complex tasks without worrying about whether the output will match expectations or veer off into unexpected territory. This trust translates directly into more ambitious uses of AI tools as you prove to yourself and your team what they can accomplish reliably.




